Merge branch 'MDL-62560-master'
[moodle.git] / mod / choice / lib.php
blob3256a8c1f978d9d499d8ccb7cb4bc71499e65cd0
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 /// Standard functions /////////////////////////////////////////////////////////
67 /**
68 * @global object
69 * @param object $course
70 * @param object $user
71 * @param object $mod
72 * @param object $choice
73 * @return object|null
75 function choice_user_outline($course, $user, $mod, $choice) {
76 global $DB;
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;
81 return $result;
83 return NULL;
86 /**
87 * Callback for the "Complete" report - prints the activity summary for the given user
89 * @param object $course
90 * @param object $user
91 * @param object $mod
92 * @param object $choice
94 function choice_user_complete($course, $user, $mod, $choice) {
95 global $DB;
96 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
97 $info = [];
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));
104 } else {
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.
115 * @global object
116 * @param object $choice
117 * @return int
119 function choice_add_instance($choice) {
120 global $DB, $CFG;
121 require_once($CFG->dirroot.'/mod/choice/locallib.php');
123 $choice->timemodified = time();
125 //insert answers
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);
143 if (!empty($choice->completionexpected)) {
144 \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id,
145 $choice->completionexpected);
148 return $choice->id;
152 * Given an object containing all the necessary data,
153 * (defined by the form in mod_form.php) this function
154 * will update an existing instance with new data.
156 * @global object
157 * @param object $choice
158 * @return bool
160 function choice_update_instance($choice) {
161 global $DB, $CFG;
162 require_once($CFG->dirroot.'/mod/choice/locallib.php');
164 $choice->id = $choice->instance;
165 $choice->timemodified = time();
167 //update, delete or insert answers
168 foreach ($choice->option as $key => $value) {
169 $value = trim($value);
170 $option = new stdClass();
171 $option->text = $value;
172 $option->choiceid = $choice->id;
173 if (isset($choice->limit[$key])) {
174 $option->maxanswers = $choice->limit[$key];
176 $option->timemodified = time();
177 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
178 $option->id=$choice->optionid[$key];
179 if (isset($value) && $value <> '') {
180 $DB->update_record("choice_options", $option);
181 } else {
182 // Remove the empty (unused) option.
183 $DB->delete_records("choice_options", array("id" => $option->id));
184 // Delete any answers associated with this option.
185 $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
187 } else {
188 if (isset($value) && $value <> '') {
189 $DB->insert_record("choice_options", $option);
194 // Add calendar events if necessary.
195 choice_set_events($choice);
196 $completionexpected = (!empty($choice->completionexpected)) ? $choice->completionexpected : null;
197 \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id, $completionexpected);
199 return $DB->update_record('choice', $choice);
204 * @global object
205 * @param object $choice
206 * @param object $user
207 * @param object $coursemodule
208 * @param array $allresponses
209 * @return array
211 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
212 global $DB;
214 $cdisplay = array('options'=>array());
216 $cdisplay['limitanswers'] = true;
217 $context = context_module::instance($coursemodule->id);
219 foreach ($choice->option as $optionid => $text) {
220 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
221 $option = new stdClass;
222 $option->attributes = new stdClass;
223 $option->attributes->value = $optionid;
224 $option->text = format_string($text);
225 $option->maxanswers = $choice->maxanswers[$optionid];
226 $option->displaylayout = $choice->display;
228 if (isset($allresponses[$optionid])) {
229 $option->countanswers = count($allresponses[$optionid]);
230 } else {
231 $option->countanswers = 0;
233 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
234 $option->attributes->checked = true;
236 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
237 $option->attributes->disabled = true;
239 $cdisplay['options'][] = $option;
243 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
245 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
246 $cdisplay['allowupdate'] = true;
249 if ($choice->showpreview && $choice->timeopen > time()) {
250 $cdisplay['previewonly'] = true;
253 return $cdisplay;
257 * Modifies responses of other users adding the option $newoptionid to them
259 * @param array $userids list of users to add option to (must be users without any answers yet)
260 * @param array $answerids list of existing attempt ids of users (will be either appended or
261 * substituted with the newoptionid, depending on $choice->allowmultiple)
262 * @param int $newoptionid
263 * @param stdClass $choice choice object, result of {@link choice_get_choice()}
264 * @param stdClass $cm
265 * @param stdClass $course
267 function choice_modify_responses($userids, $answerids, $newoptionid, $choice, $cm, $course) {
268 // Get all existing responses and the list of non-respondents.
269 $groupmode = groups_get_activity_groupmode($cm);
270 $onlyactive = $choice->includeinactive ? false : true;
271 $allresponses = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
273 // Check that the option value is valid.
274 if (!$newoptionid || !isset($choice->option[$newoptionid])) {
275 return;
278 // First add responses for users who did not make any choice yet.
279 foreach ($userids as $userid) {
280 if (isset($allresponses[0][$userid])) {
281 choice_user_submit_response($newoptionid, $choice, $userid, $course, $cm);
285 // Create the list of all options already selected by each user.
286 $optionsbyuser = []; // Mapping userid=>array of chosen choice options.
287 $usersbyanswer = []; // Mapping answerid=>userid (which answer belongs to each user).
288 foreach ($allresponses as $optionid => $responses) {
289 if ($optionid > 0) {
290 foreach ($responses as $userid => $userresponse) {
291 $optionsbyuser += [$userid => []];
292 $optionsbyuser[$userid][] = $optionid;
293 $usersbyanswer[$userresponse->answerid] = $userid;
298 // Go through the list of submitted attemptids and find which users answers need to be updated.
299 foreach ($answerids as $answerid) {
300 if (isset($usersbyanswer[$answerid])) {
301 $userid = $usersbyanswer[$answerid];
302 if (!in_array($newoptionid, $optionsbyuser[$userid])) {
303 $options = $choice->allowmultiple ?
304 array_merge($optionsbyuser[$userid], [$newoptionid]) : $newoptionid;
305 choice_user_submit_response($options, $choice, $userid, $course, $cm);
312 * Process user submitted answers for a choice,
313 * and either updating them or saving new answers.
315 * @param int|array $formanswer the id(s) of the user submitted choice options.
316 * @param object $choice the selected choice.
317 * @param int $userid user identifier.
318 * @param object $course current course.
319 * @param object $cm course context.
320 * @return void
322 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
323 global $DB, $CFG, $USER;
324 require_once($CFG->libdir.'/completionlib.php');
326 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
328 if (empty($formanswer)) {
329 print_error('atleastoneoption', 'choice', $continueurl);
332 if (is_array($formanswer)) {
333 if (!$choice->allowmultiple) {
334 print_error('multiplenotallowederror', 'choice', $continueurl);
336 $formanswers = $formanswer;
337 } else {
338 $formanswers = array($formanswer);
341 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
342 foreach ($formanswers as $key => $val) {
343 if (!isset($options[$val])) {
344 print_error('cannotsubmit', 'choice', $continueurl);
347 // Start lock to prevent synchronous access to the same data
348 // before it's updated, if using limits.
349 if ($choice->limitanswers) {
350 $timeout = 10;
351 $locktype = 'mod_choice_choice_user_submit_response';
352 // Limiting access to this choice.
353 $resouce = 'choiceid:' . $choice->id;
354 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
356 // Opening the lock.
357 $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS);
358 if (!$choicelock) {
359 print_error('cannotsubmit', 'choice', $continueurl);
363 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
365 // Array containing [answerid => optionid] mapping.
366 $existinganswers = array_map(function($answer) {
367 return $answer->optionid;
368 }, $current);
370 $context = context_module::instance($cm->id);
372 $choicesexceeded = false;
373 $countanswers = array();
374 foreach ($formanswers as $val) {
375 $countanswers[$val] = 0;
377 if($choice->limitanswers) {
378 // Find out whether groups are being used and enabled
379 if (groups_get_activity_groupmode($cm) > 0) {
380 $currentgroup = groups_get_activity_group($cm);
381 } else {
382 $currentgroup = 0;
385 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
387 if($currentgroup) {
388 // If groups are being used, retrieve responses only for users in
389 // current group
390 global $CFG;
392 $params['groupid'] = $currentgroup;
393 $sql = "SELECT ca.*
394 FROM {choice_answers} ca
395 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
396 WHERE optionid $insql
397 AND gm.groupid= :groupid";
398 } else {
399 // Groups are not used, retrieve all answers for this option ID
400 $sql = "SELECT ca.*
401 FROM {choice_answers} ca
402 WHERE optionid $insql";
405 $answers = $DB->get_records_sql($sql, $params);
406 if ($answers) {
407 foreach ($answers as $a) { //only return enrolled users.
408 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
409 $countanswers[$a->optionid]++;
414 foreach ($countanswers as $opt => $count) {
415 // Ignore the user's existing answers when checking whether an answer count has been exceeded.
416 // A user may wish to update their response with an additional choice option and shouldn't be competing with themself!
417 if (in_array($opt, $existinganswers)) {
418 continue;
420 if ($count >= $choice->maxanswers[$opt]) {
421 $choicesexceeded = true;
422 break;
427 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
428 $answersnapshots = array();
429 $deletedanswersnapshots = array();
430 if (!($choice->limitanswers && $choicesexceeded)) {
431 if ($current) {
432 // Update an existing answer.
433 foreach ($current as $c) {
434 if (in_array($c->optionid, $formanswers)) {
435 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
436 } else {
437 $deletedanswersnapshots[] = $c;
438 $DB->delete_records('choice_answers', array('id' => $c->id));
442 // Add new ones.
443 foreach ($formanswers as $f) {
444 if (!in_array($f, $existinganswers)) {
445 $newanswer = new stdClass();
446 $newanswer->optionid = $f;
447 $newanswer->choiceid = $choice->id;
448 $newanswer->userid = $userid;
449 $newanswer->timemodified = time();
450 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
451 $answersnapshots[] = $newanswer;
454 } else {
455 // Add new answer.
456 foreach ($formanswers as $answer) {
457 $newanswer = new stdClass();
458 $newanswer->choiceid = $choice->id;
459 $newanswer->userid = $userid;
460 $newanswer->optionid = $answer;
461 $newanswer->timemodified = time();
462 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
463 $answersnapshots[] = $newanswer;
466 // Update completion state
467 $completion = new completion_info($course);
468 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
469 $completion->update_state($cm, COMPLETION_COMPLETE);
472 } else {
473 // This is a choice with limited options, and one of the options selected has just run over its limit.
474 $choicelock->release();
475 print_error('choicefull', 'choice', $continueurl);
478 // Release lock.
479 if (isset($choicelock)) {
480 $choicelock->release();
483 // Trigger events.
484 foreach ($deletedanswersnapshots as $answer) {
485 \mod_choice\event\answer_deleted::create_from_object($answer, $choice, $cm, $course)->trigger();
487 foreach ($answersnapshots as $answer) {
488 \mod_choice\event\answer_created::create_from_object($answer, $choice, $cm, $course)->trigger();
493 * @param array $user
494 * @param object $cm
495 * @return void Output is echo'd
497 function choice_show_reportlink($user, $cm) {
498 $userschosen = array();
499 foreach($user as $optionid => $userlist) {
500 if ($optionid) {
501 $userschosen = array_merge($userschosen, array_keys($userlist));
504 $responsecount = count(array_unique($userschosen));
506 echo '<div class="reportlink">';
507 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
508 echo '</div>';
512 * @global object
513 * @param object $choice
514 * @param object $course
515 * @param object $coursemodule
516 * @param array $allresponses
518 * * @param bool $allresponses
519 * @return object
521 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
522 global $OUTPUT;
524 $display = clone($choice);
525 $display->coursemoduleid = $cm->id;
526 $display->courseid = $course->id;
528 if (!empty($choice->showunanswered)) {
529 $choice->option[0] = get_string('notanswered', 'choice');
530 $choice->maxanswers[0] = 0;
533 // Remove from the list of non-respondents the users who do not have access to this activity.
534 if (!empty($display->showunanswered) && $allresponses[0]) {
535 $info = new \core_availability\info_module(cm_info::create($cm));
536 $allresponses[0] = $info->filter_user_list($allresponses[0]);
539 //overwrite options value;
540 $display->options = array();
541 $allusers = [];
542 foreach ($choice->option as $optionid => $optiontext) {
543 $display->options[$optionid] = new stdClass;
544 $display->options[$optionid]->text = format_string($optiontext, true,
545 ['context' => context_module::instance($cm->id)]);
546 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
548 if (array_key_exists($optionid, $allresponses)) {
549 $display->options[$optionid]->user = $allresponses[$optionid];
550 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
553 unset($display->option);
554 unset($display->maxanswers);
556 $display->numberofuser = count(array_unique($allusers));
557 $context = context_module::instance($cm->id);
558 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
559 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
560 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
562 if (empty($allresponses)) {
563 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
564 return false;
567 return $display;
571 * @global object
572 * @param array $attemptids
573 * @param object $choice Choice main table row
574 * @param object $cm Course-module object
575 * @param object $course Course object
576 * @return bool
578 function choice_delete_responses($attemptids, $choice, $cm, $course) {
579 global $DB, $CFG, $USER;
580 require_once($CFG->libdir.'/completionlib.php');
582 if(!is_array($attemptids) || empty($attemptids)) {
583 return false;
586 foreach($attemptids as $num => $attemptid) {
587 if(empty($attemptid)) {
588 unset($attemptids[$num]);
592 $completion = new completion_info($course);
593 foreach($attemptids as $attemptid) {
594 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
595 // Trigger the event answer deleted.
596 \mod_choice\event\answer_deleted::create_from_object($todelete, $choice, $cm, $course)->trigger();
597 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
601 // Update completion state.
602 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
603 $completion->update_state($cm, COMPLETION_INCOMPLETE);
606 return true;
611 * Given an ID of an instance of this module,
612 * this function will permanently delete the instance
613 * and any data that depends on it.
615 * @global object
616 * @param int $id
617 * @return bool
619 function choice_delete_instance($id) {
620 global $DB;
622 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
623 return false;
626 $result = true;
628 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
629 $result = false;
632 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
633 $result = false;
636 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
637 $result = false;
639 // Remove old calendar events.
640 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
641 $result = false;
644 return $result;
648 * Returns text string which is the answer that matches the id
650 * @global object
651 * @param object $choice
652 * @param int $id
653 * @return string
655 function choice_get_option_text($choice, $id) {
656 global $DB;
658 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
659 return $result->text;
660 } else {
661 return get_string("notanswered", "choice");
666 * Gets a full choice record
668 * @global object
669 * @param int $choiceid
670 * @return object|bool The choice or false
672 function choice_get_choice($choiceid) {
673 global $DB;
675 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
676 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
677 foreach ($options as $option) {
678 $choice->option[$option->id] = $option->text;
679 $choice->maxanswers[$option->id] = $option->maxanswers;
681 return $choice;
684 return false;
688 * List the actions that correspond to a view of this module.
689 * This is used by the participation report.
691 * Note: This is not used by new logging system. Event with
692 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
693 * be considered as view action.
695 * @return array
697 function choice_get_view_actions() {
698 return array('view','view all','report');
702 * List the actions that correspond to a post of this module.
703 * This is used by the participation report.
705 * Note: This is not used by new logging system. Event with
706 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
707 * will be considered as post action.
709 * @return array
711 function choice_get_post_actions() {
712 return array('choose','choose again');
717 * Implementation of the function for printing the form elements that control
718 * whether the course reset functionality affects the choice.
720 * @param object $mform form passed by reference
722 function choice_reset_course_form_definition(&$mform) {
723 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
724 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
728 * Course reset form defaults.
730 * @return array
732 function choice_reset_course_form_defaults($course) {
733 return array('reset_choice'=>1);
737 * Actual implementation of the reset course functionality, delete all the
738 * choice responses for course $data->courseid.
740 * @global object
741 * @global object
742 * @param object $data the data submitted from the reset course.
743 * @return array status array
745 function choice_reset_userdata($data) {
746 global $CFG, $DB;
748 $componentstr = get_string('modulenameplural', 'choice');
749 $status = array();
751 if (!empty($data->reset_choice)) {
752 $choicessql = "SELECT ch.id
753 FROM {choice} ch
754 WHERE ch.course=?";
756 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
757 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
760 /// updating dates - shift may be negative too
761 if ($data->timeshift) {
762 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
763 // See MDL-9367.
764 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
765 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
768 return $status;
772 * @global object
773 * @global object
774 * @global object
775 * @uses CONTEXT_MODULE
776 * @param object $choice
777 * @param object $cm
778 * @param int $groupmode
779 * @param bool $onlyactive Whether to get response data for active users only.
780 * @return array
782 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
783 global $CFG, $USER, $DB;
785 $context = context_module::instance($cm->id);
787 /// Get the current group
788 if ($groupmode > 0) {
789 $currentgroup = groups_get_activity_group($cm);
790 } else {
791 $currentgroup = 0;
794 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
795 $allresponses = array();
797 /// First get all the users who have access here
798 /// To start with we assume they are all "unanswered" then move them later
799 $extrafields = get_extra_user_fields($context);
800 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
801 user_picture::fields('u', $extrafields), null, 0, 0, $onlyactive);
803 /// Get all the recorded responses for this choice
804 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
806 /// Use the responses to move users into the correct column
808 if ($rawresponses) {
809 $answeredusers = array();
810 foreach ($rawresponses as $response) {
811 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
812 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
813 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
814 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
815 $answeredusers[] = $response->userid;
818 foreach ($answeredusers as $answereduser) {
819 unset($allresponses[0][$answereduser]);
822 return $allresponses;
826 * Returns all other caps used in module
828 * @return array
830 function choice_get_extra_capabilities() {
831 return array('moodle/site:accessallgroups');
835 * @uses FEATURE_GROUPS
836 * @uses FEATURE_GROUPINGS
837 * @uses FEATURE_MOD_INTRO
838 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
839 * @uses FEATURE_GRADE_HAS_GRADE
840 * @uses FEATURE_GRADE_OUTCOMES
841 * @param string $feature FEATURE_xx constant for requested feature
842 * @return mixed True if module supports feature, null if doesn't know
844 function choice_supports($feature) {
845 switch($feature) {
846 case FEATURE_GROUPS: return true;
847 case FEATURE_GROUPINGS: return true;
848 case FEATURE_MOD_INTRO: return true;
849 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
850 case FEATURE_COMPLETION_HAS_RULES: return true;
851 case FEATURE_GRADE_HAS_GRADE: return false;
852 case FEATURE_GRADE_OUTCOMES: return false;
853 case FEATURE_BACKUP_MOODLE2: return true;
854 case FEATURE_SHOW_DESCRIPTION: return true;
856 default: return null;
861 * Adds module specific settings to the settings block
863 * @param settings_navigation $settings The settings navigation object
864 * @param navigation_node $choicenode The node to add module settings to
866 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
867 global $PAGE;
869 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
871 $groupmode = groups_get_activity_groupmode($PAGE->cm);
872 if ($groupmode) {
873 groups_get_activity_group($PAGE->cm, true);
876 $choice = choice_get_choice($PAGE->cm->instance);
878 // Check if we want to include responses from inactive users.
879 $onlyactive = $choice->includeinactive ? false : true;
881 // Big function, approx 6 SQL calls per user.
882 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
884 $allusers = [];
885 foreach($allresponses as $optionid => $userlist) {
886 if ($optionid) {
887 $allusers = array_merge($allusers, array_keys($userlist));
890 $responsecount = count(array_unique($allusers));
891 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
896 * Obtains the automatic completion state for this choice based on any conditions
897 * in forum settings.
899 * @param object $course Course
900 * @param object $cm Course-module
901 * @param int $userid User ID
902 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
903 * @return bool True if completed, false if not, $type if conditions not set.
905 function choice_get_completion_state($course, $cm, $userid, $type) {
906 global $CFG,$DB;
908 // Get choice details
909 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
910 MUST_EXIST);
912 // If completion option is enabled, evaluate it and return true/false
913 if($choice->completionsubmit) {
914 return $DB->record_exists('choice_answers', array(
915 'choiceid'=>$choice->id, 'userid'=>$userid));
916 } else {
917 // Completion option is not enabled so just return $type
918 return $type;
923 * Return a list of page types
924 * @param string $pagetype current page type
925 * @param stdClass $parentcontext Block's parent context
926 * @param stdClass $currentcontext Current context of block
928 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
929 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
930 return $module_pagetype;
934 * Prints choice summaries on MyMoodle Page
936 * Prints choice name, due date and attempt information on
937 * choice activities that have a deadline that has not already passed
938 * and it is available for completing.
940 * @deprecated since 3.3
941 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
942 * @uses CONTEXT_MODULE
943 * @param array $courses An array of course objects to get choice instances from.
944 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
946 function choice_print_overview($courses, &$htmlarray) {
947 global $USER, $DB, $OUTPUT;
949 debugging('The function choice_print_overview() is now deprecated.', DEBUG_DEVELOPER);
951 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
952 return;
954 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
955 return;
958 $now = time();
959 foreach ($choices as $choice) {
960 if ($choice->timeclose != 0 // If this choice is scheduled.
961 and $choice->timeclose >= $now // And the deadline has not passed.
962 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
964 // Visibility.
965 $class = (!$choice->visible) ? 'dimmed' : '';
967 // Link to activity.
968 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
969 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
970 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
972 // Deadline.
973 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
975 // Display relevant info based on permissions.
976 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
977 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
978 [$choice->id]);
979 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
980 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
982 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
983 // See if the user has submitted anything.
984 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
985 if ($answers > 0) {
986 // User has already selected an answer, nothing to show.
987 $str = '';
988 } else {
989 // User has not made a selection yet.
990 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
992 } else {
993 // Does not have permission to do anything on this choice activity.
994 $str = '';
997 // Make sure we have something to display.
998 if (!empty($str)) {
999 // Generate the containing div.
1000 $str = $OUTPUT->box($str, 'choice overview');
1002 if (empty($htmlarray[$choice->course]['choice'])) {
1003 $htmlarray[$choice->course]['choice'] = $str;
1004 } else {
1005 $htmlarray[$choice->course]['choice'] .= $str;
1010 return;
1015 * Get responses of a given user on a given choice.
1017 * @param stdClass $choice Choice record
1018 * @param int $userid User id
1019 * @return array of choice answers records
1020 * @since Moodle 3.6
1022 function choice_get_user_response($choice, $userid) {
1023 global $DB;
1024 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
1028 * Get my responses on a given choice.
1030 * @param stdClass $choice Choice record
1031 * @return array of choice answers records
1032 * @since Moodle 3.0
1034 function choice_get_my_response($choice) {
1035 global $USER;
1036 return choice_get_user_response($choice, $USER->id);
1041 * Get all the responses on a given choice.
1043 * @param stdClass $choice Choice record
1044 * @return array of choice answers records
1045 * @since Moodle 3.0
1047 function choice_get_all_responses($choice) {
1048 global $DB;
1049 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
1054 * Return true if we are allowd to view the choice results.
1056 * @param stdClass $choice Choice record
1057 * @param rows|null $current my choice responses
1058 * @param bool|null $choiceopen if the choice is open
1059 * @return bool true if we can view the results, false otherwise.
1060 * @since Moodle 3.0
1062 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1064 if (is_null($choiceopen)) {
1065 $timenow = time();
1067 if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
1068 // If the choice is not available, we can't see the results.
1069 return false;
1072 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1073 $choiceopen = false;
1074 } else {
1075 $choiceopen = true;
1078 if (empty($current)) {
1079 $current = choice_get_my_response($choice);
1082 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1083 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1084 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1085 return true;
1087 return false;
1091 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1093 * @param stdClass $choice choice object
1094 * @param stdClass $course course object
1095 * @param stdClass $cm course module object
1096 * @param stdClass $context context object
1097 * @since Moodle 3.0
1099 function choice_view($choice, $course, $cm, $context) {
1101 // Trigger course_module_viewed event.
1102 $params = array(
1103 'context' => $context,
1104 'objectid' => $choice->id
1107 $event = \mod_choice\event\course_module_viewed::create($params);
1108 $event->add_record_snapshot('course_modules', $cm);
1109 $event->add_record_snapshot('course', $course);
1110 $event->add_record_snapshot('choice', $choice);
1111 $event->trigger();
1113 // Completion.
1114 $completion = new completion_info($course);
1115 $completion->set_module_viewed($cm);
1119 * Check if a choice is available for the current user.
1121 * @param stdClass $choice choice record
1122 * @return array status (available or not and possible warnings)
1124 function choice_get_availability_status($choice) {
1125 $available = true;
1126 $warnings = array();
1128 $timenow = time();
1130 if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
1131 $available = false;
1132 $warnings['notopenyet'] = userdate($choice->timeopen);
1133 } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
1134 $available = false;
1135 $warnings['expired'] = userdate($choice->timeclose);
1137 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1138 $available = false;
1139 $warnings['choicesaved'] = '';
1142 // Choice is available.
1143 return array($available, $warnings);
1147 * This standard function will check all instances of this module
1148 * and make sure there are up-to-date events created for each of them.
1149 * If courseid = 0, then every choice event in the site is checked, else
1150 * only choice events belonging to the course specified are checked.
1151 * This function is used, in its new format, by restore_refresh_events()
1153 * @param int $courseid
1154 * @param int|stdClass $instance Choice module instance or ID.
1155 * @param int|stdClass $cm Course module object or ID (not used in this module).
1156 * @return bool
1158 function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
1159 global $DB, $CFG;
1160 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1162 // If we have instance information then we can just update the one event instead of updating all events.
1163 if (isset($instance)) {
1164 if (!is_object($instance)) {
1165 $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST);
1167 choice_set_events($instance);
1168 return true;
1171 if ($courseid) {
1172 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1173 return true;
1175 } else {
1176 if (! $choices = $DB->get_records("choice")) {
1177 return true;
1181 foreach ($choices as $choice) {
1182 choice_set_events($choice);
1184 return true;
1188 * Check if the module has any update that affects the current user since a given time.
1190 * @param cm_info $cm course module data
1191 * @param int $from the time to check updates from
1192 * @param array $filter if we need to check only specific updates
1193 * @return stdClass an object with the different type of areas indicating if they were updated or not
1194 * @since Moodle 3.2
1196 function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
1197 global $DB;
1199 $updates = new stdClass();
1200 $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1201 list($available, $warnings) = choice_get_availability_status($choice);
1202 if (!$available) {
1203 return $updates;
1206 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1208 if (!choice_can_view_results($choice)) {
1209 return $updates;
1211 // Check if there are new responses in the choice.
1212 $updates->answers = (object) array('updated' => false);
1213 $select = 'choiceid = :id AND timemodified > :since';
1214 $params = array('id' => $choice->id, 'since' => $from);
1215 $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1216 if (!empty($answers)) {
1217 $updates->answers->updated = true;
1218 $updates->answers->itemids = array_keys($answers);
1221 return $updates;
1225 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1227 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1228 * is not displayed on the block.
1230 * @param calendar_event $event
1231 * @param \core_calendar\action_factory $factory
1232 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1233 * @return \core_calendar\local\event\entities\action_interface|null
1235 function mod_choice_core_calendar_provide_event_action(calendar_event $event,
1236 \core_calendar\action_factory $factory,
1237 int $userid = 0) {
1238 global $USER;
1240 if (!$userid) {
1241 $userid = $USER->id;
1244 $cm = get_fast_modinfo($event->courseid, $userid)->instances['choice'][$event->instance];
1246 if (!$cm->uservisible) {
1247 // The module is not visible to the user for any reason.
1248 return null;
1251 $now = time();
1253 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < $now) {
1254 // The choice has closed so the user can no longer submit anything.
1255 return null;
1258 // The choice is actionable if we don't have a start time or the start time is
1259 // in the past.
1260 $actionable = (empty($cm->customdata['timeopen']) || $cm->customdata['timeopen'] <= $now);
1262 if ($actionable && choice_get_user_response((object)['id' => $event->instance], $userid)) {
1263 // There is no action if the user has already submitted their choice.
1264 return null;
1267 return $factory->create_instance(
1268 get_string('viewchoices', 'choice'),
1269 new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
1271 $actionable
1276 * This function calculates the minimum and maximum cutoff values for the timestart of
1277 * the given event.
1279 * It will return an array with two values, the first being the minimum cutoff value and
1280 * the second being the maximum cutoff value. Either or both values can be null, which
1281 * indicates there is no minimum or maximum, respectively.
1283 * If a cutoff is required then the function must return an array containing the cutoff
1284 * timestamp and error string to display to the user if the cutoff value is violated.
1286 * A minimum and maximum cutoff return value will look like:
1288 * [1505704373, 'The date must be after this date'],
1289 * [1506741172, 'The date must be before this date']
1292 * @param calendar_event $event The calendar event to get the time range for
1293 * @param stdClass $choice The module instance to get the range from
1295 function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $choice) {
1296 $mindate = null;
1297 $maxdate = null;
1299 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1300 if (!empty($choice->timeclose)) {
1301 $maxdate = [
1302 $choice->timeclose,
1303 get_string('openafterclose', 'choice')
1306 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1307 if (!empty($choice->timeopen)) {
1308 $mindate = [
1309 $choice->timeopen,
1310 get_string('closebeforeopen', 'choice')
1315 return [$mindate, $maxdate];
1319 * This function will update the choice module according to the
1320 * event that has been modified.
1322 * It will set the timeopen or timeclose value of the choice instance
1323 * according to the type of event provided.
1325 * @throws \moodle_exception
1326 * @param \calendar_event $event
1327 * @param stdClass $choice The module instance to get the range from
1329 function mod_choice_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $choice) {
1330 global $DB;
1332 if (!in_array($event->eventtype, [CHOICE_EVENT_TYPE_OPEN, CHOICE_EVENT_TYPE_CLOSE])) {
1333 return;
1336 $courseid = $event->courseid;
1337 $modulename = $event->modulename;
1338 $instanceid = $event->instance;
1339 $modified = false;
1341 // Something weird going on. The event is for a different module so
1342 // we should ignore it.
1343 if ($modulename != 'choice') {
1344 return;
1347 if ($choice->id != $instanceid) {
1348 return;
1351 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1352 $context = context_module::instance($coursemodule->id);
1354 // The user does not have the capability to modify this activity.
1355 if (!has_capability('moodle/course:manageactivities', $context)) {
1356 return;
1359 if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1360 // If the event is for the choice activity opening then we should
1361 // set the start time of the choice activity to be the new start
1362 // time of the event.
1363 if ($choice->timeopen != $event->timestart) {
1364 $choice->timeopen = $event->timestart;
1365 $modified = true;
1367 } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1368 // If the event is for the choice activity closing then we should
1369 // set the end time of the choice activity to be the new start
1370 // time of the event.
1371 if ($choice->timeclose != $event->timestart) {
1372 $choice->timeclose = $event->timestart;
1373 $modified = true;
1377 if ($modified) {
1378 $choice->timemodified = time();
1379 // Persist the instance changes.
1380 $DB->update_record('choice', $choice);
1381 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1382 $event->trigger();
1387 * Get icon mapping for font-awesome.
1389 function mod_choice_get_fontawesome_icon_map() {
1390 return [
1391 'mod_choice:row' => 'fa-info',
1392 'mod_choice:column' => 'fa-columns',
1397 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1398 * for the course (see resource).
1400 * Given a course_module object, this function returns any "extra" information that may be needed
1401 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1403 * @param stdClass $coursemodule The coursemodule object (record).
1404 * @return cached_cm_info An object on information that the courses
1405 * will know about (most noticeably, an icon).
1407 function choice_get_coursemodule_info($coursemodule) {
1408 global $DB;
1410 $dbparams = ['id' => $coursemodule->instance];
1411 $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
1412 if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1413 return false;
1416 $result = new cached_cm_info();
1417 $result->name = $choice->name;
1419 if ($coursemodule->showdescription) {
1420 // Convert intro to html. Do not filter cached version, filters run at display time.
1421 $result->content = format_module_intro('choice', $choice, $coursemodule->id, false);
1424 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1425 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1426 $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
1428 // Populate some other values that can be used in calendar or on dashboard.
1429 if ($choice->timeopen) {
1430 $result->customdata['timeopen'] = $choice->timeopen;
1432 if ($choice->timeclose) {
1433 $result->customdata['timeclose'] = $choice->timeclose;
1436 return $result;
1440 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1442 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1443 * @return array $descriptions the array of descriptions for the custom rules.
1445 function mod_choice_get_completion_active_rule_descriptions($cm) {
1446 // Values will be present in cm_info, and we assume these are up to date.
1447 if (empty($cm->customdata['customcompletionrules'])
1448 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1449 return [];
1452 $descriptions = [];
1453 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1454 switch ($key) {
1455 case 'completionsubmit':
1456 if (empty($val)) {
1457 continue;
1459 $descriptions[] = get_string('completionsubmit', 'choice');
1460 break;
1461 default:
1462 break;
1465 return $descriptions;