MDL-23273 mod_choice: Using locks to ensure choice limits
[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/**
c7afe6b7 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 202 $cdisplay['limitanswers'] = true;
327c67a9 203 $context = context_module::instance($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;
ba939078 210 $option->text = format_string($text);
315d4971
RW
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/**
e776b415
ZD
239 * Process user submitted answers for a choice,
240 * and either updating them or saving new answers.
241 *
242 * @param int $formanswer users submitted answers.
243 * @param object $choice the selected choice.
244 * @param int $userid user identifier.
245 * @param object $course current course.
246 * @param object $cm course context.
247 * @return void
4636bf83 248 */
bc499733 249function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
516c5eca
PS
250 global $DB, $CFG;
251 require_once($CFG->libdir.'/completionlib.php');
252
54bdf1d4
MA
253 if (empty($formanswer)) {
254 print_error('atleastoneoption', 'choice');
255 }
256
257 if (is_array($formanswer)) {
258 if (!$choice->allowmultiple) {
259 print_error('multiplenotallowederror', 'choice');
260 }
261 $formanswers = $formanswer;
262 } else {
263 $formanswers = array($formanswer);
264 }
265
e776b415
ZD
266 // Start lock to prevent synchronous access to the same data
267 // before it's updated.
268 $timeout = 10;
269 $locktype = 'mod_choice_choice_user_submit_response';
270 // Limiting access to this choice.
271 $resouce = 'choiceid:' . $choice->id;
272 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
273
274 // Opening the lock.
275 $choicelock = $lockfactory->get_lock($resouce, $timeout);
276 if (!$choicelock) {
277 print_error('cannotsubmit', 'choice');
278 }
279
54bdf1d4 280 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
327c67a9 281 $context = context_module::instance($cm->id);
c75ba879 282
cbb1677c 283 $choicesexceeded = false;
54bdf1d4
MA
284 $countanswers = array();
285 foreach ($formanswers as $val) {
286 $countanswers[$val] = 0;
287 }
c75ba879 288 if($choice->limitanswers) {
289 // Find out whether groups are being used and enabled
290 if (groups_get_activity_groupmode($cm) > 0) {
291 $currentgroup = groups_get_activity_group($cm);
292 } else {
293 $currentgroup = 0;
294 }
54bdf1d4
MA
295
296 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
297
c75ba879 298 if($currentgroup) {
299 // If groups are being used, retrieve responses only for users in
300 // current group
301 global $CFG;
54bdf1d4
MA
302
303 $params['groupid'] = $currentgroup;
cbb1677c
SH
304 $sql = "SELECT ca.*
305 FROM {choice_answers} ca
306 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
307 WHERE optionid $insql
308 AND gm.groupid= :groupid";
c75ba879 309 } else {
310 // Groups are not used, retrieve all answers for this option ID
cbb1677c
SH
311 $sql = "SELECT ca.*
312 FROM {choice_answers} ca
313 WHERE optionid $insql";
ff8d654f 314 }
315
cbb1677c 316 $answers = $DB->get_records_sql($sql, $params);
c75ba879 317 if ($answers) {
318 foreach ($answers as $a) { //only return enrolled users.
4f0c2d00 319 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
54bdf1d4 320 $countanswers[$a->optionid]++;
c75ba879 321 }
322 }
323 }
54bdf1d4 324 foreach ($countanswers as $opt => $count) {
e776b415 325 if ($count >= $choice->maxanswers[$opt]) {
54bdf1d4
MA
326 $choicesexceeded = true;
327 break;
328 }
329 }
39b3e7de 330 }
ff8d654f 331
cbb1677c 332 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
54bdf1d4
MA
333 if (!($choice->limitanswers && $choicesexceeded)) {
334 $answersnapshots = array();
39b3e7de 335 if ($current) {
e776b415 336 // Update an existing answer.
54bdf1d4
MA
337 $existingchoices = array();
338 foreach ($current as $c) {
339 if (in_array($c->optionid, $formanswers)) {
340 $existingchoices[] = $c->optionid;
cbb1677c
SH
341 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
342 $answersnapshots[] = $c;
54bdf1d4
MA
343 } else {
344 $DB->delete_records('choice_answers', array('id' => $c->id));
345 }
346 }
347
348 // Add new ones.
349 foreach ($formanswers as $f) {
350 if (!in_array($f, $existingchoices)) {
351 $newanswer = new stdClass();
352 $newanswer->optionid = $f;
353 $newanswer->choiceid = $choice->id;
354 $newanswer->userid = $userid;
355 $newanswer->timemodified = time();
356 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
357 $answersnapshots[] = $newanswer;
358 }
359 }
8a941443 360
e776b415
ZD
361 // Initialised as true, meaning we updated the answer.
362 $answerupdated = true;
39b3e7de 363 } else {
e776b415 364 // Add new answer.
54bdf1d4
MA
365 foreach ($formanswers as $answer) {
366 $newanswer = new stdClass();
367 $newanswer->choiceid = $choice->id;
368 $newanswer->userid = $userid;
369 $newanswer->optionid = $answer;
370 $newanswer->timemodified = time();
371 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
372 $answersnapshots[] = $newanswer;
373 }
bc499733
SM
374
375 // Update completion state
376 $completion = new completion_info($course);
377 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
378 $completion->update_state($cm, COMPLETION_COMPLETE);
379 }
8a941443 380
e776b415
ZD
381 // Initalised as false, meaning we submitted a new answer.
382 $answerupdated = false;
39b3e7de 383 }
384 } else {
54bdf1d4
MA
385 // Check to see if current choice already selected - if not display error.
386 $currentids = array_keys($current);
e776b415 387
54bdf1d4 388 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
e776b415
ZD
389 // Release lock before error.
390 $choicelock->release();
c7281355 391 print_error('choicefull', 'choice');
39b3e7de 392 }
393 }
e776b415
ZD
394
395 // Release lock.
396 $choicelock->release();
397
398 // Now record completed event.
399 if (isset($answerupdated)) {
400 $eventdata = array();
401 $eventdata['context'] = $context;
402 $eventdata['objectid'] = $choice->id;
403 $eventdata['userid'] = $userid;
404 $eventdata['courseid'] = $course->id;
405 $eventdata['other'] = array();
406 $eventdata['other']['choiceid'] = $choice->id;
407
408 if ($answerupdated) {
409 $eventdata['other']['optionid'] = $formanswer;
410 $event = \mod_choice\event\answer_updated::create($eventdata);
411 } else {
412 $eventdata['other']['optionid'] = $formanswers;
413 $event = \mod_choice\event\answer_submitted::create($eventdata);
414 }
415 $event->add_record_snapshot('course', $course);
416 $event->add_record_snapshot('course_modules', $cm);
417 $event->add_record_snapshot('choice', $choice);
418 foreach ($answersnapshots as $record) {
419 $event->add_record_snapshot('choice_answers', $record);
420 }
421 $event->trigger();
422 }
348630d8 423}
424
4636bf83 425/**
426 * @param array $user
427 * @param object $cm
428 * @return void Output is echo'd
429 */
a61e4188 430function choice_show_reportlink($user, $cm) {
54bdf1d4 431 $userschosen = array();
a61e4188 432 foreach($user as $optionid => $userlist) {
433 if ($optionid) {
54bdf1d4 434 $userschosen = array_merge($userschosen, array_keys($userlist));
a61e4188 435 }
7b360f33 436 }
54bdf1d4 437 $responsecount = count(array_unique($userschosen));
5c880488 438
39b3e7de 439 echo '<div class="reportlink">';
5c880488 440 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
39b3e7de 441 echo '</div>';
348630d8 442}
443
4636bf83 444/**
445 * @global object
4636bf83 446 * @param object $choice
447 * @param object $course
315d4971 448 * @param object $coursemodule
4636bf83 449 * @param array $allresponses
315d4971
RW
450
451 * * @param bool $allresponses
452 * @return object
4636bf83 453 */
634a5c0b
MG
454function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
455 global $OUTPUT;
407caeeb 456
315d4971
RW
457 $display = clone($choice);
458 $display->coursemoduleid = $cm->id;
f7e93000
RW
459 $display->courseid = $course->id;
460
315d4971
RW
461 //overwrite options value;
462 $display->options = array();
463 $totaluser = 0;
464 foreach ($choice->option as $optionid => $optiontext) {
465 $display->options[$optionid] = new stdClass;
466 $display->options[$optionid]->text = $optiontext;
467 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
468
469 if (array_key_exists($optionid, $allresponses)) {
e076641f 470 $display->options[$optionid]->user = $allresponses[$optionid];
315d4971 471 $totaluser += count($allresponses[$optionid]);
9d624d66 472 }
315d4971
RW
473 }
474 unset($display->option);
475 unset($display->maxanswers);
476
477 $display->numberofuser = $totaluser;
327c67a9 478 $context = context_module::instance($cm->id);
315d4971
RW
479 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
480 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
481 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
f7e93000 482
9acb7700 483 if (empty($allresponses)) {
8f0767f1 484 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
9acb7700 485 return false;
39b3e7de 486 }
c2a4d016 487
315d4971 488 return $display;
9d624d66 489}
348630d8 490
4636bf83 491/**
492 * @global object
493 * @param array $attemptids
bc499733
SM
494 * @param object $choice Choice main table row
495 * @param object $cm Course-module object
496 * @param object $course Course object
4636bf83 497 * @return bool
498 */
bc499733 499function choice_delete_responses($attemptids, $choice, $cm, $course) {
516c5eca
PS
500 global $DB, $CFG;
501 require_once($CFG->libdir.'/completionlib.php');
502
dabfd0ed 503 if(!is_array($attemptids) || empty($attemptids)) {
348630d8 504 return false;
505 }
506
507 foreach($attemptids as $num => $attemptid) {
508 if(empty($attemptid)) {
509 unset($attemptids[$num]);
510 }
511 }
512
bc499733 513 $completion = new completion_info($course);
348630d8 514 foreach($attemptids as $attemptid) {
54bdf1d4
MA
515 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
516 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
bc499733
SM
517 // Update completion state
518 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
519 $completion->update_state($cm, COMPLETION_INCOMPLETE, $attemptid);
520 }
348630d8 521 }
ebd3c7ac 522 }
348630d8 523 return true;
524}
525
04eba58f 526
4636bf83 527/**
528 * Given an ID of an instance of this module,
529 * this function will permanently delete the instance
530 * and any data that depends on it.
531 *
532 * @global object
533 * @param int $id
534 * @return bool
535 */
04eba58f 536function choice_delete_instance($id) {
c18269c7 537 global $DB;
04eba58f 538
c18269c7 539 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
04eba58f 540 return false;
541 }
542
543 $result = true;
544
c18269c7 545 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
04eba58f 546 $result = false;
547 }
548
c18269c7 549 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
04eba58f 550 $result = false;
551 }
a77a6009 552
c18269c7 553 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
6fd87e3b 554 $result = false;
ebd3c7ac 555 }
04eba58f 556
557 return $result;
558}
559
4636bf83 560/**
561 * Returns text string which is the answer that matches the id
562 *
563 * @global object
564 * @param object $choice
565 * @param int $id
566 * @return string
567 */
a77a6009 568function choice_get_option_text($choice, $id) {
407caeeb 569 global $DB;
4636bf83 570
407caeeb 571 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
a77a6009 572 return $result->text;
6fd87e3b 573 } else {
574 return get_string("notanswered", "choice");
ff8d654f 575 }
c4016bc1 576}
577
4636bf83 578/**
579 * Gets a full choice record
580 *
581 * @global object
582 * @param int $choiceid
583 * @return object|bool The choice or false
584 */
cd3fccff 585function choice_get_choice($choiceid) {
407caeeb 586 global $DB;
a77a6009 587
407caeeb 588 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
589 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
ff8d654f 590 foreach ($options as $option) {
ebd3c7ac 591 $choice->option[$option->id] = $option->text;
c9ff813c 592 $choice->maxanswers[$option->id] = $option->maxanswers;
ff8d654f 593 }
a77a6009 594 return $choice;
595 }
596 }
597 return false;
cd3fccff 598}
599
4636bf83 600/**
b2b4ec30
RT
601 * List the actions that correspond to a view of this module.
602 * This is used by the participation report.
603 *
604 * Note: This is not used by new logging system. Event with
605 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
606 * be considered as view action.
607 *
4636bf83 608 * @return array
609 */
f3221af9 610function choice_get_view_actions() {
cf051cc4 611 return array('view','view all','report');
f3221af9 612}
613
4636bf83 614/**
b2b4ec30
RT
615 * List the actions that correspond to a post of this module.
616 * This is used by the participation report.
617 *
618 * Note: This is not used by new logging system. Event with
619 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
620 * will be considered as post action.
621 *
4636bf83 622 * @return array
623 */
f3221af9 624function choice_get_post_actions() {
625 return array('choose','choose again');
626}
627
0b5a80a1 628
629/**
630 * Implementation of the function for printing the form elements that control
631 * whether the course reset functionality affects the choice.
1adbd2c3 632 *
4636bf83 633 * @param object $mform form passed by reference
0b5a80a1 634 */
635function choice_reset_course_form_definition(&$mform) {
636 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
637 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
638}
639
640/**
641 * Course reset form defaults.
4636bf83 642 *
643 * @return array
0b5a80a1 644 */
645function choice_reset_course_form_defaults($course) {
646 return array('reset_choice'=>1);
647}
648
649/**
72d2982e 650 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 651 * choice responses for course $data->courseid.
4636bf83 652 *
653 * @global object
654 * @global object
655 * @param object $data the data submitted from the reset course.
0b5a80a1 656 * @return array status array
657 */
658function choice_reset_userdata($data) {
407caeeb 659 global $CFG, $DB;
0b5a80a1 660
661 $componentstr = get_string('modulenameplural', 'choice');
662 $status = array();
663
664 if (!empty($data->reset_choice)) {
665 $choicessql = "SELECT ch.id
f7e93000
RW
666 FROM {choice} ch
667 WHERE ch.course=?";
0b5a80a1 668
407caeeb 669 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
0b5a80a1 670 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
671 }
672
673 /// updating dates - shift may be negative too
674 if ($data->timeshift) {
675 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
676 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
677 }
678
679 return $status;
680}
681
4636bf83 682/**
683 * @global object
684 * @global object
685 * @global object
686 * @uses CONTEXT_MODULE
687 * @param object $choice
688 * @param object $cm
689 * @param int $groupmode
690 * @return array
691 */
a61e4188 692function choice_get_response_data($choice, $cm, $groupmode) {
407caeeb 693 global $CFG, $USER, $DB;
a61e4188 694
327c67a9 695 $context = context_module::instance($cm->id);
a61e4188 696
697/// Get the current group
698 if ($groupmode > 0) {
699 $currentgroup = groups_get_activity_group($cm);
700 } else {
701 $currentgroup = 0;
702 }
703
5d9d5227 704/// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
705 $allresponses = array();
a61e4188 706
707/// First get all the users who have access here
708/// To start with we assume they are all "unanswered" then move them later
9695ff81 709 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup, user_picture::fields('u', array('idnumber')));
a61e4188 710
711/// Get all the recorded responses for this choice
407caeeb 712 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
a61e4188 713
714/// Use the responses to move users into the correct column
715
5d9d5227 716 if ($rawresponses) {
54bdf1d4 717 $answeredusers = array();
5d9d5227 718 foreach ($rawresponses as $response) {
719 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
720 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
721 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
54bdf1d4
MA
722 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
723 $answeredusers[] = $response->userid;
a61e4188 724 }
725 }
54bdf1d4
MA
726 foreach ($answeredusers as $answereduser) {
727 unset($allresponses[0][$answereduser]);
728 }
f7e93000 729 }
5d9d5227 730 return $allresponses;
f432bebf 731}
a61e4188 732
f432bebf 733/**
734 * Returns all other caps used in module
4636bf83 735 *
736 * @return array
f432bebf 737 */
db19ec01 738function choice_get_extra_capabilities() {
f432bebf 739 return array('moodle/site:accessallgroups');
a61e4188 740}
f432bebf 741
18a2a0cb 742/**
4636bf83 743 * @uses FEATURE_GROUPS
744 * @uses FEATURE_GROUPINGS
4636bf83 745 * @uses FEATURE_MOD_INTRO
746 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
747 * @uses FEATURE_GRADE_HAS_GRADE
748 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 749 * @param string $feature FEATURE_xx constant for requested feature
750 * @return mixed True if module supports feature, null if doesn't know
751 */
752function choice_supports($feature) {
753 switch($feature) {
42f103be 754 case FEATURE_GROUPS: return true;
755 case FEATURE_GROUPINGS: return true;
dc5c2bd9 756 case FEATURE_MOD_INTRO: return true;
18a2a0cb 757 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
bc499733 758 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 759 case FEATURE_GRADE_HAS_GRADE: return false;
760 case FEATURE_GRADE_OUTCOMES: return false;
98baf0d7 761 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 762 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 763
18a2a0cb 764 default: return null;
765 }
766}
97011c64 767
0b29477b
SH
768/**
769 * Adds module specific settings to the settings block
770 *
771 * @param settings_navigation $settings The settings navigation object
772 * @param navigation_node $choicenode The node to add module settings to
773 */
774function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
775 global $PAGE;
97011c64 776
777 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
778
779 $groupmode = groups_get_activity_groupmode($PAGE->cm);
780 if ($groupmode) {
781 groups_get_activity_group($PAGE->cm, true);
782 }
56115eea
SH
783 // We only actually need the choice id here
784 $choice = new stdClass;
785 $choice->id = $PAGE->cm->instance;
97011c64 786 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode); // Big function, approx 6 SQL calls per user
787
788 $responsecount =0;
789 foreach($allresponses as $optionid => $userlist) {
790 if ($optionid) {
791 $responsecount += count($userlist);
792 }
793 }
0b29477b 794 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
97011c64 795 }
98baf0d7 796}
bc499733
SM
797
798/**
799 * Obtains the automatic completion state for this choice based on any conditions
800 * in forum settings.
801 *
802 * @param object $course Course
803 * @param object $cm Course-module
804 * @param int $userid User ID
805 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
806 * @return bool True if completed, false if not, $type if conditions not set.
807 */
808function choice_get_completion_state($course, $cm, $userid, $type) {
809 global $CFG,$DB;
810
811 // Get choice details
812 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
813 MUST_EXIST);
814
516c5eca 815 // If completion option is enabled, evaluate it and return true/false
bc499733
SM
816 if($choice->completionsubmit) {
817 return $DB->record_exists('choice_answers', array(
818 'choiceid'=>$choice->id, 'userid'=>$userid));
819 } else {
820 // Completion option is not enabled so just return $type
821 return $type;
822 }
823}
b1627a92
DC
824
825/**
826 * Return a list of page types
827 * @param string $pagetype current page type
828 * @param stdClass $parentcontext Block's parent context
829 * @param stdClass $currentcontext Current context of block
830 */
b38e2e28 831function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
832 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
833 return $module_pagetype;
834}