MDL-41283 report_participation: Fixed legacy actions returned from api's
[moodle.git] / mod / choice / lib.php
blob59d9854ee1fea75c74856e878863a88f95c478f3
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.
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
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
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;
78 return NULL;
81 /**
82 * @global object
83 * @param object $course
84 * @param object $user
85 * @param object $mod
86 * @param object $choice
87 * @return string|void
89 function choice_user_complete($course, $user, $mod, $choice) {
90 global $DB;
91 if ($answer = $DB->get_record('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
92 $result = new stdClass();
93 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
94 $result->time = $answer->timemodified;
95 echo get_string("answered", "choice").": $result->info. ".get_string("updated", '', userdate($result->time));
96 } else {
97 print_string("notanswered", "choice");
102 * Given an object containing all the necessary data,
103 * (defined by the form in mod_form.php) this function
104 * will create a new instance and return the id number
105 * of the new instance.
107 * @global object
108 * @param object $choice
109 * @return int
111 function choice_add_instance($choice) {
112 global $DB;
114 $choice->timemodified = time();
116 if (empty($choice->timerestrict)) {
117 $choice->timeopen = 0;
118 $choice->timeclose = 0;
121 //insert answers
122 $choice->id = $DB->insert_record("choice", $choice);
123 foreach ($choice->option as $key => $value) {
124 $value = trim($value);
125 if (isset($value) && $value <> '') {
126 $option = new stdClass();
127 $option->text = $value;
128 $option->choiceid = $choice->id;
129 if (isset($choice->limit[$key])) {
130 $option->maxanswers = $choice->limit[$key];
132 $option->timemodified = time();
133 $DB->insert_record("choice_options", $option);
137 return $choice->id;
141 * Given an object containing all the necessary data,
142 * (defined by the form in mod_form.php) this function
143 * will update an existing instance with new data.
145 * @global object
146 * @param object $choice
147 * @return bool
149 function choice_update_instance($choice) {
150 global $DB;
152 $choice->id = $choice->instance;
153 $choice->timemodified = time();
156 if (empty($choice->timerestrict)) {
157 $choice->timeopen = 0;
158 $choice->timeclose = 0;
161 //update, delete or insert answers
162 foreach ($choice->option as $key => $value) {
163 $value = trim($value);
164 $option = new stdClass();
165 $option->text = $value;
166 $option->choiceid = $choice->id;
167 if (isset($choice->limit[$key])) {
168 $option->maxanswers = $choice->limit[$key];
170 $option->timemodified = time();
171 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
172 $option->id=$choice->optionid[$key];
173 if (isset($value) && $value <> '') {
174 $DB->update_record("choice_options", $option);
175 } else { //empty old option - needs to be deleted.
176 $DB->delete_records("choice_options", array("id"=>$option->id));
178 } else {
179 if (isset($value) && $value <> '') {
180 $DB->insert_record("choice_options", $option);
185 return $DB->update_record('choice', $choice);
190 * @global object
191 * @param object $choice
192 * @param object $user
193 * @param object $coursemodule
194 * @param array $allresponses
195 * @return array
197 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
198 global $DB;
200 $cdisplay = array('options'=>array());
202 $cdisplay['limitanswers'] = true;
203 $context = context_module::instance($coursemodule->id);
205 foreach ($choice->option as $optionid => $text) {
206 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
207 $option = new stdClass;
208 $option->attributes = new stdClass;
209 $option->attributes->value = $optionid;
210 $option->text = $text;
211 $option->maxanswers = $choice->maxanswers[$optionid];
212 $option->displaylayout = $choice->display;
214 if (isset($allresponses[$optionid])) {
215 $option->countanswers = count($allresponses[$optionid]);
216 } else {
217 $option->countanswers = 0;
219 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
220 $option->attributes->checked = true;
222 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
223 $option->attributes->disabled = true;
225 $cdisplay['options'][] = $option;
229 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
231 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
232 $cdisplay['allowupdate'] = true;
235 return $cdisplay;
239 * @global object
240 * @param int $formanswer
241 * @param object $choice
242 * @param int $userid
243 * @param object $course Course object
244 * @param object $cm
246 function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
247 global $DB, $CFG;
248 require_once($CFG->libdir.'/completionlib.php');
250 $current = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
251 $context = context_module::instance($cm->id);
253 $countanswers=0;
254 if($choice->limitanswers) {
255 // Find out whether groups are being used and enabled
256 if (groups_get_activity_groupmode($cm) > 0) {
257 $currentgroup = groups_get_activity_group($cm);
258 } else {
259 $currentgroup = 0;
261 if($currentgroup) {
262 // If groups are being used, retrieve responses only for users in
263 // current group
264 global $CFG;
265 $answers = $DB->get_records_sql("
266 SELECT
267 ca.*
268 FROM
269 {choice_answers} ca
270 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
271 WHERE
272 optionid=?
273 AND gm.groupid=?", array($formanswer, $currentgroup));
274 } else {
275 // Groups are not used, retrieve all answers for this option ID
276 $answers = $DB->get_records("choice_answers", array("optionid" => $formanswer));
279 if ($answers) {
280 foreach ($answers as $a) { //only return enrolled users.
281 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
282 $countanswers++;
286 $maxans = $choice->maxanswers[$formanswer];
289 if (!($choice->limitanswers && ($countanswers >= $maxans) )) {
290 if ($current) {
292 $newanswer = $current;
293 $newanswer->optionid = $formanswer;
294 $newanswer->timemodified = time();
295 $DB->update_record("choice_answers", $newanswer);
297 $eventdata = array();
298 $eventdata['context'] = $context;
299 $eventdata['objectid'] = $newanswer->id;
300 $eventdata['userid'] = $userid;
301 $eventdata['courseid'] = $course->id;
302 $eventdata['other'] = array();
303 $eventdata['other']['choiceid'] = $choice->id;
304 $eventdata['other']['optionid'] = $formanswer;
306 $event = \mod_choice\event\answer_updated::create($eventdata);
307 $event->add_record_snapshot('choice_answers', $newanswer);
308 $event->add_record_snapshot('course', $course);
309 $event->add_record_snapshot('course_modules', $cm);
310 $event->trigger();
311 } else {
312 $newanswer = new stdClass();
313 $newanswer->choiceid = $choice->id;
314 $newanswer->userid = $userid;
315 $newanswer->optionid = $formanswer;
316 $newanswer->timemodified = time();
317 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
319 // Update completion state
320 $completion = new completion_info($course);
321 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
322 $completion->update_state($cm, COMPLETION_COMPLETE);
325 $eventdata = array();
326 $eventdata['context'] = $context;
327 $eventdata['objectid'] = $newanswer->id;
328 $eventdata['userid'] = $userid;
329 $eventdata['courseid'] = $course->id;
330 $eventdata['other'] = array();
331 $eventdata['other']['choiceid'] = $choice->id;
332 $eventdata['other']['optionid'] = $formanswer;
334 $event = \mod_choice\event\answer_submitted::create($eventdata);
335 $event->add_record_snapshot('choice_answers', $newanswer);
336 $event->add_record_snapshot('course', $course);
337 $event->add_record_snapshot('course_modules', $cm);
338 $event->trigger();
340 } else {
341 if (!($current->optionid==$formanswer)) { //check to see if current choice already selected - if not display error
342 print_error('choicefull', 'choice');
348 * @param array $user
349 * @param object $cm
350 * @return void Output is echo'd
352 function choice_show_reportlink($user, $cm) {
353 $responsecount =0;
354 foreach($user as $optionid => $userlist) {
355 if ($optionid) {
356 $responsecount += count($userlist);
360 echo '<div class="reportlink">';
361 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
362 echo '</div>';
366 * @global object
367 * @param object $choice
368 * @param object $course
369 * @param object $coursemodule
370 * @param array $allresponses
372 * * @param bool $allresponses
373 * @return object
375 function prepare_choice_show_results($choice, $course, $cm, $allresponses, $forcepublish=false) {
376 global $CFG, $CHOICE_COLUMN_HEIGHT, $FULLSCRIPT, $PAGE, $OUTPUT, $DB;
378 $display = clone($choice);
379 $display->coursemoduleid = $cm->id;
380 $display->courseid = $course->id;
382 //overwrite options value;
383 $display->options = array();
384 $totaluser = 0;
385 foreach ($choice->option as $optionid => $optiontext) {
386 $display->options[$optionid] = new stdClass;
387 $display->options[$optionid]->text = $optiontext;
388 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
390 if (array_key_exists($optionid, $allresponses)) {
391 $display->options[$optionid]->user = $allresponses[$optionid];
392 $totaluser += count($allresponses[$optionid]);
395 unset($display->option);
396 unset($display->maxanswers);
398 $display->numberofuser = $totaluser;
399 $context = context_module::instance($cm->id);
400 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
401 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
402 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
404 if (empty($allresponses)) {
405 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
406 return false;
410 $totalresponsecount = 0;
411 foreach ($allresponses as $optionid => $userlist) {
412 if ($choice->showunanswered || $optionid) {
413 $totalresponsecount += count($userlist);
417 $hascapfullnames = has_capability('moodle/site:viewfullnames', $context);
419 $viewresponses = has_capability('mod/choice:readresponses', $context);
420 switch ($forcepublish) {
421 case CHOICE_PUBLISH_NAMES:
422 echo '<div id="tablecontainer">';
423 if ($viewresponses) {
424 echo '<form id="attemptsform" method="post" action="'.$FULLSCRIPT.'" onsubmit="var menu = document.getElementById(\'menuaction\'); return (menu.options[menu.selectedIndex].value == \'delete\' ? \''.addslashes_js(get_string('deleteattemptcheck','quiz')).'\' : true);">';
425 echo '<div>';
426 echo '<input type="hidden" name="id" value="'.$cm->id.'" />';
427 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
428 echo '<input type="hidden" name="mode" value="overview" />';
431 echo "<table cellpadding=\"5\" cellspacing=\"10\" class=\"results names\">";
432 echo "<tr>";
434 $columncount = array(); // number of votes in each column
435 if ($choice->showunanswered) {
436 $columncount[0] = 0;
437 echo "<th class=\"col0 header\" scope=\"col\">";
438 print_string('notanswered', 'choice');
439 echo "</th>";
441 $count = 1;
442 foreach ($choice->option as $optionid => $optiontext) {
443 $columncount[$optionid] = 0; // init counters
444 echo "<th class=\"col$count header\" scope=\"col\">";
445 echo format_string($optiontext);
446 echo "</th>";
447 $count++;
449 echo "</tr><tr>";
451 if ($choice->showunanswered) {
452 echo "<td class=\"col$count data\" >";
453 // added empty row so that when the next iteration is empty,
454 // we do not get <table></table> error from w3c validator
455 // MDL-7861
456 echo "<table class=\"choiceresponse\"><tr><td></td></tr>";
457 if (!empty($allresponses[0])) {
458 foreach ($allresponses[0] as $user) {
459 echo "<tr>";
460 echo "<td class=\"picture\">";
461 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
462 echo "</td><td class=\"fullname\">";
463 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">";
464 echo fullname($user, $hascapfullnames);
465 echo "</a>";
466 echo "</td></tr>";
469 echo "</table></td>";
471 $count = 1;
472 foreach ($choice->option as $optionid => $optiontext) {
473 echo '<td class="col'.$count.' data" >';
475 // added empty row so that when the next iteration is empty,
476 // we do not get <table></table> error from w3c validator
477 // MDL-7861
478 echo '<table class="choiceresponse"><tr><td></td></tr>';
479 if (isset($allresponses[$optionid])) {
480 foreach ($allresponses[$optionid] as $user) {
481 $columncount[$optionid] += 1;
482 echo '<tr><td class="attemptcell">';
483 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
484 echo '<input type="checkbox" name="attemptid[]" value="'. $user->id. '" />';
486 echo '</td><td class="picture">';
487 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
488 echo '</td><td class="fullname">';
489 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">";
490 echo fullname($user, $hascapfullnames);
491 echo '</a>';
492 echo '</td></tr>';
495 $count++;
496 echo '</table></td>';
498 echo "</tr><tr>";
499 $count = 1;
501 if ($choice->showunanswered) {
502 echo "<td></td>";
505 foreach ($choice->option as $optionid => $optiontext) {
506 echo "<td align=\"center\" class=\"col$count count\">";
507 if ($choice->limitanswers) {
508 echo get_string("taken", "choice").":";
509 echo $columncount[$optionid];
510 echo "<br/>";
511 echo get_string("limit", "choice").":";
512 echo $choice->maxanswers[$optionid];
513 } else {
514 if (isset($columncount[$optionid])) {
515 echo $columncount[$optionid];
518 echo "</td>";
519 $count++;
521 echo "</tr>";
523 /// Print "Select all" etc.
524 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
525 echo '<tr><td></td><td>';
526 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall').'</a> / ';
527 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('deselectall').'</a> ';
528 echo '&nbsp;&nbsp;';
529 echo html_writer::label(get_string('withselected', 'choice'), 'menuaction');
530 echo html_writer::select(array('delete' => get_string('delete')), 'action', '', array(''=>get_string('withselectedusers')), array('id'=>'menuaction', 'class' => 'autosubmit'));
531 $PAGE->requires->yui_module('moodle-core-formautosubmit',
532 'M.core.init_formautosubmit',
533 array(array('selectid' => 'menuaction'))
535 echo '<noscript id="noscriptmenuaction" style="display:inline">';
536 echo '<div>';
537 echo '<input type="submit" value="'.get_string('go').'" /></div></noscript>';
538 echo '</td><td></td></tr>';
541 echo "</table></div>";
542 if ($viewresponses) {
543 echo "</form></div>";
545 break;
547 return $display;
551 * @global object
552 * @param array $attemptids
553 * @param object $choice Choice main table row
554 * @param object $cm Course-module object
555 * @param object $course Course object
556 * @return bool
558 function choice_delete_responses($attemptids, $choice, $cm, $course) {
559 global $DB, $CFG;
560 require_once($CFG->libdir.'/completionlib.php');
562 if(!is_array($attemptids) || empty($attemptids)) {
563 return false;
566 foreach($attemptids as $num => $attemptid) {
567 if(empty($attemptid)) {
568 unset($attemptids[$num]);
572 $completion = new completion_info($course);
573 foreach($attemptids as $attemptid) {
574 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $attemptid))) {
575 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $attemptid));
576 // Update completion state
577 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
578 $completion->update_state($cm, COMPLETION_INCOMPLETE, $attemptid);
582 return true;
587 * Given an ID of an instance of this module,
588 * this function will permanently delete the instance
589 * and any data that depends on it.
591 * @global object
592 * @param int $id
593 * @return bool
595 function choice_delete_instance($id) {
596 global $DB;
598 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
599 return false;
602 $result = true;
604 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
605 $result = false;
608 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
609 $result = false;
612 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
613 $result = false;
616 return $result;
620 * Returns text string which is the answer that matches the id
622 * @global object
623 * @param object $choice
624 * @param int $id
625 * @return string
627 function choice_get_option_text($choice, $id) {
628 global $DB;
630 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
631 return $result->text;
632 } else {
633 return get_string("notanswered", "choice");
638 * Gets a full choice record
640 * @global object
641 * @param int $choiceid
642 * @return object|bool The choice or false
644 function choice_get_choice($choiceid) {
645 global $DB;
647 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
648 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
649 foreach ($options as $option) {
650 $choice->option[$option->id] = $option->text;
651 $choice->maxanswers[$option->id] = $option->maxanswers;
653 return $choice;
656 return false;
660 * List the actions that correspond to a view of this module.
661 * This is used by the participation report.
663 * Note: This is not used by new logging system. Event with
664 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
665 * be considered as view action.
667 * @return array
669 function choice_get_view_actions() {
670 return array('view');
674 * List the actions that correspond to a post of this module.
675 * This is used by the participation report.
677 * Note: This is not used by new logging system. Event with
678 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
679 * will be considered as post action.
681 * @return array
683 function choice_get_post_actions() {
684 return array('choose','choose again');
689 * Implementation of the function for printing the form elements that control
690 * whether the course reset functionality affects the choice.
692 * @param object $mform form passed by reference
694 function choice_reset_course_form_definition(&$mform) {
695 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
696 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
700 * Course reset form defaults.
702 * @return array
704 function choice_reset_course_form_defaults($course) {
705 return array('reset_choice'=>1);
709 * Actual implementation of the reset course functionality, delete all the
710 * choice responses for course $data->courseid.
712 * @global object
713 * @global object
714 * @param object $data the data submitted from the reset course.
715 * @return array status array
717 function choice_reset_userdata($data) {
718 global $CFG, $DB;
720 $componentstr = get_string('modulenameplural', 'choice');
721 $status = array();
723 if (!empty($data->reset_choice)) {
724 $choicessql = "SELECT ch.id
725 FROM {choice} ch
726 WHERE ch.course=?";
728 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
729 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
732 /// updating dates - shift may be negative too
733 if ($data->timeshift) {
734 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
735 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
738 return $status;
742 * @global object
743 * @global object
744 * @global object
745 * @uses CONTEXT_MODULE
746 * @param object $choice
747 * @param object $cm
748 * @param int $groupmode
749 * @return array
751 function choice_get_response_data($choice, $cm, $groupmode) {
752 global $CFG, $USER, $DB;
754 $context = context_module::instance($cm->id);
756 /// Get the current group
757 if ($groupmode > 0) {
758 $currentgroup = groups_get_activity_group($cm);
759 } else {
760 $currentgroup = 0;
763 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
764 $allresponses = array();
766 /// First get all the users who have access here
767 /// To start with we assume they are all "unanswered" then move them later
768 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, user_picture::fields('u', array('idnumber')));
770 /// Get all the recorded responses for this choice
771 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
773 /// Use the responses to move users into the correct column
775 if ($rawresponses) {
776 foreach ($rawresponses as $response) {
777 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
778 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
779 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
780 unset($allresponses[0][$response->userid]); // Remove from unanswered column
784 return $allresponses;
788 * Returns all other caps used in module
790 * @return array
792 function choice_get_extra_capabilities() {
793 return array('moodle/site:accessallgroups');
797 * @uses FEATURE_GROUPS
798 * @uses FEATURE_GROUPINGS
799 * @uses FEATURE_GROUPMEMBERSONLY
800 * @uses FEATURE_MOD_INTRO
801 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
802 * @uses FEATURE_GRADE_HAS_GRADE
803 * @uses FEATURE_GRADE_OUTCOMES
804 * @param string $feature FEATURE_xx constant for requested feature
805 * @return mixed True if module supports feature, null if doesn't know
807 function choice_supports($feature) {
808 switch($feature) {
809 case FEATURE_GROUPS: return true;
810 case FEATURE_GROUPINGS: return true;
811 case FEATURE_GROUPMEMBERSONLY: return true;
812 case FEATURE_MOD_INTRO: return true;
813 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
814 case FEATURE_COMPLETION_HAS_RULES: return true;
815 case FEATURE_GRADE_HAS_GRADE: return false;
816 case FEATURE_GRADE_OUTCOMES: return false;
817 case FEATURE_BACKUP_MOODLE2: return true;
818 case FEATURE_SHOW_DESCRIPTION: return true;
820 default: return null;
825 * Adds module specific settings to the settings block
827 * @param settings_navigation $settings The settings navigation object
828 * @param navigation_node $choicenode The node to add module settings to
830 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
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);
839 // We only actually need the choice id here
840 $choice = new stdClass;
841 $choice->id = $PAGE->cm->instance;
842 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode); // Big function, approx 6 SQL calls per user
844 $responsecount =0;
845 foreach($allresponses as $optionid => $userlist) {
846 if ($optionid) {
847 $responsecount += count($userlist);
850 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
855 * Obtains the automatic completion state for this choice based on any conditions
856 * in forum settings.
858 * @param object $course Course
859 * @param object $cm Course-module
860 * @param int $userid User ID
861 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
862 * @return bool True if completed, false if not, $type if conditions not set.
864 function choice_get_completion_state($course, $cm, $userid, $type) {
865 global $CFG,$DB;
867 // Get choice details
868 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
869 MUST_EXIST);
871 // If completion option is enabled, evaluate it and return true/false
872 if($choice->completionsubmit) {
873 return $DB->record_exists('choice_answers', array(
874 'choiceid'=>$choice->id, 'userid'=>$userid));
875 } else {
876 // Completion option is not enabled so just return $type
877 return $type;
882 * Return a list of page types
883 * @param string $pagetype current page type
884 * @param stdClass $parentcontext Block's parent context
885 * @param stdClass $currentcontext Current context of block
887 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
888 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
889 return $module_pagetype;