MDL-55253 mod_choice: prevent direct script access to lib files.
[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
73b1d580
SB
24defined('MOODLE_INTERNAL') || die();
25
17da2e6f 26/** @global int $CHOICE_COLUMN_HEIGHT */
27global $CHOICE_COLUMN_HEIGHT;
28$CHOICE_COLUMN_HEIGHT = 300;
6d6c9389 29
315d4971
RW
30/** @global int $CHOICE_COLUMN_WIDTH */
31global $CHOICE_COLUMN_WIDTH;
32$CHOICE_COLUMN_WIDTH = 300;
33
8f7dc7f1 34define('CHOICE_PUBLISH_ANONYMOUS', '0');
35define('CHOICE_PUBLISH_NAMES', '1');
6d6c9389 36
c100a341 37define('CHOICE_SHOWRESULTS_NOT', '0');
38define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
39define('CHOICE_SHOWRESULTS_AFTER_CLOSE', '2');
40define('CHOICE_SHOWRESULTS_ALWAYS', '3');
f9af7fd0 41
6fd87e3b 42define('CHOICE_DISPLAY_HORIZONTAL', '0');
43define('CHOICE_DISPLAY_VERTICAL', '1');
44
4636bf83 45/** @global array $CHOICE_PUBLISH */
17da2e6f 46global $CHOICE_PUBLISH;
8f7dc7f1 47$CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS => get_string('publishanonymous', 'choice'),
48 CHOICE_PUBLISH_NAMES => get_string('publishnames', 'choice'));
6d6c9389 49
4636bf83 50/** @global array $CHOICE_SHOWRESULTS */
17da2e6f 51global $CHOICE_SHOWRESULTS;
c100a341 52$CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT => get_string('publishnot', 'choice'),
53 CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
54 CHOICE_SHOWRESULTS_AFTER_CLOSE => get_string('publishafterclose', 'choice'),
55 CHOICE_SHOWRESULTS_ALWAYS => get_string('publishalways', 'choice'));
f9af7fd0 56
4636bf83 57/** @global array $CHOICE_DISPLAY */
17da2e6f 58global $CHOICE_DISPLAY;
6fd87e3b 59$CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL => get_string('displayhorizontal', 'choice'),
60 CHOICE_DISPLAY_VERTICAL => get_string('displayvertical','choice'));
6d6c9389 61
62/// Standard functions /////////////////////////////////////////////////////////
63
4636bf83 64/**
65 * @global object
66 * @param object $course
67 * @param object $user
68 * @param object $mod
69 * @param object $choice
70 * @return object|null
71 */
0d22e7cc 72function choice_user_outline($course, $user, $mod, $choice) {
407caeeb 73 global $DB;
74 if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
39790bd8 75 $result = new stdClass();
7cfc54b9 76 $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
d1a67362 77 $result->time = $answer->timemodified;
0d22e7cc 78 return $result;
79 }
80 return NULL;
81}
82
4636bf83 83/**
42dfbb54
MG
84 * Callback for the "Complete" report - prints the activity summary for the given user
85 *
4636bf83 86 * @param object $course
87 * @param object $user
88 * @param object $mod
89 * @param object $choice
4636bf83 90 */
0d22e7cc 91function choice_user_complete($course, $user, $mod, $choice) {
407caeeb 92 global $DB;
42dfbb54
MG
93 if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
94 $info = [];
95 foreach ($answers as $answer) {
96 $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
97 }
98 core_collator::asort($info);
99 echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
100 get_string("updated", '', userdate($answer->timemodified));
0d22e7cc 101 } else {
c4016bc1 102 print_string("notanswered", "choice");
0d22e7cc 103 }
104}
105
4636bf83 106/**
107 * Given an object containing all the necessary data,
108 * (defined by the form in mod_form.php) this function
109 * will create a new instance and return the id number
110 * of the new instance.
111 *
112 * @global object
113 * @param object $choice
114 * @return int
115 */
04eba58f 116function choice_add_instance($choice) {
9be80529
SB
117 global $DB, $CFG;
118 require_once($CFG->dirroot.'/mod/choice/locallib.php');
04eba58f 119
120 $choice->timemodified = time();
121
ebd3c7ac 122 if (empty($choice->timerestrict)) {
d30772b2 123 $choice->timeopen = 0;
124 $choice->timeclose = 0;
125 }
126
ff8d654f 127 //insert answers
9d97f08e
PS
128 $choice->id = $DB->insert_record("choice", $choice);
129 foreach ($choice->option as $key => $value) {
130 $value = trim($value);
131 if (isset($value) && $value <> '') {
39790bd8 132 $option = new stdClass();
9d97f08e
PS
133 $option->text = $value;
134 $option->choiceid = $choice->id;
135 if (isset($choice->limit[$key])) {
136 $option->maxanswers = $choice->limit[$key];
6fd87e3b 137 }
9d97f08e
PS
138 $option->timemodified = time();
139 $DB->insert_record("choice_options", $option);
6fd87e3b 140 }
141 }
9d97f08e 142
9be80529
SB
143 // Add calendar events if necessary.
144 choice_set_events($choice);
145
a77a6009 146 return $choice->id;
04eba58f 147}
148
4636bf83 149/**
150 * Given an object containing all the necessary data,
151 * (defined by the form in mod_form.php) this function
152 * will update an existing instance with new data.
153 *
154 * @global object
155 * @param object $choice
156 * @return bool
157 */
04eba58f 158function choice_update_instance($choice) {
9be80529
SB
159 global $DB, $CFG;
160 require_once($CFG->dirroot.'/mod/choice/locallib.php');
04eba58f 161
162 $choice->id = $choice->instance;
163 $choice->timemodified = time();
164
d30772b2 165
ebd3c7ac 166 if (empty($choice->timerestrict)) {
d30772b2 167 $choice->timeopen = 0;
168 $choice->timeclose = 0;
169 }
ff8d654f 170
ebd3c7ac 171 //update, delete or insert answers
172 foreach ($choice->option as $key => $value) {
a77a6009 173 $value = trim($value);
39790bd8 174 $option = new stdClass();
ebd3c7ac 175 $option->text = $value;
176 $option->choiceid = $choice->id;
177 if (isset($choice->limit[$key])) {
178 $option->maxanswers = $choice->limit[$key];
179 }
180 $option->timemodified = time();
a2e67a9a 181 if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
ebd3c7ac 182 $option->id=$choice->optionid[$key];
af834f3e 183 if (isset($value) && $value <> '') {
c18269c7 184 $DB->update_record("choice_options", $option);
025188da
SB
185 } else {
186 // Remove the empty (unused) option.
187 $DB->delete_records("choice_options", array("id" => $option->id));
188 // Delete any answers associated with this option.
189 $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
c9ff813c 190 }
ebd3c7ac 191 } else {
192 if (isset($value) && $value <> '') {
c18269c7 193 $DB->insert_record("choice_options", $option);
a77a6009 194 }
ff8d654f 195 }
6fd87e3b 196 }
d30772b2 197
9be80529
SB
198 // Add calendar events if necessary.
199 choice_set_events($choice);
200
c18269c7 201 return $DB->update_record('choice', $choice);
ff8d654f 202
04eba58f 203}
204
4636bf83 205/**
206 * @global object
207 * @param object $choice
208 * @param object $user
315d4971 209 * @param object $coursemodule
4636bf83 210 * @param array $allresponses
315d4971 211 * @return array
4636bf83 212 */
315d4971 213function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
407caeeb 214 global $DB;
3c56a7cc 215
315d4971 216 $cdisplay = array('options'=>array());
a61e4188 217
315d4971 218 $cdisplay['limitanswers'] = true;
327c67a9 219 $context = context_module::instance($coursemodule->id);
3c56a7cc 220
348630d8 221 foreach ($choice->option as $optionid => $text) {
a5f35b9f 222 if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
315d4971
RW
223 $option = new stdClass;
224 $option->attributes = new stdClass;
225 $option->attributes->value = $optionid;
ba939078 226 $option->text = format_string($text);
315d4971
RW
227 $option->maxanswers = $choice->maxanswers[$optionid];
228 $option->displaylayout = $choice->display;
229
55963a3a 230 if (isset($allresponses[$optionid])) {
315d4971 231 $option->countanswers = count($allresponses[$optionid]);
55963a3a 232 } else {
315d4971 233 $option->countanswers = 0;
55963a3a 234 }
315d4971
RW
235 if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
236 $option->attributes->checked = true;
dabfd0ed 237 }
315d4971
RW
238 if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
239 $option->attributes->disabled = true;
dabfd0ed 240 }
e076641f 241 $cdisplay['options'][] = $option;
348630d8 242 }
e076641f 243 }
348630d8 244
315d4971 245 $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
ebd3c7ac 246
315d4971
RW
247 if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
248 $cdisplay['allowupdate'] = true;
e076641f 249 }
348630d8 250
c30dbd69
TB
251 if ($choice->showpreview && $choice->timeopen > time()) {
252 $cdisplay['previewonly'] = true;
253 }
254
315d4971 255 return $cdisplay;
e076641f 256}
348630d8 257
4636bf83 258/**
e776b415
ZD
259 * Process user submitted answers for a choice,
260 * and either updating them or saving new answers.
261 *
262 * @param int $formanswer users submitted answers.
263 * @param object $choice the selected choice.
264 * @param int $userid user identifier.
265 * @param object $course current course.
266 * @param object $cm course context.
267 * @return void
4636bf83 268 */
bc499733 269function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
516c5eca
PS
270 global $DB, $CFG;
271 require_once($CFG->libdir.'/completionlib.php');
272
5b83949a
ZD
273 $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
274
54bdf1d4 275 if (empty($formanswer)) {
5b83949a 276 print_error('atleastoneoption', 'choice', $continueurl);
54bdf1d4
MA
277 }
278
279 if (is_array($formanswer)) {
280 if (!$choice->allowmultiple) {
5b83949a 281 print_error('multiplenotallowederror', 'choice', $continueurl);
54bdf1d4
MA
282 }
283 $formanswers = $formanswer;
284 } else {
285 $formanswers = array($formanswer);
286 }
287
0bca1297
DW
288 $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
289 foreach ($formanswers as $key => $val) {
290 if (!isset($options[$val])) {
291 print_error('cannotsubmit', 'choice', $continueurl);
292 }
293 }
e776b415 294 // Start lock to prevent synchronous access to the same data
5b83949a
ZD
295 // before it's updated, if using limits.
296 if ($choice->limitanswers) {
297 $timeout = 10;
298 $locktype = 'mod_choice_choice_user_submit_response';
299 // Limiting access to this choice.
300 $resouce = 'choiceid:' . $choice->id;
301 $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
302
303 // Opening the lock.
304 $choicelock = $lockfactory->get_lock($resouce, $timeout);
305 if (!$choicelock) {
306 print_error('cannotsubmit', 'choice', $continueurl);
307 }
e776b415
ZD
308 }
309
54bdf1d4 310 $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
327c67a9 311 $context = context_module::instance($cm->id);
c75ba879 312
cbb1677c 313 $choicesexceeded = false;
54bdf1d4
MA
314 $countanswers = array();
315 foreach ($formanswers as $val) {
316 $countanswers[$val] = 0;
317 }
c75ba879 318 if($choice->limitanswers) {
319 // Find out whether groups are being used and enabled
320 if (groups_get_activity_groupmode($cm) > 0) {
321 $currentgroup = groups_get_activity_group($cm);
322 } else {
323 $currentgroup = 0;
324 }
54bdf1d4
MA
325
326 list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
327
c75ba879 328 if($currentgroup) {
329 // If groups are being used, retrieve responses only for users in
330 // current group
331 global $CFG;
54bdf1d4
MA
332
333 $params['groupid'] = $currentgroup;
cbb1677c
SH
334 $sql = "SELECT ca.*
335 FROM {choice_answers} ca
336 INNER JOIN {groups_members} gm ON ca.userid=gm.userid
337 WHERE optionid $insql
338 AND gm.groupid= :groupid";
c75ba879 339 } else {
340 // Groups are not used, retrieve all answers for this option ID
cbb1677c
SH
341 $sql = "SELECT ca.*
342 FROM {choice_answers} ca
343 WHERE optionid $insql";
ff8d654f 344 }
345
cbb1677c 346 $answers = $DB->get_records_sql($sql, $params);
c75ba879 347 if ($answers) {
348 foreach ($answers as $a) { //only return enrolled users.
4f0c2d00 349 if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
54bdf1d4 350 $countanswers[$a->optionid]++;
c75ba879 351 }
352 }
353 }
54bdf1d4 354 foreach ($countanswers as $opt => $count) {
e776b415 355 if ($count >= $choice->maxanswers[$opt]) {
54bdf1d4
MA
356 $choicesexceeded = true;
357 break;
358 }
359 }
39b3e7de 360 }
ff8d654f 361
cbb1677c 362 // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
54bdf1d4
MA
363 if (!($choice->limitanswers && $choicesexceeded)) {
364 $answersnapshots = array();
39b3e7de 365 if ($current) {
e776b415 366 // Update an existing answer.
54bdf1d4
MA
367 $existingchoices = array();
368 foreach ($current as $c) {
369 if (in_array($c->optionid, $formanswers)) {
370 $existingchoices[] = $c->optionid;
cbb1677c
SH
371 $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
372 $answersnapshots[] = $c;
54bdf1d4
MA
373 } else {
374 $DB->delete_records('choice_answers', array('id' => $c->id));
375 }
376 }
377
378 // Add new ones.
379 foreach ($formanswers as $f) {
380 if (!in_array($f, $existingchoices)) {
381 $newanswer = new stdClass();
382 $newanswer->optionid = $f;
383 $newanswer->choiceid = $choice->id;
384 $newanswer->userid = $userid;
385 $newanswer->timemodified = time();
386 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
387 $answersnapshots[] = $newanswer;
388 }
389 }
8a941443 390
e776b415
ZD
391 // Initialised as true, meaning we updated the answer.
392 $answerupdated = true;
39b3e7de 393 } else {
e776b415 394 // Add new answer.
54bdf1d4
MA
395 foreach ($formanswers as $answer) {
396 $newanswer = new stdClass();
397 $newanswer->choiceid = $choice->id;
398 $newanswer->userid = $userid;
399 $newanswer->optionid = $answer;
400 $newanswer->timemodified = time();
401 $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
402 $answersnapshots[] = $newanswer;
403 }
bc499733
SM
404
405 // Update completion state
406 $completion = new completion_info($course);
407 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
408 $completion->update_state($cm, COMPLETION_COMPLETE);
409 }
8a941443 410
e776b415
ZD
411 // Initalised as false, meaning we submitted a new answer.
412 $answerupdated = false;
39b3e7de 413 }
414 } else {
54bdf1d4
MA
415 // Check to see if current choice already selected - if not display error.
416 $currentids = array_keys($current);
e776b415 417
54bdf1d4 418 if (array_diff($currentids, $formanswers) || array_diff($formanswers, $currentids) ) {
e776b415
ZD
419 // Release lock before error.
420 $choicelock->release();
5b83949a 421 print_error('choicefull', 'choice', $continueurl);
39b3e7de 422 }
423 }
e776b415
ZD
424
425 // Release lock.
5b83949a
ZD
426 if (isset($choicelock)) {
427 $choicelock->release();
428 }
e776b415
ZD
429
430 // Now record completed event.
431 if (isset($answerupdated)) {
432 $eventdata = array();
433 $eventdata['context'] = $context;
434 $eventdata['objectid'] = $choice->id;
435 $eventdata['userid'] = $userid;
436 $eventdata['courseid'] = $course->id;
437 $eventdata['other'] = array();
438 $eventdata['other']['choiceid'] = $choice->id;
439
440 if ($answerupdated) {
441 $eventdata['other']['optionid'] = $formanswer;
442 $event = \mod_choice\event\answer_updated::create($eventdata);
443 } else {
444 $eventdata['other']['optionid'] = $formanswers;
445 $event = \mod_choice\event\answer_submitted::create($eventdata);
446 }
447 $event->add_record_snapshot('course', $course);
448 $event->add_record_snapshot('course_modules', $cm);
449 $event->add_record_snapshot('choice', $choice);
450 foreach ($answersnapshots as $record) {
451 $event->add_record_snapshot('choice_answers', $record);
39b3e7de 452 }
e776b415 453 $event->trigger();
39b3e7de 454 }
348630d8 455}
456
4636bf83 457/**
458 * @param array $user
459 * @param object $cm
460 * @return void Output is echo'd
461 */
a61e4188 462function choice_show_reportlink($user, $cm) {
54bdf1d4 463 $userschosen = array();
a61e4188 464 foreach($user as $optionid => $userlist) {
465 if ($optionid) {
54bdf1d4 466 $userschosen = array_merge($userschosen, array_keys($userlist));
a61e4188 467 }
7b360f33 468 }
54bdf1d4 469 $responsecount = count(array_unique($userschosen));
5c880488 470
39b3e7de 471 echo '<div class="reportlink">';
5c880488 472 echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
39b3e7de 473 echo '</div>';
348630d8 474}
475
4636bf83 476/**
477 * @global object
4636bf83 478 * @param object $choice
479 * @param object $course
315d4971 480 * @param object $coursemodule
4636bf83 481 * @param array $allresponses
315d4971
RW
482
483 * * @param bool $allresponses
484 * @return object
4636bf83 485 */
634a5c0b
MG
486function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
487 global $OUTPUT;
407caeeb 488
315d4971
RW
489 $display = clone($choice);
490 $display->coursemoduleid = $cm->id;
f7e93000
RW
491 $display->courseid = $course->id;
492
315d4971
RW
493 //overwrite options value;
494 $display->options = array();
540200ae 495 $allusers = [];
315d4971
RW
496 foreach ($choice->option as $optionid => $optiontext) {
497 $display->options[$optionid] = new stdClass;
498 $display->options[$optionid]->text = $optiontext;
499 $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
500
501 if (array_key_exists($optionid, $allresponses)) {
e076641f 502 $display->options[$optionid]->user = $allresponses[$optionid];
540200ae 503 $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
9d624d66 504 }
315d4971
RW
505 }
506 unset($display->option);
507 unset($display->maxanswers);
508
540200ae 509 $display->numberofuser = count(array_unique($allusers));
327c67a9 510 $context = context_module::instance($cm->id);
315d4971
RW
511 $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
512 $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
513 $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
f7e93000 514
9acb7700 515 if (empty($allresponses)) {
8f0767f1 516 echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
9acb7700 517 return false;
39b3e7de 518 }
c2a4d016 519
315d4971 520 return $display;
9d624d66 521}
348630d8 522
4636bf83 523/**
524 * @global object
525 * @param array $attemptids
bc499733
SM
526 * @param object $choice Choice main table row
527 * @param object $cm Course-module object
528 * @param object $course Course object
4636bf83 529 * @return bool
530 */
bc499733 531function choice_delete_responses($attemptids, $choice, $cm, $course) {
e62f6a01 532 global $DB, $CFG, $USER;
516c5eca
PS
533 require_once($CFG->libdir.'/completionlib.php');
534
dabfd0ed 535 if(!is_array($attemptids) || empty($attemptids)) {
348630d8 536 return false;
537 }
538
539 foreach($attemptids as $num => $attemptid) {
540 if(empty($attemptid)) {
541 unset($attemptids[$num]);
542 }
543 }
544
e62f6a01 545 $context = context_module::instance($cm->id);
bc499733 546 $completion = new completion_info($course);
348630d8 547 foreach($attemptids as $attemptid) {
54bdf1d4 548 if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
e62f6a01
SB
549 // Trigger the event answer deleted.
550 $eventdata = array();
da826886 551 $eventdata['objectid'] = $todelete->id;
e62f6a01
SB
552 $eventdata['context'] = $context;
553 $eventdata['userid'] = $USER->id;
554 $eventdata['courseid'] = $course->id;
555 $eventdata['relateduserid'] = $todelete->userid;
556 $eventdata['other'] = array();
557 $eventdata['other']['choiceid'] = $choice->id;
da826886 558 $eventdata['other']['optionid'] = $todelete->optionid;
e62f6a01
SB
559 $event = \mod_choice\event\answer_deleted::create($eventdata);
560 $event->add_record_snapshot('course', $course);
561 $event->add_record_snapshot('course_modules', $cm);
562 $event->add_record_snapshot('choice', $choice);
da826886 563 $event->add_record_snapshot('choice_answers', $todelete);
e62f6a01
SB
564 $event->trigger();
565
54bdf1d4 566 $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
348630d8 567 }
ebd3c7ac 568 }
da826886
MN
569
570 // Update completion state.
571 if ($completion->is_enabled($cm) && $choice->completionsubmit) {
572 $completion->update_state($cm, COMPLETION_INCOMPLETE);
573 }
574
348630d8 575 return true;
576}
577
04eba58f 578
4636bf83 579/**
580 * Given an ID of an instance of this module,
581 * this function will permanently delete the instance
582 * and any data that depends on it.
583 *
584 * @global object
585 * @param int $id
586 * @return bool
587 */
04eba58f 588function choice_delete_instance($id) {
c18269c7 589 global $DB;
04eba58f 590
c18269c7 591 if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
04eba58f 592 return false;
593 }
594
595 $result = true;
596
c18269c7 597 if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
04eba58f 598 $result = false;
599 }
600
c18269c7 601 if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
04eba58f 602 $result = false;
603 }
a77a6009 604
c18269c7 605 if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
6fd87e3b 606 $result = false;
ebd3c7ac 607 }
9be80529
SB
608 // Remove old calendar events.
609 if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
610 $result = false;
611 }
04eba58f 612
613 return $result;
614}
615
4636bf83 616/**
617 * Returns text string which is the answer that matches the id
618 *
619 * @global object
620 * @param object $choice
621 * @param int $id
622 * @return string
623 */
a77a6009 624function choice_get_option_text($choice, $id) {
407caeeb 625 global $DB;
4636bf83 626
407caeeb 627 if ($result = $DB->get_record("choice_options", array("id" => $id))) {
a77a6009 628 return $result->text;
6fd87e3b 629 } else {
630 return get_string("notanswered", "choice");
ff8d654f 631 }
c4016bc1 632}
633
4636bf83 634/**
635 * Gets a full choice record
636 *
637 * @global object
638 * @param int $choiceid
639 * @return object|bool The choice or false
640 */
cd3fccff 641function choice_get_choice($choiceid) {
407caeeb 642 global $DB;
a77a6009 643
407caeeb 644 if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
645 if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
ff8d654f 646 foreach ($options as $option) {
ebd3c7ac 647 $choice->option[$option->id] = $option->text;
c9ff813c 648 $choice->maxanswers[$option->id] = $option->maxanswers;
ff8d654f 649 }
a77a6009 650 return $choice;
651 }
652 }
653 return false;
cd3fccff 654}
655
4636bf83 656/**
b2b4ec30
RT
657 * List the actions that correspond to a view of this module.
658 * This is used by the participation report.
659 *
660 * Note: This is not used by new logging system. Event with
661 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
662 * be considered as view action.
663 *
4636bf83 664 * @return array
665 */
f3221af9 666function choice_get_view_actions() {
cf051cc4 667 return array('view','view all','report');
f3221af9 668}
669
4636bf83 670/**
b2b4ec30
RT
671 * List the actions that correspond to a post of this module.
672 * This is used by the participation report.
673 *
674 * Note: This is not used by new logging system. Event with
675 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
676 * will be considered as post action.
677 *
4636bf83 678 * @return array
679 */
f3221af9 680function choice_get_post_actions() {
681 return array('choose','choose again');
682}
683
0b5a80a1 684
685/**
686 * Implementation of the function for printing the form elements that control
687 * whether the course reset functionality affects the choice.
1adbd2c3 688 *
4636bf83 689 * @param object $mform form passed by reference
0b5a80a1 690 */
691function choice_reset_course_form_definition(&$mform) {
692 $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
693 $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
694}
695
696/**
697 * Course reset form defaults.
4636bf83 698 *
699 * @return array
0b5a80a1 700 */
701function choice_reset_course_form_defaults($course) {
702 return array('reset_choice'=>1);
703}
704
705/**
72d2982e 706 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 707 * choice responses for course $data->courseid.
4636bf83 708 *
709 * @global object
710 * @global object
711 * @param object $data the data submitted from the reset course.
0b5a80a1 712 * @return array status array
713 */
714function choice_reset_userdata($data) {
407caeeb 715 global $CFG, $DB;
0b5a80a1 716
717 $componentstr = get_string('modulenameplural', 'choice');
718 $status = array();
719
720 if (!empty($data->reset_choice)) {
721 $choicessql = "SELECT ch.id
f7e93000
RW
722 FROM {choice} ch
723 WHERE ch.course=?";
0b5a80a1 724
407caeeb 725 $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
0b5a80a1 726 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
727 }
728
729 /// updating dates - shift may be negative too
730 if ($data->timeshift) {
731 shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
732 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
733 }
734
735 return $status;
736}
737
4636bf83 738/**
739 * @global object
740 * @global object
741 * @global object
742 * @uses CONTEXT_MODULE
743 * @param object $choice
744 * @param object $cm
745 * @param int $groupmode
6de3eee0 746 * @param bool $onlyactive Whether to get response data for active users only.
4636bf83 747 * @return array
748 */
6de3eee0 749function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
407caeeb 750 global $CFG, $USER, $DB;
a61e4188 751
327c67a9 752 $context = context_module::instance($cm->id);
a61e4188 753
754/// Get the current group
755 if ($groupmode > 0) {
756 $currentgroup = groups_get_activity_group($cm);
757 } else {
758 $currentgroup = 0;
759 }
760
5d9d5227 761/// Initialise the returned array, which is a matrix: $allresponses[responseid][userid] = responseobject
762 $allresponses = array();
a61e4188 763
764/// First get all the users who have access here
765/// To start with we assume they are all "unanswered" then move them later
6de3eee0
TB
766 $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
767 user_picture::fields('u', array('idnumber')), null, 0, 0, $onlyactive);
a61e4188 768
769/// Get all the recorded responses for this choice
407caeeb 770 $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
a61e4188 771
772/// Use the responses to move users into the correct column
773
5d9d5227 774 if ($rawresponses) {
54bdf1d4 775 $answeredusers = array();
5d9d5227 776 foreach ($rawresponses as $response) {
777 if (isset($allresponses[0][$response->userid])) { // This person is enrolled and in correct group
778 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
779 $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
54bdf1d4
MA
780 $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
781 $answeredusers[] = $response->userid;
a61e4188 782 }
783 }
54bdf1d4
MA
784 foreach ($answeredusers as $answereduser) {
785 unset($allresponses[0][$answereduser]);
786 }
f7e93000 787 }
5d9d5227 788 return $allresponses;
f432bebf 789}
a61e4188 790
f432bebf 791/**
792 * Returns all other caps used in module
4636bf83 793 *
794 * @return array
f432bebf 795 */
db19ec01 796function choice_get_extra_capabilities() {
f432bebf 797 return array('moodle/site:accessallgroups');
a61e4188 798}
f432bebf 799
18a2a0cb 800/**
4636bf83 801 * @uses FEATURE_GROUPS
802 * @uses FEATURE_GROUPINGS
4636bf83 803 * @uses FEATURE_MOD_INTRO
804 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
805 * @uses FEATURE_GRADE_HAS_GRADE
806 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 807 * @param string $feature FEATURE_xx constant for requested feature
808 * @return mixed True if module supports feature, null if doesn't know
809 */
810function choice_supports($feature) {
811 switch($feature) {
42f103be 812 case FEATURE_GROUPS: return true;
813 case FEATURE_GROUPINGS: return true;
dc5c2bd9 814 case FEATURE_MOD_INTRO: return true;
18a2a0cb 815 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
bc499733 816 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 817 case FEATURE_GRADE_HAS_GRADE: return false;
818 case FEATURE_GRADE_OUTCOMES: return false;
98baf0d7 819 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 820 case FEATURE_SHOW_DESCRIPTION: return true;
42f103be 821
18a2a0cb 822 default: return null;
823 }
824}
97011c64 825
0b29477b
SH
826/**
827 * Adds module specific settings to the settings block
828 *
829 * @param settings_navigation $settings The settings navigation object
830 * @param navigation_node $choicenode The node to add module settings to
831 */
832function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
833 global $PAGE;
97011c64 834
835 if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
836
837 $groupmode = groups_get_activity_groupmode($PAGE->cm);
838 if ($groupmode) {
839 groups_get_activity_group($PAGE->cm, true);
840 }
6de3eee0
TB
841
842 $choice = choice_get_choice($PAGE->cm->instance);
843
844 // Check if we want to include responses from inactive users.
845 $onlyactive = $choice->includeinactive ? false : true;
846
847 // Big function, approx 6 SQL calls per user.
848 $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
97011c64 849
540200ae 850 $allusers = [];
97011c64 851 foreach($allresponses as $optionid => $userlist) {
852 if ($optionid) {
540200ae 853 $allusers = array_merge($allusers, array_keys($userlist));
97011c64 854 }
855 }
540200ae 856 $responsecount = count(array_unique($allusers));
0b29477b 857 $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
97011c64 858 }
98baf0d7 859}
bc499733
SM
860
861/**
862 * Obtains the automatic completion state for this choice based on any conditions
863 * in forum settings.
864 *
865 * @param object $course Course
866 * @param object $cm Course-module
867 * @param int $userid User ID
868 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
869 * @return bool True if completed, false if not, $type if conditions not set.
870 */
871function choice_get_completion_state($course, $cm, $userid, $type) {
872 global $CFG,$DB;
873
874 // Get choice details
875 $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
876 MUST_EXIST);
877
516c5eca 878 // If completion option is enabled, evaluate it and return true/false
bc499733
SM
879 if($choice->completionsubmit) {
880 return $DB->record_exists('choice_answers', array(
881 'choiceid'=>$choice->id, 'userid'=>$userid));
882 } else {
883 // Completion option is not enabled so just return $type
884 return $type;
885 }
886}
b1627a92
DC
887
888/**
889 * Return a list of page types
890 * @param string $pagetype current page type
891 * @param stdClass $parentcontext Block's parent context
892 * @param stdClass $currentcontext Current context of block
893 */
b38e2e28 894function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
895 $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
896 return $module_pagetype;
897}
c04b66a5
SB
898
899/**
900 * Prints choice summaries on MyMoodle Page
901 *
902 * Prints choice name, due date and attempt information on
903 * choice activities that have a deadline that has not already passed
904 * and it is available for completing.
905 * @uses CONTEXT_MODULE
906 * @param array $courses An array of course objects to get choice instances from.
907 * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output )
908 */
909function choice_print_overview($courses, &$htmlarray) {
910 global $USER, $DB, $OUTPUT;
911
912 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
913 return;
914 }
915 if (!$choices = get_all_instances_in_courses('choice', $courses)) {
916 return;
917 }
918
919 $now = time();
920 foreach ($choices as $choice) {
921 if ($choice->timeclose != 0 // If this choice is scheduled.
922 and $choice->timeclose >= $now // And the deadline has not passed.
923 and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available.
924
925 // Visibility.
926 $class = (!$choice->visible) ? 'dimmed' : '';
927
928 // Link to activity.
929 $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule));
930 $url = html_writer::link($url, format_string($choice->name), array('class' => $class));
931 $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name');
932
933 // Deadline.
934 $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info');
935
936 // Display relevant info based on permissions.
937 if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) {
540200ae
MG
938 $attempts = $DB->count_records_sql('SELECT COUNT(DISTINCT userid) FROM {choice_answers} WHERE choiceid = ?',
939 [$choice->id]);
940 $url = new moodle_url('/mod/choice/report.php', ['id' => $choice->coursemodule]);
941 $str .= $OUTPUT->box(html_writer::link($url, get_string('viewallresponses', 'choice', $attempts)), 'info');
c04b66a5
SB
942
943 } else if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) {
944 // See if the user has submitted anything.
945 $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
946 if ($answers > 0) {
947 // User has already selected an answer, nothing to show.
948 $str = '';
949 } else {
950 // User has not made a selection yet.
951 $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info');
952 }
953 } else {
954 // Does not have permission to do anything on this choice activity.
955 $str = '';
956 }
957
958 // Make sure we have something to display.
959 if (!empty($str)) {
960 // Generate the containing div.
961 $str = $OUTPUT->box($str, 'choice overview');
962
963 if (empty($htmlarray[$choice->course]['choice'])) {
964 $htmlarray[$choice->course]['choice'] = $str;
965 } else {
966 $htmlarray[$choice->course]['choice'] .= $str;
967 }
968 }
969 }
970 }
971 return;
86e5b0a7 972}
b87f31db
JL
973
974
975/**
976 * Get my responses on a given choice.
977 *
978 * @param stdClass $choice Choice record
979 * @return array of choice answers records
980 * @since Moodle 3.0
981 */
982function choice_get_my_response($choice) {
983 global $DB, $USER;
984 return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id));
985}
986
4b93c3e3
JL
987
988/**
989 * Get all the responses on a given choice.
990 *
991 * @param stdClass $choice Choice record
992 * @return array of choice answers records
993 * @since Moodle 3.0
994 */
995function choice_get_all_responses($choice) {
996 global $DB;
997 return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
998}
999
1000
b87f31db
JL
1001/**
1002 * Return true if we are allowd to view the choice results.
1003 *
1004 * @param stdClass $choice Choice record
1005 * @param rows|null $current my choice responses
1006 * @param bool|null $choiceopen if the choice is open
1007 * @return bool true if we can view the results, false otherwise.
1008 * @since Moodle 3.0
1009 */
1010function choice_can_view_results($choice, $current = null, $choiceopen = null) {
1011
1012 if (is_null($choiceopen)) {
1013 $timenow = time();
1014 if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
1015 $choiceopen = false;
1016 } else {
1017 $choiceopen = true;
1018 }
1019 }
1020 if (empty($current)) {
1021 $current = choice_get_my_response($choice);
1022 }
1023
1024 if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1025 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1026 ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1027 return true;
1028 }
1029 return false;
1030}
4c4d3b73
JL
1031
1032/**
1033 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1034 *
1035 * @param stdClass $choice choice object
1036 * @param stdClass $course course object
1037 * @param stdClass $cm course module object
1038 * @param stdClass $context context object
1039 * @since Moodle 3.0
1040 */
1041function choice_view($choice, $course, $cm, $context) {
1042
1043 // Trigger course_module_viewed event.
1044 $params = array(
1045 'context' => $context,
1046 'objectid' => $choice->id
1047 );
1048
1049 $event = \mod_choice\event\course_module_viewed::create($params);
1050 $event->add_record_snapshot('course_modules', $cm);
1051 $event->add_record_snapshot('course', $course);
1052 $event->add_record_snapshot('choice', $choice);
1053 $event->trigger();
1054
1055 // Completion.
1056 $completion = new completion_info($course);
1057 $completion->set_module_viewed($cm);
1058}
3dd0ac55
JL
1059
1060/**
1061 * Check if a choice is available for the current user.
1062 *
1063 * @param stdClass $choice choice record
1064 * @return array status (available or not and possible warnings)
1065 */
1066function choice_get_availability_status($choice) {
1067 $available = true;
1068 $warnings = array();
1069
1070 if ($choice->timeclose != 0) {
1071 $timenow = time();
1072
1073 if ($choice->timeopen > $timenow) {
1074 $available = false;
1075 $warnings['notopenyet'] = userdate($choice->timeopen);
1076 } else if ($timenow > $choice->timeclose) {
1077 $available = false;
1078 $warnings['expired'] = userdate($choice->timeclose);
1079 }
1080 }
531bcb13
JO
1081 if (!$choice->allowupdate && choice_get_my_response($choice)) {
1082 $available = false;
1083 $warnings['choicesaved'] = '';
1084 }
3dd0ac55
JL
1085
1086 // Choice is available.
1087 return array($available, $warnings);
1088}
9be80529
SB
1089
1090/**
1091 * This standard function will check all instances of this module
1092 * and make sure there are up-to-date events created for each of them.
1093 * If courseid = 0, then every chat event in the site is checked, else
1094 * only chat events belonging to the course specified are checked.
1095 * This function is used, in its new format, by restore_refresh_events()
1096 *
1097 * @param int $courseid
1098 * @return bool
1099 */
1100function choice_refresh_events($courseid = 0) {
1101 global $DB, $CFG;
1102 require_once($CFG->dirroot.'/mod/choice/locallib.php');
1103
1104 if ($courseid) {
1105 if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1106 return true;
1107 }
1108 } else {
1109 if (! $choices = $DB->get_records("choice")) {
1110 return true;
1111 }
1112 }
1113
1114 foreach ($choices as $choice) {
1115 choice_set_events($choice);
1116 }
1117 return true;
1118}
1119