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);
183 } else { //empty old option - needs to be deleted.
184 $DB->delete_records("choice_options", array("id"=>$option->id));
187 if (isset($value) && $value <> '') {
188 $DB->insert_record("choice_options", $option);
193 // Add calendar events if necessary.
194 choice_set_events($choice);
196 return $DB->update_record('choice', $choice);
202 * @param object $choice
203 * @param object $user
204 * @param object $coursemodule
205 * @param array $allresponses
208 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
211 $cdisplay = array('options'=>array());
213 $cdisplay['limitanswers'] = true;
214 $context = context_module::instance($coursemodule->id);
216 foreach ($choice->option as $optionid => $text) {
217 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
218 $option = new stdClass;
219 $option->attributes = new stdClass;
220 $option->attributes->value = $optionid;
221 $option->text = format_string($text);
222 $option->maxanswers = $choice->maxanswers[$optionid];
223 $option->displaylayout = $choice->display;
225 if (isset($allresponses[$optionid])) {
226 $option->countanswers = count($allresponses[$optionid]);
228 $option->countanswers = 0;
230 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
231 $option->attributes->checked = true;
233 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
234 $option->attributes->disabled = true;
236 $cdisplay['options'][] = $option;
240 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
242 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
243 $cdisplay['allowupdate'] = true;
246 if ($choice->showpreview && $choice->timeopen > time()) {
247 $cdisplay['previewonly'] = true;
254 * Process user submitted answers for a choice,
255 * and either updating them or saving new answers.
257 * @param int $formanswer users submitted answers.
258 * @param object $choice the selected choice.
259 * @param int $userid user identifier.
260 * @param object $course current course.
261 * @param object $cm course context.
264 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
266 require_once($CFG->libdir.'/completionlib.php');
268 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
270 if (empty($formanswer)) {
271 print_error('atleastoneoption', 'choice', $continueurl);
274 if (is_array($formanswer)) {
275 if (!$choice->allowmultiple) {
276 print_error('multiplenotallowederror', 'choice', $continueurl);
278 $formanswers = $formanswer;
280 $formanswers = array($formanswer);
283 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
284 foreach ($formanswers as $key => $val) {
285 if (!isset($options[$val])) {
286 print_error('cannotsubmit', 'choice', $continueurl);
289 // Start lock to prevent synchronous access to the same data
290 // before it's updated, if using limits.
291 if ($choice->limitanswers) {
293 $locktype = 'mod_choice_choice_user_submit_response';
294 // Limiting access to this choice.
295 $resouce = 'choiceid:' . $choice->id;
296 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
299 $choicelock = $lockfactory->get_lock($resouce, $timeout);
301 print_error('cannotsubmit', 'choice', $continueurl);
305 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
306 $context = context_module::instance($cm->id);
308 $choicesexceeded = false;
309 $countanswers = array();
310 foreach ($formanswers as $val) {
311 $countanswers[$val] = 0;
313 if($choice->limitanswers) {
314 // Find out whether groups are being used and enabled
315 if (groups_get_activity_groupmode($cm) > 0) {
316 $currentgroup = groups_get_activity_group($cm);
321 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
324 // If groups are being used, retrieve responses only for users in
328 $params['groupid'] = $currentgroup;
330 FROM {choice_answers} ca
331 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
332 WHERE optionid $insql
333 AND gm.groupid= :groupid";
335 // Groups are not used, retrieve all answers for this option ID
337 FROM {choice_answers} ca
338 WHERE optionid $insql";
341 $answers = $DB->get_records_sql($sql, $params);
343 foreach ($answers as $a) { //only return enrolled users.
344 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
345 $countanswers[$a->optionid]++;
349 foreach ($countanswers as $opt => $count) {
350 if ($count >= $choice->maxanswers[$opt]) {
351 $choicesexceeded = true;
357 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
358 if (!($choice->limitanswers && $choicesexceeded)) {
359 $answersnapshots = array();
361 // Update an existing answer.
362 $existingchoices = array();
363 foreach ($current as $c) {
364 if (in_array($c->optionid, $formanswers)) {
365 $existingchoices[] = $c->optionid;
366 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
367 $answersnapshots[] = $c;
369 $DB->delete_records('choice_answers', array('id' => $c->id));
374 foreach ($formanswers as $f) {
375 if (!in_array($f, $existingchoices)) {
376 $newanswer = new stdClass();
377 $newanswer->optionid = $f;
378 $newanswer->choiceid = $choice->id;
379 $newanswer->userid = $userid;
380 $newanswer->timemodified = time();
381 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
382 $answersnapshots[] = $newanswer;
386 // Initialised as true, meaning we updated the answer.
387 $answerupdated = true;
390 foreach ($formanswers as $answer) {
391 $newanswer = new stdClass();
392 $newanswer->choiceid = $choice->id;
393 $newanswer->userid = $userid;
394 $newanswer->optionid = $answer;
395 $newanswer->timemodified = time();
396 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
397 $answersnapshots[] = $newanswer;
400 // Update completion state
401 $completion = new completion_info($course);
402 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
403 $completion->update_state($cm, COMPLETION_COMPLETE);
406 // Initalised as false, meaning we submitted a new answer.
407 $answerupdated = false;
410 // Check to see if current choice already selected - if not display error.
411 $currentids = array_keys($current);
413 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
414 // Release lock before error.
415 $choicelock->release();
416 print_error('choicefull', 'choice', $continueurl);
421 if (isset($choicelock)) {
422 $choicelock->release();
425 // Now record completed event.
426 if (isset($answerupdated)) {
427 $eventdata = array();
428 $eventdata['context'] = $context;
429 $eventdata['objectid'] = $choice->id;
430 $eventdata['userid'] = $userid;
431 $eventdata['courseid'] = $course->id;
432 $eventdata['other'] = array();
433 $eventdata['other']['choiceid'] = $choice->id;
435 if ($answerupdated) {
436 $eventdata['other']['optionid'] = $formanswer;
437 $event = \mod_choice\event\answer_updated::create($eventdata);
439 $eventdata['other']['optionid'] = $formanswers;
440 $event = \mod_choice\event\answer_submitted::create($eventdata);
442 $event->add_record_snapshot('course', $course);
443 $event->add_record_snapshot('course_modules', $cm);
444 $event->add_record_snapshot('choice', $choice);
445 foreach ($answersnapshots as $record) {
446 $event->add_record_snapshot('choice_answers', $record);
455 * @return void Output is echo'd
457 function choice_show_reportlink($user, $cm) {
458 $userschosen = array();
459 foreach($user as $optionid => $userlist) {
461 $userschosen = array_merge($userschosen, array_keys($userlist));
464 $responsecount = count(array_unique($userschosen));
466 echo '<div class="reportlink">';
467 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
473 * @param object $choice
474 * @param object $course
475 * @param object $coursemodule
476 * @param array $allresponses
478 * * @param bool $allresponses
481 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
484 $display = clone($choice);
485 $display->coursemoduleid = $cm->id;
486 $display->courseid = $course->id;
488 //overwrite options value;
489 $display->options = array();
491 foreach ($choice->option as $optionid => $optiontext) {
492 $display->options[$optionid] = new stdClass;
493 $display->options[$optionid]->text = $optiontext;
494 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
496 if (array_key_exists($optionid, $allresponses)) {
497 $display->options[$optionid]->user = $allresponses[$optionid];
498 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
501 unset($display->option);
502 unset($display->maxanswers);
504 $display->numberofuser = count(array_unique($allusers));
505 $context = context_module::instance($cm->id);
506 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
507 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
508 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
510 if (empty($allresponses)) {
511 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
520 * @param array $attemptids
521 * @param object $choice Choice main table row
522 * @param object $cm Course-module object
523 * @param object $course Course object
526 function choice_delete_responses($attemptids, $choice, $cm, $course) {
527 global $DB, $CFG, $USER;
528 require_once($CFG->libdir.'/completionlib.php');
530 if(!is_array($attemptids) || empty($attemptids)) {
534 foreach($attemptids as $num => $attemptid) {
535 if(empty($attemptid)) {
536 unset($attemptids[$num]);
540 $context = context_module::instance($cm->id);
541 $completion = new completion_info($course);
542 foreach($attemptids as $attemptid) {
543 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
544 // Trigger the event answer deleted.
545 $eventdata = array();
546 $eventdata['objectid'] = $todelete->id;
547 $eventdata['context'] = $context;
548 $eventdata['userid'] = $USER->id;
549 $eventdata['courseid'] = $course->id;
550 $eventdata['relateduserid'] = $todelete->userid;
551 $eventdata['other'] = array();
552 $eventdata['other']['choiceid'] = $choice->id;
553 $eventdata['other']['optionid'] = $todelete->optionid;
554 $event = \mod_choice\event\answer_deleted::create($eventdata);
555 $event->add_record_snapshot('course', $course);
556 $event->add_record_snapshot('course_modules', $cm);
557 $event->add_record_snapshot('choice', $choice);
558 $event->add_record_snapshot('choice_answers', $todelete);
561 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
565 // Update completion state.
566 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
567 $completion->update_state($cm, COMPLETION_INCOMPLETE);
575 * Given an ID of an instance of this module,
576 * this function will permanently delete the instance
577 * and any data that depends on it.
583 function choice_delete_instance($id) {
586 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
592 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
596 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
600 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
603 // Remove old calendar events.
604 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
612 * Returns text string which is the answer that matches the id
615 * @param object $choice
619 function choice_get_option_text($choice, $id) {
622 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
623 return $result->text;
625 return get_string("notanswered", "choice");
630 * Gets a full choice record
633 * @param int $choiceid
634 * @return object|bool The choice or false
636 function choice_get_choice($choiceid) {
639 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
640 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
641 foreach ($options as $option) {
642 $choice->option[$option->id] = $option->text;
643 $choice->maxanswers[$option->id] = $option->maxanswers;
652 * List the actions that correspond to a view of this module.
653 * This is used by the participation report.
655 * Note: This is not used by new logging system. Event with
656 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
657 * be considered as view action.
661 function choice_get_view_actions() {
662 return array('view','view all','report');
666 * List the actions that correspond to a post of this module.
667 * This is used by the participation report.
669 * Note: This is not used by new logging system. Event with
670 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
671 * will be considered as post action.
675 function choice_get_post_actions() {
676 return array('choose','choose again');
681 * Implementation of the function for printing the form elements that control
682 * whether the course reset functionality affects the choice.
684 * @param object $mform form passed by reference
686 function choice_reset_course_form_definition(&$mform) {
687 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
688 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
692 * Course reset form defaults.
696 function choice_reset_course_form_defaults($course) {
697 return array('reset_choice'=>1);
701 * Actual implementation of the reset course functionality, delete all the
702 * choice responses for course $data->courseid.
706 * @param object $data the data submitted from the reset course.
707 * @return array status array
709 function choice_reset_userdata($data) {
712 $componentstr = get_string('modulenameplural', 'choice');
715 if (!empty($data->reset_choice)) {
716 $choicessql = "SELECT ch.id
720 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
721 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
724 /// updating dates - shift may be negative too
725 if ($data->timeshift) {
726 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
727 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
737 * @uses CONTEXT_MODULE
738 * @param object $choice
740 * @param int $groupmode
741 * @param bool $onlyactive Whether to get response data for active users only.
744 function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
745 global $CFG, $USER, $DB;
747 $context = context_module::instance($cm->id);
749 /// Get the current group
750 if ($groupmode > 0) {
751 $currentgroup = groups_get_activity_group($cm);
756 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
757 $allresponses = array();
759 /// First get all the users who have access here
760 /// To start with we assume they are all "unanswered" then move them later
761 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
762 user_picture::fields('u', array('idnumber')), null, 0, 0, $onlyactive);
764 /// Get all the recorded responses for this choice
765 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
767 /// Use the responses to move users into the correct column
770 $answeredusers = array();
771 foreach ($rawresponses as $response) {
772 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
773 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
774 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
775 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
776 $answeredusers[] = $response->userid;
779 foreach ($answeredusers as $answereduser) {
780 unset($allresponses[0][$answereduser]);
783 return $allresponses;
787 * Returns all other caps used in module
791 function choice_get_extra_capabilities() {
792 return array('moodle/site:accessallgroups');
796 * @uses FEATURE_GROUPS
797 * @uses FEATURE_GROUPINGS
798 * @uses FEATURE_MOD_INTRO
799 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
800 * @uses FEATURE_GRADE_HAS_GRADE
801 * @uses FEATURE_GRADE_OUTCOMES
802 * @param string $feature FEATURE_xx constant for requested feature
803 * @return mixed True if module supports feature, null if doesn't know
805 function choice_supports($feature) {
807 case FEATURE_GROUPS: return true;
808 case FEATURE_GROUPINGS: return true;
809 case FEATURE_MOD_INTRO: return true;
810 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
811 case FEATURE_COMPLETION_HAS_RULES: return true;
812 case FEATURE_GRADE_HAS_GRADE: return false;
813 case FEATURE_GRADE_OUTCOMES: return false;
814 case FEATURE_BACKUP_MOODLE2: return true;
815 case FEATURE_SHOW_DESCRIPTION: return true;
817 default: return null;
822 * Adds module specific settings to the settings block
824 * @param settings_navigation $settings The settings navigation object
825 * @param navigation_node $choicenode The node to add module settings to
827 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
830 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
832 $groupmode = groups_get_activity_groupmode($PAGE->cm);
834 groups_get_activity_group($PAGE->cm, true);
837 $choice = choice_get_choice($PAGE->cm->instance);
839 // Check if we want to include responses from inactive users.
840 $onlyactive = $choice->includeinactive ? false : true;
842 // Big function, approx 6 SQL calls per user.
843 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
846 foreach($allresponses as $optionid => $userlist) {
848 $allusers = array_merge($allusers, array_keys($userlist));
851 $responsecount = count(array_unique($allusers));
852 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
857 * Obtains the automatic completion state for this choice based on any conditions
860 * @param object $course Course
861 * @param object $cm Course-module
862 * @param int $userid User ID
863 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
864 * @return bool True if completed, false if not, $type if conditions not set.
866 function choice_get_completion_state($course, $cm, $userid, $type) {
869 // Get choice details
870 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
873 // If completion option is enabled, evaluate it and return true/false
874 if($choice->completionsubmit) {
875 return $DB->record_exists('choice_answers', array(
876 'choiceid'=>$choice->id, 'userid'=>$userid));
878 // Completion option is not enabled so just return $type
884 * Return a list of page types
885 * @param string $pagetype current page type
886 * @param stdClass $parentcontext Block's parent context
887 * @param stdClass $currentcontext Current context of block
889 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
890 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
891 return $module_pagetype;
895 * Prints choice summaries on MyMoodle Page
897 * Prints choice name, due date and attempt information on
898 * choice activities that have a deadline that has not already passed
899 * and it is available for completing.
900 * @uses CONTEXT_MODULE
901 * @param array $courses An array of course objects to get choice instances from.
902 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
904 function choice_print_overview($courses, &$htmlarray) {
905 global $USER, $DB, $OUTPUT;
907 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
910 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
915 foreach ($choices as $choice) {
916 if ($choice->timeclose != 0 // If this choice is scheduled.
917 and $choice->timeclose >= $now // And the deadline has not passed.
918 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
921 $class = (!$choice->visible) ? 'dimmed' : '';
924 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
925 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
926 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
929 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
931 // Display relevant info based on permissions.
932 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
933 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
935 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
936 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
938 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
939 // See if the user has submitted anything.
940 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
942 // User has already selected an answer, nothing to show.
945 // User has not made a selection yet.
946 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
949 // Does not have permission to do anything on this choice activity.
953 // Make sure we have something to display.
955 // Generate the containing div.
956 $str = $OUTPUT->box($str, 'choice overview');
958 if (empty($htmlarray[$choice->course]['choice'])) {
959 $htmlarray[$choice->course]['choice'] = $str;
961 $htmlarray[$choice->course]['choice'] .= $str;
971 * Get my responses on a given choice.
973 * @param stdClass $choice Choice record
974 * @return array of choice answers records
977 function choice_get_my_response($choice) {
979 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
984 * Get all the responses on a given choice.
986 * @param stdClass $choice Choice record
987 * @return array of choice answers records
990 function choice_get_all_responses($choice) {
992 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
997 * Return true if we are allowd to view the choice results.
999 * @param stdClass $choice Choice record
1000 * @param rows|null $current my choice responses
1001 * @param bool|null $choiceopen if the choice is open
1002 * @return bool true if we can view the results, false otherwise.
1005 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1007 if (is_null($choiceopen)) {
1009 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1010 $choiceopen = false;
1015 if (empty($current)) {
1016 $current = choice_get_my_response($choice);
1019 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1020 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1021 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1028 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1030 * @param stdClass $choice choice object
1031 * @param stdClass $course course object
1032 * @param stdClass $cm course module object
1033 * @param stdClass $context context object
1036 function choice_view($choice, $course, $cm, $context) {
1038 // Trigger course_module_viewed event.
1040 'context' => $context,
1041 'objectid' => $choice->id
1044 $event = \mod_choice\event\course_module_viewed::create($params);
1045 $event->add_record_snapshot('course_modules', $cm);
1046 $event->add_record_snapshot('course', $course);
1047 $event->add_record_snapshot('choice', $choice);
1051 $completion = new completion_info($course);
1052 $completion->set_module_viewed($cm);
1056 * Check if a choice is available for the current user.
1058 * @param stdClass $choice choice record
1059 * @return array status (available or not and possible warnings)
1061 function choice_get_availability_status($choice) {
1063 $warnings = array();
1065 if ($choice->timeclose != 0) {
1068 if ($choice->timeopen > $timenow) {
1070 $warnings['notopenyet'] = userdate($choice->timeopen);
1071 } else if ($timenow > $choice->timeclose) {
1073 $warnings['expired'] = userdate($choice->timeclose);
1076 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1078 $warnings['choicesaved'] = '';
1081 // Choice is available.
1082 return array($available, $warnings);
1086 * This standard function will check all instances of this module
1087 * and make sure there are up-to-date events created for each of them.
1088 * If courseid = 0, then every chat event in the site is checked, else
1089 * only chat events belonging to the course specified are checked.
1090 * This function is used, in its new format, by restore_refresh_events()
1092 * @param int $courseid
1095 function choice_refresh_events($courseid = 0) {
1097 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1100 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1104 if (! $choices = $DB->get_records("choice")) {
1109 foreach ($choices as $choice) {
1110 choice_set_events($choice);