weekly release 4.2.1+
[moodle.git] / mod / choice / lib.php
blobb9c3cbbbaad41d28562af964ab5bd4f8a3a5bdf4
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package mod_choice
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 require_once(__DIR__ . '/deprecatedlib.php');
67 /// Standard functions /////////////////////////////////////////////////////////
69 /**
70 * @global object
71 * @param object $course
72 * @param object $user
73 * @param object $mod
74 * @param object $choice
75 * @return object|null
77 function choice_user_outline($course, $user, $mod, $choice) {
78 global $DB;
79 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
80 $result = new stdClass();
81 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
82 $result->time = $answer->timemodified;
83 return $result;
85 return NULL;
88 /**
89 * Callback for the "Complete" report - prints the activity summary for the given user
91 * @param object $course
92 * @param object $user
93 * @param object $mod
94 * @param object $choice
96 function choice_user_complete($course, $user, $mod, $choice) {
97 global $DB;
98 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
99 $info = [];
100 foreach ($answers as $answer) {
101 $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
103 core_collator::asort($info);
104 echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
105 get_string("updated", '', userdate($answer->timemodified));
106 } else {
107 print_string("notanswered", "choice");
112 * Given an object containing all the necessary data,
113 * (defined by the form in mod_form.php) this function
114 * will create a new instance and return the id number
115 * of the new instance.
117 * @global object
118 * @param object $choice
119 * @return int
121 function choice_add_instance($choice) {
122 global $DB, $CFG;
123 require_once($CFG->dirroot.'/mod/choice/locallib.php');
125 $choice->timemodified = time();
127 //insert answers
128 $choice->id = $DB->insert_record("choice", $choice);
129 foreach ($choice->option as $key => $value) {
130 $value = trim($value);
131 if (isset($value) && $value <> '') {
132 $option = new stdClass();
133 $option->text = $value;
134 $option->choiceid = $choice->id;
135 if (isset($choice->limit[$key])) {
136 $option->maxanswers = $choice->limit[$key];
138 $option->timemodified = time();
139 $DB->insert_record("choice_options", $option);
143 // Add calendar events if necessary.
144 choice_set_events($choice);
145 if (!empty($choice->completionexpected)) {
146 \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id,
147 $choice->completionexpected);
150 return $choice->id;
154 * Given an object containing all the necessary data,
155 * (defined by the form in mod_form.php) this function
156 * will update an existing instance with new data.
158 * @global object
159 * @param object $choice
160 * @return bool
162 function choice_update_instance($choice) {
163 global $DB, $CFG;
164 require_once($CFG->dirroot.'/mod/choice/locallib.php');
166 $choice->id = $choice->instance;
167 $choice->timemodified = time();
169 //update, delete or insert answers
170 foreach ($choice->option as $key => $value) {
171 $value = trim($value);
172 $option = new stdClass();
173 $option->text = $value;
174 $option->choiceid = $choice->id;
175 if (isset($choice->limit[$key])) {
176 $option->maxanswers = $choice->limit[$key];
178 $option->timemodified = time();
179 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
180 $option->id=$choice->optionid[$key];
181 if (isset($value) && $value <> '') {
182 $DB->update_record("choice_options", $option);
183 } else {
184 // Remove the empty (unused) option.
185 $DB->delete_records("choice_options", array("id" => $option->id));
186 // Delete any answers associated with this option.
187 $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
189 } else {
190 if (isset($value) && $value <> '') {
191 $DB->insert_record("choice_options", $option);
196 // Add calendar events if necessary.
197 choice_set_events($choice);
198 $completionexpected = (!empty($choice->completionexpected)) ? $choice->completionexpected : null;
199 \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id, $completionexpected);
201 return $DB->update_record('choice', $choice);
206 * @global object
207 * @param object $choice
208 * @param object $user
209 * @param object $coursemodule
210 * @param array $allresponses
211 * @return array
213 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
214 global $DB;
216 $cdisplay = array('options'=>array());
218 $cdisplay['limitanswers'] = $choice->limitanswers;
219 $cdisplay['showavailable'] = $choice->showavailable;
221 $context = context_module::instance($coursemodule->id);
223 foreach ($choice->option as $optionid => $text) {
224 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
225 $option = new stdClass;
226 $option->attributes = new stdClass;
227 $option->attributes->value = $optionid;
228 $option->text = format_string($text);
229 $option->maxanswers = $choice->maxanswers[$optionid];
230 $option->displaylayout = $choice->display;
232 if (isset($allresponses[$optionid])) {
233 $option->countanswers = count($allresponses[$optionid]);
234 } else {
235 $option->countanswers = 0;
237 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
238 $option->attributes->checked = true;
240 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
241 $option->attributes->disabled = true;
243 $cdisplay['options'][] = $option;
247 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
249 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
250 $cdisplay['allowupdate'] = true;
253 if ($choice->showpreview && $choice->timeopen > time()) {
254 $cdisplay['previewonly'] = true;
257 return $cdisplay;
261 * Modifies responses of other users adding the option $newoptionid to them
263 * @param array $userids list of users to add option to (must be users without any answers yet)
264 * @param array $answerids list of existing attempt ids of users (will be either appended or
265 * substituted with the newoptionid, depending on $choice->allowmultiple)
266 * @param int $newoptionid
267 * @param stdClass $choice choice object, result of {@link choice_get_choice()}
268 * @param stdClass $cm
269 * @param stdClass $course
271 function choice_modify_responses($userids, $answerids, $newoptionid, $choice, $cm, $course) {
272 // Get all existing responses and the list of non-respondents.
273 $groupmode = groups_get_activity_groupmode($cm);
274 $onlyactive = $choice->includeinactive ? false : true;
275 $allresponses = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
277 // Check that the option value is valid.
278 if (!$newoptionid || !isset($choice->option[$newoptionid])) {
279 return;
282 // First add responses for users who did not make any choice yet.
283 foreach ($userids as $userid) {
284 if (isset($allresponses[0][$userid])) {
285 choice_user_submit_response($newoptionid, $choice, $userid, $course, $cm);
289 // Create the list of all options already selected by each user.
290 $optionsbyuser = []; // Mapping userid=>array of chosen choice options.
291 $usersbyanswer = []; // Mapping answerid=>userid (which answer belongs to each user).
292 foreach ($allresponses as $optionid => $responses) {
293 if ($optionid > 0) {
294 foreach ($responses as $userid => $userresponse) {
295 $optionsbyuser += [$userid => []];
296 $optionsbyuser[$userid][] = $optionid;
297 $usersbyanswer[$userresponse->answerid] = $userid;
302 // Go through the list of submitted attemptids and find which users answers need to be updated.
303 foreach ($answerids as $answerid) {
304 if (isset($usersbyanswer[$answerid])) {
305 $userid = $usersbyanswer[$answerid];
306 if (!in_array($newoptionid, $optionsbyuser[$userid])) {
307 $options = $choice->allowmultiple ?
308 array_merge($optionsbyuser[$userid], [$newoptionid]) : $newoptionid;
309 choice_user_submit_response($options, $choice, $userid, $course, $cm);
316 * Process user submitted answers for a choice,
317 * and either updating them or saving new answers.
319 * @param int|array $formanswer the id(s) of the user submitted choice options.
320 * @param object $choice the selected choice.
321 * @param int $userid user identifier.
322 * @param object $course current course.
323 * @param object $cm course context.
324 * @return void
326 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
327 global $DB, $CFG, $USER;
328 require_once($CFG->libdir.'/completionlib.php');
330 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
332 if (empty($formanswer)) {
333 throw new \moodle_exception('atleastoneoption', 'choice', $continueurl);
336 if (is_array($formanswer)) {
337 if (!$choice->allowmultiple) {
338 throw new \moodle_exception('multiplenotallowederror', 'choice', $continueurl);
340 $formanswers = $formanswer;
341 } else {
342 $formanswers = array($formanswer);
345 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
346 foreach ($formanswers as $key => $val) {
347 if (!isset($options[$val])) {
348 throw new \moodle_exception('cannotsubmit', 'choice', $continueurl);
351 // Start lock to prevent synchronous access to the same data
352 // before it's updated, if using limits.
353 if ($choice->limitanswers) {
354 $timeout = 10;
355 $locktype = 'mod_choice_choice_user_submit_response';
356 // Limiting access to this choice.
357 $resouce = 'choiceid:' . $choice->id;
358 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
360 // Opening the lock.
361 $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS);
362 if (!$choicelock) {
363 throw new \moodle_exception('cannotsubmit', 'choice', $continueurl);
367 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
369 // Array containing [answerid => optionid] mapping.
370 $existinganswers = array_map(function($answer) {
371 return $answer->optionid;
372 }, $current);
374 $context = context_module::instance($cm->id);
376 $choicesexceeded = false;
377 $countanswers = array();
378 foreach ($formanswers as $val) {
379 $countanswers[$val] = 0;
381 if($choice->limitanswers) {
382 // Find out whether groups are being used and enabled
383 if (groups_get_activity_groupmode($cm) > 0) {
384 $currentgroup = groups_get_activity_group($cm);
385 } else {
386 $currentgroup = 0;
389 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
391 if($currentgroup) {
392 // If groups are being used, retrieve responses only for users in
393 // current group
394 global $CFG;
396 $params['groupid'] = $currentgroup;
397 $sql = "SELECT ca.*
398 FROM {choice_answers} ca
399 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
400 WHERE optionid $insql
401 AND gm.groupid= :groupid";
402 } else {
403 // Groups are not used, retrieve all answers for this option ID
404 $sql = "SELECT ca.*
405 FROM {choice_answers} ca
406 WHERE optionid $insql";
409 $answers = $DB->get_records_sql($sql, $params);
410 if ($answers) {
411 foreach ($answers as $a) { //only return enrolled users.
412 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
413 $countanswers[$a->optionid]++;
418 foreach ($countanswers as $opt => $count) {
419 // Ignore the user's existing answers when checking whether an answer count has been exceeded.
420 // A user may wish to update their response with an additional choice option and shouldn't be competing with themself!
421 if (in_array($opt, $existinganswers)) {
422 continue;
424 if ($count >= $choice->maxanswers[$opt]) {
425 $choicesexceeded = true;
426 break;
431 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
432 $answersnapshots = array();
433 $deletedanswersnapshots = array();
434 if (!($choice->limitanswers && $choicesexceeded)) {
435 if ($current) {
436 // Update an existing answer.
437 foreach ($current as $c) {
438 if (in_array($c->optionid, $formanswers)) {
439 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
440 } else {
441 $deletedanswersnapshots[] = $c;
442 $DB->delete_records('choice_answers', array('id' => $c->id));
446 // Add new ones.
447 foreach ($formanswers as $f) {
448 if (!in_array($f, $existinganswers)) {
449 $newanswer = new stdClass();
450 $newanswer->optionid = $f;
451 $newanswer->choiceid = $choice->id;
452 $newanswer->userid = $userid;
453 $newanswer->timemodified = time();
454 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
455 $answersnapshots[] = $newanswer;
458 } else {
459 // Add new answer.
460 foreach ($formanswers as $answer) {
461 $newanswer = new stdClass();
462 $newanswer->choiceid = $choice->id;
463 $newanswer->userid = $userid;
464 $newanswer->optionid = $answer;
465 $newanswer->timemodified = time();
466 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
467 $answersnapshots[] = $newanswer;
470 // Update completion state
471 $completion = new completion_info($course);
472 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
473 $completion->update_state($cm, COMPLETION_COMPLETE);
476 } else {
477 // This is a choice with limited options, and one of the options selected has just run over its limit.
478 $choicelock->release();
479 throw new \moodle_exception('choicefull', 'choice', $continueurl);
482 // Release lock.
483 if (isset($choicelock)) {
484 $choicelock->release();
487 // Trigger events.
488 foreach ($deletedanswersnapshots as $answer) {
489 \mod_choice\event\answer_deleted::create_from_object($answer, $choice, $cm, $course)->trigger();
491 foreach ($answersnapshots as $answer) {
492 \mod_choice\event\answer_created::create_from_object($answer, $choice, $cm, $course)->trigger();
497 * @param array $user
498 * @param object $cm
499 * @return void Output is echo'd
501 function choice_show_reportlink($user, $cm) {
502 $userschosen = array();
503 foreach($user as $optionid => $userlist) {
504 if ($optionid) {
505 $userschosen = array_merge($userschosen, array_keys($userlist));
508 $responsecount = count(array_unique($userschosen));
510 echo '<div class="reportlink">';
511 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
512 echo '</div>';
516 * @global object
517 * @param object $choice
518 * @param object $course
519 * @param object $coursemodule
520 * @param array $allresponses
522 * * @param bool $allresponses
523 * @return object
525 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
526 global $OUTPUT;
528 $display = clone($choice);
529 $display->coursemoduleid = $cm->id;
530 $display->courseid = $course->id;
532 if (!empty($choice->showunanswered)) {
533 $choice->option[0] = get_string('notanswered', 'choice');
534 $choice->maxanswers[0] = 0;
537 // Remove from the list of non-respondents the users who do not have access to this activity.
538 if (!empty($display->showunanswered) && $allresponses[0]) {
539 $info = new \core_availability\info_module(cm_info::create($cm));
540 $allresponses[0] = $info->filter_user_list($allresponses[0]);
543 //overwrite options value;
544 $display->options = array();
545 $allusers = [];
546 foreach ($choice->option as $optionid => $optiontext) {
547 $display->options[$optionid] = new stdClass;
548 $display->options[$optionid]->text = format_string($optiontext, true,
549 ['context' => context_module::instance($cm->id)]);
550 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
552 if (array_key_exists($optionid, $allresponses)) {
553 $display->options[$optionid]->user = $allresponses[$optionid];
554 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
557 unset($display->option);
558 unset($display->maxanswers);
560 $display->numberofuser = count(array_unique($allusers));
561 $context = context_module::instance($cm->id);
562 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
563 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
564 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
566 if (empty($allresponses)) {
567 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
568 return false;
571 return $display;
575 * @global object
576 * @param array $attemptids
577 * @param object $choice Choice main table row
578 * @param object $cm Course-module object
579 * @param object $course Course object
580 * @return bool
582 function choice_delete_responses($attemptids, $choice, $cm, $course) {
583 global $DB, $CFG, $USER;
584 require_once($CFG->libdir.'/completionlib.php');
586 if(!is_array($attemptids) || empty($attemptids)) {
587 return false;
590 foreach($attemptids as $num => $attemptid) {
591 if(empty($attemptid)) {
592 unset($attemptids[$num]);
596 $completion = new completion_info($course);
597 foreach($attemptids as $attemptid) {
598 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
599 // Trigger the event answer deleted.
600 \mod_choice\event\answer_deleted::create_from_object($todelete, $choice, $cm, $course)->trigger();
601 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
605 // Update completion state.
606 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
607 $completion->update_state($cm, COMPLETION_INCOMPLETE);
610 return true;
615 * Given an ID of an instance of this module,
616 * this function will permanently delete the instance
617 * and any data that depends on it.
619 * @global object
620 * @param int $id
621 * @return bool
623 function choice_delete_instance($id) {
624 global $DB;
626 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
627 return false;
630 $result = true;
632 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
633 $result = false;
636 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
637 $result = false;
640 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
641 $result = false;
643 // Remove old calendar events.
644 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
645 $result = false;
648 return $result;
652 * Returns text string which is the answer that matches the id
654 * @global object
655 * @param object $choice
656 * @param int $id
657 * @return string
659 function choice_get_option_text($choice, $id) {
660 global $DB;
662 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
663 return $result->text;
664 } else {
665 return get_string("notanswered", "choice");
670 * Gets a full choice record
672 * @global object
673 * @param int $choiceid
674 * @return object|bool The choice or false
676 function choice_get_choice($choiceid) {
677 global $DB;
679 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
680 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
681 foreach ($options as $option) {
682 $choice->option[$option->id] = $option->text;
683 $choice->maxanswers[$option->id] = $option->maxanswers;
685 return $choice;
688 return false;
692 * List the actions that correspond to a view of this module.
693 * This is used by the participation report.
695 * Note: This is not used by new logging system. Event with
696 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
697 * be considered as view action.
699 * @return array
701 function choice_get_view_actions() {
702 return array('view','view all','report');
706 * List the actions that correspond to a post of this module.
707 * This is used by the participation report.
709 * Note: This is not used by new logging system. Event with
710 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
711 * will be considered as post action.
713 * @return array
715 function choice_get_post_actions() {
716 return array('choose','choose again');
721 * Implementation of the function for printing the form elements that control
722 * whether the course reset functionality affects the choice.
724 * @param MoodleQuickForm $mform form passed by reference
726 function choice_reset_course_form_definition(&$mform) {
727 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
728 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
732 * Course reset form defaults.
734 * @return array
736 function choice_reset_course_form_defaults($course) {
737 return array('reset_choice'=>1);
741 * Actual implementation of the reset course functionality, delete all the
742 * choice responses for course $data->courseid.
744 * @global object
745 * @global object
746 * @param object $data the data submitted from the reset course.
747 * @return array status array
749 function choice_reset_userdata($data) {
750 global $CFG, $DB;
752 $componentstr = get_string('modulenameplural', 'choice');
753 $status = array();
755 if (!empty($data->reset_choice)) {
756 $choicessql = "SELECT ch.id
757 FROM {choice} ch
758 WHERE ch.course=?";
760 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
761 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
764 /// updating dates - shift may be negative too
765 if ($data->timeshift) {
766 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
767 // See MDL-9367.
768 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
769 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
772 return $status;
776 * @global object
777 * @global object
778 * @global object
779 * @uses CONTEXT_MODULE
780 * @param object $choice
781 * @param object $cm
782 * @param int $groupmode
783 * @param bool $onlyactive Whether to get response data for active users only.
784 * @return array
786 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
787 global $CFG, $USER, $DB;
789 $context = context_module::instance($cm->id);
791 /// Get the current group
792 if ($groupmode > 0) {
793 $currentgroup = groups_get_activity_group($cm);
794 } else {
795 $currentgroup = 0;
798 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
799 $allresponses = array();
801 /// First get all the users who have access here
802 /// To start with we assume they are all "unanswered" then move them later
803 // TODO Does not support custom user profile fields (MDL-70456).
804 $userfieldsapi = \core_user\fields::for_identity($context, false)->with_userpic();
805 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
806 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
807 $userfields, null, 0, 0, $onlyactive);
809 /// Get all the recorded responses for this choice
810 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
812 /// Use the responses to move users into the correct column
814 if ($rawresponses) {
815 $answeredusers = array();
816 foreach ($rawresponses as $response) {
817 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
818 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
819 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
820 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
821 $answeredusers[] = $response->userid;
824 foreach ($answeredusers as $answereduser) {
825 unset($allresponses[0][$answereduser]);
828 return $allresponses;
832 * @uses FEATURE_GROUPS
833 * @uses FEATURE_GROUPINGS
834 * @uses FEATURE_MOD_INTRO
835 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
836 * @uses FEATURE_GRADE_HAS_GRADE
837 * @uses FEATURE_GRADE_OUTCOMES
838 * @param string $feature FEATURE_xx constant for requested feature
839 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
841 function choice_supports($feature) {
842 switch($feature) {
843 case FEATURE_GROUPS: return true;
844 case FEATURE_GROUPINGS: return true;
845 case FEATURE_MOD_INTRO: return true;
846 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
847 case FEATURE_COMPLETION_HAS_RULES: return true;
848 case FEATURE_GRADE_HAS_GRADE: return false;
849 case FEATURE_GRADE_OUTCOMES: return false;
850 case FEATURE_BACKUP_MOODLE2: return true;
851 case FEATURE_SHOW_DESCRIPTION: return true;
852 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_COMMUNICATION;
854 default: return null;
859 * Adds module specific settings to the settings block
861 * @param settings_navigation $settings The settings navigation object
862 * @param navigation_node $choicenode The node to add module settings to
864 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
865 if (has_capability('mod/choice:readresponses', $settings->get_page()->cm->context)) {
866 $choicenode->add(get_string('responses', 'choice'),
867 new moodle_url('/mod/choice/report.php', array('id' => $settings->get_page()->cm->id)));
872 * Return a list of page types
873 * @param string $pagetype current page type
874 * @param stdClass $parentcontext Block's parent context
875 * @param stdClass $currentcontext Current context of block
877 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
878 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
879 return $module_pagetype;
883 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
885 function choice_print_overview() {
886 throw new coding_exception('choice_print_overview() can not be used any more and is obsolete.');
891 * Get responses of a given user on a given choice.
893 * @param stdClass $choice Choice record
894 * @param int $userid User id
895 * @return array of choice answers records
896 * @since Moodle 3.6
898 function choice_get_user_response($choice, $userid) {
899 global $DB;
900 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
904 * Get my responses on a given choice.
906 * @param stdClass $choice Choice record
907 * @return array of choice answers records
908 * @since Moodle 3.0
910 function choice_get_my_response($choice) {
911 global $USER;
912 return choice_get_user_response($choice, $USER->id);
917 * Get all the responses on a given choice.
919 * @param stdClass $choice Choice record
920 * @return array of choice answers records
921 * @since Moodle 3.0
923 function choice_get_all_responses($choice) {
924 global $DB;
925 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
930 * Return true if we are allowd to view the choice results.
932 * @param stdClass $choice Choice record
933 * @param rows|null $current my choice responses
934 * @param bool|null $choiceopen if the choice is open
935 * @return bool true if we can view the results, false otherwise.
936 * @since Moodle 3.0
938 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
940 if (is_null($choiceopen)) {
941 $timenow = time();
943 if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
944 // If the choice is not available, we can't see the results.
945 return false;
948 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
949 $choiceopen = false;
950 } else {
951 $choiceopen = true;
954 if (empty($current)) {
955 $current = choice_get_my_response($choice);
958 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
959 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
960 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
961 return true;
963 return false;
967 * Mark the activity completed (if required) and trigger the course_module_viewed event.
969 * @param stdClass $choice choice object
970 * @param stdClass $course course object
971 * @param stdClass $cm course module object
972 * @param stdClass $context context object
973 * @since Moodle 3.0
975 function choice_view($choice, $course, $cm, $context) {
977 // Trigger course_module_viewed event.
978 $params = array(
979 'context' => $context,
980 'objectid' => $choice->id
983 $event = \mod_choice\event\course_module_viewed::create($params);
984 $event->add_record_snapshot('course_modules', $cm);
985 $event->add_record_snapshot('course', $course);
986 $event->add_record_snapshot('choice', $choice);
987 $event->trigger();
989 // Completion.
990 $completion = new completion_info($course);
991 $completion->set_module_viewed($cm);
995 * Check if a choice is available for the current user.
997 * @param stdClass $choice choice record
998 * @return array status (available or not and possible warnings)
1000 function choice_get_availability_status($choice) {
1001 $available = true;
1002 $warnings = array();
1004 $timenow = time();
1006 if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
1007 $available = false;
1008 $warnings['notopenyet'] = userdate($choice->timeopen);
1009 } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
1010 $available = false;
1011 $warnings['expired'] = userdate($choice->timeclose);
1013 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1014 $available = false;
1015 $warnings['choicesaved'] = '';
1018 // Choice is available.
1019 return array($available, $warnings);
1023 * This standard function will check all instances of this module
1024 * and make sure there are up-to-date events created for each of them.
1025 * If courseid = 0, then every choice event in the site is checked, else
1026 * only choice events belonging to the course specified are checked.
1027 * This function is used, in its new format, by restore_refresh_events()
1029 * @param int $courseid
1030 * @param int|stdClass $instance Choice module instance or ID.
1031 * @param int|stdClass $cm Course module object or ID (not used in this module).
1032 * @return bool
1034 function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
1035 global $DB, $CFG;
1036 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1038 // If we have instance information then we can just update the one event instead of updating all events.
1039 if (isset($instance)) {
1040 if (!is_object($instance)) {
1041 $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST);
1043 choice_set_events($instance);
1044 return true;
1047 if ($courseid) {
1048 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1049 return true;
1051 } else {
1052 if (! $choices = $DB->get_records("choice")) {
1053 return true;
1057 foreach ($choices as $choice) {
1058 choice_set_events($choice);
1060 return true;
1064 * Check if the module has any update that affects the current user since a given time.
1066 * @param cm_info $cm course module data
1067 * @param int $from the time to check updates from
1068 * @param array $filter if we need to check only specific updates
1069 * @return stdClass an object with the different type of areas indicating if they were updated or not
1070 * @since Moodle 3.2
1072 function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
1073 global $DB;
1075 $updates = new stdClass();
1076 $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1077 list($available, $warnings) = choice_get_availability_status($choice);
1078 if (!$available) {
1079 return $updates;
1082 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1084 if (!choice_can_view_results($choice)) {
1085 return $updates;
1087 // Check if there are new responses in the choice.
1088 $updates->answers = (object) array('updated' => false);
1089 $select = 'choiceid = :id AND timemodified > :since';
1090 $params = array('id' => $choice->id, 'since' => $from);
1091 $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1092 if (!empty($answers)) {
1093 $updates->answers->updated = true;
1094 $updates->answers->itemids = array_keys($answers);
1097 return $updates;
1101 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1103 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1104 * is not displayed on the block.
1106 * @param calendar_event $event
1107 * @param \core_calendar\action_factory $factory
1108 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1109 * @return \core_calendar\local\event\entities\action_interface|null
1111 function mod_choice_core_calendar_provide_event_action(calendar_event $event,
1112 \core_calendar\action_factory $factory,
1113 int $userid = 0) {
1114 global $USER;
1116 if (!$userid) {
1117 $userid = $USER->id;
1120 $cm = get_fast_modinfo($event->courseid, $userid)->instances['choice'][$event->instance];
1122 if (!$cm->uservisible) {
1123 // The module is not visible to the user for any reason.
1124 return null;
1127 $completion = new \completion_info($cm->get_course());
1129 $completiondata = $completion->get_data($cm, false, $userid);
1131 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1132 return null;
1135 $now = time();
1137 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < $now) {
1138 // The choice has closed so the user can no longer submit anything.
1139 return null;
1142 // The choice is actionable if we don't have a start time or the start time is
1143 // in the past.
1144 $actionable = (empty($cm->customdata['timeopen']) || $cm->customdata['timeopen'] <= $now);
1146 if ($actionable && choice_get_user_response((object)['id' => $event->instance], $userid)) {
1147 // There is no action if the user has already submitted their choice.
1148 return null;
1151 return $factory->create_instance(
1152 get_string('viewchoices', 'choice'),
1153 new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
1155 $actionable
1160 * This function calculates the minimum and maximum cutoff values for the timestart of
1161 * the given event.
1163 * It will return an array with two values, the first being the minimum cutoff value and
1164 * the second being the maximum cutoff value. Either or both values can be null, which
1165 * indicates there is no minimum or maximum, respectively.
1167 * If a cutoff is required then the function must return an array containing the cutoff
1168 * timestamp and error string to display to the user if the cutoff value is violated.
1170 * A minimum and maximum cutoff return value will look like:
1172 * [1505704373, 'The date must be after this date'],
1173 * [1506741172, 'The date must be before this date']
1176 * @param calendar_event $event The calendar event to get the time range for
1177 * @param stdClass $choice The module instance to get the range from
1179 function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $choice) {
1180 $mindate = null;
1181 $maxdate = null;
1183 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1184 if (!empty($choice->timeclose)) {
1185 $maxdate = [
1186 $choice->timeclose,
1187 get_string('openafterclose', 'choice')
1190 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1191 if (!empty($choice->timeopen)) {
1192 $mindate = [
1193 $choice->timeopen,
1194 get_string('closebeforeopen', 'choice')
1199 return [$mindate, $maxdate];
1203 * This function will update the choice module according to the
1204 * event that has been modified.
1206 * It will set the timeopen or timeclose value of the choice instance
1207 * according to the type of event provided.
1209 * @throws \moodle_exception
1210 * @param \calendar_event $event
1211 * @param stdClass $choice The module instance to get the range from
1213 function mod_choice_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $choice) {
1214 global $DB;
1216 if (!in_array($event->eventtype, [CHOICE_EVENT_TYPE_OPEN, CHOICE_EVENT_TYPE_CLOSE])) {
1217 return;
1220 $courseid = $event->courseid;
1221 $modulename = $event->modulename;
1222 $instanceid = $event->instance;
1223 $modified = false;
1225 // Something weird going on. The event is for a different module so
1226 // we should ignore it.
1227 if ($modulename != 'choice') {
1228 return;
1231 if ($choice->id != $instanceid) {
1232 return;
1235 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1236 $context = context_module::instance($coursemodule->id);
1238 // The user does not have the capability to modify this activity.
1239 if (!has_capability('moodle/course:manageactivities', $context)) {
1240 return;
1243 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1244 // If the event is for the choice activity opening then we should
1245 // set the start time of the choice activity to be the new start
1246 // time of the event.
1247 if ($choice->timeopen != $event->timestart) {
1248 $choice->timeopen = $event->timestart;
1249 $modified = true;
1251 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1252 // If the event is for the choice activity closing then we should
1253 // set the end time of the choice activity to be the new start
1254 // time of the event.
1255 if ($choice->timeclose != $event->timestart) {
1256 $choice->timeclose = $event->timestart;
1257 $modified = true;
1261 if ($modified) {
1262 $choice->timemodified = time();
1263 // Persist the instance changes.
1264 $DB->update_record('choice', $choice);
1265 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1266 $event->trigger();
1271 * Get icon mapping for font-awesome.
1273 function mod_choice_get_fontawesome_icon_map() {
1274 return [
1275 'mod_choice:row' => 'fa-info',
1276 'mod_choice:column' => 'fa-columns',
1281 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1282 * for the course (see resource).
1284 * Given a course_module object, this function returns any "extra" information that may be needed
1285 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1287 * @param stdClass $coursemodule The coursemodule object (record).
1288 * @return cached_cm_info An object on information that the courses
1289 * will know about (most noticeably, an icon).
1291 function choice_get_coursemodule_info($coursemodule) {
1292 global $DB;
1294 $dbparams = ['id' => $coursemodule->instance];
1295 $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
1296 if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1297 return false;
1300 $result = new cached_cm_info();
1301 $result->name = $choice->name;
1303 if ($coursemodule->showdescription) {
1304 // Convert intro to html. Do not filter cached version, filters run at display time.
1305 $result->content = format_module_intro('choice', $choice, $coursemodule->id, false);
1308 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1309 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1310 $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
1312 // Populate some other values that can be used in calendar or on dashboard.
1313 if ($choice->timeopen) {
1314 $result->customdata['timeopen'] = $choice->timeopen;
1316 if ($choice->timeclose) {
1317 $result->customdata['timeclose'] = $choice->timeclose;
1320 return $result;
1324 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1326 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1327 * @return array $descriptions the array of descriptions for the custom rules.
1329 function mod_choice_get_completion_active_rule_descriptions($cm) {
1330 // Values will be present in cm_info, and we assume these are up to date.
1331 if (empty($cm->customdata['customcompletionrules'])
1332 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1333 return [];
1336 $descriptions = [];
1337 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1338 switch ($key) {
1339 case 'completionsubmit':
1340 if (!empty($val)) {
1341 $descriptions[] = get_string('completionsubmit', 'choice');
1343 break;
1344 default:
1345 break;
1348 return $descriptions;
1352 * Callback to fetch the activity event type lang string.
1354 * @param string $eventtype The event type.
1355 * @return lang_string The event type lang string.
1357 function mod_choice_core_calendar_get_event_action_string(string $eventtype): string {
1358 $modulename = get_string('modulename', 'choice');
1360 switch ($eventtype) {
1361 case CHOICE_EVENT_TYPE_OPEN:
1362 $identifier = 'calendarstart';
1363 break;
1364 case CHOICE_EVENT_TYPE_CLOSE:
1365 $identifier = 'calendarend';
1366 break;
1367 default:
1368 return get_string('requiresaction', 'calendar', $modulename);
1371 return get_string($identifier, 'choice', $modulename);