3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 /** @global int $CHOICE_COLUMN_HEIGHT */
25 global $CHOICE_COLUMN_HEIGHT;
26 $CHOICE_COLUMN_HEIGHT = 300;
28 /** @global int $CHOICE_COLUMN_WIDTH */
29 global $CHOICE_COLUMN_WIDTH;
30 $CHOICE_COLUMN_WIDTH = 300;
32 define('CHOICE_PUBLISH_ANONYMOUS', '0');
33 define('CHOICE_PUBLISH_NAMES', '1');
35 define('CHOICE_SHOWRESULTS_NOT', '0');
36 define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
37 define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
38 define('CHOICE_SHOWRESULTS_ALWAYS', '3');
40 define('CHOICE_DISPLAY_HORIZONTAL', '0');
41 define('CHOICE_DISPLAY_VERTICAL', '1');
43 /** @global array $CHOICE_PUBLISH */
44 global $CHOICE_PUBLISH;
45 $CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
46 CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
48 /** @global array $CHOICE_SHOWRESULTS */
49 global $CHOICE_SHOWRESULTS;
50 $CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT => get_string('publishnot', 'choice'),
51 CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
52 CHOICE_SHOWRESULTS_AFTER_CLOSE => get_string('publishafterclose', 'choice'),
53 CHOICE_SHOWRESULTS_ALWAYS => get_string('publishalways', 'choice'));
55 /** @global array $CHOICE_DISPLAY */
56 global $CHOICE_DISPLAY;
57 $CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
58 CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
60 /// Standard functions /////////////////////////////////////////////////////////
64 * @param object $course
67 * @param object $choice
70 function choice_user_outline($course, $user, $mod, $choice) {
72 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
73 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
74 $result->time = $answer->timemodified;
82 * @param object $course
85 * @param object $choice
88 function choice_user_complete($course, $user, $mod, $choice) {
90 if ($answer = $DB->get_record('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
91 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
92 $result->time = $answer->timemodified;
93 echo get_string("answered", "choice").": $result->info. ".get_string("updated", '', userdate($result->time));
95 print_string("notanswered", "choice");
100 * Given an object containing all the necessary data,
101 * (defined by the form in mod_form.php) this function
102 * will create a new instance and return the id number
103 * of the new instance.
106 * @param object $choice
109 function choice_add_instance($choice) {
112 $choice->timemodified = time();
114 if (empty($choice->timerestrict)) {
115 $choice->timeopen = 0;
116 $choice->timeclose = 0;
120 $choice->id = $DB->insert_record("choice", $choice);
121 foreach ($choice->option as $key => $value) {
122 $value = trim($value);
123 if (isset($value) && $value <> '') {
124 $option = new object();
125 $option->text = $value;
126 $option->choiceid = $choice->id;
127 if (isset($choice->limit[$key])) {
128 $option->maxanswers = $choice->limit[$key];
130 $option->timemodified = time();
131 $DB->insert_record("choice_options", $option);
139 * Given an object containing all the necessary data,
140 * (defined by the form in mod_form.php) this function
141 * will update an existing instance with new data.
144 * @param object $choice
147 function choice_update_instance($choice) {
150 $choice->id = $choice->instance;
151 $choice->timemodified = time();
154 if (empty($choice->timerestrict)) {
155 $choice->timeopen = 0;
156 $choice->timeclose = 0;
159 //update, delete or insert answers
160 foreach ($choice->option as $key => $value) {
161 $value = trim($value);
162 $option = new object();
163 $option->text = $value;
164 $option->choiceid = $choice->id;
165 if (isset($choice->limit[$key])) {
166 $option->maxanswers = $choice->limit[$key];
168 $option->timemodified = time();
169 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
170 $option->id=$choice->optionid[$key];
171 if (isset($value) && $value <> '') {
172 $DB->update_record("choice_options", $option);
173 } else { //empty old option - needs to be deleted.
174 $DB->delete_records("choice_options", array("id"=>$option->id));
177 if (isset($value) && $value <> '') {
178 $DB->insert_record("choice_options", $option);
183 return $DB->update_record('choice', $choice);
189 * @param object $choice
190 * @param object $user
191 * @param object $coursemodule
192 * @param array $allresponses
195 function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
198 $cdisplay = array('options'=>array());
200 $cdisplay['limitanswers'] = true;
201 $context = get_context_instance(CONTEXT_MODULE, $coursemodule->id);
203 foreach ($choice->option as $optionid => $text) {
204 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
205 $option = new stdClass;
206 $option->attributes = new stdClass;
207 $option->attributes->value = $optionid;
208 $option->text = $text;
209 $option->maxanswers = $choice->maxanswers[$optionid];
210 $option->displaylayout = $choice->display;
212 if (isset($allresponses[$optionid])) {
213 $option->countanswers = count($allresponses[$optionid]);
215 $option->countanswers = 0;
217 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
218 $option->attributes->checked = true;
220 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
221 $option->attributes->disabled = true;
223 $cdisplay['options'][] = $option;
227 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
229 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
230 $cdisplay['allowupdate'] = true;
238 * @param int $formanswer
239 * @param object $choice
241 * @param int $courseid
244 function choice_user_submit_response($formanswer, $choice, $userid, $courseid, $cm) {
246 $current = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
247 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
250 if($choice->limitanswers) {
251 // Find out whether groups are being used and enabled
252 if (groups_get_activity_groupmode($cm) > 0) {
253 $currentgroup = groups_get_activity_group($cm);
258 // If groups are being used, retrieve responses only for users in
261 $answers = $DB->get_records_sql("
266 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
269 AND gm.groupid=?", array($formanswer, $currentgroup));
271 // Groups are not used, retrieve all answers for this option ID
272 $answers = $DB->get_records("choice_answers", array("optionid" => $formanswer));
276 foreach ($answers as $a) { //only return enrolled users.
277 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
282 $maxans = $choice->maxanswers[$formanswer];
285 if (!($choice->limitanswers && ($countanswers >= $maxans) )) {
288 $newanswer = $current;
289 $newanswer->optionid = $formanswer;
290 $newanswer->timemodified = time();
291 $DB->update_record("choice_answers", $newanswer);
292 add_to_log($courseid, "choice", "choose again", "view.php?id=$cm->id", $choice->id, $cm->id);
295 $newanswer->choiceid = $choice->id;
296 $newanswer->userid = $userid;
297 $newanswer->optionid = $formanswer;
298 $newanswer->timemodified = time();
299 $DB->insert_record("choice_answers", $newanswer);
300 add_to_log($courseid, "choice", "choose", "view.php?id=$cm->id", $choice->id, $cm->id);
303 if (!($current->optionid==$formanswer)) { //check to see if current choice already selected - if not display error
304 print_error('choicefull', 'choice');
312 * @return void Output is echo'd
314 function choice_show_reportlink($user, $cm) {
316 foreach($user as $optionid => $userlist) {
318 $responsecount += count($userlist);
322 echo '<div class="reportlink">';
323 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
329 * @param object $choice
330 * @param object $course
331 * @param object $coursemodule
332 * @param array $allresponses
334 * * @param bool $allresponses
337 function prepare_choice_show_results($choice, $course, $cm, $allresponses, $forcepublish=false) {
338 global $CFG, $CHOICE_COLUMN_HEIGHT, $FULLSCRIPT, $PAGE, $OUTPUT, $DB;
340 $display = clone($choice);
341 $display->coursemoduleid = $cm->id;
342 $display->courseid = $course->id;
344 //overwrite options value;
345 $display->options = array();
347 foreach ($choice->option as $optionid => $optiontext) {
348 $display->options[$optionid] = new stdClass;
349 $display->options[$optionid]->text = $optiontext;
350 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
352 if (array_key_exists($optionid, $allresponses)) {
353 $display->options[$optionid]->user = $allresponses[$optionid]; //->user;
354 $totaluser += count($allresponses[$optionid]);
357 unset($display->option);
358 unset($display->maxanswers);
360 $display->numberofuser = $totaluser;
361 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
362 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
363 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
364 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
366 if (empty($allresponses)) {
367 echo $OUTPUT->heading(get_string("nousersyet"));
372 $totalresponsecount = 0;
373 foreach ($allresponses as $optionid => $userlist) {
374 if ($choice->showunanswered || $optionid) {
375 $totalresponsecount += count($userlist);
379 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
381 $hascapfullnames = has_capability('moodle/site:viewfullnames', $context);
383 $viewresponses = has_capability('mod/choice:readresponses', $context);
384 switch ($forcepublish) {
385 case CHOICE_PUBLISH_NAMES:
386 echo '<div id="tablecontainer">';
387 if ($viewresponses) {
388 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);">';
390 echo '<input type="hidden" name="id" value="'.$cm->id.'" />';
391 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
392 echo '<input type="hidden" name="mode" value="overview" />';
395 echo "<table cellpadding=\"5\" cellspacing=\"10\" class=\"results names\">";
398 $columncount = array(); // number of votes in each column
399 if ($choice->showunanswered) {
401 echo "<th class=\"col0 header\" scope=\"col\">";
402 print_string('notanswered', 'choice');
406 foreach ($choice->option as $optionid => $optiontext) {
407 $columncount[$optionid] = 0; // init counters
408 echo "<th class=\"col$count header\" scope=\"col\">";
409 echo format_string($optiontext);
415 if ($choice->showunanswered) {
416 echo "<td class=\"col$count data\" >";
417 // added empty row so that when the next iteration is empty,
418 // we do not get <table></table> erro from w3c validator
420 echo "<table class=\"choiceresponse\"><tr><td></td></tr>";
421 if (!empty($allresponses[0])) {
422 foreach ($allresponses[0] as $user) {
424 echo "<td class=\"picture\">";
425 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
426 echo "</td><td class=\"fullname\">";
427 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">";
428 echo fullname($user, $hascapfullnames);
433 echo "</table></td>";
436 foreach ($choice->option as $optionid => $optiontext) {
437 echo '<td class="col'.$count.' data" >';
439 // added empty row so that when the next iteration is empty,
440 // we do not get <table></table> erro from w3c validator
442 echo '<table class="choiceresponse"><tr><td></td></tr>';
443 if (isset($allresponses[$optionid])) {
444 foreach ($allresponses[$optionid] as $user) {
445 $columncount[$optionid] += 1;
446 echo '<tr><td class="attemptcell">';
447 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
448 echo '<input type="checkbox" name="attemptid[]" value="'. $user->id. '" />';
450 echo '</td><td class="picture">';
451 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
452 echo '</td><td class="fullname">';
453 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">";
454 echo fullname($user, $hascapfullnames);
460 echo '</table></td>';
465 if ($choice->showunanswered) {
469 foreach ($choice->option as $optionid => $optiontext) {
470 echo "<td align=\"center\" class=\"col$count count\">";
471 if ($choice->limitanswers) {
472 echo get_string("taken", "choice").":";
473 echo $columncount[$optionid];
475 echo get_string("limit", "choice").":";
476 echo $choice->maxanswers[$optionid];
478 if (isset($columncount[$optionid])) {
479 echo $columncount[$optionid];
487 /// Print "Select all" etc.
488 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
489 echo '<tr><td></td><td>';
490 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall').'</a> / ';
491 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('deselectall').'</a> ';
493 echo html_writer::label(get_string('withselected', 'choice'), 'menuaction');
494 echo html_writer::select(array('delete' => get_string('delete')), 'action', '', array(''=>get_string('withselectedusers')), array('id'=>'menuaction'));
495 $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('attemptsform', 'menuaction', ''));
496 echo '<noscript id="noscriptmenuaction" style="display:inline">';
498 echo '<input type="submit" value="'.get_string('go').'" /></div></noscript>';
499 echo '</td><td></td></tr>';
502 echo "</table></div>";
503 if ($viewresponses) {
504 echo "</form></div>";
513 * @param array $attemptids
514 * @param int $choiceid
517 function choice_delete_responses($attemptids, $choiceid) {
519 if(!is_array($attemptids) || empty($attemptids)) {
523 foreach($attemptids as $num => $attemptid) {
524 if(empty($attemptid)) {
525 unset($attemptids[$num]);
529 foreach($attemptids as $attemptid) {
530 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choiceid, 'userid' => $attemptid))) {
531 $DB->delete_records('choice_answers', array('choiceid' => $choiceid, 'userid' => $attemptid));
539 * Given an ID of an instance of this module,
540 * this function will permanently delete the instance
541 * and any data that depends on it.
547 function choice_delete_instance($id) {
550 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
556 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
560 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
564 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
572 * Returns the users with data in one choice
573 * (users with records in choice_responses, students)
575 * @param int $choiceid
578 function choice_get_participants($choiceid) {
582 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
585 WHERE a.choiceid = ? AND
586 u.id = a.userid", array($choiceid));
588 //Return students array (it contains an array of unique users)
593 * Returns text string which is the answer that matches the id
596 * @param object $choice
600 function choice_get_option_text($choice, $id) {
603 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
604 return $result->text;
606 return get_string("notanswered", "choice");
611 * Gets a full choice record
614 * @param int $choiceid
615 * @return object|bool The choice or false
617 function choice_get_choice($choiceid) {
620 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
621 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
622 foreach ($options as $option) {
623 $choice->option[$option->id] = $option->text;
624 $choice->maxanswers[$option->id] = $option->maxanswers;
635 function choice_get_view_actions() {
636 return array('view','view all','report');
642 function choice_get_post_actions() {
643 return array('choose','choose again');
648 * Implementation of the function for printing the form elements that control
649 * whether the course reset functionality affects the choice.
651 * @param object $mform form passed by reference
653 function choice_reset_course_form_definition(&$mform) {
654 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
655 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
659 * Course reset form defaults.
663 function choice_reset_course_form_defaults($course) {
664 return array('reset_choice'=>1);
668 * Actual implementation of the rest coures functionality, delete all the
669 * choice responses for course $data->courseid.
673 * @param object $data the data submitted from the reset course.
674 * @return array status array
676 function choice_reset_userdata($data) {
679 $componentstr = get_string('modulenameplural', 'choice');
682 if (!empty($data->reset_choice)) {
683 $choicessql = "SELECT ch.id
687 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
688 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
691 /// updating dates - shift may be negative too
692 if ($data->timeshift) {
693 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
694 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
704 * @uses CONTEXT_MODULE
705 * @param object $choice
707 * @param int $groupmode
710 function choice_get_response_data($choice, $cm, $groupmode) {
711 global $CFG, $USER, $DB;
713 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
715 /// Get the current group
716 if ($groupmode > 0) {
717 $currentgroup = groups_get_activity_group($cm);
722 /// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
723 $allresponses = array();
725 /// First get all the users who have access here
726 /// To start with we assume they are all "unanswered" then move them later
727 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, user_picture::fields('u', array('idnumber')), 'u.lastname ASC,u.firstname ASC');
729 /// Get all the recorded responses for this choice
730 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
732 /// Use the responses to move users into the correct column
735 foreach ($rawresponses as $response) {
736 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
737 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
738 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
739 unset($allresponses[0][$response->userid]); // Remove from unanswered column
743 return $allresponses;
747 * Returns all other caps used in module
751 function choice_get_extra_capabilities() {
752 return array('moodle/site:accessallgroups');
756 * @uses FEATURE_GROUPS
757 * @uses FEATURE_GROUPINGS
758 * @uses FEATURE_GROUPMEMBERSONLY
759 * @uses FEATURE_MOD_INTRO
760 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
761 * @uses FEATURE_GRADE_HAS_GRADE
762 * @uses FEATURE_GRADE_OUTCOMES
763 * @param string $feature FEATURE_xx constant for requested feature
764 * @return mixed True if module supports feature, null if doesn't know
766 function choice_supports($feature) {
768 case FEATURE_GROUPS: return true;
769 case FEATURE_GROUPINGS: return true;
770 case FEATURE_GROUPMEMBERSONLY: return true;
771 case FEATURE_MOD_INTRO: return true;
772 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
773 case FEATURE_GRADE_HAS_GRADE: return false;
774 case FEATURE_GRADE_OUTCOMES: return false;
775 case FEATURE_BACKUP_MOODLE2: return true;
777 default: return null;
782 * Adds module specific settings to the settings block
784 * @param settings_navigation $settings The settings navigation object
785 * @param navigation_node $choicenode The node to add module settings to
787 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
790 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
792 $groupmode = groups_get_activity_groupmode($PAGE->cm);
794 groups_get_activity_group($PAGE->cm, true);
796 // We only actually need the choice id here
797 $choice = new stdClass;
798 $choice->id = $PAGE->cm->instance;
799 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode); // Big function, approx 6 SQL calls per user
802 foreach($allresponses as $optionid => $userlist) {
804 $responsecount += count($userlist);
807 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));