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) {
116 require_once($CFG->dirroot.'/mod/choice/locallib.php');
118 $choice->timemodified = time();
120 if (empty($choice->timerestrict)) {
121 $choice->timeopen = 0;
122 $choice->timeclose = 0;
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);
148 * Given an object containing all the necessary data,
149 * (defined by the form in mod_form.php) this function
150 * will update an existing instance with new data.
153 * @param object $choice
156 function choice_update_instance($choice) {
158 require_once($CFG->dirroot.'/mod/choice/locallib.php');
160 $choice->id = $choice->instance;
161 $choice->timemodified = time();
164 if (empty($choice->timerestrict)) {
165 $choice->timeopen = 0;
166 $choice->timeclose = 0;
169 //update, delete or insert answers
170 foreach ($choice->option as $key => $value) {
171 $value = trim($value);
172 $option = new stdClass();
173 $option->text = $value;
174 $option->choiceid = $choice->id;
175 if (isset($choice->limit[$key])) {
176 $option->maxanswers = $choice->limit[$key];
178 $option->timemodified = time();
179 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
180 $option->id=$choice->optionid[$key];
181 if (isset($value) && $value <> '') {
182 $DB->update_record("choice_options", $option);
184 // Remove the empty (unused) option.
185 $DB->delete_records("choice_options", array("id" => $option->id));
186 // Delete any answers associated with this option.
187 $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
190 if (isset($value) && $value <> '') {
191 $DB->insert_record("choice_options", $option);
196 // Add calendar events if necessary.
197 choice_set_events($choice);
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 * Process user submitted answers for a choice,
258 * and either updating them or saving new answers.
260 * @param int $formanswer users submitted answers.
261 * @param object $choice the selected choice.
262 * @param int $userid user identifier.
263 * @param object $course current course.
264 * @param object $cm course context.
267 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
269 require_once($CFG->libdir.'/completionlib.php');
271 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
273 if (empty($formanswer)) {
274 print_error('atleastoneoption', 'choice', $continueurl);
277 if (is_array($formanswer)) {
278 if (!$choice->allowmultiple) {
279 print_error('multiplenotallowederror', 'choice', $continueurl);
281 $formanswers = $formanswer;
283 $formanswers = array($formanswer);
286 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
287 foreach ($formanswers as $key => $val) {
288 if (!isset($options[$val])) {
289 print_error('cannotsubmit', 'choice', $continueurl);
292 // Start lock to prevent synchronous access to the same data
293 // before it's updated, if using limits.
294 if ($choice->limitanswers) {
296 $locktype = 'mod_choice_choice_user_submit_response';
297 // Limiting access to this choice.
298 $resouce = 'choiceid:' . $choice->id;
299 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
302 $choicelock = $lockfactory->get_lock($resouce, $timeout);
304 print_error('cannotsubmit', 'choice', $continueurl);
308 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
309 $context = context_module::instance($cm->id);
311 $choicesexceeded = false;
312 $countanswers = array();
313 foreach ($formanswers as $val) {
314 $countanswers[$val] = 0;
316 if($choice->limitanswers) {
317 // Find out whether groups are being used and enabled
318 if (groups_get_activity_groupmode($cm) > 0) {
319 $currentgroup = groups_get_activity_group($cm);
324 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
327 // If groups are being used, retrieve responses only for users in
331 $params['groupid'] = $currentgroup;
333 FROM {choice_answers} ca
334 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
335 WHERE optionid $insql
336 AND gm.groupid= :groupid";
338 // Groups are not used, retrieve all answers for this option ID
340 FROM {choice_answers} ca
341 WHERE optionid $insql";
344 $answers = $DB->get_records_sql($sql, $params);
346 foreach ($answers as $a) { //only return enrolled users.
347 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
348 $countanswers[$a->optionid]++;
352 foreach ($countanswers as $opt => $count) {
353 if ($count >= $choice->maxanswers[$opt]) {
354 $choicesexceeded = true;
360 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
361 if (!($choice->limitanswers && $choicesexceeded)) {
362 $answersnapshots = array();
364 // Update an existing answer.
365 $existingchoices = array();
366 foreach ($current as $c) {
367 if (in_array($c->optionid, $formanswers)) {
368 $existingchoices[] = $c->optionid;
369 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
370 $answersnapshots[] = $c;
372 $DB->delete_records('choice_answers', array('id' => $c->id));
377 foreach ($formanswers as $f) {
378 if (!in_array($f, $existingchoices)) {
379 $newanswer = new stdClass();
380 $newanswer->optionid = $f;
381 $newanswer->choiceid = $choice->id;
382 $newanswer->userid = $userid;
383 $newanswer->timemodified = time();
384 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
385 $answersnapshots[] = $newanswer;
389 // Initialised as true, meaning we updated the answer.
390 $answerupdated = true;
393 foreach ($formanswers as $answer) {
394 $newanswer = new stdClass();
395 $newanswer->choiceid = $choice->id;
396 $newanswer->userid = $userid;
397 $newanswer->optionid = $answer;
398 $newanswer->timemodified = time();
399 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
400 $answersnapshots[] = $newanswer;
403 // Update completion state
404 $completion = new completion_info($course);
405 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
406 $completion->update_state($cm, COMPLETION_COMPLETE);
409 // Initalised as false, meaning we submitted a new answer.
410 $answerupdated = false;
413 // Check to see if current choice already selected - if not display error.
414 $currentids = array_keys($current);
416 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
417 // Release lock before error.
418 $choicelock->release();
419 print_error('choicefull', 'choice', $continueurl);
424 if (isset($choicelock)) {
425 $choicelock->release();
428 // Now record completed event.
429 if (isset($answerupdated)) {
430 $eventdata = array();
431 $eventdata['context'] = $context;
432 $eventdata['objectid'] = $choice->id;
433 $eventdata['userid'] = $userid;
434 $eventdata['courseid'] = $course->id;
435 $eventdata['other'] = array();
436 $eventdata['other']['choiceid'] = $choice->id;
438 if ($answerupdated) {
439 $eventdata['other']['optionid'] = $formanswer;
440 $event = \mod_choice\event\answer_updated::create($eventdata);
442 $eventdata['other']['optionid'] = $formanswers;
443 $event = \mod_choice\event\answer_submitted::create($eventdata);
445 $event->add_record_snapshot('course', $course);
446 $event->add_record_snapshot('course_modules', $cm);
447 $event->add_record_snapshot('choice', $choice);
448 foreach ($answersnapshots as $record) {
449 $event->add_record_snapshot('choice_answers', $record);
458 * @return void Output is echo'd
460 function choice_show_reportlink($user, $cm) {
461 $userschosen = array();
462 foreach($user as $optionid => $userlist) {
464 $userschosen = array_merge($userschosen, array_keys($userlist));
467 $responsecount = count(array_unique($userschosen));
469 echo '<div class="reportlink">';
470 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
476 * @param object $choice
477 * @param object $course
478 * @param object $coursemodule
479 * @param array $allresponses
481 * * @param bool $allresponses
484 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
487 $display = clone($choice);
488 $display->coursemoduleid = $cm->id;
489 $display->courseid = $course->id;
491 //overwrite options value;
492 $display->options = array();
494 foreach ($choice->option as $optionid => $optiontext) {
495 $display->options[$optionid] = new stdClass;
496 $display->options[$optionid]->text = $optiontext;
497 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
499 if (array_key_exists($optionid, $allresponses)) {
500 $display->options[$optionid]->user = $allresponses[$optionid];
501 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
504 unset($display->option);
505 unset($display->maxanswers);
507 $display->numberofuser = count(array_unique($allusers));
508 $context = context_module::instance($cm->id);
509 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
510 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
511 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
513 if (empty($allresponses)) {
514 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
523 * @param array $attemptids
524 * @param object $choice Choice main table row
525 * @param object $cm Course-module object
526 * @param object $course Course object
529 function choice_delete_responses($attemptids, $choice, $cm, $course) {
530 global $DB, $CFG, $USER;
531 require_once($CFG->libdir.'/completionlib.php');
533 if(!is_array($attemptids) || empty($attemptids)) {
537 foreach($attemptids as $num => $attemptid) {
538 if(empty($attemptid)) {
539 unset($attemptids[$num]);
543 $context = context_module::instance($cm->id);
544 $completion = new completion_info($course);
545 foreach($attemptids as $attemptid) {
546 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
547 // Trigger the event answer deleted.
548 $eventdata = array();
549 $eventdata['objectid'] = $todelete->id;
550 $eventdata['context'] = $context;
551 $eventdata['userid'] = $USER->id;
552 $eventdata['courseid'] = $course->id;
553 $eventdata['relateduserid'] = $todelete->userid;
554 $eventdata['other'] = array();
555 $eventdata['other']['choiceid'] = $choice->id;
556 $eventdata['other']['optionid'] = $todelete->optionid;
557 $event = \mod_choice\event\answer_deleted::create($eventdata);
558 $event->add_record_snapshot('course', $course);
559 $event->add_record_snapshot('course_modules', $cm);
560 $event->add_record_snapshot('choice', $choice);
561 $event->add_record_snapshot('choice_answers', $todelete);
564 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
568 // Update completion state.
569 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
570 $completion->update_state($cm, COMPLETION_INCOMPLETE);
578 * Given an ID of an instance of this module,
579 * this function will permanently delete the instance
580 * and any data that depends on it.
586 function choice_delete_instance($id) {
589 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
595 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
599 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
603 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
606 // Remove old calendar events.
607 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
615 * Returns text string which is the answer that matches the id
618 * @param object $choice
622 function choice_get_option_text($choice, $id) {
625 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
626 return $result->text;
628 return get_string("notanswered", "choice");
633 * Gets a full choice record
636 * @param int $choiceid
637 * @return object|bool The choice or false
639 function choice_get_choice($choiceid) {
642 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
643 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
644 foreach ($options as $option) {
645 $choice->option[$option->id] = $option->text;
646 $choice->maxanswers[$option->id] = $option->maxanswers;
655 * List the actions that correspond to a view of this module.
656 * This is used by the participation report.
658 * Note: This is not used by new logging system. Event with
659 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
660 * be considered as view action.
664 function choice_get_view_actions() {
665 return array('view','view all','report');
669 * List the actions that correspond to a post of this module.
670 * This is used by the participation report.
672 * Note: This is not used by new logging system. Event with
673 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
674 * will be considered as post action.
678 function choice_get_post_actions() {
679 return array('choose','choose again');
684 * Implementation of the function for printing the form elements that control
685 * whether the course reset functionality affects the choice.
687 * @param object $mform form passed by reference
689 function choice_reset_course_form_definition(&$mform) {
690 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
691 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
695 * Course reset form defaults.
699 function choice_reset_course_form_defaults($course) {
700 return array('reset_choice'=>1);
704 * Actual implementation of the reset course functionality, delete all the
705 * choice responses for course $data->courseid.
709 * @param object $data the data submitted from the reset course.
710 * @return array status array
712 function choice_reset_userdata($data) {
715 $componentstr = get_string('modulenameplural', 'choice');
718 if (!empty($data->reset_choice)) {
719 $choicessql = "SELECT ch.id
723 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
724 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
727 /// updating dates - shift may be negative too
728 if ($data->timeshift) {
729 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
730 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
740 * @uses CONTEXT_MODULE
741 * @param object $choice
743 * @param int $groupmode
744 * @param bool $onlyactive Whether to get response data for active users only.
747 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
748 global $CFG, $USER, $DB;
750 $context = context_module::instance($cm->id);
752 /// Get the current group
753 if ($groupmode > 0) {
754 $currentgroup = groups_get_activity_group($cm);
759 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
760 $allresponses = array();
762 /// First get all the users who have access here
763 /// To start with we assume they are all "unanswered" then move them later
764 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
765 user_picture::fields('u', array('idnumber')), null, 0, 0, $onlyactive);
767 /// Get all the recorded responses for this choice
768 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
770 /// Use the responses to move users into the correct column
773 $answeredusers = array();
774 foreach ($rawresponses as $response) {
775 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
776 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
777 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
778 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
779 $answeredusers[] = $response->userid;
782 foreach ($answeredusers as $answereduser) {
783 unset($allresponses[0][$answereduser]);
786 return $allresponses;
790 * Returns all other caps used in module
794 function choice_get_extra_capabilities() {
795 return array('moodle/site:accessallgroups');
799 * @uses FEATURE_GROUPS
800 * @uses FEATURE_GROUPINGS
801 * @uses FEATURE_MOD_INTRO
802 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
803 * @uses FEATURE_GRADE_HAS_GRADE
804 * @uses FEATURE_GRADE_OUTCOMES
805 * @param string $feature FEATURE_xx constant for requested feature
806 * @return mixed True if module supports feature, null if doesn't know
808 function choice_supports($feature) {
810 case FEATURE_GROUPS: return true;
811 case FEATURE_GROUPINGS: return true;
812 case FEATURE_MOD_INTRO: return true;
813 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
814 case FEATURE_COMPLETION_HAS_RULES: return true;
815 case FEATURE_GRADE_HAS_GRADE: return false;
816 case FEATURE_GRADE_OUTCOMES: return false;
817 case FEATURE_BACKUP_MOODLE2: return true;
818 case FEATURE_SHOW_DESCRIPTION: return true;
820 default: return null;
825 * Adds module specific settings to the settings block
827 * @param settings_navigation $settings The settings navigation object
828 * @param navigation_node $choicenode The node to add module settings to
830 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
833 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
835 $groupmode = groups_get_activity_groupmode($PAGE->cm);
837 groups_get_activity_group($PAGE->cm, true);
840 $choice = choice_get_choice($PAGE->cm->instance);
842 // Check if we want to include responses from inactive users.
843 $onlyactive = $choice->includeinactive ? false : true;
845 // Big function, approx 6 SQL calls per user.
846 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
849 foreach($allresponses as $optionid => $userlist) {
851 $allusers = array_merge($allusers, array_keys($userlist));
854 $responsecount = count(array_unique($allusers));
855 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
860 * Obtains the automatic completion state for this choice based on any conditions
863 * @param object $course Course
864 * @param object $cm Course-module
865 * @param int $userid User ID
866 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
867 * @return bool True if completed, false if not, $type if conditions not set.
869 function choice_get_completion_state($course, $cm, $userid, $type) {
872 // Get choice details
873 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
876 // If completion option is enabled, evaluate it and return true/false
877 if($choice->completionsubmit) {
878 return $DB->record_exists('choice_answers', array(
879 'choiceid'=>$choice->id, 'userid'=>$userid));
881 // Completion option is not enabled so just return $type
887 * Return a list of page types
888 * @param string $pagetype current page type
889 * @param stdClass $parentcontext Block's parent context
890 * @param stdClass $currentcontext Current context of block
892 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
893 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
894 return $module_pagetype;
898 * Prints choice summaries on MyMoodle Page
900 * Prints choice name, due date and attempt information on
901 * choice activities that have a deadline that has not already passed
902 * and it is available for completing.
903 * @uses CONTEXT_MODULE
904 * @param array $courses An array of course objects to get choice instances from.
905 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
907 function choice_print_overview($courses, &$htmlarray) {
908 global $USER, $DB, $OUTPUT;
910 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
913 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
918 foreach ($choices as $choice) {
919 if ($choice->timeclose != 0 // If this choice is scheduled.
920 and $choice->timeclose >= $now // And the deadline has not passed.
921 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
924 $class = (!$choice->visible) ? 'dimmed' : '';
927 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
928 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
929 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
932 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
934 // Display relevant info based on permissions.
935 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
936 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
938 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
939 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
941 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
942 // See if the user has submitted anything.
943 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
945 // User has already selected an answer, nothing to show.
948 // User has not made a selection yet.
949 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
952 // Does not have permission to do anything on this choice activity.
956 // Make sure we have something to display.
958 // Generate the containing div.
959 $str = $OUTPUT->box($str, 'choice overview');
961 if (empty($htmlarray[$choice->course]['choice'])) {
962 $htmlarray[$choice->course]['choice'] = $str;
964 $htmlarray[$choice->course]['choice'] .= $str;
974 * Get my responses on a given choice.
976 * @param stdClass $choice Choice record
977 * @return array of choice answers records
980 function choice_get_my_response($choice) {
982 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
987 * Get all the responses on a given choice.
989 * @param stdClass $choice Choice record
990 * @return array of choice answers records
993 function choice_get_all_responses($choice) {
995 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
1000 * Return true if we are allowd to view the choice results.
1002 * @param stdClass $choice Choice record
1003 * @param rows|null $current my choice responses
1004 * @param bool|null $choiceopen if the choice is open
1005 * @return bool true if we can view the results, false otherwise.
1008 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1010 if (is_null($choiceopen)) {
1012 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1013 $choiceopen = false;
1018 if (empty($current)) {
1019 $current = choice_get_my_response($choice);
1022 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1023 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1024 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1031 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1033 * @param stdClass $choice choice object
1034 * @param stdClass $course course object
1035 * @param stdClass $cm course module object
1036 * @param stdClass $context context object
1039 function choice_view($choice, $course, $cm, $context) {
1041 // Trigger course_module_viewed event.
1043 'context' => $context,
1044 'objectid' => $choice->id
1047 $event = \mod_choice\event\course_module_viewed::create($params);
1048 $event->add_record_snapshot('course_modules', $cm);
1049 $event->add_record_snapshot('course', $course);
1050 $event->add_record_snapshot('choice', $choice);
1054 $completion = new completion_info($course);
1055 $completion->set_module_viewed($cm);
1059 * Check if a choice is available for the current user.
1061 * @param stdClass $choice choice record
1062 * @return array status (available or not and possible warnings)
1064 function choice_get_availability_status($choice) {
1066 $warnings = array();
1068 if ($choice->timeclose != 0) {
1071 if ($choice->timeopen > $timenow) {
1073 $warnings['notopenyet'] = userdate($choice->timeopen);
1074 } else if ($timenow > $choice->timeclose) {
1076 $warnings['expired'] = userdate($choice->timeclose);
1079 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1081 $warnings['choicesaved'] = '';
1084 // Choice is available.
1085 return array($available, $warnings);
1089 * This standard function will check all instances of this module
1090 * and make sure there are up-to-date events created for each of them.
1091 * If courseid = 0, then every chat event in the site is checked, else
1092 * only chat events belonging to the course specified are checked.
1093 * This function is used, in its new format, by restore_refresh_events()
1095 * @param int $courseid
1098 function choice_refresh_events($courseid = 0) {
1100 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1103 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1107 if (! $choices = $DB->get_records("choice")) {
1112 foreach ($choices as $choice) {
1113 choice_set_events($choice);