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 /** @global int $CHOICE_COLUMN_HEIGHT */
25 global $CHOICE_COLUMN_HEIGHT;
26 $CHOICE_COLUMN_HEIGHT = 300;
28 /** @global int $CHOICE_COLUMN_WIDTH */
29 global $CHOICE_COLUMN_WIDTH;
30 $CHOICE_COLUMN_WIDTH = 300;
32 define('CHOICE_PUBLISH_ANONYMOUS', '0');
33 define('CHOICE_PUBLISH_NAMES', '1');
35 define('CHOICE_SHOWRESULTS_NOT', '0');
36 define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
37 define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
38 define('CHOICE_SHOWRESULTS_ALWAYS', '3');
40 define('CHOICE_DISPLAY_HORIZONTAL', '0');
41 define('CHOICE_DISPLAY_VERTICAL', '1');
43 /** @global array $CHOICE_PUBLISH */
44 global $CHOICE_PUBLISH;
45 $CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
46 CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
48 /** @global array $CHOICE_SHOWRESULTS */
49 global $CHOICE_SHOWRESULTS;
50 $CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT => get_string('publishnot', 'choice'),
51 CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
52 CHOICE_SHOWRESULTS_AFTER_CLOSE => get_string('publishafterclose', 'choice'),
53 CHOICE_SHOWRESULTS_ALWAYS => get_string('publishalways', 'choice'));
55 /** @global array $CHOICE_DISPLAY */
56 global $CHOICE_DISPLAY;
57 $CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
58 CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
60 /// Standard functions /////////////////////////////////////////////////////////
64 * @param object $course
67 * @param object $choice
70 function choice_user_outline($course, $user, $mod, $choice) {
72 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
73 $result = new stdClass();
74 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
75 $result->time = $answer->timemodified;
82 * Callback for the "Complete" report - prints the activity summary for the given user
84 * @param object $course
87 * @param object $choice
89 function choice_user_complete($course, $user, $mod, $choice) {
91 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
93 foreach ($answers as $answer) {
94 $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
96 core_collator::asort($info);
97 echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
98 get_string("updated", '', userdate($answer->timemodified));
100 print_string("notanswered", "choice");
105 * Given an object containing all the necessary data,
106 * (defined by the form in mod_form.php) this function
107 * will create a new instance and return the id number
108 * of the new instance.
111 * @param object $choice
114 function choice_add_instance($choice) {
117 $choice->timemodified = time();
119 if (empty($choice->timerestrict)) {
120 $choice->timeopen = 0;
121 $choice->timeclose = 0;
125 $choice->id = $DB->insert_record("choice", $choice);
126 foreach ($choice->option as $key => $value) {
127 $value = trim($value);
128 if (isset($value) && $value <> '') {
129 $option = new stdClass();
130 $option->text = $value;
131 $option->choiceid = $choice->id;
132 if (isset($choice->limit[$key])) {
133 $option->maxanswers = $choice->limit[$key];
135 $option->timemodified = time();
136 $DB->insert_record("choice_options", $option);
144 * Given an object containing all the necessary data,
145 * (defined by the form in mod_form.php) this function
146 * will update an existing instance with new data.
149 * @param object $choice
152 function choice_update_instance($choice) {
155 $choice->id = $choice->instance;
156 $choice->timemodified = time();
159 if (empty($choice->timerestrict)) {
160 $choice->timeopen = 0;
161 $choice->timeclose = 0;
164 //update, delete or insert answers
165 foreach ($choice->option as $key => $value) {
166 $value = trim($value);
167 $option = new stdClass();
168 $option->text = $value;
169 $option->choiceid = $choice->id;
170 if (isset($choice->limit[$key])) {
171 $option->maxanswers = $choice->limit[$key];
173 $option->timemodified = time();
174 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
175 $option->id=$choice->optionid[$key];
176 if (isset($value) && $value <> '') {
177 $DB->update_record("choice_options", $option);
178 } else { //empty old option - needs to be deleted.
179 $DB->delete_records("choice_options", array("id"=>$option->id));
182 if (isset($value) && $value <> '') {
183 $DB->insert_record("choice_options", $option);
188 return $DB->update_record('choice', $choice);
194 * @param object $choice
195 * @param object $user
196 * @param object $coursemodule
197 * @param array $allresponses
200 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
203 $cdisplay = array('options'=>array());
205 $cdisplay['limitanswers'] = true;
206 $context = context_module::instance($coursemodule->id);
208 foreach ($choice->option as $optionid => $text) {
209 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
210 $option = new stdClass;
211 $option->attributes = new stdClass;
212 $option->attributes->value = $optionid;
213 $option->text = format_string($text);
214 $option->maxanswers = $choice->maxanswers[$optionid];
215 $option->displaylayout = $choice->display;
217 if (isset($allresponses[$optionid])) {
218 $option->countanswers = count($allresponses[$optionid]);
220 $option->countanswers = 0;
222 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
223 $option->attributes->checked = true;
225 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
226 $option->attributes->disabled = true;
228 $cdisplay['options'][] = $option;
232 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
234 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
235 $cdisplay['allowupdate'] = true;
238 if ($choice->showpreview && $choice->timeopen > time()) {
239 $cdisplay['previewonly'] = true;
246 * Process user submitted answers for a choice,
247 * and either updating them or saving new answers.
249 * @param int $formanswer users submitted answers.
250 * @param object $choice the selected choice.
251 * @param int $userid user identifier.
252 * @param object $course current course.
253 * @param object $cm course context.
256 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
258 require_once($CFG->libdir.'/completionlib.php');
260 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
262 if (empty($formanswer)) {
263 print_error('atleastoneoption', 'choice', $continueurl);
266 if (is_array($formanswer)) {
267 if (!$choice->allowmultiple) {
268 print_error('multiplenotallowederror', 'choice', $continueurl);
270 $formanswers = $formanswer;
272 $formanswers = array($formanswer);
275 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
276 foreach ($formanswers as $key => $val) {
277 if (!isset($options[$val])) {
278 print_error('cannotsubmit', 'choice', $continueurl);
281 // Start lock to prevent synchronous access to the same data
282 // before it's updated, if using limits.
283 if ($choice->limitanswers) {
285 $locktype = 'mod_choice_choice_user_submit_response';
286 // Limiting access to this choice.
287 $resouce = 'choiceid:' . $choice->id;
288 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
291 $choicelock = $lockfactory->get_lock($resouce, $timeout);
293 print_error('cannotsubmit', 'choice', $continueurl);
297 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
298 $context = context_module::instance($cm->id);
300 $choicesexceeded = false;
301 $countanswers = array();
302 foreach ($formanswers as $val) {
303 $countanswers[$val] = 0;
305 if($choice->limitanswers) {
306 // Find out whether groups are being used and enabled
307 if (groups_get_activity_groupmode($cm) > 0) {
308 $currentgroup = groups_get_activity_group($cm);
313 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
316 // If groups are being used, retrieve responses only for users in
320 $params['groupid'] = $currentgroup;
322 FROM {choice_answers} ca
323 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
324 WHERE optionid $insql
325 AND gm.groupid= :groupid";
327 // Groups are not used, retrieve all answers for this option ID
329 FROM {choice_answers} ca
330 WHERE optionid $insql";
333 $answers = $DB->get_records_sql($sql, $params);
335 foreach ($answers as $a) { //only return enrolled users.
336 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
337 $countanswers[$a->optionid]++;
341 foreach ($countanswers as $opt => $count) {
342 if ($count >= $choice->maxanswers[$opt]) {
343 $choicesexceeded = true;
349 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
350 if (!($choice->limitanswers && $choicesexceeded)) {
351 $answersnapshots = array();
353 // Update an existing answer.
354 $existingchoices = array();
355 foreach ($current as $c) {
356 if (in_array($c->optionid, $formanswers)) {
357 $existingchoices[] = $c->optionid;
358 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
359 $answersnapshots[] = $c;
361 $DB->delete_records('choice_answers', array('id' => $c->id));
366 foreach ($formanswers as $f) {
367 if (!in_array($f, $existingchoices)) {
368 $newanswer = new stdClass();
369 $newanswer->optionid = $f;
370 $newanswer->choiceid = $choice->id;
371 $newanswer->userid = $userid;
372 $newanswer->timemodified = time();
373 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
374 $answersnapshots[] = $newanswer;
378 // Initialised as true, meaning we updated the answer.
379 $answerupdated = true;
382 foreach ($formanswers as $answer) {
383 $newanswer = new stdClass();
384 $newanswer->choiceid = $choice->id;
385 $newanswer->userid = $userid;
386 $newanswer->optionid = $answer;
387 $newanswer->timemodified = time();
388 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
389 $answersnapshots[] = $newanswer;
392 // Update completion state
393 $completion = new completion_info($course);
394 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
395 $completion->update_state($cm, COMPLETION_COMPLETE);
398 // Initalised as false, meaning we submitted a new answer.
399 $answerupdated = false;
402 // Check to see if current choice already selected - if not display error.
403 $currentids = array_keys($current);
405 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
406 // Release lock before error.
407 $choicelock->release();
408 print_error('choicefull', 'choice', $continueurl);
413 if (isset($choicelock)) {
414 $choicelock->release();
417 // Now record completed event.
418 if (isset($answerupdated)) {
419 $eventdata = array();
420 $eventdata['context'] = $context;
421 $eventdata['objectid'] = $choice->id;
422 $eventdata['userid'] = $userid;
423 $eventdata['courseid'] = $course->id;
424 $eventdata['other'] = array();
425 $eventdata['other']['choiceid'] = $choice->id;
427 if ($answerupdated) {
428 $eventdata['other']['optionid'] = $formanswer;
429 $event = \mod_choice\event\answer_updated::create($eventdata);
431 $eventdata['other']['optionid'] = $formanswers;
432 $event = \mod_choice\event\answer_submitted::create($eventdata);
434 $event->add_record_snapshot('course', $course);
435 $event->add_record_snapshot('course_modules', $cm);
436 $event->add_record_snapshot('choice', $choice);
437 foreach ($answersnapshots as $record) {
438 $event->add_record_snapshot('choice_answers', $record);
447 * @return void Output is echo'd
449 function choice_show_reportlink($user, $cm) {
450 $userschosen = array();
451 foreach($user as $optionid => $userlist) {
453 $userschosen = array_merge($userschosen, array_keys($userlist));
456 $responsecount = count(array_unique($userschosen));
458 echo '<div class="reportlink">';
459 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
465 * @param object $choice
466 * @param object $course
467 * @param object $coursemodule
468 * @param array $allresponses
470 * * @param bool $allresponses
473 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
476 $display = clone($choice);
477 $display->coursemoduleid = $cm->id;
478 $display->courseid = $course->id;
480 //overwrite options value;
481 $display->options = array();
483 foreach ($choice->option as $optionid => $optiontext) {
484 $display->options[$optionid] = new stdClass;
485 $display->options[$optionid]->text = $optiontext;
486 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
488 if (array_key_exists($optionid, $allresponses)) {
489 $display->options[$optionid]->user = $allresponses[$optionid];
490 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
493 unset($display->option);
494 unset($display->maxanswers);
496 $display->numberofuser = count(array_unique($allusers));
497 $context = context_module::instance($cm->id);
498 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
499 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
500 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
502 if (empty($allresponses)) {
503 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
512 * @param array $attemptids
513 * @param object $choice Choice main table row
514 * @param object $cm Course-module object
515 * @param object $course Course object
518 function choice_delete_responses($attemptids, $choice, $cm, $course) {
519 global $DB, $CFG, $USER;
520 require_once($CFG->libdir.'/completionlib.php');
522 if(!is_array($attemptids) || empty($attemptids)) {
526 foreach($attemptids as $num => $attemptid) {
527 if(empty($attemptid)) {
528 unset($attemptids[$num]);
532 $context = context_module::instance($cm->id);
533 $completion = new completion_info($course);
534 foreach($attemptids as $attemptid) {
535 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
536 // Trigger the event answer deleted.
537 $eventdata = array();
538 $eventdata['objectid'] = $todelete->id;
539 $eventdata['context'] = $context;
540 $eventdata['userid'] = $USER->id;
541 $eventdata['courseid'] = $course->id;
542 $eventdata['relateduserid'] = $todelete->userid;
543 $eventdata['other'] = array();
544 $eventdata['other']['choiceid'] = $choice->id;
545 $eventdata['other']['optionid'] = $todelete->optionid;
546 $event = \mod_choice\event\answer_deleted::create($eventdata);
547 $event->add_record_snapshot('course', $course);
548 $event->add_record_snapshot('course_modules', $cm);
549 $event->add_record_snapshot('choice', $choice);
550 $event->add_record_snapshot('choice_answers', $todelete);
553 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
557 // Update completion state.
558 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
559 $completion->update_state($cm, COMPLETION_INCOMPLETE);
567 * Given an ID of an instance of this module,
568 * this function will permanently delete the instance
569 * and any data that depends on it.
575 function choice_delete_instance($id) {
578 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
584 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
588 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
592 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
600 * Returns text string which is the answer that matches the id
603 * @param object $choice
607 function choice_get_option_text($choice, $id) {
610 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
611 return $result->text;
613 return get_string("notanswered", "choice");
618 * Gets a full choice record
621 * @param int $choiceid
622 * @return object|bool The choice or false
624 function choice_get_choice($choiceid) {
627 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
628 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
629 foreach ($options as $option) {
630 $choice->option[$option->id] = $option->text;
631 $choice->maxanswers[$option->id] = $option->maxanswers;
640 * List the actions that correspond to a view of this module.
641 * This is used by the participation report.
643 * Note: This is not used by new logging system. Event with
644 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
645 * be considered as view action.
649 function choice_get_view_actions() {
650 return array('view','view all','report');
654 * List the actions that correspond to a post of this module.
655 * This is used by the participation report.
657 * Note: This is not used by new logging system. Event with
658 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
659 * will be considered as post action.
663 function choice_get_post_actions() {
664 return array('choose','choose again');
669 * Implementation of the function for printing the form elements that control
670 * whether the course reset functionality affects the choice.
672 * @param object $mform form passed by reference
674 function choice_reset_course_form_definition(&$mform) {
675 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
676 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
680 * Course reset form defaults.
684 function choice_reset_course_form_defaults($course) {
685 return array('reset_choice'=>1);
689 * Actual implementation of the reset course functionality, delete all the
690 * choice responses for course $data->courseid.
694 * @param object $data the data submitted from the reset course.
695 * @return array status array
697 function choice_reset_userdata($data) {
700 $componentstr = get_string('modulenameplural', 'choice');
703 if (!empty($data->reset_choice)) {
704 $choicessql = "SELECT ch.id
708 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
709 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
712 /// updating dates - shift may be negative too
713 if ($data->timeshift) {
714 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
715 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
725 * @uses CONTEXT_MODULE
726 * @param object $choice
728 * @param int $groupmode
729 * @param bool $onlyactive Whether to get response data for active users only.
732 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
733 global $CFG, $USER, $DB;
735 $context = context_module::instance($cm->id);
737 /// Get the current group
738 if ($groupmode > 0) {
739 $currentgroup = groups_get_activity_group($cm);
744 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
745 $allresponses = array();
747 /// First get all the users who have access here
748 /// To start with we assume they are all "unanswered" then move them later
749 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
750 user_picture::fields('u', array('idnumber')), null, 0, 0, $onlyactive);
752 /// Get all the recorded responses for this choice
753 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
755 /// Use the responses to move users into the correct column
758 $answeredusers = array();
759 foreach ($rawresponses as $response) {
760 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
761 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
762 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
763 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
764 $answeredusers[] = $response->userid;
767 foreach ($answeredusers as $answereduser) {
768 unset($allresponses[0][$answereduser]);
771 return $allresponses;
775 * Returns all other caps used in module
779 function choice_get_extra_capabilities() {
780 return array('moodle/site:accessallgroups');
784 * @uses FEATURE_GROUPS
785 * @uses FEATURE_GROUPINGS
786 * @uses FEATURE_MOD_INTRO
787 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
788 * @uses FEATURE_GRADE_HAS_GRADE
789 * @uses FEATURE_GRADE_OUTCOMES
790 * @param string $feature FEATURE_xx constant for requested feature
791 * @return mixed True if module supports feature, null if doesn't know
793 function choice_supports($feature) {
795 case FEATURE_GROUPS: return true;
796 case FEATURE_GROUPINGS: return true;
797 case FEATURE_MOD_INTRO: return true;
798 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
799 case FEATURE_COMPLETION_HAS_RULES: return true;
800 case FEATURE_GRADE_HAS_GRADE: return false;
801 case FEATURE_GRADE_OUTCOMES: return false;
802 case FEATURE_BACKUP_MOODLE2: return true;
803 case FEATURE_SHOW_DESCRIPTION: return true;
805 default: return null;
810 * Adds module specific settings to the settings block
812 * @param settings_navigation $settings The settings navigation object
813 * @param navigation_node $choicenode The node to add module settings to
815 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
818 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
820 $groupmode = groups_get_activity_groupmode($PAGE->cm);
822 groups_get_activity_group($PAGE->cm, true);
825 $choice = choice_get_choice($PAGE->cm->instance);
827 // Check if we want to include responses from inactive users.
828 $onlyactive = $choice->includeinactive ? false : true;
830 // Big function, approx 6 SQL calls per user.
831 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
834 foreach($allresponses as $optionid => $userlist) {
836 $allusers = array_merge($allusers, array_keys($userlist));
839 $responsecount = count(array_unique($allusers));
840 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
845 * Obtains the automatic completion state for this choice based on any conditions
848 * @param object $course Course
849 * @param object $cm Course-module
850 * @param int $userid User ID
851 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
852 * @return bool True if completed, false if not, $type if conditions not set.
854 function choice_get_completion_state($course, $cm, $userid, $type) {
857 // Get choice details
858 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
861 // If completion option is enabled, evaluate it and return true/false
862 if($choice->completionsubmit) {
863 return $DB->record_exists('choice_answers', array(
864 'choiceid'=>$choice->id, 'userid'=>$userid));
866 // Completion option is not enabled so just return $type
872 * Return a list of page types
873 * @param string $pagetype current page type
874 * @param stdClass $parentcontext Block's parent context
875 * @param stdClass $currentcontext Current context of block
877 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
878 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
879 return $module_pagetype;
883 * Prints choice summaries on MyMoodle Page
885 * Prints choice name, due date and attempt information on
886 * choice activities that have a deadline that has not already passed
887 * and it is available for completing.
888 * @uses CONTEXT_MODULE
889 * @param array $courses An array of course objects to get choice instances from.
890 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
892 function choice_print_overview($courses, &$htmlarray) {
893 global $USER, $DB, $OUTPUT;
895 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
898 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
903 foreach ($choices as $choice) {
904 if ($choice->timeclose != 0 // If this choice is scheduled.
905 and $choice->timeclose >= $now // And the deadline has not passed.
906 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
909 $class = (!$choice->visible) ? 'dimmed' : '';
912 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
913 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
914 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
917 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
919 // Display relevant info based on permissions.
920 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
921 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
923 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
924 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
926 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
927 // See if the user has submitted anything.
928 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
930 // User has already selected an answer, nothing to show.
933 // User has not made a selection yet.
934 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
937 // Does not have permission to do anything on this choice activity.
941 // Make sure we have something to display.
943 // Generate the containing div.
944 $str = $OUTPUT->box($str, 'choice overview');
946 if (empty($htmlarray[$choice->course]['choice'])) {
947 $htmlarray[$choice->course]['choice'] = $str;
949 $htmlarray[$choice->course]['choice'] .= $str;
959 * Get my responses on a given choice.
961 * @param stdClass $choice Choice record
962 * @return array of choice answers records
965 function choice_get_my_response($choice) {
967 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
972 * Get all the responses on a given choice.
974 * @param stdClass $choice Choice record
975 * @return array of choice answers records
978 function choice_get_all_responses($choice) {
980 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
985 * Return true if we are allowd to view the choice results.
987 * @param stdClass $choice Choice record
988 * @param rows|null $current my choice responses
989 * @param bool|null $choiceopen if the choice is open
990 * @return bool true if we can view the results, false otherwise.
993 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
995 if (is_null($choiceopen)) {
997 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1003 if (empty($current)) {
1004 $current = choice_get_my_response($choice);
1007 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1008 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1009 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1016 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1018 * @param stdClass $choice choice object
1019 * @param stdClass $course course object
1020 * @param stdClass $cm course module object
1021 * @param stdClass $context context object
1024 function choice_view($choice, $course, $cm, $context) {
1026 // Trigger course_module_viewed event.
1028 'context' => $context,
1029 'objectid' => $choice->id
1032 $event = \mod_choice\event\course_module_viewed::create($params);
1033 $event->add_record_snapshot('course_modules', $cm);
1034 $event->add_record_snapshot('course', $course);
1035 $event->add_record_snapshot('choice', $choice);
1039 $completion = new completion_info($course);
1040 $completion->set_module_viewed($cm);
1044 * Check if a choice is available for the current user.
1046 * @param stdClass $choice choice record
1047 * @return array status (available or not and possible warnings)
1049 function choice_get_availability_status($choice) {
1051 $warnings = array();
1053 if ($choice->timeclose != 0) {
1056 if ($choice->timeopen > $timenow) {
1058 $warnings['notopenyet'] = userdate($choice->timeopen);
1059 } else if ($timenow > $choice->timeclose) {
1061 $warnings['expired'] = userdate($choice->timeclose);
1064 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1066 $warnings['choicesaved'] = '';
1069 // Choice is available.
1070 return array($available, $warnings);