Merge branch 'MDL-55136_dataobject' of git://github.com/davosmith/moodle
[moodle.git] / mod / choice / lib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * @package   mod_choice
20  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
21  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22  */
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 /////////////////////////////////////////////////////////
62 /**
63  * @global object
64  * @param object $course
65  * @param object $user
66  * @param object $mod
67  * @param object $choice
68  * @return object|null
69  */
70 function choice_user_outline($course, $user, $mod, $choice) {
71     global $DB;
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;
76         return $result;
77     }
78     return NULL;
79 }
81 /**
82  * Callback for the "Complete" report - prints the activity summary for the given user
83  *
84  * @param object $course
85  * @param object $user
86  * @param object $mod
87  * @param object $choice
88  */
89 function choice_user_complete($course, $user, $mod, $choice) {
90     global $DB;
91     if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
92         $info = [];
93         foreach ($answers as $answer) {
94             $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
95         }
96         core_collator::asort($info);
97         echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
98                 get_string("updated", '', userdate($answer->timemodified));
99     } else {
100         print_string("notanswered", "choice");
101     }
104 /**
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.
109  *
110  * @global object
111  * @param object $choice
112  * @return int
113  */
114 function choice_add_instance($choice) {
115     global $DB;
117     $choice->timemodified = time();
119     if (empty($choice->timerestrict)) {
120         $choice->timeopen = 0;
121         $choice->timeclose = 0;
122     }
124     //insert answers
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];
134             }
135             $option->timemodified = time();
136             $DB->insert_record("choice_options", $option);
137         }
138     }
140     return $choice->id;
143 /**
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.
147  *
148  * @global object
149  * @param object $choice
150  * @return bool
151  */
152 function choice_update_instance($choice) {
153     global $DB;
155     $choice->id = $choice->instance;
156     $choice->timemodified = time();
159     if (empty($choice->timerestrict)) {
160         $choice->timeopen = 0;
161         $choice->timeclose = 0;
162     }
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];
172         }
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));
180             }
181         } else {
182             if (isset($value) && $value <> '') {
183                 $DB->insert_record("choice_options", $option);
184             }
185         }
186     }
188     return $DB->update_record('choice', $choice);
192 /**
193  * @global object
194  * @param object $choice
195  * @param object $user
196  * @param object $coursemodule
197  * @param array $allresponses
198  * @return array
199  */
200 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
201     global $DB;
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]);
219             } else {
220                 $option->countanswers = 0;
221             }
222             if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
223                 $option->attributes->checked = true;
224             }
225             if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
226                 $option->attributes->disabled = true;
227             }
228             $cdisplay['options'][] = $option;
229         }
230     }
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;
236     }
238     if ($choice->showpreview && $choice->timeopen > time()) {
239         $cdisplay['previewonly'] = true;
240     }
242     return $cdisplay;
245 /**
246  * Process user submitted answers for a choice,
247  * and either updating them or saving new answers.
248  *
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.
254  * @return void
255  */
256 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
257     global $DB, $CFG;
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);
264     }
266     if (is_array($formanswer)) {
267         if (!$choice->allowmultiple) {
268             print_error('multiplenotallowederror', 'choice', $continueurl);
269         }
270         $formanswers = $formanswer;
271     } else {
272         $formanswers = array($formanswer);
273     }
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);
279         }
280     }
281     // Start lock to prevent synchronous access to the same data
282     // before it's updated, if using limits.
283     if ($choice->limitanswers) {
284         $timeout = 10;
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);
290         // Opening the lock.
291         $choicelock = $lockfactory->get_lock($resouce, $timeout);
292         if (!$choicelock) {
293             print_error('cannotsubmit', 'choice', $continueurl);
294         }
295     }
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;
304     }
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);
309         } else {
310             $currentgroup = 0;
311         }
313         list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
315         if($currentgroup) {
316             // If groups are being used, retrieve responses only for users in
317             // current group
318             global $CFG;
320             $params['groupid'] = $currentgroup;
321             $sql = "SELECT ca.*
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";
326         } else {
327             // Groups are not used, retrieve all answers for this option ID
328             $sql = "SELECT ca.*
329                       FROM {choice_answers} ca
330                      WHERE optionid $insql";
331         }
333         $answers = $DB->get_records_sql($sql, $params);
334         if ($answers) {
335             foreach ($answers as $a) { //only return enrolled users.
336                 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
337                     $countanswers[$a->optionid]++;
338                 }
339             }
340         }
341         foreach ($countanswers as $opt => $count) {
342             if ($count >= $choice->maxanswers[$opt]) {
343                 $choicesexceeded = true;
344                 break;
345             }
346         }
347     }
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();
352         if ($current) {
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;
360                 } else {
361                     $DB->delete_records('choice_answers', array('id' => $c->id));
362                 }
363             }
365             // Add new ones.
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;
375                 }
376             }
378             // Initialised as true, meaning we updated the answer.
379             $answerupdated = true;
380         } else {
381             // Add new answer.
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;
390             }
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);
396             }
398             // Initalised as false, meaning we submitted a new answer.
399             $answerupdated = false;
400         }
401     } else {
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);
409         }
410     }
412     // Release lock.
413     if (isset($choicelock)) {
414         $choicelock->release();
415     }
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);
430         } else {
431             $eventdata['other']['optionid'] = $formanswers;
432             $event = \mod_choice\event\answer_submitted::create($eventdata);
433         }
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);
439         }
440         $event->trigger();
441     }
444 /**
445  * @param array $user
446  * @param object $cm
447  * @return void Output is echo'd
448  */
449 function choice_show_reportlink($user, $cm) {
450     $userschosen = array();
451     foreach($user as $optionid => $userlist) {
452         if ($optionid) {
453             $userschosen = array_merge($userschosen, array_keys($userlist));
454         }
455     }
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>";
460     echo '</div>';
463 /**
464  * @global object
465  * @param object $choice
466  * @param object $course
467  * @param object $coursemodule
468  * @param array $allresponses
470  *  * @param bool $allresponses
471  * @return object
472  */
473 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
474     global $OUTPUT;
476     $display = clone($choice);
477     $display->coursemoduleid = $cm->id;
478     $display->courseid = $course->id;
480     //overwrite options value;
481     $display->options = array();
482     $allusers = [];
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]));
491         }
492     }
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);
504         return false;
505     }
507     return $display;
510 /**
511  * @global object
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
516  * @return bool
517  */
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)) {
523         return false;
524     }
526     foreach($attemptids as $num => $attemptid) {
527         if(empty($attemptid)) {
528             unset($attemptids[$num]);
529         }
530     }
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);
551             $event->trigger();
553             $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
554         }
555     }
557     // Update completion state.
558     if ($completion->is_enabled($cm) && $choice->completionsubmit) {
559         $completion->update_state($cm, COMPLETION_INCOMPLETE);
560     }
562     return true;
566 /**
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.
570  *
571  * @global object
572  * @param int $id
573  * @return bool
574  */
575 function choice_delete_instance($id) {
576     global $DB;
578     if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
579         return false;
580     }
582     $result = true;
584     if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
585         $result = false;
586     }
588     if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
589         $result = false;
590     }
592     if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
593         $result = false;
594     }
596     return $result;
599 /**
600  * Returns text string which is the answer that matches the id
601  *
602  * @global object
603  * @param object $choice
604  * @param int $id
605  * @return string
606  */
607 function choice_get_option_text($choice, $id) {
608     global $DB;
610     if ($result = $DB->get_record("choice_options", array("id" => $id))) {
611         return $result->text;
612     } else {
613         return get_string("notanswered", "choice");
614     }
617 /**
618  * Gets a full choice record
619  *
620  * @global object
621  * @param int $choiceid
622  * @return object|bool The choice or false
623  */
624 function choice_get_choice($choiceid) {
625     global $DB;
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;
632             }
633             return $choice;
634         }
635     }
636     return false;
639 /**
640  * List the actions that correspond to a view of this module.
641  * This is used by the participation report.
642  *
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.
646  *
647  * @return array
648  */
649 function choice_get_view_actions() {
650     return array('view','view all','report');
653 /**
654  * List the actions that correspond to a post of this module.
655  * This is used by the participation report.
656  *
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.
660  *
661  * @return array
662  */
663 function choice_get_post_actions() {
664     return array('choose','choose again');
668 /**
669  * Implementation of the function for printing the form elements that control
670  * whether the course reset functionality affects the choice.
671  *
672  * @param object $mform form passed by reference
673  */
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'));
679 /**
680  * Course reset form defaults.
681  *
682  * @return array
683  */
684 function choice_reset_course_form_defaults($course) {
685     return array('reset_choice'=>1);
688 /**
689  * Actual implementation of the reset course functionality, delete all the
690  * choice responses for course $data->courseid.
691  *
692  * @global object
693  * @global object
694  * @param object $data the data submitted from the reset course.
695  * @return array status array
696  */
697 function choice_reset_userdata($data) {
698     global $CFG, $DB;
700     $componentstr = get_string('modulenameplural', 'choice');
701     $status = array();
703     if (!empty($data->reset_choice)) {
704         $choicessql = "SELECT ch.id
705                        FROM {choice} ch
706                        WHERE ch.course=?";
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);
710     }
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);
716     }
718     return $status;
721 /**
722  * @global object
723  * @global object
724  * @global object
725  * @uses CONTEXT_MODULE
726  * @param object $choice
727  * @param object $cm
728  * @param int $groupmode
729  * @param bool $onlyactive Whether to get response data for active users only.
730  * @return array
731  */
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);
740     } else {
741         $currentgroup = 0;
742     }
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
757     if ($rawresponses) {
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;
765             }
766         }
767         foreach ($answeredusers as $answereduser) {
768             unset($allresponses[0][$answereduser]);
769         }
770     }
771     return $allresponses;
774 /**
775  * Returns all other caps used in module
776  *
777  * @return array
778  */
779 function choice_get_extra_capabilities() {
780     return array('moodle/site:accessallgroups');
783 /**
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
792  */
793 function choice_supports($feature) {
794     switch($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;
806     }
809 /**
810  * Adds module specific settings to the settings block
811  *
812  * @param settings_navigation $settings The settings navigation object
813  * @param navigation_node $choicenode The node to add module settings to
814  */
815 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
816     global $PAGE;
818     if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
820         $groupmode = groups_get_activity_groupmode($PAGE->cm);
821         if ($groupmode) {
822             groups_get_activity_group($PAGE->cm, true);
823         }
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);
833         $allusers = [];
834         foreach($allresponses as $optionid => $userlist) {
835             if ($optionid) {
836                 $allusers = array_merge($allusers, array_keys($userlist));
837             }
838         }
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)));
841     }
844 /**
845  * Obtains the automatic completion state for this choice based on any conditions
846  * in forum settings.
847  *
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.
853  */
854 function choice_get_completion_state($course, $cm, $userid, $type) {
855     global $CFG,$DB;
857     // Get choice details
858     $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
859             MUST_EXIST);
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));
865     } else {
866         // Completion option is not enabled so just return $type
867         return $type;
868     }
871 /**
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
876  */
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;
882 /**
883  * Prints choice summaries on MyMoodle Page
884  *
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 )
891  */
892 function choice_print_overview($courses, &$htmlarray) {
893     global $USER, $DB, $OUTPUT;
895     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
896         return;
897     }
898     if (!$choices = get_all_instances_in_courses('choice', $courses)) {
899         return;
900     }
902     $now = time();
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.
908             // Visibility.
909             $class = (!$choice->visible) ? 'dimmed' : '';
911             // Link to activity.
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');
916              // Deadline.
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 = ?',
922                     [$choice->id]);
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));
929                 if ($answers > 0) {
930                     // User has already selected an answer, nothing to show.
931                     $str = '';
932                 } else {
933                     // User has not made a selection yet.
934                     $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
935                 }
936             } else {
937                 // Does not have permission to do anything on this choice activity.
938                 $str = '';
939             }
941             // Make sure we have something to display.
942             if (!empty($str)) {
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;
948                 } else {
949                     $htmlarray[$choice->course]['choice'] .= $str;
950                 }
951             }
952         }
953     }
954     return;
958 /**
959  * Get my responses on a given choice.
960  *
961  * @param stdClass $choice Choice record
962  * @return array of choice answers records
963  * @since  Moodle 3.0
964  */
965 function choice_get_my_response($choice) {
966     global $DB, $USER;
967     return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
971 /**
972  * Get all the responses on a given choice.
973  *
974  * @param stdClass $choice Choice record
975  * @return array of choice answers records
976  * @since  Moodle 3.0
977  */
978 function choice_get_all_responses($choice) {
979     global $DB;
980     return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
984 /**
985  * Return true if we are allowd to view the choice results.
986  *
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.
991  * @since  Moodle 3.0
992  */
993 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
995     if (is_null($choiceopen)) {
996         $timenow = time();
997         if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
998             $choiceopen = false;
999         } else {
1000             $choiceopen = true;
1001         }
1002     }
1003     if (empty($current)) {
1004         $current = choice_get_my_response($choice);
1005     }
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)) {
1010         return true;
1011     }
1012     return false;
1015 /**
1016  * Mark the activity completed (if required) and trigger the course_module_viewed event.
1017  *
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
1022  * @since Moodle 3.0
1023  */
1024 function choice_view($choice, $course, $cm, $context) {
1026     // Trigger course_module_viewed event.
1027     $params = array(
1028         'context' => $context,
1029         'objectid' => $choice->id
1030     );
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);
1036     $event->trigger();
1038     // Completion.
1039     $completion = new completion_info($course);
1040     $completion->set_module_viewed($cm);
1043 /**
1044  * Check if a choice is available for the current user.
1045  *
1046  * @param  stdClass  $choice            choice record
1047  * @return array                       status (available or not and possible warnings)
1048  */
1049 function choice_get_availability_status($choice) {
1050     $available = true;
1051     $warnings = array();
1053     if ($choice->timeclose != 0) {
1054         $timenow = time();
1056         if ($choice->timeopen > $timenow) {
1057             $available = false;
1058             $warnings['notopenyet'] = userdate($choice->timeopen);
1059         } else if ($timenow > $choice->timeclose) {
1060             $available = false;
1061             $warnings['expired'] = userdate($choice->timeclose);
1062         }
1063     }
1064     if (!$choice->allowupdate && choice_get_my_response($choice)) {
1065         $available = false;
1066         $warnings['choicesaved'] = '';
1067     }
1069     // Choice is available.
1070     return array($available, $warnings);