3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') || die();
26 /** @global int $CHOICE_COLUMN_HEIGHT */
27 global $CHOICE_COLUMN_HEIGHT;
28 $CHOICE_COLUMN_HEIGHT = 300;
30 /** @global int $CHOICE_COLUMN_WIDTH */
31 global $CHOICE_COLUMN_WIDTH;
32 $CHOICE_COLUMN_WIDTH = 300;
34 define('CHOICE_PUBLISH_ANONYMOUS', '0');
35 define('CHOICE_PUBLISH_NAMES', '1');
37 define('CHOICE_SHOWRESULTS_NOT', '0');
38 define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
39 define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
40 define('CHOICE_SHOWRESULTS_ALWAYS', '3');
42 define('CHOICE_DISPLAY_HORIZONTAL', '0');
43 define('CHOICE_DISPLAY_VERTICAL', '1');
45 define('CHOICE_EVENT_TYPE_OPEN', 'open');
46 define('CHOICE_EVENT_TYPE_CLOSE', 'close');
48 /** @global array $CHOICE_PUBLISH */
49 global $CHOICE_PUBLISH;
50 $CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
51 CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
53 /** @global array $CHOICE_SHOWRESULTS */
54 global $CHOICE_SHOWRESULTS;
55 $CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT => get_string('publishnot', 'choice'),
56 CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
57 CHOICE_SHOWRESULTS_AFTER_CLOSE => get_string('publishafterclose', 'choice'),
58 CHOICE_SHOWRESULTS_ALWAYS => get_string('publishalways', 'choice'));
60 /** @global array $CHOICE_DISPLAY */
61 global $CHOICE_DISPLAY;
62 $CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
63 CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
65 /// Standard functions /////////////////////////////////////////////////////////
69 * @param object $course
72 * @param object $choice
75 function choice_user_outline($course, $user, $mod, $choice) {
77 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
78 $result = new stdClass();
79 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
80 $result->time = $answer->timemodified;
87 * Callback for the "Complete" report - prints the activity summary for the given user
89 * @param object $course
92 * @param object $choice
94 function choice_user_complete($course, $user, $mod, $choice) {
96 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
98 foreach ($answers as $answer) {
99 $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
101 core_collator::asort($info);
102 echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
103 get_string("updated", '', userdate($answer->timemodified));
105 print_string("notanswered", "choice");
110 * Given an object containing all the necessary data,
111 * (defined by the form in mod_form.php) this function
112 * will create a new instance and return the id number
113 * of the new instance.
116 * @param object $choice
119 function choice_add_instance($choice) {
121 require_once($CFG->dirroot.'/mod/choice/locallib.php');
123 $choice->timemodified = time();
126 $choice->id = $DB->insert_record("choice", $choice);
127 foreach ($choice->option as $key => $value) {
128 $value = trim($value);
129 if (isset($value) && $value <> '') {
130 $option = new stdClass();
131 $option->text = $value;
132 $option->choiceid = $choice->id;
133 if (isset($choice->limit[$key])) {
134 $option->maxanswers = $choice->limit[$key];
136 $option->timemodified = time();
137 $DB->insert_record("choice_options", $option);
141 // Add calendar events if necessary.
142 choice_set_events($choice);
148 * Given an object containing all the necessary data,
149 * (defined by the form in mod_form.php) this function
150 * will update an existing instance with new data.
153 * @param object $choice
156 function choice_update_instance($choice) {
158 require_once($CFG->dirroot.'/mod/choice/locallib.php');
160 $choice->id = $choice->instance;
161 $choice->timemodified = time();
163 //update, delete or insert answers
164 foreach ($choice->option as $key => $value) {
165 $value = trim($value);
166 $option = new stdClass();
167 $option->text = $value;
168 $option->choiceid = $choice->id;
169 if (isset($choice->limit[$key])) {
170 $option->maxanswers = $choice->limit[$key];
172 $option->timemodified = time();
173 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
174 $option->id=$choice->optionid[$key];
175 if (isset($value) && $value <> '') {
176 $DB->update_record("choice_options", $option);
178 // Remove the empty (unused) option.
179 $DB->delete_records("choice_options", array("id" => $option->id));
180 // Delete any answers associated with this option.
181 $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
184 if (isset($value) && $value <> '') {
185 $DB->insert_record("choice_options", $option);
190 // Add calendar events if necessary.
191 choice_set_events($choice);
193 return $DB->update_record('choice', $choice);
199 * @param object $choice
200 * @param object $user
201 * @param object $coursemodule
202 * @param array $allresponses
205 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
208 $cdisplay = array('options'=>array());
210 $cdisplay['limitanswers'] = true;
211 $context = context_module::instance($coursemodule->id);
213 foreach ($choice->option as $optionid => $text) {
214 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
215 $option = new stdClass;
216 $option->attributes = new stdClass;
217 $option->attributes->value = $optionid;
218 $option->text = format_string($text);
219 $option->maxanswers = $choice->maxanswers[$optionid];
220 $option->displaylayout = $choice->display;
222 if (isset($allresponses[$optionid])) {
223 $option->countanswers = count($allresponses[$optionid]);
225 $option->countanswers = 0;
227 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
228 $option->attributes->checked = true;
230 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
231 $option->attributes->disabled = true;
233 $cdisplay['options'][] = $option;
237 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
239 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
240 $cdisplay['allowupdate'] = true;
243 if ($choice->showpreview && $choice->timeopen > time()) {
244 $cdisplay['previewonly'] = true;
251 * Modifies responses of other users adding the option $newoptionid to them
253 * @param array $userids list of users to add option to (must be users without any answers yet)
254 * @param array $answerids list of existing attempt ids of users (will be either appended or
255 * substituted with the newoptionid, depending on $choice->allowmultiple)
256 * @param int $newoptionid
257 * @param stdClass $choice choice object, result of {@link choice_get_choice()}
258 * @param stdClass $cm
259 * @param stdClass $course
261 function choice_modify_responses($userids, $answerids, $newoptionid, $choice, $cm, $course) {
262 // Get all existing responses and the list of non-respondents.
263 $groupmode = groups_get_activity_groupmode($cm);
264 $onlyactive = $choice->includeinactive ? false : true;
265 $allresponses = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
267 // Check that the option value is valid.
268 if (!$newoptionid || !isset($choice->option[$newoptionid])) {
272 // First add responses for users who did not make any choice yet.
273 foreach ($userids as $userid) {
274 if (isset($allresponses[0][$userid])) {
275 choice_user_submit_response($newoptionid, $choice, $userid, $course, $cm);
279 // Create the list of all options already selected by each user.
280 $optionsbyuser = []; // Mapping userid=>array of chosen choice options.
281 $usersbyanswer = []; // Mapping answerid=>userid (which answer belongs to each user).
282 foreach ($allresponses as $optionid => $responses) {
284 foreach ($responses as $userid => $userresponse) {
285 $optionsbyuser += [$userid => []];
286 $optionsbyuser[$userid][] = $optionid;
287 $usersbyanswer[$userresponse->answerid] = $userid;
292 // Go through the list of submitted attemptids and find which users answers need to be updated.
293 foreach ($answerids as $answerid) {
294 if (isset($usersbyanswer[$answerid])) {
295 $userid = $usersbyanswer[$answerid];
296 if (!in_array($newoptionid, $optionsbyuser[$userid])) {
297 $options = $choice->allowmultiple ?
298 array_merge($optionsbyuser[$userid], [$newoptionid]) : $newoptionid;
299 choice_user_submit_response($options, $choice, $userid, $course, $cm);
306 * Process user submitted answers for a choice,
307 * and either updating them or saving new answers.
309 * @param int $formanswer users submitted answers.
310 * @param object $choice the selected choice.
311 * @param int $userid user identifier.
312 * @param object $course current course.
313 * @param object $cm course context.
316 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
317 global $DB, $CFG, $USER;
318 require_once($CFG->libdir.'/completionlib.php');
320 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
322 if (empty($formanswer)) {
323 print_error('atleastoneoption', 'choice', $continueurl);
326 if (is_array($formanswer)) {
327 if (!$choice->allowmultiple) {
328 print_error('multiplenotallowederror', 'choice', $continueurl);
330 $formanswers = $formanswer;
332 $formanswers = array($formanswer);
335 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
336 foreach ($formanswers as $key => $val) {
337 if (!isset($options[$val])) {
338 print_error('cannotsubmit', 'choice', $continueurl);
341 // Start lock to prevent synchronous access to the same data
342 // before it's updated, if using limits.
343 if ($choice->limitanswers) {
345 $locktype = 'mod_choice_choice_user_submit_response';
346 // Limiting access to this choice.
347 $resouce = 'choiceid:' . $choice->id;
348 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
351 $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS);
353 print_error('cannotsubmit', 'choice', $continueurl);
357 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
358 $context = context_module::instance($cm->id);
360 $choicesexceeded = false;
361 $countanswers = array();
362 foreach ($formanswers as $val) {
363 $countanswers[$val] = 0;
365 if($choice->limitanswers) {
366 // Find out whether groups are being used and enabled
367 if (groups_get_activity_groupmode($cm) > 0) {
368 $currentgroup = groups_get_activity_group($cm);
373 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
376 // If groups are being used, retrieve responses only for users in
380 $params['groupid'] = $currentgroup;
382 FROM {choice_answers} ca
383 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
384 WHERE optionid $insql
385 AND gm.groupid= :groupid";
387 // Groups are not used, retrieve all answers for this option ID
389 FROM {choice_answers} ca
390 WHERE optionid $insql";
393 $answers = $DB->get_records_sql($sql, $params);
395 foreach ($answers as $a) { //only return enrolled users.
396 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
397 $countanswers[$a->optionid]++;
401 foreach ($countanswers as $opt => $count) {
402 if ($count >= $choice->maxanswers[$opt]) {
403 $choicesexceeded = true;
409 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
410 $answersnapshots = array();
411 $deletedanswersnapshots = array();
412 if (!($choice->limitanswers && $choicesexceeded)) {
414 // Update an existing answer.
415 $existingchoices = array();
416 foreach ($current as $c) {
417 if (in_array($c->optionid, $formanswers)) {
418 $existingchoices[] = $c->optionid;
419 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
421 $deletedanswersnapshots[] = $c;
422 $DB->delete_records('choice_answers', array('id' => $c->id));
427 foreach ($formanswers as $f) {
428 if (!in_array($f, $existingchoices)) {
429 $newanswer = new stdClass();
430 $newanswer->optionid = $f;
431 $newanswer->choiceid = $choice->id;
432 $newanswer->userid = $userid;
433 $newanswer->timemodified = time();
434 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
435 $answersnapshots[] = $newanswer;
440 foreach ($formanswers as $answer) {
441 $newanswer = new stdClass();
442 $newanswer->choiceid = $choice->id;
443 $newanswer->userid = $userid;
444 $newanswer->optionid = $answer;
445 $newanswer->timemodified = time();
446 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
447 $answersnapshots[] = $newanswer;
450 // Update completion state
451 $completion = new completion_info($course);
452 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
453 $completion->update_state($cm, COMPLETION_COMPLETE);
457 // Check to see if current choice already selected - if not display error.
458 $currentids = array_keys($current);
460 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
461 // Release lock before error.
462 $choicelock->release();
463 print_error('choicefull', 'choice', $continueurl);
468 if (isset($choicelock)) {
469 $choicelock->release();
473 foreach ($deletedanswersnapshots as $answer) {
474 \mod_choice\event\answer_deleted::create_from_object($answer, $choice, $cm, $course)->trigger();
476 foreach ($answersnapshots as $answer) {
477 \mod_choice\event\answer_created::create_from_object($answer, $choice, $cm, $course)->trigger();
484 * @return void Output is echo'd
486 function choice_show_reportlink($user, $cm) {
487 $userschosen = array();
488 foreach($user as $optionid => $userlist) {
490 $userschosen = array_merge($userschosen, array_keys($userlist));
493 $responsecount = count(array_unique($userschosen));
495 echo '<div class="reportlink">';
496 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
502 * @param object $choice
503 * @param object $course
504 * @param object $coursemodule
505 * @param array $allresponses
507 * * @param bool $allresponses
510 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
513 $display = clone($choice);
514 $display->coursemoduleid = $cm->id;
515 $display->courseid = $course->id;
517 if (!empty($choice->showunanswered)) {
518 $choice->option[0] = get_string('notanswered', 'choice');
519 $choice->maxanswers[0] = 0;
522 // Remove from the list of non-respondents the users who do not have access to this activity.
523 if (!empty($display->showunanswered) && $allresponses[0]) {
524 $info = new \core_availability\info_module(cm_info::create($cm));
525 $allresponses[0] = $info->filter_user_list($allresponses[0]);
528 //overwrite options value;
529 $display->options = array();
531 foreach ($choice->option as $optionid => $optiontext) {
532 $display->options[$optionid] = new stdClass;
533 $display->options[$optionid]->text = $optiontext;
534 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
536 if (array_key_exists($optionid, $allresponses)) {
537 $display->options[$optionid]->user = $allresponses[$optionid];
538 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
541 unset($display->option);
542 unset($display->maxanswers);
544 $display->numberofuser = count(array_unique($allusers));
545 $context = context_module::instance($cm->id);
546 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
547 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
548 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
550 if (empty($allresponses)) {
551 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
560 * @param array $attemptids
561 * @param object $choice Choice main table row
562 * @param object $cm Course-module object
563 * @param object $course Course object
566 function choice_delete_responses($attemptids, $choice, $cm, $course) {
567 global $DB, $CFG, $USER;
568 require_once($CFG->libdir.'/completionlib.php');
570 if(!is_array($attemptids) || empty($attemptids)) {
574 foreach($attemptids as $num => $attemptid) {
575 if(empty($attemptid)) {
576 unset($attemptids[$num]);
580 $completion = new completion_info($course);
581 foreach($attemptids as $attemptid) {
582 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
583 // Trigger the event answer deleted.
584 \mod_choice\event\answer_deleted::create_from_object($todelete, $choice, $cm, $course)->trigger();
585 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
589 // Update completion state.
590 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
591 $completion->update_state($cm, COMPLETION_INCOMPLETE);
599 * Given an ID of an instance of this module,
600 * this function will permanently delete the instance
601 * and any data that depends on it.
607 function choice_delete_instance($id) {
610 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
616 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
620 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
624 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
627 // Remove old calendar events.
628 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
636 * Returns text string which is the answer that matches the id
639 * @param object $choice
643 function choice_get_option_text($choice, $id) {
646 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
647 return $result->text;
649 return get_string("notanswered", "choice");
654 * Gets a full choice record
657 * @param int $choiceid
658 * @return object|bool The choice or false
660 function choice_get_choice($choiceid) {
663 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
664 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
665 foreach ($options as $option) {
666 $choice->option[$option->id] = $option->text;
667 $choice->maxanswers[$option->id] = $option->maxanswers;
676 * List the actions that correspond to a view of this module.
677 * This is used by the participation report.
679 * Note: This is not used by new logging system. Event with
680 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
681 * be considered as view action.
685 function choice_get_view_actions() {
686 return array('view','view all','report');
690 * List the actions that correspond to a post of this module.
691 * This is used by the participation report.
693 * Note: This is not used by new logging system. Event with
694 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
695 * will be considered as post action.
699 function choice_get_post_actions() {
700 return array('choose','choose again');
705 * Implementation of the function for printing the form elements that control
706 * whether the course reset functionality affects the choice.
708 * @param object $mform form passed by reference
710 function choice_reset_course_form_definition(&$mform) {
711 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
712 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
716 * Course reset form defaults.
720 function choice_reset_course_form_defaults($course) {
721 return array('reset_choice'=>1);
725 * Actual implementation of the reset course functionality, delete all the
726 * choice responses for course $data->courseid.
730 * @param object $data the data submitted from the reset course.
731 * @return array status array
733 function choice_reset_userdata($data) {
736 $componentstr = get_string('modulenameplural', 'choice');
739 if (!empty($data->reset_choice)) {
740 $choicessql = "SELECT ch.id
744 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
745 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
748 /// updating dates - shift may be negative too
749 if ($data->timeshift) {
750 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
751 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
761 * @uses CONTEXT_MODULE
762 * @param object $choice
764 * @param int $groupmode
765 * @param bool $onlyactive Whether to get response data for active users only.
768 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
769 global $CFG, $USER, $DB;
771 $context = context_module::instance($cm->id);
773 /// Get the current group
774 if ($groupmode > 0) {
775 $currentgroup = groups_get_activity_group($cm);
780 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
781 $allresponses = array();
783 /// First get all the users who have access here
784 /// To start with we assume they are all "unanswered" then move them later
785 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
786 user_picture::fields('u', array('idnumber')), null, 0, 0, $onlyactive);
788 /// Get all the recorded responses for this choice
789 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
791 /// Use the responses to move users into the correct column
794 $answeredusers = array();
795 foreach ($rawresponses as $response) {
796 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
797 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
798 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
799 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
800 $answeredusers[] = $response->userid;
803 foreach ($answeredusers as $answereduser) {
804 unset($allresponses[0][$answereduser]);
807 return $allresponses;
811 * Returns all other caps used in module
815 function choice_get_extra_capabilities() {
816 return array('moodle/site:accessallgroups');
820 * @uses FEATURE_GROUPS
821 * @uses FEATURE_GROUPINGS
822 * @uses FEATURE_MOD_INTRO
823 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
824 * @uses FEATURE_GRADE_HAS_GRADE
825 * @uses FEATURE_GRADE_OUTCOMES
826 * @param string $feature FEATURE_xx constant for requested feature
827 * @return mixed True if module supports feature, null if doesn't know
829 function choice_supports($feature) {
831 case FEATURE_GROUPS: return true;
832 case FEATURE_GROUPINGS: return true;
833 case FEATURE_MOD_INTRO: return true;
834 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
835 case FEATURE_COMPLETION_HAS_RULES: return true;
836 case FEATURE_GRADE_HAS_GRADE: return false;
837 case FEATURE_GRADE_OUTCOMES: return false;
838 case FEATURE_BACKUP_MOODLE2: return true;
839 case FEATURE_SHOW_DESCRIPTION: return true;
841 default: return null;
846 * Adds module specific settings to the settings block
848 * @param settings_navigation $settings The settings navigation object
849 * @param navigation_node $choicenode The node to add module settings to
851 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
854 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
856 $groupmode = groups_get_activity_groupmode($PAGE->cm);
858 groups_get_activity_group($PAGE->cm, true);
861 $choice = choice_get_choice($PAGE->cm->instance);
863 // Check if we want to include responses from inactive users.
864 $onlyactive = $choice->includeinactive ? false : true;
866 // Big function, approx 6 SQL calls per user.
867 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
870 foreach($allresponses as $optionid => $userlist) {
872 $allusers = array_merge($allusers, array_keys($userlist));
875 $responsecount = count(array_unique($allusers));
876 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
881 * Obtains the automatic completion state for this choice based on any conditions
884 * @param object $course Course
885 * @param object $cm Course-module
886 * @param int $userid User ID
887 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
888 * @return bool True if completed, false if not, $type if conditions not set.
890 function choice_get_completion_state($course, $cm, $userid, $type) {
893 // Get choice details
894 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
897 // If completion option is enabled, evaluate it and return true/false
898 if($choice->completionsubmit) {
899 return $DB->record_exists('choice_answers', array(
900 'choiceid'=>$choice->id, 'userid'=>$userid));
902 // Completion option is not enabled so just return $type
908 * Return a list of page types
909 * @param string $pagetype current page type
910 * @param stdClass $parentcontext Block's parent context
911 * @param stdClass $currentcontext Current context of block
913 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
914 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
915 return $module_pagetype;
919 * Prints choice summaries on MyMoodle Page
921 * Prints choice name, due date and attempt information on
922 * choice activities that have a deadline that has not already passed
923 * and it is available for completing.
925 * @deprecated since 3.3
926 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
927 * @uses CONTEXT_MODULE
928 * @param array $courses An array of course objects to get choice instances from.
929 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
931 function choice_print_overview($courses, &$htmlarray) {
932 global $USER, $DB, $OUTPUT;
934 debugging('The function choice_print_overview() is now deprecated.', DEBUG_DEVELOPER);
936 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
939 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
944 foreach ($choices as $choice) {
945 if ($choice->timeclose != 0 // If this choice is scheduled.
946 and $choice->timeclose >= $now // And the deadline has not passed.
947 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
950 $class = (!$choice->visible) ? 'dimmed' : '';
953 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
954 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
955 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
958 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
960 // Display relevant info based on permissions.
961 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
962 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
964 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
965 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
967 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
968 // See if the user has submitted anything.
969 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
971 // User has already selected an answer, nothing to show.
974 // User has not made a selection yet.
975 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
978 // Does not have permission to do anything on this choice activity.
982 // Make sure we have something to display.
984 // Generate the containing div.
985 $str = $OUTPUT->box($str, 'choice overview');
987 if (empty($htmlarray[$choice->course]['choice'])) {
988 $htmlarray[$choice->course]['choice'] = $str;
990 $htmlarray[$choice->course]['choice'] .= $str;
1000 * Get my responses on a given choice.
1002 * @param stdClass $choice Choice record
1003 * @return array of choice answers records
1006 function choice_get_my_response($choice) {
1008 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
1013 * Get all the responses on a given choice.
1015 * @param stdClass $choice Choice record
1016 * @return array of choice answers records
1019 function choice_get_all_responses($choice) {
1021 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
1026 * Return true if we are allowd to view the choice results.
1028 * @param stdClass $choice Choice record
1029 * @param rows|null $current my choice responses
1030 * @param bool|null $choiceopen if the choice is open
1031 * @return bool true if we can view the results, false otherwise.
1034 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1036 if (is_null($choiceopen)) {
1039 if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
1040 // If the choice is not available, we can't see the results.
1044 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1045 $choiceopen = false;
1050 if (empty($current)) {
1051 $current = choice_get_my_response($choice);
1054 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1055 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1056 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1063 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1065 * @param stdClass $choice choice object
1066 * @param stdClass $course course object
1067 * @param stdClass $cm course module object
1068 * @param stdClass $context context object
1071 function choice_view($choice, $course, $cm, $context) {
1073 // Trigger course_module_viewed event.
1075 'context' => $context,
1076 'objectid' => $choice->id
1079 $event = \mod_choice\event\course_module_viewed::create($params);
1080 $event->add_record_snapshot('course_modules', $cm);
1081 $event->add_record_snapshot('course', $course);
1082 $event->add_record_snapshot('choice', $choice);
1086 $completion = new completion_info($course);
1087 $completion->set_module_viewed($cm);
1091 * Check if a choice is available for the current user.
1093 * @param stdClass $choice choice record
1094 * @return array status (available or not and possible warnings)
1096 function choice_get_availability_status($choice) {
1098 $warnings = array();
1102 if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
1104 $warnings['notopenyet'] = userdate($choice->timeopen);
1105 } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
1107 $warnings['expired'] = userdate($choice->timeclose);
1109 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1111 $warnings['choicesaved'] = '';
1114 // Choice is available.
1115 return array($available, $warnings);
1119 * This standard function will check all instances of this module
1120 * and make sure there are up-to-date events created for each of them.
1121 * If courseid = 0, then every chat event in the site is checked, else
1122 * only chat events belonging to the course specified are checked.
1123 * This function is used, in its new format, by restore_refresh_events()
1125 * @param int $courseid
1128 function choice_refresh_events($courseid = 0) {
1130 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1133 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1137 if (! $choices = $DB->get_records("choice")) {
1142 foreach ($choices as $choice) {
1143 choice_set_events($choice);
1149 * Check if the module has any update that affects the current user since a given time.
1151 * @param cm_info $cm course module data
1152 * @param int $from the time to check updates from
1153 * @param array $filter if we need to check only specific updates
1154 * @return stdClass an object with the different type of areas indicating if they were updated or not
1157 function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
1160 $updates = new stdClass();
1161 $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1162 list($available, $warnings) = choice_get_availability_status($choice);
1167 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1169 if (!choice_can_view_results($choice)) {
1172 // Check if there are new responses in the choice.
1173 $updates->answers = (object) array('updated' => false);
1174 $select = 'choiceid = :id AND timemodified > :since';
1175 $params = array('id' => $choice->id, 'since' => $from);
1176 $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1177 if (!empty($answers)) {
1178 $updates->answers->updated = true;
1179 $updates->answers->itemids = array_keys($answers);
1186 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1188 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1189 * is not displayed on the block.
1191 * @param calendar_event $event
1192 * @param \core_calendar\action_factory $factory
1193 * @return \core_calendar\local\event\entities\action_interface|null
1195 function mod_choice_core_calendar_provide_event_action(calendar_event $event,
1196 \core_calendar\action_factory $factory) {
1199 $cm = get_fast_modinfo($event->courseid)->instances['choice'][$event->instance];
1200 $choice = $DB->get_record('choice', array('id' => $event->instance), 'id, timeopen, timeclose');
1203 if ($choice->timeclose && $choice->timeclose < $now) {
1204 // The choice has closed so the user can no longer submit anything.
1208 if (choice_get_my_response($choice)) {
1209 // There is no action if the user has already submitted their choice.
1213 // The choice is actionable if we don't have a start time or the start time is
1215 $actionable = (!$choice->timeopen || $choice->timeopen <= $now);
1217 return $factory->create_instance(
1218 get_string('viewchoices', 'choice'),
1219 new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
1226 * Get icon mapping for font-awesome.
1228 function mod_choice_get_fontawesome_icon_map() {
1230 'mod_choice:row' => 'fa-info',
1231 'mod_choice:column' => 'fa-columns',
1236 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1237 * for the course (see resource).
1239 * Given a course_module object, this function returns any "extra" information that may be needed
1240 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1242 * @param stdClass $coursemodule The coursemodule object (record).
1243 * @return cached_cm_info An object on information that the courses
1244 * will know about (most noticeably, an icon).
1246 function choice_get_coursemodule_info($coursemodule) {
1249 $dbparams = ['id' => $coursemodule->instance];
1250 $fields = 'id, completionsubmit';
1251 if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1255 $result = new cached_cm_info();
1257 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1258 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1259 $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
1266 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1268 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1269 * @return array $descriptions the array of descriptions for the custom rules.
1271 function mod_choice_get_completion_active_rule_descriptions($cm) {
1272 // Values will be present in cm_info, and we assume these are up to date.
1273 if (empty($cm->customdata['customcompletionrules'])
1274 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1279 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1281 case 'completionsubmit':
1285 $descriptions[] = get_string('completionsubmit', 'choice');
1291 return $descriptions;