MDL-32438 choice: fix fatal error on making choice
[moodle.git] / mod / choice / lib.php
CommitLineData
4636bf83 1<?php
2
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/>.
0d22e7cc 17
4636bf83 18/**
750eb434 19 * @package mod-choice
4636bf83 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 */
23
17da2e6f 24/** @global int $CHOICE_COLUMN_HEIGHT */
25global $CHOICE_COLUMN_HEIGHT;
26$CHOICE_COLUMN_HEIGHT = 300;
6d6c9389 27
315d4971
RW
28/** @global int $CHOICE_COLUMN_WIDTH */
29global $CHOICE_COLUMN_WIDTH;
30$CHOICE_COLUMN_WIDTH = 300;
31
8f7dc7f1 32define('CHOICE_PUBLISH_ANONYMOUS', '0');
33define('CHOICE_PUBLISH_NAMES', '1');
6d6c9389 34
c100a341 35define('CHOICE_SHOWRESULTS_NOT', '0');
36define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
37define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
38define('CHOICE_SHOWRESULTS_ALWAYS', '3');
f9af7fd0 39
6fd87e3b 40define('CHOICE_DISPLAY_HORIZONTAL', '0');
41define('CHOICE_DISPLAY_VERTICAL', '1');
42
4636bf83 43/** @global array $CHOICE_PUBLISH */
17da2e6f 44global $CHOICE_PUBLISH;
8f7dc7f1 45$CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
46 CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
6d6c9389 47
4636bf83 48/** @global array $CHOICE_SHOWRESULTS */
17da2e6f 49global $CHOICE_SHOWRESULTS;
c100a341 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'));
f9af7fd0 54
4636bf83 55/** @global array $CHOICE_DISPLAY */
17da2e6f 56global $CHOICE_DISPLAY;
6fd87e3b 57$CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
58 CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
6d6c9389 59
60/// Standard functions /////////////////////////////////////////////////////////
61
4636bf83 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 */
0d22e7cc 70function choice_user_outline($course, $user, $mod, $choice) {
407caeeb 71 global $DB;
72 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
39790bd8 73 $result = new stdClass();
7cfc54b9 74 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
d1a67362 75 $result->time = $answer->timemodified;
0d22e7cc 76 return $result;
77 }
78 return NULL;
79}
80
4636bf83 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 */
0d22e7cc 89function choice_user_complete($course, $user, $mod, $choice) {
407caeeb 90 global $DB;
91 if ($answer = $DB->get_record('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
39790bd8 92 $result = new stdClass();
7cfc54b9 93 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
d1a67362 94 $result->time = $answer->timemodified;
7cfc54b9 95 echo get_string("answered", "choice").": $result->info. ".get_string("updated", '', userdate($result->time));
0d22e7cc 96 } else {
c4016bc1 97 print_string("notanswered", "choice");
0d22e7cc 98 }
99}
100
4636bf83 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 */
04eba58f 111function choice_add_instance($choice) {
c18269c7 112 global $DB;
04eba58f 113
114 $choice->timemodified = time();
115
ebd3c7ac 116 if (empty($choice->timerestrict)) {
d30772b2 117 $choice->timeopen = 0;
118 $choice->timeclose = 0;
119 }
120
ff8d654f 121 //insert answers
9d97f08e
PS
122 $choice->id = $DB->insert_record("choice", $choice);
123 foreach ($choice->option as $key => $value) {
124 $value = trim($value);
125 if (isset($value) && $value <> '') {
39790bd8 126 $option = new stdClass();
9d97f08e
PS
127 $option->text = $value;
128 $option->choiceid = $choice->id;
129 if (isset($choice->limit[$key])) {
130 $option->maxanswers = $choice->limit[$key];
6fd87e3b 131 }
9d97f08e
PS
132 $option->timemodified = time();
133 $DB->insert_record("choice_options", $option);
6fd87e3b 134 }
135 }
9d97f08e 136
a77a6009 137 return $choice->id;
04eba58f 138}
139
4636bf83 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 */
04eba58f 149function choice_update_instance($choice) {
c18269c7 150 global $DB;
04eba58f 151
152 $choice->id = $choice->instance;
153 $choice->timemodified = time();
154
d30772b2 155
ebd3c7ac 156 if (empty($choice->timerestrict)) {
d30772b2 157 $choice->timeopen = 0;
158 $choice->timeclose = 0;
159 }
ff8d654f 160
ebd3c7ac 161 //update, delete or insert answers
162 foreach ($choice->option as $key => $value) {
a77a6009 163 $value = trim($value);
39790bd8 164 $option = new stdClass();
ebd3c7ac 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();
a2e67a9a 171 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
ebd3c7ac 172 $option->id=$choice->optionid[$key];
af834f3e 173 if (isset($value) && $value <> '') {
c18269c7 174 $DB->update_record("choice_options", $option);
b9135eca 175 } else { //empty old option - needs to be deleted.
c18269c7 176 $DB->delete_records("choice_options", array("id"=>$option->id));
c9ff813c 177 }
ebd3c7ac 178 } else {
179 if (isset($value) && $value <> '') {
c18269c7 180 $DB->insert_record("choice_options", $option);
a77a6009 181 }
ff8d654f 182 }
6fd87e3b 183 }
d30772b2 184
c18269c7 185 return $DB->update_record('choice', $choice);
ff8d654f 186
04eba58f 187}
188
4636bf83 189/**
190 * @global object
191 * @param object $choice
192 * @param object $user
315d4971 193 * @param object $coursemodule
4636bf83 194 * @param array $allresponses
315d4971 195 * @return array
4636bf83 196 */
315d4971 197function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
407caeeb 198 global $DB;
3c56a7cc 199
315d4971 200 $cdisplay = array('options'=>array());
a61e4188 201
315d4971
RW
202 $cdisplay['limitanswers'] = true;
203 $context = get_context_instance(CONTEXT_MODULE, $coursemodule->id);
3c56a7cc 204
348630d8 205 foreach ($choice->option as $optionid => $text) {
a5f35b9f 206 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
315d4971
RW
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;
213
55963a3a 214 if (isset($allresponses[$optionid])) {
315d4971 215 $option->countanswers = count($allresponses[$optionid]);
55963a3a 216 } else {
315d4971 217 $option->countanswers = 0;
55963a3a 218 }
315d4971
RW
219 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
220 $option->attributes->checked = true;
dabfd0ed 221 }
315d4971
RW
222 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
223 $option->attributes->disabled = true;
dabfd0ed 224 }
e076641f 225 $cdisplay['options'][] = $option;
348630d8 226 }
e076641f 227 }
348630d8 228
315d4971 229 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
ebd3c7ac 230
315d4971
RW
231 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
232 $cdisplay['allowupdate'] = true;
e076641f 233 }
348630d8 234
315d4971 235 return $cdisplay;
e076641f 236}
348630d8 237
4636bf83 238/**
239 * @global object
240 * @param int $formanswer
241 * @param object $choice
242 * @param int $userid
bc499733 243 * @param object $course Course object
4636bf83 244 * @param object $cm
245 */
bc499733 246function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
516c5eca
PS
247 global $DB, $CFG;
248 require_once($CFG->libdir.'/completionlib.php');
249
407caeeb 250 $current = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
dabfd0ed 251 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
c75ba879 252
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;
407caeeb 265 $answers = $DB->get_records_sql("
266SELECT
c75ba879 267 ca.*
407caeeb 268FROM
269 {choice_answers} ca
270 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
c75ba879 271WHERE
407caeeb 272 optionid=?
273 AND gm.groupid=?", array($formanswer, $currentgroup));
c75ba879 274 } else {
275 // Groups are not used, retrieve all answers for this option ID
407caeeb 276 $answers = $DB->get_records("choice_answers", array("optionid" => $formanswer));
ff8d654f 277 }
278
c75ba879 279 if ($answers) {
280 foreach ($answers as $a) { //only return enrolled users.
4f0c2d00 281 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
c75ba879 282 $countanswers++;
283 }
284 }
285 }
286 $maxans = $choice->maxanswers[$formanswer];
39b3e7de 287 }
ff8d654f 288
289 if (!($choice->limitanswers && ($countanswers >= $maxans) )) {
39b3e7de 290 if ($current) {
ebd3c7ac 291
39b3e7de 292 $newanswer = $current;
293 $newanswer->optionid = $formanswer;
294 $newanswer->timemodified = time();
7826abc7 295 $DB->update_record("choice_answers", $newanswer);
bc499733 296 add_to_log($course->id, "choice", "choose again", "view.php?id=$cm->id", $choice->id, $cm->id);
39b3e7de 297 } else {
b09912f8 298 $newanswer = new stdClass();
39b3e7de 299 $newanswer->choiceid = $choice->id;
300 $newanswer->userid = $userid;
301 $newanswer->optionid = $formanswer;
302 $newanswer->timemodified = time();
7826abc7 303 $DB->insert_record("choice_answers", $newanswer);
bc499733
SM
304
305 // Update completion state
306 $completion = new completion_info($course);
307 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
308 $completion->update_state($cm, COMPLETION_COMPLETE);
309 }
310 add_to_log($course->id, "choice", "choose", "view.php?id=$cm->id", $choice->id, $cm->id);
39b3e7de 311 }
312 } else {
313 if (!($current->optionid==$formanswer)) { //check to see if current choice already selected - if not display error
c7281355 314 print_error('choicefull', 'choice');
39b3e7de 315 }
316 }
348630d8 317}
318
4636bf83 319/**
320 * @param array $user
321 * @param object $cm
322 * @return void Output is echo'd
323 */
a61e4188 324function choice_show_reportlink($user, $cm) {
325 $responsecount =0;
326 foreach($user as $optionid => $userlist) {
327 if ($optionid) {
328 $responsecount += count($userlist);
329 }
7b360f33 330 }
5c880488 331
39b3e7de 332 echo '<div class="reportlink">';
5c880488 333 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
39b3e7de 334 echo '</div>';
348630d8 335}
336
4636bf83 337/**
338 * @global object
4636bf83 339 * @param object $choice
340 * @param object $course
315d4971 341 * @param object $coursemodule
4636bf83 342 * @param array $allresponses
315d4971
RW
343
344 * * @param bool $allresponses
345 * @return object
4636bf83 346 */
315d4971 347function prepare_choice_show_results($choice, $course, $cm, $allresponses, $forcepublish=false) {
db8935ef 348 global $CFG, $CHOICE_COLUMN_HEIGHT, $FULLSCRIPT, $PAGE, $OUTPUT, $DB;
407caeeb 349
315d4971
RW
350 $display = clone($choice);
351 $display->coursemoduleid = $cm->id;
f7e93000
RW
352 $display->courseid = $course->id;
353
315d4971
RW
354 //overwrite options value;
355 $display->options = array();
356 $totaluser = 0;
357 foreach ($choice->option as $optionid => $optiontext) {
358 $display->options[$optionid] = new stdClass;
359 $display->options[$optionid]->text = $optiontext;
360 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
361
362 if (array_key_exists($optionid, $allresponses)) {
e076641f 363 $display->options[$optionid]->user = $allresponses[$optionid];
315d4971 364 $totaluser += count($allresponses[$optionid]);
9d624d66 365 }
315d4971
RW
366 }
367 unset($display->option);
368 unset($display->maxanswers);
369
370 $display->numberofuser = $totaluser;
371 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
372 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
373 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
374 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
f7e93000 375
9acb7700 376 if (empty($allresponses)) {
5ddd4e06 377 echo $OUTPUT->heading(get_string("nousersyet"));
9acb7700 378 return false;
39b3e7de 379 }
c2a4d016 380
315d4971 381
c2a4d016 382 $totalresponsecount = 0;
5d9d5227 383 foreach ($allresponses as $optionid => $userlist) {
c2a4d016 384 if ($choice->showunanswered || $optionid) {
385 $totalresponsecount += count($userlist);
386 }
387 }
407caeeb 388
a61e4188 389 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
348630d8 390
a61e4188 391 $hascapfullnames = has_capability('moodle/site:viewfullnames', $context);
407caeeb 392
393 $viewresponses = has_capability('mod/choice:readresponses', $context);
39b3e7de 394 switch ($forcepublish) {
395 case CHOICE_PUBLISH_NAMES:
4ec64b4f 396 echo '<div id="tablecontainer">';
397 if ($viewresponses) {
11e7b506 398 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);">';
95aa949b 399 echo '<div>';
348630d8 400 echo '<input type="hidden" name="id" value="'.$cm->id.'" />';
afb6f77d 401 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
348630d8 402 echo '<input type="hidden" name="mode" value="overview" />';
4ec64b4f 403 }
ff8d654f 404
d71bc1ab 405 echo "<table cellpadding=\"5\" cellspacing=\"10\" class=\"results names\">";
348630d8 406 echo "<tr>";
407caeeb 407
aa4836f4 408 $columncount = array(); // number of votes in each column
a61e4188 409 if ($choice->showunanswered) {
410 $columncount[0] = 0;
411 echo "<th class=\"col0 header\" scope=\"col\">";
412 print_string('notanswered', 'choice');
413 echo "</th>";
414 }
415 $count = 1;
416 foreach ($choice->option as $optionid => $optiontext) {
aa4836f4 417 $columncount[$optionid] = 0; // init counters
a61e4188 418 echo "<th class=\"col$count header\" scope=\"col\">";
419 echo format_string($optiontext);
348630d8 420 echo "</th>";
421 $count++;
422 }
423 echo "</tr><tr>";
424
82ab7cb5 425 if ($choice->showunanswered) {
a61e4188 426 echo "<td class=\"col$count data\" >";
95aa949b 427 // added empty row so that when the next iteration is empty,
034ef761 428 // we do not get <table></table> error from w3c validator
95aa949b 429 // MDL-7861
430 echo "<table class=\"choiceresponse\"><tr><td></td></tr>";
82ab7cb5 431 if (!empty($allresponses[0])) {
432 foreach ($allresponses[0] as $user) {
433 echo "<tr>";
434 echo "<td class=\"picture\">";
812dbaf7 435 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
82ab7cb5 436 echo "</td><td class=\"fullname\">";
437 echo "<a href=\"$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">";
438 echo fullname($user, $hascapfullnames);
439 echo "</a>";
440 echo "</td></tr>";
441 }
348630d8 442 }
a61e4188 443 echo "</table></td>";
444 }
a82fb0b6 445 $count = 1;
a61e4188 446 foreach ($choice->option as $optionid => $optiontext) {
447 echo '<td class="col'.$count.' data" >';
448
449 // added empty row so that when the next iteration is empty,
034ef761 450 // we do not get <table></table> error from w3c validator
a61e4188 451 // MDL-7861
452 echo '<table class="choiceresponse"><tr><td></td></tr>';
5d9d5227 453 if (isset($allresponses[$optionid])) {
454 foreach ($allresponses[$optionid] as $user) {
a61e4188 455 $columncount[$optionid] += 1;
456 echo '<tr><td class="attemptcell">';
cb4db90d 457 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
a61e4188 458 echo '<input type="checkbox" name="attemptid[]" value="'. $user->id. '" />';
459 }
460 echo '</td><td class="picture">';
812dbaf7 461 echo $OUTPUT->user_picture($user, array('courseid'=>$course->id));
a61e4188 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 $count++;
470 echo '</table></td>';
348630d8 471 }
472 echo "</tr><tr>";
a82fb0b6 473 $count = 1;
407caeeb 474
a61e4188 475 if ($choice->showunanswered) {
476 echo "<td></td>";
477 }
3a11c09f 478
a61e4188 479 foreach ($choice->option as $optionid => $optiontext) {
a82fb0b6 480 echo "<td align=\"center\" class=\"col$count count\">";
a61e4188 481 if ($choice->limitanswers) {
348630d8 482 echo get_string("taken", "choice").":";
aa4836f4 483 echo $columncount[$optionid];
71502268 484 echo "<br/>";
348630d8 485 echo get_string("limit", "choice").":";
b723a4f8 486 echo $choice->maxanswers[$optionid];
19e559e4 487 } else {
a61e4188 488 if (isset($columncount[$optionid])) {
489 echo $columncount[$optionid];
490 }
348630d8 491 }
492 echo "</td>";
493 $count++;
494 }
3402a6f3 495 echo "</tr>";
407caeeb 496
39b3e7de 497 /// Print "Select all" etc.
cb4db90d 498 if ($viewresponses and has_capability('mod/choice:deleteresponses',$context)) {
3402a6f3 499 echo '<tr><td></td><td>';
9b854b2d
DM
500 echo '<a href="javascript:select_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('selectall').'</a> / ';
501 echo '<a href="javascript:deselect_all_in(\'DIV\',null,\'tablecontainer\');">'.get_string('deselectall').'</a> ';
39b3e7de 502 echo '&nbsp;&nbsp;';
9b854b2d
DM
503 echo html_writer::label(get_string('withselected', 'choice'), 'menuaction');
504 echo html_writer::select(array('delete' => get_string('delete')), 'action', '', array(''=>get_string('withselectedusers')), array('id'=>'menuaction'));
edc28287
PS
505 $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('attemptsform', 'menuaction', ''));
506 echo '<noscript id="noscriptmenuaction" style="display:inline">';
95aa949b 507 echo '<div>';
508 echo '<input type="submit" value="'.get_string('go').'" /></div></noscript>';
3402a6f3 509 echo '</td><td></td></tr>';
39b3e7de 510 }
407caeeb 511
4ec64b4f 512 echo "</table></div>";
a61e4188 513 if ($viewresponses) {
4ec64b4f 514 echo "</form></div>";
dabfd0ed 515 }
348630d8 516 break;
9d624d66 517 }
315d4971 518 return $display;
9d624d66 519}
348630d8 520
4636bf83 521/**
522 * @global object
523 * @param array $attemptids
bc499733
SM
524 * @param object $choice Choice main table row
525 * @param object $cm Course-module object
526 * @param object $course Course object
4636bf83 527 * @return bool
528 */
bc499733 529function choice_delete_responses($attemptids, $choice, $cm, $course) {
516c5eca
PS
530 global $DB, $CFG;
531 require_once($CFG->libdir.'/completionlib.php');
532
dabfd0ed 533 if(!is_array($attemptids) || empty($attemptids)) {
348630d8 534 return false;
535 }
536
537 foreach($attemptids as $num => $attemptid) {
538 if(empty($attemptid)) {
539 unset($attemptids[$num]);
540 }
541 }
542
bc499733 543 $completion = new completion_info($course);
348630d8 544 foreach($attemptids as $attemptid) {
bc499733
SM
545 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $attemptid))) {
546 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $attemptid));
547 // Update completion state
548 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
549 $completion->update_state($cm, COMPLETION_INCOMPLETE, $attemptid);
550 }
348630d8 551 }
ebd3c7ac 552 }
348630d8 553 return true;
554}
555
04eba58f 556
4636bf83 557/**
558 * Given an ID of an instance of this module,
559 * this function will permanently delete the instance
560 * and any data that depends on it.
561 *
562 * @global object
563 * @param int $id
564 * @return bool
565 */
04eba58f 566function choice_delete_instance($id) {
c18269c7 567 global $DB;
04eba58f 568
c18269c7 569 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
04eba58f 570 return false;
571 }
572
573 $result = true;
574
c18269c7 575 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
04eba58f 576 $result = false;
577 }
578
c18269c7 579 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
04eba58f 580 $result = false;
581 }
a77a6009 582
c18269c7 583 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
6fd87e3b 584 $result = false;
ebd3c7ac 585 }
04eba58f 586
587 return $result;
588}
589
4636bf83 590/**
591 * Returns text string which is the answer that matches the id
592 *
593 * @global object
594 * @param object $choice
595 * @param int $id
596 * @return string
597 */
a77a6009 598function choice_get_option_text($choice, $id) {
407caeeb 599 global $DB;
4636bf83 600
407caeeb 601 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
a77a6009 602 return $result->text;
6fd87e3b 603 } else {
604 return get_string("notanswered", "choice");
ff8d654f 605 }
c4016bc1 606}
607
4636bf83 608/**
609 * Gets a full choice record
610 *
611 * @global object
612 * @param int $choiceid
613 * @return object|bool The choice or false
614 */
cd3fccff 615function choice_get_choice($choiceid) {
407caeeb 616 global $DB;
a77a6009 617
407caeeb 618 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
619 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
ff8d654f 620 foreach ($options as $option) {
ebd3c7ac 621 $choice->option[$option->id] = $option->text;
c9ff813c 622 $choice->maxanswers[$option->id] = $option->maxanswers;
ff8d654f 623 }
a77a6009 624 return $choice;
625 }
626 }
627 return false;
cd3fccff 628}
629
4636bf83 630/**
631 * @return array
632 */
f3221af9 633function choice_get_view_actions() {
634 return array('view','view all','report');
635}
636
4636bf83 637/**
638 * @return array
639 */
f3221af9 640function choice_get_post_actions() {
641 return array('choose','choose again');
642}
643
0b5a80a1 644
645/**
646 * Implementation of the function for printing the form elements that control
647 * whether the course reset functionality affects the choice.
1adbd2c3 648 *
4636bf83 649 * @param object $mform form passed by reference
0b5a80a1 650 */
651function choice_reset_course_form_definition(&$mform) {
652 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
653 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
654}
655
656/**
657 * Course reset form defaults.
4636bf83 658 *
659 * @return array
0b5a80a1 660 */
661function choice_reset_course_form_defaults($course) {
662 return array('reset_choice'=>1);
663}
664
665/**
72d2982e 666 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 667 * choice responses for course $data->courseid.
4636bf83 668 *
669 * @global object
670 * @global object
671 * @param object $data the data submitted from the reset course.
0b5a80a1 672 * @return array status array
673 */
674function choice_reset_userdata($data) {
407caeeb 675 global $CFG, $DB;
0b5a80a1 676
677 $componentstr = get_string('modulenameplural', 'choice');
678 $status = array();
679
680 if (!empty($data->reset_choice)) {
681 $choicessql = "SELECT ch.id
f7e93000
RW
682 FROM {choice} ch
683 WHERE ch.course=?";
0b5a80a1 684
407caeeb 685 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
0b5a80a1 686 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
687 }
688
689 /// updating dates - shift may be negative too
690 if ($data->timeshift) {
691 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
692 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
693 }
694
695 return $status;
696}
697
4636bf83 698/**
699 * @global object
700 * @global object
701 * @global object
702 * @uses CONTEXT_MODULE
703 * @param object $choice
704 * @param object $cm
705 * @param int $groupmode
706 * @return array
707 */
a61e4188 708function choice_get_response_data($choice, $cm, $groupmode) {
407caeeb 709 global $CFG, $USER, $DB;
a61e4188 710
711 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
712
713/// Get the current group
714 if ($groupmode > 0) {
715 $currentgroup = groups_get_activity_group($cm);
716 } else {
717 $currentgroup = 0;
718 }
719
5d9d5227 720/// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
721 $allresponses = array();
a61e4188 722
723/// First get all the users who have access here
724/// To start with we assume they are all "unanswered" then move them later
3a11c09f 725 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, user_picture::fields('u', array('idnumber')), 'u.lastname ASC,u.firstname ASC');
a61e4188 726
727/// Get all the recorded responses for this choice
407caeeb 728 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
a61e4188 729
730/// Use the responses to move users into the correct column
731
5d9d5227 732 if ($rawresponses) {
733 foreach ($rawresponses as $response) {
734 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
735 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
736 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
737 unset($allresponses[0][$response->userid]); // Remove from unanswered column
a61e4188 738 }
739 }
f7e93000 740 }
5d9d5227 741 return $allresponses;
f432bebf 742}
a61e4188 743
f432bebf 744/**
745 * Returns all other caps used in module
4636bf83 746 *
747 * @return array
f432bebf 748 */
db19ec01 749function choice_get_extra_capabilities() {
f432bebf 750 return array('moodle/site:accessallgroups');
a61e4188 751}
f432bebf 752
18a2a0cb 753/**
4636bf83 754 * @uses FEATURE_GROUPS
755 * @uses FEATURE_GROUPINGS
756 * @uses FEATURE_GROUPMEMBERSONLY
757 * @uses FEATURE_MOD_INTRO
758 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
759 * @uses FEATURE_GRADE_HAS_GRADE
760 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 761 * @param string $feature FEATURE_xx constant for requested feature
762 * @return mixed True if module supports feature, null if doesn't know
763 */
764function choice_supports($feature) {
765 switch($feature) {
42f103be 766 case FEATURE_GROUPS: return true;
767 case FEATURE_GROUPINGS: return true;
768 case FEATURE_GROUPMEMBERSONLY: return true;
dc5c2bd9 769 case FEATURE_MOD_INTRO: return true;
18a2a0cb 770 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
bc499733 771 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 772 case FEATURE_GRADE_HAS_GRADE: return false;
773 case FEATURE_GRADE_OUTCOMES: return false;
98baf0d7 774 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 775 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 776
18a2a0cb 777 default: return null;
778 }
779}
97011c64 780
0b29477b
SH
781/**
782 * Adds module specific settings to the settings block
783 *
784 * @param settings_navigation $settings The settings navigation object
785 * @param navigation_node $choicenode The node to add module settings to
786 */
787function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
788 global $PAGE;
97011c64 789
790 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
791
792 $groupmode = groups_get_activity_groupmode($PAGE->cm);
793 if ($groupmode) {
794 groups_get_activity_group($PAGE->cm, true);
795 }
56115eea
SH
796 // We only actually need the choice id here
797 $choice = new stdClass;
798 $choice->id = $PAGE->cm->instance;
97011c64 799 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode); // Big function, approx 6 SQL calls per user
800
801 $responsecount =0;
802 foreach($allresponses as $optionid => $userlist) {
803 if ($optionid) {
804 $responsecount += count($userlist);
805 }
806 }
0b29477b 807 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
97011c64 808 }
98baf0d7 809}
bc499733
SM
810
811/**
812 * Obtains the automatic completion state for this choice based on any conditions
813 * in forum settings.
814 *
815 * @param object $course Course
816 * @param object $cm Course-module
817 * @param int $userid User ID
818 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
819 * @return bool True if completed, false if not, $type if conditions not set.
820 */
821function choice_get_completion_state($course, $cm, $userid, $type) {
822 global $CFG,$DB;
823
824 // Get choice details
825 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
826 MUST_EXIST);
827
516c5eca 828 // If completion option is enabled, evaluate it and return true/false
bc499733
SM
829 if($choice->completionsubmit) {
830 return $DB->record_exists('choice_answers', array(
831 'choiceid'=>$choice->id, 'userid'=>$userid));
832 } else {
833 // Completion option is not enabled so just return $type
834 return $type;
835 }
836}
b1627a92
DC
837
838/**
839 * Return a list of page types
840 * @param string $pagetype current page type
841 * @param stdClass $parentcontext Block's parent context
842 * @param stdClass $currentcontext Current context of block
843 */
b38e2e28 844function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
845 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
846 return $module_pagetype;
847}