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