MDL-44153 mod_choice: unified @package use
[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  * @global object
83  * @param object $course
84  * @param object $user
85  * @param object $mod
86  * @param object $choice
87  * @return string|void
88  */
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");
98     }
99 }
101 /**
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.
106  *
107  * @global object
108  * @param object $choice
109  * @return int
110  */
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;
119     }
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];
131             }
132             $option->timemodified = time();
133             $DB->insert_record("choice_options", $option);
134         }
135     }
137     return $choice->id;
140 /**
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.
144  *
145  * @global object
146  * @param object $choice
147  * @return bool
148  */
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;
159     }
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];
169         }
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));
177             }
178         } else {
179             if (isset($value) && $value <> '') {
180                 $DB->insert_record("choice_options", $option);
181             }
182         }
183     }
185     return $DB->update_record('choice', $choice);
189 /**
190  * @global object
191  * @param object $choice
192  * @param object $user
193  * @param object $coursemodule
194  * @param array $allresponses
195  * @return array
196  */
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;
218             }
219             if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
220                 $option->attributes->checked = true;
221             }
222             if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
223                 $option->attributes->disabled = true;
224             }
225             $cdisplay['options'][] = $option;
226         }
227     }
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;
233     }
235     return $cdisplay;
238 /**
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
245  */
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;
260         }
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));
277         }
279         if ($answers) {
280             foreach ($answers as $a) { //only return enrolled users.
281                 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
282                     $countanswers++;
283                 }
284             }
285         }
286         $maxans = $choice->maxanswers[$formanswer];
287     }
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);
323             }
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();
339         }
340     } else {
341         if (!($current->optionid==$formanswer)) { //check to see if current choice already selected - if not display error
342             print_error('choicefull', 'choice');
343         }
344     }
347 /**
348  * @param array $user
349  * @param object $cm
350  * @return void Output is echo'd
351  */
352 function choice_show_reportlink($user, $cm) {
353     $responsecount =0;
354     foreach($user as $optionid => $userlist) {
355         if ($optionid) {
356             $responsecount += count($userlist);
357         }
358     }
360     echo '<div class="reportlink">';
361     echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
362     echo '</div>';
365 /**
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
374  */
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]);
393         }
394     }
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;
407     }
410     $totalresponsecount = 0;
411     foreach ($allresponses as $optionid => $userlist) {
412         if ($choice->showunanswered || $optionid) {
413             $totalresponsecount += count($userlist);
414         }
415     }
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" />';
429             }
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>";
440             }
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++;
448             }
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>";
467                     }
468                 }
469                 echo "</table></td>";
470             }
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. '" />';
485                             }
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>';
493                        }
494                     }
495                     $count++;
496                     echo '</table></td>';
497             }
498             echo "</tr><tr>";
499             $count = 1;
501             if ($choice->showunanswered) {
502                 echo "<td></td>";
503             }
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];
516                     }
517                 }
518                 echo "</td>";
519                 $count++;
520             }
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'))
534                 );
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>';
539             }
541             echo "</table></div>";
542             if ($viewresponses) {
543                 echo "</form></div>";
544             }
545             break;
546     }
547     return $display;
550 /**
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
557  */
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;
564     }
566     foreach($attemptids as $num => $attemptid) {
567         if(empty($attemptid)) {
568             unset($attemptids[$num]);
569         }
570     }
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);
579             }
580         }
581     }
582     return true;
586 /**
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.
590  *
591  * @global object
592  * @param int $id
593  * @return bool
594  */
595 function choice_delete_instance($id) {
596     global $DB;
598     if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
599         return false;
600     }
602     $result = true;
604     if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
605         $result = false;
606     }
608     if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
609         $result = false;
610     }
612     if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
613         $result = false;
614     }
616     return $result;
619 /**
620  * Returns text string which is the answer that matches the id
621  *
622  * @global object
623  * @param object $choice
624  * @param int $id
625  * @return string
626  */
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");
634     }
637 /**
638  * Gets a full choice record
639  *
640  * @global object
641  * @param int $choiceid
642  * @return object|bool The choice or false
643  */
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;
652             }
653             return $choice;
654         }
655     }
656     return false;
659 /**
660  * @return array
661  */
662 function choice_get_view_actions() {
663     return array('view','view all','report');
666 /**
667  * @return array
668  */
669 function choice_get_post_actions() {
670     return array('choose','choose again');
674 /**
675  * Implementation of the function for printing the form elements that control
676  * whether the course reset functionality affects the choice.
677  *
678  * @param object $mform form passed by reference
679  */
680 function choice_reset_course_form_definition(&$mform) {
681     $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
682     $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
685 /**
686  * Course reset form defaults.
687  *
688  * @return array
689  */
690 function choice_reset_course_form_defaults($course) {
691     return array('reset_choice'=>1);
694 /**
695  * Actual implementation of the reset course functionality, delete all the
696  * choice responses for course $data->courseid.
697  *
698  * @global object
699  * @global object
700  * @param object $data the data submitted from the reset course.
701  * @return array status array
702  */
703 function choice_reset_userdata($data) {
704     global $CFG, $DB;
706     $componentstr = get_string('modulenameplural', 'choice');
707     $status = array();
709     if (!empty($data->reset_choice)) {
710         $choicessql = "SELECT ch.id
711                        FROM {choice} ch
712                        WHERE ch.course=?";
714         $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
715         $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
716     }
718     /// updating dates - shift may be negative too
719     if ($data->timeshift) {
720         shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
721         $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
722     }
724     return $status;
727 /**
728  * @global object
729  * @global object
730  * @global object
731  * @uses CONTEXT_MODULE
732  * @param object $choice
733  * @param object $cm
734  * @param int $groupmode
735  * @return array
736  */
737 function choice_get_response_data($choice, $cm, $groupmode) {
738     global $CFG, $USER, $DB;
740     $context = context_module::instance($cm->id);
742 /// Get the current group
743     if ($groupmode > 0) {
744         $currentgroup = groups_get_activity_group($cm);
745     } else {
746         $currentgroup = 0;
747     }
749 /// Initialise the returned array, which is a matrix:  $allresponses[responseid][userid] = responseobject
750     $allresponses = array();
752 /// First get all the users who have access here
753 /// To start with we assume they are all "unanswered" then move them later
754     $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, user_picture::fields('u', array('idnumber')));
756 /// Get all the recorded responses for this choice
757     $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
759 /// Use the responses to move users into the correct column
761     if ($rawresponses) {
762         foreach ($rawresponses as $response) {
763             if (isset($allresponses[0][$response->userid])) {   // This person is enrolled and in correct group
764                 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
765                 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
766                 unset($allresponses[0][$response->userid]);   // Remove from unanswered column
767             }
768         }
769     }
770     return $allresponses;
773 /**
774  * Returns all other caps used in module
775  *
776  * @return array
777  */
778 function choice_get_extra_capabilities() {
779     return array('moodle/site:accessallgroups');
782 /**
783  * @uses FEATURE_GROUPS
784  * @uses FEATURE_GROUPINGS
785  * @uses FEATURE_GROUPMEMBERSONLY
786  * @uses FEATURE_MOD_INTRO
787  * @uses FEATURE_COMPLETION_TRACKS_VIEWS
788  * @uses FEATURE_GRADE_HAS_GRADE
789  * @uses FEATURE_GRADE_OUTCOMES
790  * @param string $feature FEATURE_xx constant for requested feature
791  * @return mixed True if module supports feature, null if doesn't know
792  */
793 function choice_supports($feature) {
794     switch($feature) {
795         case FEATURE_GROUPS:                  return true;
796         case FEATURE_GROUPINGS:               return true;
797         case FEATURE_GROUPMEMBERSONLY:        return true;
798         case FEATURE_MOD_INTRO:               return true;
799         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
800         case FEATURE_COMPLETION_HAS_RULES:    return true;
801         case FEATURE_GRADE_HAS_GRADE:         return false;
802         case FEATURE_GRADE_OUTCOMES:          return false;
803         case FEATURE_BACKUP_MOODLE2:          return true;
804         case FEATURE_SHOW_DESCRIPTION:        return true;
806         default: return null;
807     }
810 /**
811  * Adds module specific settings to the settings block
812  *
813  * @param settings_navigation $settings The settings navigation object
814  * @param navigation_node $choicenode The node to add module settings to
815  */
816 function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
817     global $PAGE;
819     if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
821         $groupmode = groups_get_activity_groupmode($PAGE->cm);
822         if ($groupmode) {
823             groups_get_activity_group($PAGE->cm, true);
824         }
825         // We only actually need the choice id here
826         $choice = new stdClass;
827         $choice->id = $PAGE->cm->instance;
828         $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode);   // Big function, approx 6 SQL calls per user
830         $responsecount =0;
831         foreach($allresponses as $optionid => $userlist) {
832             if ($optionid) {
833                 $responsecount += count($userlist);
834             }
835         }
836         $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
837     }
840 /**
841  * Obtains the automatic completion state for this choice based on any conditions
842  * in forum settings.
843  *
844  * @param object $course Course
845  * @param object $cm Course-module
846  * @param int $userid User ID
847  * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
848  * @return bool True if completed, false if not, $type if conditions not set.
849  */
850 function choice_get_completion_state($course, $cm, $userid, $type) {
851     global $CFG,$DB;
853     // Get choice details
854     $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
855             MUST_EXIST);
857     // If completion option is enabled, evaluate it and return true/false
858     if($choice->completionsubmit) {
859         return $DB->record_exists('choice_answers', array(
860                 'choiceid'=>$choice->id, 'userid'=>$userid));
861     } else {
862         // Completion option is not enabled so just return $type
863         return $type;
864     }
867 /**
868  * Return a list of page types
869  * @param string $pagetype current page type
870  * @param stdClass $parentcontext Block's parent context
871  * @param stdClass $currentcontext Current context of block
872  */
873 function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
874     $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
875     return $module_pagetype;