MDL-71144 mod_choice: Deprecate choice_get_completion_state()
[moodle.git] / mod / choice / lib.php
blob98584b7e117ae1f3c8d43f71aec28b4c54531398
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 print_error('atleastoneoption', 'choice', $continueurl);
336 if (is_array($formanswer)) {
337 if (!$choice->allowmultiple) {
338 print_error('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 print_error('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 print_error('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 print_error('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 object $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, null if doesn't know
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;
853 default: return null;
858 * Adds module specific settings to the settings block
860 * @param settings_navigation $settings The settings navigation object
861 * @param navigation_node $choicenode The node to add module settings to
863 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
864 global $PAGE;
866 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
868 $groupmode = groups_get_activity_groupmode($PAGE->cm);
869 if ($groupmode) {
870 groups_get_activity_group($PAGE->cm, true);
873 $choice = choice_get_choice($PAGE->cm->instance);
875 // Check if we want to include responses from inactive users.
876 $onlyactive = $choice->includeinactive ? false : true;
878 // Big function, approx 6 SQL calls per user.
879 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
881 $allusers = [];
882 foreach($allresponses as $optionid => $userlist) {
883 if ($optionid) {
884 $allusers = array_merge($allusers, array_keys($userlist));
887 $responsecount = count(array_unique($allusers));
888 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
893 * Return a list of page types
894 * @param string $pagetype current page type
895 * @param stdClass $parentcontext Block's parent context
896 * @param stdClass $currentcontext Current context of block
898 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
899 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
900 return $module_pagetype;
904 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
906 function choice_print_overview() {
907 throw new coding_exception('choice_print_overview() can not be used any more and is obsolete.');
912 * Get responses of a given user on a given choice.
914 * @param stdClass $choice Choice record
915 * @param int $userid User id
916 * @return array of choice answers records
917 * @since Moodle 3.6
919 function choice_get_user_response($choice, $userid) {
920 global $DB;
921 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
925 * Get my responses on a given choice.
927 * @param stdClass $choice Choice record
928 * @return array of choice answers records
929 * @since Moodle 3.0
931 function choice_get_my_response($choice) {
932 global $USER;
933 return choice_get_user_response($choice, $USER->id);
938 * Get all the responses on a given choice.
940 * @param stdClass $choice Choice record
941 * @return array of choice answers records
942 * @since Moodle 3.0
944 function choice_get_all_responses($choice) {
945 global $DB;
946 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
951 * Return true if we are allowd to view the choice results.
953 * @param stdClass $choice Choice record
954 * @param rows|null $current my choice responses
955 * @param bool|null $choiceopen if the choice is open
956 * @return bool true if we can view the results, false otherwise.
957 * @since Moodle 3.0
959 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
961 if (is_null($choiceopen)) {
962 $timenow = time();
964 if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
965 // If the choice is not available, we can't see the results.
966 return false;
969 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
970 $choiceopen = false;
971 } else {
972 $choiceopen = true;
975 if (empty($current)) {
976 $current = choice_get_my_response($choice);
979 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
980 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
981 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
982 return true;
984 return false;
988 * Mark the activity completed (if required) and trigger the course_module_viewed event.
990 * @param stdClass $choice choice object
991 * @param stdClass $course course object
992 * @param stdClass $cm course module object
993 * @param stdClass $context context object
994 * @since Moodle 3.0
996 function choice_view($choice, $course, $cm, $context) {
998 // Trigger course_module_viewed event.
999 $params = array(
1000 'context' => $context,
1001 'objectid' => $choice->id
1004 $event = \mod_choice\event\course_module_viewed::create($params);
1005 $event->add_record_snapshot('course_modules', $cm);
1006 $event->add_record_snapshot('course', $course);
1007 $event->add_record_snapshot('choice', $choice);
1008 $event->trigger();
1010 // Completion.
1011 $completion = new completion_info($course);
1012 $completion->set_module_viewed($cm);
1016 * Check if a choice is available for the current user.
1018 * @param stdClass $choice choice record
1019 * @return array status (available or not and possible warnings)
1021 function choice_get_availability_status($choice) {
1022 $available = true;
1023 $warnings = array();
1025 $timenow = time();
1027 if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
1028 $available = false;
1029 $warnings['notopenyet'] = userdate($choice->timeopen);
1030 } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
1031 $available = false;
1032 $warnings['expired'] = userdate($choice->timeclose);
1034 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1035 $available = false;
1036 $warnings['choicesaved'] = '';
1039 // Choice is available.
1040 return array($available, $warnings);
1044 * This standard function will check all instances of this module
1045 * and make sure there are up-to-date events created for each of them.
1046 * If courseid = 0, then every choice event in the site is checked, else
1047 * only choice events belonging to the course specified are checked.
1048 * This function is used, in its new format, by restore_refresh_events()
1050 * @param int $courseid
1051 * @param int|stdClass $instance Choice module instance or ID.
1052 * @param int|stdClass $cm Course module object or ID (not used in this module).
1053 * @return bool
1055 function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
1056 global $DB, $CFG;
1057 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1059 // If we have instance information then we can just update the one event instead of updating all events.
1060 if (isset($instance)) {
1061 if (!is_object($instance)) {
1062 $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST);
1064 choice_set_events($instance);
1065 return true;
1068 if ($courseid) {
1069 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1070 return true;
1072 } else {
1073 if (! $choices = $DB->get_records("choice")) {
1074 return true;
1078 foreach ($choices as $choice) {
1079 choice_set_events($choice);
1081 return true;
1085 * Check if the module has any update that affects the current user since a given time.
1087 * @param cm_info $cm course module data
1088 * @param int $from the time to check updates from
1089 * @param array $filter if we need to check only specific updates
1090 * @return stdClass an object with the different type of areas indicating if they were updated or not
1091 * @since Moodle 3.2
1093 function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
1094 global $DB;
1096 $updates = new stdClass();
1097 $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1098 list($available, $warnings) = choice_get_availability_status($choice);
1099 if (!$available) {
1100 return $updates;
1103 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1105 if (!choice_can_view_results($choice)) {
1106 return $updates;
1108 // Check if there are new responses in the choice.
1109 $updates->answers = (object) array('updated' => false);
1110 $select = 'choiceid = :id AND timemodified > :since';
1111 $params = array('id' => $choice->id, 'since' => $from);
1112 $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1113 if (!empty($answers)) {
1114 $updates->answers->updated = true;
1115 $updates->answers->itemids = array_keys($answers);
1118 return $updates;
1122 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1124 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1125 * is not displayed on the block.
1127 * @param calendar_event $event
1128 * @param \core_calendar\action_factory $factory
1129 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1130 * @return \core_calendar\local\event\entities\action_interface|null
1132 function mod_choice_core_calendar_provide_event_action(calendar_event $event,
1133 \core_calendar\action_factory $factory,
1134 int $userid = 0) {
1135 global $USER;
1137 if (!$userid) {
1138 $userid = $USER->id;
1141 $cm = get_fast_modinfo($event->courseid, $userid)->instances['choice'][$event->instance];
1143 if (!$cm->uservisible) {
1144 // The module is not visible to the user for any reason.
1145 return null;
1148 $completion = new \completion_info($cm->get_course());
1150 $completiondata = $completion->get_data($cm, false, $userid);
1152 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1153 return null;
1156 $now = time();
1158 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < $now) {
1159 // The choice has closed so the user can no longer submit anything.
1160 return null;
1163 // The choice is actionable if we don't have a start time or the start time is
1164 // in the past.
1165 $actionable = (empty($cm->customdata['timeopen']) || $cm->customdata['timeopen'] <= $now);
1167 if ($actionable && choice_get_user_response((object)['id' => $event->instance], $userid)) {
1168 // There is no action if the user has already submitted their choice.
1169 return null;
1172 return $factory->create_instance(
1173 get_string('viewchoices', 'choice'),
1174 new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
1176 $actionable
1181 * This function calculates the minimum and maximum cutoff values for the timestart of
1182 * the given event.
1184 * It will return an array with two values, the first being the minimum cutoff value and
1185 * the second being the maximum cutoff value. Either or both values can be null, which
1186 * indicates there is no minimum or maximum, respectively.
1188 * If a cutoff is required then the function must return an array containing the cutoff
1189 * timestamp and error string to display to the user if the cutoff value is violated.
1191 * A minimum and maximum cutoff return value will look like:
1193 * [1505704373, 'The date must be after this date'],
1194 * [1506741172, 'The date must be before this date']
1197 * @param calendar_event $event The calendar event to get the time range for
1198 * @param stdClass $choice The module instance to get the range from
1200 function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $choice) {
1201 $mindate = null;
1202 $maxdate = null;
1204 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1205 if (!empty($choice->timeclose)) {
1206 $maxdate = [
1207 $choice->timeclose,
1208 get_string('openafterclose', 'choice')
1211 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1212 if (!empty($choice->timeopen)) {
1213 $mindate = [
1214 $choice->timeopen,
1215 get_string('closebeforeopen', 'choice')
1220 return [$mindate, $maxdate];
1224 * This function will update the choice module according to the
1225 * event that has been modified.
1227 * It will set the timeopen or timeclose value of the choice instance
1228 * according to the type of event provided.
1230 * @throws \moodle_exception
1231 * @param \calendar_event $event
1232 * @param stdClass $choice The module instance to get the range from
1234 function mod_choice_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $choice) {
1235 global $DB;
1237 if (!in_array($event->eventtype, [CHOICE_EVENT_TYPE_OPEN, CHOICE_EVENT_TYPE_CLOSE])) {
1238 return;
1241 $courseid = $event->courseid;
1242 $modulename = $event->modulename;
1243 $instanceid = $event->instance;
1244 $modified = false;
1246 // Something weird going on. The event is for a different module so
1247 // we should ignore it.
1248 if ($modulename != 'choice') {
1249 return;
1252 if ($choice->id != $instanceid) {
1253 return;
1256 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1257 $context = context_module::instance($coursemodule->id);
1259 // The user does not have the capability to modify this activity.
1260 if (!has_capability('moodle/course:manageactivities', $context)) {
1261 return;
1264 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1265 // If the event is for the choice activity opening then we should
1266 // set the start time of the choice activity to be the new start
1267 // time of the event.
1268 if ($choice->timeopen != $event->timestart) {
1269 $choice->timeopen = $event->timestart;
1270 $modified = true;
1272 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1273 // If the event is for the choice activity closing then we should
1274 // set the end time of the choice activity to be the new start
1275 // time of the event.
1276 if ($choice->timeclose != $event->timestart) {
1277 $choice->timeclose = $event->timestart;
1278 $modified = true;
1282 if ($modified) {
1283 $choice->timemodified = time();
1284 // Persist the instance changes.
1285 $DB->update_record('choice', $choice);
1286 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1287 $event->trigger();
1292 * Get icon mapping for font-awesome.
1294 function mod_choice_get_fontawesome_icon_map() {
1295 return [
1296 'mod_choice:row' => 'fa-info',
1297 'mod_choice:column' => 'fa-columns',
1302 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1303 * for the course (see resource).
1305 * Given a course_module object, this function returns any "extra" information that may be needed
1306 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1308 * @param stdClass $coursemodule The coursemodule object (record).
1309 * @return cached_cm_info An object on information that the courses
1310 * will know about (most noticeably, an icon).
1312 function choice_get_coursemodule_info($coursemodule) {
1313 global $DB;
1315 $dbparams = ['id' => $coursemodule->instance];
1316 $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
1317 if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1318 return false;
1321 $result = new cached_cm_info();
1322 $result->name = $choice->name;
1324 if ($coursemodule->showdescription) {
1325 // Convert intro to html. Do not filter cached version, filters run at display time.
1326 $result->content = format_module_intro('choice', $choice, $coursemodule->id, false);
1329 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1330 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1331 $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
1333 // Populate some other values that can be used in calendar or on dashboard.
1334 if ($choice->timeopen) {
1335 $result->customdata['timeopen'] = $choice->timeopen;
1337 if ($choice->timeclose) {
1338 $result->customdata['timeclose'] = $choice->timeclose;
1341 return $result;
1345 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1347 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1348 * @return array $descriptions the array of descriptions for the custom rules.
1350 function mod_choice_get_completion_active_rule_descriptions($cm) {
1351 // Values will be present in cm_info, and we assume these are up to date.
1352 if (empty($cm->customdata['customcompletionrules'])
1353 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1354 return [];
1357 $descriptions = [];
1358 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1359 switch ($key) {
1360 case 'completionsubmit':
1361 if (!empty($val)) {
1362 $descriptions[] = get_string('completionsubmit', 'choice');
1364 break;
1365 default:
1366 break;
1369 return $descriptions;