Merge branch 'MDL-53803_m32v1' of https://github.com/sbourget/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, $CFG;
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;
123     }
125     //insert answers
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];
135             }
136             $option->timemodified = time();
137             $DB->insert_record("choice_options", $option);
138         }
139     }
141     // Add calendar events if necessary.
142     choice_set_events($choice);
144     return $choice->id;
147 /**
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.
151  *
152  * @global object
153  * @param object $choice
154  * @return bool
155  */
156 function choice_update_instance($choice) {
157     global $DB, $CFG;
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;
167     }
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];
177         }
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 {
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));
188             }
189         } else {
190             if (isset($value) && $value <> '') {
191                 $DB->insert_record("choice_options", $option);
192             }
193         }
194     }
196     // Add calendar events if necessary.
197     choice_set_events($choice);
199     return $DB->update_record('choice', $choice);
203 /**
204  * @global object
205  * @param object $choice
206  * @param object $user
207  * @param object $coursemodule
208  * @param array $allresponses
209  * @return array
210  */
211 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
212     global $DB;
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]);
230             } else {
231                 $option->countanswers = 0;
232             }
233             if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
234                 $option->attributes->checked = true;
235             }
236             if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
237                 $option->attributes->disabled = true;
238             }
239             $cdisplay['options'][] = $option;
240         }
241     }
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;
247     }
249     if ($choice->showpreview && $choice->timeopen > time()) {
250         $cdisplay['previewonly'] = true;
251     }
253     return $cdisplay;
256 /**
257  * Process user submitted answers for a choice,
258  * and either updating them or saving new answers.
259  *
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.
265  * @return void
266  */
267 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
268     global $DB, $CFG;
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);
275     }
277     if (is_array($formanswer)) {
278         if (!$choice->allowmultiple) {
279             print_error('multiplenotallowederror', 'choice', $continueurl);
280         }
281         $formanswers = $formanswer;
282     } else {
283         $formanswers = array($formanswer);
284     }
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);
290         }
291     }
292     // Start lock to prevent synchronous access to the same data
293     // before it's updated, if using limits.
294     if ($choice->limitanswers) {
295         $timeout = 10;
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);
301         // Opening the lock.
302         $choicelock = $lockfactory->get_lock($resouce, $timeout);
303         if (!$choicelock) {
304             print_error('cannotsubmit', 'choice', $continueurl);
305         }
306     }
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;
315     }
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);
320         } else {
321             $currentgroup = 0;
322         }
324         list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
326         if($currentgroup) {
327             // If groups are being used, retrieve responses only for users in
328             // current group
329             global $CFG;
331             $params['groupid'] = $currentgroup;
332             $sql = "SELECT ca.*
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";
337         } else {
338             // Groups are not used, retrieve all answers for this option ID
339             $sql = "SELECT ca.*
340                       FROM {choice_answers} ca
341                      WHERE optionid $insql";
342         }
344         $answers = $DB->get_records_sql($sql, $params);
345         if ($answers) {
346             foreach ($answers as $a) { //only return enrolled users.
347                 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
348                     $countanswers[$a->optionid]++;
349                 }
350             }
351         }
352         foreach ($countanswers as $opt => $count) {
353             if ($count >= $choice->maxanswers[$opt]) {
354                 $choicesexceeded = true;
355                 break;
356             }
357         }
358     }
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();
363         if ($current) {
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;
371                 } else {
372                     $DB->delete_records('choice_answers', array('id' => $c->id));
373                 }
374             }
376             // Add new ones.
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;
386                 }
387             }
389             // Initialised as true, meaning we updated the answer.
390             $answerupdated = true;
391         } else {
392             // Add new answer.
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;
401             }
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);
407             }
409             // Initalised as false, meaning we submitted a new answer.
410             $answerupdated = false;
411         }
412     } else {
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);
420         }
421     }
423     // Release lock.
424     if (isset($choicelock)) {
425         $choicelock->release();
426     }
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);
441         } else {
442             $eventdata['other']['optionid'] = $formanswers;
443             $event = \mod_choice\event\answer_submitted::create($eventdata);
444         }
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);
450         }
451         $event->trigger();
452     }
455 /**
456  * @param array $user
457  * @param object $cm
458  * @return void Output is echo'd
459  */
460 function choice_show_reportlink($user, $cm) {
461     $userschosen = array();
462     foreach($user as $optionid => $userlist) {
463         if ($optionid) {
464             $userschosen = array_merge($userschosen, array_keys($userlist));
465         }
466     }
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>";
471     echo '</div>';
474 /**
475  * @global object
476  * @param object $choice
477  * @param object $course
478  * @param object $coursemodule
479  * @param array $allresponses
481  *  * @param bool $allresponses
482  * @return object
483  */
484 function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
485     global $OUTPUT;
487     $display = clone($choice);
488     $display->coursemoduleid = $cm->id;
489     $display->courseid = $course->id;
491     //overwrite options value;
492     $display->options = array();
493     $allusers = [];
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]));
502         }
503     }
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);
515         return false;
516     }
518     return $display;
521 /**
522  * @global object
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
527  * @return bool
528  */
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)) {
534         return false;
535     }
537     foreach($attemptids as $num => $attemptid) {
538         if(empty($attemptid)) {
539             unset($attemptids[$num]);
540         }
541     }
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);
562             $event->trigger();
564             $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
565         }
566     }
568     // Update completion state.
569     if ($completion->is_enabled($cm) && $choice->completionsubmit) {
570         $completion->update_state($cm, COMPLETION_INCOMPLETE);
571     }
573     return true;
577 /**
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.
581  *
582  * @global object
583  * @param int $id
584  * @return bool
585  */
586 function choice_delete_instance($id) {
587     global $DB;
589     if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
590         return false;
591     }
593     $result = true;
595     if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
596         $result = false;
597     }
599     if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
600         $result = false;
601     }
603     if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
604         $result = false;
605     }
606     // Remove old calendar events.
607     if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
608         $result = false;
609     }
611     return $result;
614 /**
615  * Returns text string which is the answer that matches the id
616  *
617  * @global object
618  * @param object $choice
619  * @param int $id
620  * @return string
621  */
622 function choice_get_option_text($choice, $id) {
623     global $DB;
625     if ($result = $DB->get_record("choice_options", array("id" => $id))) {
626         return $result->text;
627     } else {
628         return get_string("notanswered", "choice");
629     }
632 /**
633  * Gets a full choice record
634  *
635  * @global object
636  * @param int $choiceid
637  * @return object|bool The choice or false
638  */
639 function choice_get_choice($choiceid) {
640     global $DB;
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;
647             }
648             return $choice;
649         }
650     }
651     return false;
654 /**
655  * List the actions that correspond to a view of this module.
656  * This is used by the participation report.
657  *
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.
661  *
662  * @return array
663  */
664 function choice_get_view_actions() {
665     return array('view','view all','report');
668 /**
669  * List the actions that correspond to a post of this module.
670  * This is used by the participation report.
671  *
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.
675  *
676  * @return array
677  */
678 function choice_get_post_actions() {
679     return array('choose','choose again');
683 /**
684  * Implementation of the function for printing the form elements that control
685  * whether the course reset functionality affects the choice.
686  *
687  * @param object $mform form passed by reference
688  */
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'));
694 /**
695  * Course reset form defaults.
696  *
697  * @return array
698  */
699 function choice_reset_course_form_defaults($course) {
700     return array('reset_choice'=>1);
703 /**
704  * Actual implementation of the reset course functionality, delete all the
705  * choice responses for course $data->courseid.
706  *
707  * @global object
708  * @global object
709  * @param object $data the data submitted from the reset course.
710  * @return array status array
711  */
712 function choice_reset_userdata($data) {
713     global $CFG, $DB;
715     $componentstr = get_string('modulenameplural', 'choice');
716     $status = array();
718     if (!empty($data->reset_choice)) {
719         $choicessql = "SELECT ch.id
720                        FROM {choice} ch
721                        WHERE ch.course=?";
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);
725     }
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);
731     }
733     return $status;
736 /**
737  * @global object
738  * @global object
739  * @global object
740  * @uses CONTEXT_MODULE
741  * @param object $choice
742  * @param object $cm
743  * @param int $groupmode
744  * @param bool $onlyactive Whether to get response data for active users only.
745  * @return array
746  */
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);
755     } else {
756         $currentgroup = 0;
757     }
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
772     if ($rawresponses) {
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;
780             }
781         }
782         foreach ($answeredusers as $answereduser) {
783             unset($allresponses[0][$answereduser]);
784         }
785     }
786     return $allresponses;
789 /**
790  * Returns all other caps used in module
791  *
792  * @return array
793  */
794 function choice_get_extra_capabilities() {
795     return array('moodle/site:accessallgroups');
798 /**
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
807  */
808 function choice_supports($feature) {
809     switch($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;
821     }
824 /**
825  * Adds module specific settings to the settings block
826  *
827  * @param settings_navigation $settings The settings navigation object
828  * @param navigation_node $choicenode The node to add module settings to
829  */
830 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
831     global $PAGE;
833     if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
835         $groupmode = groups_get_activity_groupmode($PAGE->cm);
836         if ($groupmode) {
837             groups_get_activity_group($PAGE->cm, true);
838         }
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);
848         $allusers = [];
849         foreach($allresponses as $optionid => $userlist) {
850             if ($optionid) {
851                 $allusers = array_merge($allusers, array_keys($userlist));
852             }
853         }
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)));
856     }
859 /**
860  * Obtains the automatic completion state for this choice based on any conditions
861  * in forum settings.
862  *
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.
868  */
869 function choice_get_completion_state($course, $cm, $userid, $type) {
870     global $CFG,$DB;
872     // Get choice details
873     $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
874             MUST_EXIST);
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));
880     } else {
881         // Completion option is not enabled so just return $type
882         return $type;
883     }
886 /**
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
891  */
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;
897 /**
898  * Prints choice summaries on MyMoodle Page
899  *
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 )
906  */
907 function choice_print_overview($courses, &$htmlarray) {
908     global $USER, $DB, $OUTPUT;
910     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
911         return;
912     }
913     if (!$choices = get_all_instances_in_courses('choice', $courses)) {
914         return;
915     }
917     $now = time();
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.
923             // Visibility.
924             $class = (!$choice->visible) ? 'dimmed' : '';
926             // Link to activity.
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');
931              // Deadline.
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 = ?',
937                     [$choice->id]);
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));
944                 if ($answers > 0) {
945                     // User has already selected an answer, nothing to show.
946                     $str = '';
947                 } else {
948                     // User has not made a selection yet.
949                     $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
950                 }
951             } else {
952                 // Does not have permission to do anything on this choice activity.
953                 $str = '';
954             }
956             // Make sure we have something to display.
957             if (!empty($str)) {
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;
963                 } else {
964                     $htmlarray[$choice->course]['choice'] .= $str;
965                 }
966             }
967         }
968     }
969     return;
973 /**
974  * Get my responses on a given choice.
975  *
976  * @param stdClass $choice Choice record
977  * @return array of choice answers records
978  * @since  Moodle 3.0
979  */
980 function choice_get_my_response($choice) {
981     global $DB, $USER;
982     return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
986 /**
987  * Get all the responses on a given choice.
988  *
989  * @param stdClass $choice Choice record
990  * @return array of choice answers records
991  * @since  Moodle 3.0
992  */
993 function choice_get_all_responses($choice) {
994     global $DB;
995     return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
999 /**
1000  * Return true if we are allowd to view the choice results.
1001  *
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.
1006  * @since  Moodle 3.0
1007  */
1008 function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1010     if (is_null($choiceopen)) {
1011         $timenow = time();
1012         if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1013             $choiceopen = false;
1014         } else {
1015             $choiceopen = true;
1016         }
1017     }
1018     if (empty($current)) {
1019         $current = choice_get_my_response($choice);
1020     }
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)) {
1025         return true;
1026     }
1027     return false;
1030 /**
1031  * Mark the activity completed (if required) and trigger the course_module_viewed event.
1032  *
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
1037  * @since Moodle 3.0
1038  */
1039 function choice_view($choice, $course, $cm, $context) {
1041     // Trigger course_module_viewed event.
1042     $params = array(
1043         'context' => $context,
1044         'objectid' => $choice->id
1045     );
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);
1051     $event->trigger();
1053     // Completion.
1054     $completion = new completion_info($course);
1055     $completion->set_module_viewed($cm);
1058 /**
1059  * Check if a choice is available for the current user.
1060  *
1061  * @param  stdClass  $choice            choice record
1062  * @return array                       status (available or not and possible warnings)
1063  */
1064 function choice_get_availability_status($choice) {
1065     $available = true;
1066     $warnings = array();
1068     if ($choice->timeclose != 0) {
1069         $timenow = time();
1071         if ($choice->timeopen > $timenow) {
1072             $available = false;
1073             $warnings['notopenyet'] = userdate($choice->timeopen);
1074         } else if ($timenow > $choice->timeclose) {
1075             $available = false;
1076             $warnings['expired'] = userdate($choice->timeclose);
1077         }
1078     }
1079     if (!$choice->allowupdate && choice_get_my_response($choice)) {
1080         $available = false;
1081         $warnings['choicesaved'] = '';
1082     }
1084     // Choice is available.
1085     return array($available, $warnings);
1088 /**
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()
1094  *
1095  * @param int $courseid
1096  * @return bool
1097  */
1098 function choice_refresh_events($courseid = 0) {
1099     global $DB, $CFG;
1100     require_once($CFG->dirroot.'/mod/choice/locallib.php');
1102     if ($courseid) {
1103         if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1104             return true;
1105         }
1106     } else {
1107         if (! $choices = $DB->get_records("choice")) {
1108             return true;
1109         }
1110     }
1112     foreach ($choices as $choice) {
1113         choice_set_events($choice);
1114     }
1115     return true;