3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') ||
die();
26 /** @global int $CHOICE_COLUMN_HEIGHT */
27 global $CHOICE_COLUMN_HEIGHT;
28 $CHOICE_COLUMN_HEIGHT = 300;
30 /** @global int $CHOICE_COLUMN_WIDTH */
31 global $CHOICE_COLUMN_WIDTH;
32 $CHOICE_COLUMN_WIDTH = 300;
34 define('CHOICE_PUBLISH_ANONYMOUS', '0');
35 define('CHOICE_PUBLISH_NAMES', '1');
37 define('CHOICE_SHOWRESULTS_NOT', '0');
38 define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
39 define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
40 define('CHOICE_SHOWRESULTS_ALWAYS', '3');
42 define('CHOICE_DISPLAY_HORIZONTAL', '0');
43 define('CHOICE_DISPLAY_VERTICAL', '1');
45 define('CHOICE_EVENT_TYPE_OPEN', 'open');
46 define('CHOICE_EVENT_TYPE_CLOSE', 'close');
48 /** @global array $CHOICE_PUBLISH */
49 global $CHOICE_PUBLISH;
50 $CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS
=> get_string('publishanonymous', 'choice'),
51 CHOICE_PUBLISH_NAMES
=> get_string('publishnames', 'choice'));
53 /** @global array $CHOICE_SHOWRESULTS */
54 global $CHOICE_SHOWRESULTS;
55 $CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT
=> get_string('publishnot', 'choice'),
56 CHOICE_SHOWRESULTS_AFTER_ANSWER
=> get_string('publishafteranswer', 'choice'),
57 CHOICE_SHOWRESULTS_AFTER_CLOSE
=> get_string('publishafterclose', 'choice'),
58 CHOICE_SHOWRESULTS_ALWAYS
=> get_string('publishalways', 'choice'));
60 /** @global array $CHOICE_DISPLAY */
61 global $CHOICE_DISPLAY;
62 $CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL
=> get_string('displayhorizontal', 'choice'),
63 CHOICE_DISPLAY_VERTICAL
=> get_string('displayvertical','choice'));
65 /// Standard functions /////////////////////////////////////////////////////////
69 * @param object $course
72 * @param object $choice
75 function choice_user_outline($course, $user, $mod, $choice) {
77 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id
, 'userid' => $user->id
))) {
78 $result = new stdClass();
79 $result->info
= "'".format_string(choice_get_option_text($choice, $answer->optionid
))."'";
80 $result->time
= $answer->timemodified
;
87 * Callback for the "Complete" report - prints the activity summary for the given user
89 * @param object $course
92 * @param object $choice
94 function choice_user_complete($course, $user, $mod, $choice) {
96 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id
, "userid" => $user->id
))) {
98 foreach ($answers as $answer) {
99 $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid
)) . "'";
101 core_collator
::asort($info);
102 echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
103 get_string("updated", '', userdate($answer->timemodified
));
105 print_string("notanswered", "choice");
110 * Given an object containing all the necessary data,
111 * (defined by the form in mod_form.php) this function
112 * will create a new instance and return the id number
113 * of the new instance.
116 * @param object $choice
119 function choice_add_instance($choice) {
121 require_once($CFG->dirroot
.'/mod/choice/locallib.php');
123 $choice->timemodified
= time();
126 $choice->id
= $DB->insert_record("choice", $choice);
127 foreach ($choice->option
as $key => $value) {
128 $value = trim($value);
129 if (isset($value) && $value <> '') {
130 $option = new stdClass();
131 $option->text
= $value;
132 $option->choiceid
= $choice->id
;
133 if (isset($choice->limit
[$key])) {
134 $option->maxanswers
= $choice->limit
[$key];
136 $option->timemodified
= time();
137 $DB->insert_record("choice_options", $option);
141 // Add calendar events if necessary.
142 choice_set_events($choice);
143 if (!empty($choice->completionexpected
)) {
144 \core_completion\api
::update_completion_date_event($choice->coursemodule
, 'choice', $choice->id
,
145 $choice->completionexpected
);
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.
157 * @param object $choice
160 function choice_update_instance($choice) {
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);
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
));
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);
205 * @param object $choice
206 * @param object $user
207 * @param object $coursemodule
208 * @param array $allresponses
211 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
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]);
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;
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])) {
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) {
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.
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;
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
) {
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);
357 $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS
);
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
;
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);
385 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED
);
388 // If groups are being used, retrieve responses only for users in
392 $params['groupid'] = $currentgroup;
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";
399 // Groups are not used, retrieve all answers for this option ID
401 FROM {choice_answers} ca
402 WHERE optionid $insql";
405 $answers = $DB->get_records_sql($sql, $params);
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)) {
420 if ($count >= $choice->maxanswers
[$opt]) {
421 $choicesexceeded = true;
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)) {
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
));
437 $deletedanswersnapshots[] = $c;
438 $DB->delete_records('choice_answers', array('id' => $c->id
));
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;
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
);
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);
479 if (isset($choicelock)) {
480 $choicelock->release();
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();
495 * @return void Output is echo'd
497 function choice_show_reportlink($user, $cm) {
498 $userschosen = array();
499 foreach($user as $optionid => $userlist) {
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>";
513 * @param object $choice
514 * @param object $course
515 * @param object $coursemodule
516 * @param array $allresponses
518 * * @param bool $allresponses
521 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
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();
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);
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
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)) {
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
);
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.
619 function choice_delete_instance($id) {
622 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
628 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
632 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
636 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
639 // Remove old calendar events.
640 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id
))) {
648 * Returns text string which is the answer that matches the id
651 * @param object $choice
655 function choice_get_option_text($choice, $id) {
658 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
659 return $result->text
;
661 return get_string("notanswered", "choice");
666 * Gets a full choice record
669 * @param int $choiceid
670 * @return object|bool The choice or false
672 function choice_get_choice($choiceid) {
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
;
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.
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.
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.
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.
742 * @param object $data the data submitted from the reset course.
743 * @return array status array
745 function choice_reset_userdata($data) {
748 $componentstr = get_string('modulenameplural', 'choice');
751 if (!empty($data->reset_choice
)) {
752 $choicessql = "SELECT ch.id
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.
764 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift
, $data->courseid
);
765 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
775 * @uses CONTEXT_MODULE
776 * @param object $choice
778 * @param int $groupmode
779 * @param bool $onlyactive Whether to get response data for active users only.
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);
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
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
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) {
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) {
869 if (has_capability('mod/choice:readresponses', $PAGE->cm
->context
)) {
871 $groupmode = groups_get_activity_groupmode($PAGE->cm
);
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);
885 foreach($allresponses as $optionid => $userlist) {
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
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) {
908 // Get choice details
909 $choice = $DB->get_record('choice', array('id'=>$cm->instance
), '*',
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));
917 // Completion option is not enabled so just 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) {
954 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
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.
965 $class = (!$choice->visible
) ?
'dimmed' : '';
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');
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 = ?',
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
));
986 // User has already selected an answer, nothing to show.
989 // User has not made a selection yet.
990 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
993 // Does not have permission to do anything on this choice activity.
997 // Make sure we have something to display.
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;
1005 $htmlarray[$choice->course
]['choice'] .= $str;
1015 * Get my responses on a given choice.
1017 * @param stdClass $choice Choice record
1018 * @return array of choice answers records
1021 function choice_get_my_response($choice) {
1023 return $DB->get_records('choice_answers', array('choiceid' => $choice->id
, 'userid' => $USER->id
), 'optionid');
1028 * Get all the responses on a given choice.
1030 * @param stdClass $choice Choice record
1031 * @return array of choice answers records
1034 function choice_get_all_responses($choice) {
1036 return $DB->get_records('choice_answers', array('choiceid' => $choice->id
));
1041 * Return true if we are allowd to view the choice results.
1043 * @param stdClass $choice Choice record
1044 * @param rows|null $current my choice responses
1045 * @param bool|null $choiceopen if the choice is open
1046 * @return bool true if we can view the results, false otherwise.
1049 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1051 if (is_null($choiceopen)) {
1054 if ($choice->timeopen
!= 0 && $timenow < $choice->timeopen
) {
1055 // If the choice is not available, we can't see the results.
1059 if ($choice->timeclose
!= 0 && $timenow > $choice->timeclose
) {
1060 $choiceopen = false;
1065 if (empty($current)) {
1066 $current = choice_get_my_response($choice);
1069 if ($choice->showresults
== CHOICE_SHOWRESULTS_ALWAYS
or
1070 ($choice->showresults
== CHOICE_SHOWRESULTS_AFTER_ANSWER
and !empty($current)) or
1071 ($choice->showresults
== CHOICE_SHOWRESULTS_AFTER_CLOSE
and !$choiceopen)) {
1078 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1080 * @param stdClass $choice choice object
1081 * @param stdClass $course course object
1082 * @param stdClass $cm course module object
1083 * @param stdClass $context context object
1086 function choice_view($choice, $course, $cm, $context) {
1088 // Trigger course_module_viewed event.
1090 'context' => $context,
1091 'objectid' => $choice->id
1094 $event = \mod_choice\event\course_module_viewed
::create($params);
1095 $event->add_record_snapshot('course_modules', $cm);
1096 $event->add_record_snapshot('course', $course);
1097 $event->add_record_snapshot('choice', $choice);
1101 $completion = new completion_info($course);
1102 $completion->set_module_viewed($cm);
1106 * Check if a choice is available for the current user.
1108 * @param stdClass $choice choice record
1109 * @return array status (available or not and possible warnings)
1111 function choice_get_availability_status($choice) {
1113 $warnings = array();
1117 if (!empty($choice->timeopen
) && ($choice->timeopen
> $timenow)) {
1119 $warnings['notopenyet'] = userdate($choice->timeopen
);
1120 } else if (!empty($choice->timeclose
) && ($timenow > $choice->timeclose
)) {
1122 $warnings['expired'] = userdate($choice->timeclose
);
1124 if (!$choice->allowupdate
&& choice_get_my_response($choice)) {
1126 $warnings['choicesaved'] = '';
1129 // Choice is available.
1130 return array($available, $warnings);
1134 * This standard function will check all instances of this module
1135 * and make sure there are up-to-date events created for each of them.
1136 * If courseid = 0, then every choice event in the site is checked, else
1137 * only choice events belonging to the course specified are checked.
1138 * This function is used, in its new format, by restore_refresh_events()
1140 * @param int $courseid
1141 * @param int|stdClass $instance Choice module instance or ID.
1142 * @param int|stdClass $cm Course module object or ID (not used in this module).
1145 function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
1147 require_once($CFG->dirroot
.'/mod/choice/locallib.php');
1149 // If we have instance information then we can just update the one event instead of updating all events.
1150 if (isset($instance)) {
1151 if (!is_object($instance)) {
1152 $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST
);
1154 choice_set_events($instance);
1159 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1163 if (! $choices = $DB->get_records("choice")) {
1168 foreach ($choices as $choice) {
1169 choice_set_events($choice);
1175 * Check if the module has any update that affects the current user since a given time.
1177 * @param cm_info $cm course module data
1178 * @param int $from the time to check updates from
1179 * @param array $filter if we need to check only specific updates
1180 * @return stdClass an object with the different type of areas indicating if they were updated or not
1183 function choice_check_updates_since(cm_info
$cm, $from, $filter = array()) {
1186 $updates = new stdClass();
1187 $choice = $DB->get_record($cm->modname
, array('id' => $cm->instance
), '*', MUST_EXIST
);
1188 list($available, $warnings) = choice_get_availability_status($choice);
1193 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1195 if (!choice_can_view_results($choice)) {
1198 // Check if there are new responses in the choice.
1199 $updates->answers
= (object) array('updated' => false);
1200 $select = 'choiceid = :id AND timemodified > :since';
1201 $params = array('id' => $choice->id
, 'since' => $from);
1202 $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1203 if (!empty($answers)) {
1204 $updates->answers
->updated
= true;
1205 $updates->answers
->itemids
= array_keys($answers);
1212 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1214 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1215 * is not displayed on the block.
1217 * @param calendar_event $event
1218 * @param \core_calendar\action_factory $factory
1219 * @return \core_calendar\local\event\entities\action_interface|null
1221 function mod_choice_core_calendar_provide_event_action(calendar_event
$event,
1222 \core_calendar\action_factory
$factory) {
1224 $cm = get_fast_modinfo($event->courseid
)->instances
['choice'][$event->instance
];
1227 if (!empty($cm->customdata
['timeclose']) && $cm->customdata
['timeclose'] < $now) {
1228 // The choice has closed so the user can no longer submit anything.
1232 // The choice is actionable if we don't have a start time or the start time is
1234 $actionable = (empty($cm->customdata
['timeopen']) ||
$cm->customdata
['timeopen'] <= $now);
1236 if ($actionable && choice_get_my_response((object)['id' => $event->instance
])) {
1237 // There is no action if the user has already submitted their choice.
1241 return $factory->create_instance(
1242 get_string('viewchoices', 'choice'),
1243 new \
moodle_url('/mod/choice/view.php', array('id' => $cm->id
)),
1250 * This function calculates the minimum and maximum cutoff values for the timestart of
1253 * It will return an array with two values, the first being the minimum cutoff value and
1254 * the second being the maximum cutoff value. Either or both values can be null, which
1255 * indicates there is no minimum or maximum, respectively.
1257 * If a cutoff is required then the function must return an array containing the cutoff
1258 * timestamp and error string to display to the user if the cutoff value is violated.
1260 * A minimum and maximum cutoff return value will look like:
1262 * [1505704373, 'The date must be after this date'],
1263 * [1506741172, 'The date must be before this date']
1266 * @param calendar_event $event The calendar event to get the time range for
1267 * @param stdClass $choice The module instance to get the range from
1269 function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, \stdClass
$choice) {
1273 if ($event->eventtype
== CHOICE_EVENT_TYPE_OPEN
) {
1274 if (!empty($choice->timeclose
)) {
1277 get_string('openafterclose', 'choice')
1280 } else if ($event->eventtype
== CHOICE_EVENT_TYPE_CLOSE
) {
1281 if (!empty($choice->timeopen
)) {
1284 get_string('closebeforeopen', 'choice')
1289 return [$mindate, $maxdate];
1293 * This function will update the choice module according to the
1294 * event that has been modified.
1296 * It will set the timeopen or timeclose value of the choice instance
1297 * according to the type of event provided.
1299 * @throws \moodle_exception
1300 * @param \calendar_event $event
1301 * @param stdClass $choice The module instance to get the range from
1303 function mod_choice_core_calendar_event_timestart_updated(\calendar_event
$event, \stdClass
$choice) {
1306 if (!in_array($event->eventtype
, [CHOICE_EVENT_TYPE_OPEN
, CHOICE_EVENT_TYPE_CLOSE
])) {
1310 $courseid = $event->courseid
;
1311 $modulename = $event->modulename
;
1312 $instanceid = $event->instance
;
1315 // Something weird going on. The event is for a different module so
1316 // we should ignore it.
1317 if ($modulename != 'choice') {
1321 if ($choice->id
!= $instanceid) {
1325 $coursemodule = get_fast_modinfo($courseid)->instances
[$modulename][$instanceid];
1326 $context = context_module
::instance($coursemodule->id
);
1328 // The user does not have the capability to modify this activity.
1329 if (!has_capability('moodle/course:manageactivities', $context)) {
1333 if ($event->eventtype
== CHOICE_EVENT_TYPE_OPEN
) {
1334 // If the event is for the choice activity opening then we should
1335 // set the start time of the choice activity to be the new start
1336 // time of the event.
1337 if ($choice->timeopen
!= $event->timestart
) {
1338 $choice->timeopen
= $event->timestart
;
1341 } else if ($event->eventtype
== CHOICE_EVENT_TYPE_CLOSE
) {
1342 // If the event is for the choice activity closing then we should
1343 // set the end time of the choice activity to be the new start
1344 // time of the event.
1345 if ($choice->timeclose
!= $event->timestart
) {
1346 $choice->timeclose
= $event->timestart
;
1352 $choice->timemodified
= time();
1353 // Persist the instance changes.
1354 $DB->update_record('choice', $choice);
1355 $event = \core\event\course_module_updated
::create_from_cm($coursemodule, $context);
1361 * Get icon mapping for font-awesome.
1363 function mod_choice_get_fontawesome_icon_map() {
1365 'mod_choice:row' => 'fa-info',
1366 'mod_choice:column' => 'fa-columns',
1371 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1372 * for the course (see resource).
1374 * Given a course_module object, this function returns any "extra" information that may be needed
1375 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1377 * @param stdClass $coursemodule The coursemodule object (record).
1378 * @return cached_cm_info An object on information that the courses
1379 * will know about (most noticeably, an icon).
1381 function choice_get_coursemodule_info($coursemodule) {
1384 $dbparams = ['id' => $coursemodule->instance
];
1385 $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
1386 if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1390 $result = new cached_cm_info();
1391 $result->name
= $choice->name
;
1393 if ($coursemodule->showdescription
) {
1394 // Convert intro to html. Do not filter cached version, filters run at display time.
1395 $result->content
= format_module_intro('choice', $choice, $coursemodule->id
, false);
1398 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1399 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
1400 $result->customdata
['customcompletionrules']['completionsubmit'] = $choice->completionsubmit
;
1402 // Populate some other values that can be used in calendar or on dashboard.
1403 if ($choice->timeopen
) {
1404 $result->customdata
['timeopen'] = $choice->timeopen
;
1406 if ($choice->timeclose
) {
1407 $result->customdata
['timeclose'] = $choice->timeclose
;
1414 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1416 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1417 * @return array $descriptions the array of descriptions for the custom rules.
1419 function mod_choice_get_completion_active_rule_descriptions($cm) {
1420 // Values will be present in cm_info, and we assume these are up to date.
1421 if (empty($cm->customdata
['customcompletionrules'])
1422 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
1427 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
1429 case 'completionsubmit':
1433 $descriptions[] = get_string('completionsubmit', 'choice');
1439 return $descriptions;