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/>.
17
18/**
19 * @package   mod_choice
20 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
21 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 */
23
24defined('MOODLE_INTERNAL') || die();
25
26/** @global int $CHOICE_COLUMN_HEIGHT */
27global $CHOICE_COLUMN_HEIGHT;
28$CHOICE_COLUMN_HEIGHT = 300;
29
30/** @global int $CHOICE_COLUMN_WIDTH */
31global $CHOICE_COLUMN_WIDTH;
32$CHOICE_COLUMN_WIDTH = 300;
33
34define('CHOICE_PUBLISH_ANONYMOUS', '0');
35define('CHOICE_PUBLISH_NAMES',     '1');
36
37define('CHOICE_SHOWRESULTS_NOT',          '0');
38define('CHOICE_SHOWRESULTS_AFTER_ANSWER', '1');
39define('CHOICE_SHOWRESULTS_AFTER_CLOSE',  '2');
40define('CHOICE_SHOWRESULTS_ALWAYS',       '3');
41
42define('CHOICE_DISPLAY_HORIZONTAL',  '0');
43define('CHOICE_DISPLAY_VERTICAL',    '1');
44
45define('CHOICE_EVENT_TYPE_OPEN', 'open');
46define('CHOICE_EVENT_TYPE_CLOSE', 'close');
47
48/** @global array $CHOICE_PUBLISH */
49global $CHOICE_PUBLISH;
50$CHOICE_PUBLISH = array (CHOICE_PUBLISH_ANONYMOUS  => get_string('publishanonymous', 'choice'),
51                         CHOICE_PUBLISH_NAMES      => get_string('publishnames', 'choice'));
52
53/** @global array $CHOICE_SHOWRESULTS */
54global $CHOICE_SHOWRESULTS;
55$CHOICE_SHOWRESULTS = array (CHOICE_SHOWRESULTS_NOT          => get_string('publishnot', 'choice'),
56                         CHOICE_SHOWRESULTS_AFTER_ANSWER => get_string('publishafteranswer', 'choice'),
57                         CHOICE_SHOWRESULTS_AFTER_CLOSE  => get_string('publishafterclose', 'choice'),
58                         CHOICE_SHOWRESULTS_ALWAYS       => get_string('publishalways', 'choice'));
59
60/** @global array $CHOICE_DISPLAY */
61global $CHOICE_DISPLAY;
62$CHOICE_DISPLAY = array (CHOICE_DISPLAY_HORIZONTAL   => get_string('displayhorizontal', 'choice'),
63                         CHOICE_DISPLAY_VERTICAL     => get_string('displayvertical','choice'));
64
65/// Standard functions /////////////////////////////////////////////////////////
66
67/**
68 * @global object
69 * @param object $course
70 * @param object $user
71 * @param object $mod
72 * @param object $choice
73 * @return object|null
74 */
75function choice_user_outline($course, $user, $mod, $choice) {
76    global $DB;
77    if ($answer = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id))) {
78        $result = new stdClass();
79        $result->info = "'".format_string(choice_get_option_text($choice, $answer->optionid))."'";
80        $result->time = $answer->timemodified;
81        return $result;
82    }
83    return NULL;
84}
85
86/**
87 * Callback for the "Complete" report - prints the activity summary for the given user
88 *
89 * @param object $course
90 * @param object $user
91 * @param object $mod
92 * @param object $choice
93 */
94function choice_user_complete($course, $user, $mod, $choice) {
95    global $DB;
96    if ($answers = $DB->get_records('choice_answers', array("choiceid" => $choice->id, "userid" => $user->id))) {
97        $info = [];
98        foreach ($answers as $answer) {
99            $info[] = "'" . format_string(choice_get_option_text($choice, $answer->optionid)) . "'";
100        }
101        core_collator::asort($info);
102        echo get_string("answered", "choice") . ": ". join(', ', $info) . ". " .
103                get_string("updated", '', userdate($answer->timemodified));
104    } else {
105        print_string("notanswered", "choice");
106    }
107}
108
109/**
110 * Given an object containing all the necessary data,
111 * (defined by the form in mod_form.php) this function
112 * will create a new instance and return the id number
113 * of the new instance.
114 *
115 * @global object
116 * @param object $choice
117 * @return int
118 */
119function choice_add_instance($choice) {
120    global $DB, $CFG;
121    require_once($CFG->dirroot.'/mod/choice/locallib.php');
122
123    $choice->timemodified = time();
124
125    //insert answers
126    $choice->id = $DB->insert_record("choice", $choice);
127    foreach ($choice->option as $key => $value) {
128        $value = trim($value);
129        if (isset($value) && $value <> '') {
130            $option = new stdClass();
131            $option->text = $value;
132            $option->choiceid = $choice->id;
133            if (isset($choice->limit[$key])) {
134                $option->maxanswers = $choice->limit[$key];
135            }
136            $option->timemodified = time();
137            $DB->insert_record("choice_options", $option);
138        }
139    }
140
141    // Add calendar events if necessary.
142    choice_set_events($choice);
143    if (!empty($choice->completionexpected)) {
144        \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id,
145                $choice->completionexpected);
146    }
147
148    return $choice->id;
149}
150
151/**
152 * Given an object containing all the necessary data,
153 * (defined by the form in mod_form.php) this function
154 * will update an existing instance with new data.
155 *
156 * @global object
157 * @param object $choice
158 * @return bool
159 */
160function choice_update_instance($choice) {
161    global $DB, $CFG;
162    require_once($CFG->dirroot.'/mod/choice/locallib.php');
163
164    $choice->id = $choice->instance;
165    $choice->timemodified = time();
166
167    //update, delete or insert answers
168    foreach ($choice->option as $key => $value) {
169        $value = trim($value);
170        $option = new stdClass();
171        $option->text = $value;
172        $option->choiceid = $choice->id;
173        if (isset($choice->limit[$key])) {
174            $option->maxanswers = $choice->limit[$key];
175        }
176        $option->timemodified = time();
177        if (isset($choice->optionid[$key]) && !empty($choice->optionid[$key])){//existing choice record
178            $option->id=$choice->optionid[$key];
179            if (isset($value) && $value <> '') {
180                $DB->update_record("choice_options", $option);
181            } else {
182                // Remove the empty (unused) option.
183                $DB->delete_records("choice_options", array("id" => $option->id));
184                // Delete any answers associated with this option.
185                $DB->delete_records("choice_answers", array("choiceid" => $choice->id, "optionid" => $option->id));
186            }
187        } else {
188            if (isset($value) && $value <> '') {
189                $DB->insert_record("choice_options", $option);
190            }
191        }
192    }
193
194    // Add calendar events if necessary.
195    choice_set_events($choice);
196    $completionexpected = (!empty($choice->completionexpected)) ? $choice->completionexpected : null;
197    \core_completion\api::update_completion_date_event($choice->coursemodule, 'choice', $choice->id, $completionexpected);
198
199    return $DB->update_record('choice', $choice);
200
201}
202
203/**
204 * @global object
205 * @param object $choice
206 * @param object $user
207 * @param object $coursemodule
208 * @param array $allresponses
209 * @return array
210 */
211function choice_prepare_options($choice, $user, $coursemodule, $allresponses) {
212    global $DB;
213
214    $cdisplay = array('options'=>array());
215
216    $cdisplay['limitanswers'] = true;
217    $context = context_module::instance($coursemodule->id);
218
219    foreach ($choice->option as $optionid => $text) {
220        if (isset($text)) { //make sure there are no dud entries in the db with blank text values.
221            $option = new stdClass;
222            $option->attributes = new stdClass;
223            $option->attributes->value = $optionid;
224            $option->text = format_string($text);
225            $option->maxanswers = $choice->maxanswers[$optionid];
226            $option->displaylayout = $choice->display;
227
228            if (isset($allresponses[$optionid])) {
229                $option->countanswers = count($allresponses[$optionid]);
230            } else {
231                $option->countanswers = 0;
232            }
233            if ($DB->record_exists('choice_answers', array('choiceid' => $choice->id, 'userid' => $user->id, 'optionid' => $optionid))) {
234                $option->attributes->checked = true;
235            }
236            if ( $choice->limitanswers && ($option->countanswers >= $option->maxanswers) && empty($option->attributes->checked)) {
237                $option->attributes->disabled = true;
238            }
239            $cdisplay['options'][] = $option;
240        }
241    }
242
243    $cdisplay['hascapability'] = is_enrolled($context, NULL, 'mod/choice:choose'); //only enrolled users are allowed to make a choice
244
245    if ($choice->allowupdate && $DB->record_exists('choice_answers', array('choiceid'=> $choice->id, 'userid'=> $user->id))) {
246        $cdisplay['allowupdate'] = true;
247    }
248
249    if ($choice->showpreview && $choice->timeopen > time()) {
250        $cdisplay['previewonly'] = true;
251    }
252
253    return $cdisplay;
254}
255
256/**
257 * Modifies responses of other users adding the option $newoptionid to them
258 *
259 * @param array $userids list of users to add option to (must be users without any answers yet)
260 * @param array $answerids list of existing attempt ids of users (will be either appended or
261 *      substituted with the newoptionid, depending on $choice->allowmultiple)
262 * @param int $newoptionid
263 * @param stdClass $choice choice object, result of {@link choice_get_choice()}
264 * @param stdClass $cm
265 * @param stdClass $course
266 */
267function choice_modify_responses($userids, $answerids, $newoptionid, $choice, $cm, $course) {
268    // Get all existing responses and the list of non-respondents.
269    $groupmode = groups_get_activity_groupmode($cm);
270    $onlyactive = $choice->includeinactive ? false : true;
271    $allresponses = choice_get_response_data($choice, $cm, $groupmode, $onlyactive);
272
273    // Check that the option value is valid.
274    if (!$newoptionid || !isset($choice->option[$newoptionid])) {
275        return;
276    }
277
278    // First add responses for users who did not make any choice yet.
279    foreach ($userids as $userid) {
280        if (isset($allresponses[0][$userid])) {
281            choice_user_submit_response($newoptionid, $choice, $userid, $course, $cm);
282        }
283    }
284
285    // Create the list of all options already selected by each user.
286    $optionsbyuser = []; // Mapping userid=>array of chosen choice options.
287    $usersbyanswer = []; // Mapping answerid=>userid (which answer belongs to each user).
288    foreach ($allresponses as $optionid => $responses) {
289        if ($optionid > 0) {
290            foreach ($responses as $userid => $userresponse) {
291                $optionsbyuser += [$userid => []];
292                $optionsbyuser[$userid][] = $optionid;
293                $usersbyanswer[$userresponse->answerid] = $userid;
294            }
295        }
296    }
297
298    // Go through the list of submitted attemptids and find which users answers need to be updated.
299    foreach ($answerids as $answerid) {
300        if (isset($usersbyanswer[$answerid])) {
301            $userid = $usersbyanswer[$answerid];
302            if (!in_array($newoptionid, $optionsbyuser[$userid])) {
303                $options = $choice->allowmultiple ?
304                        array_merge($optionsbyuser[$userid], [$newoptionid]) : $newoptionid;
305                choice_user_submit_response($options, $choice, $userid, $course, $cm);
306            }
307        }
308    }
309}
310
311/**
312 * Process user submitted answers for a choice,
313 * and either updating them or saving new answers.
314 *
315 * @param int|array $formanswer the id(s) of the user submitted choice options.
316 * @param object $choice the selected choice.
317 * @param int $userid user identifier.
318 * @param object $course current course.
319 * @param object $cm course context.
320 * @return void
321 */
322function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm) {
323    global $DB, $CFG, $USER;
324    require_once($CFG->libdir.'/completionlib.php');
325
326    $continueurl = new moodle_url('/mod/choice/view.php', array('id' => $cm->id));
327
328    if (empty($formanswer)) {
329        print_error('atleastoneoption', 'choice', $continueurl);
330    }
331
332    if (is_array($formanswer)) {
333        if (!$choice->allowmultiple) {
334            print_error('multiplenotallowederror', 'choice', $continueurl);
335        }
336        $formanswers = $formanswer;
337    } else {
338        $formanswers = array($formanswer);
339    }
340
341    $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
342    foreach ($formanswers as $key => $val) {
343        if (!isset($options[$val])) {
344            print_error('cannotsubmit', 'choice', $continueurl);
345        }
346    }
347    // Start lock to prevent synchronous access to the same data
348    // before it's updated, if using limits.
349    if ($choice->limitanswers) {
350        $timeout = 10;
351        $locktype = 'mod_choice_choice_user_submit_response';
352        // Limiting access to this choice.
353        $resouce = 'choiceid:' . $choice->id;
354        $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
355
356        // Opening the lock.
357        $choicelock = $lockfactory->get_lock($resouce, $timeout, MINSECS);
358        if (!$choicelock) {
359            print_error('cannotsubmit', 'choice', $continueurl);
360        }
361    }
362
363    $current = $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid));
364
365    // Array containing [answerid => optionid] mapping.
366    $existinganswers = array_map(function($answer) {
367        return $answer->optionid;
368    }, $current);
369
370    $context = context_module::instance($cm->id);
371
372    $choicesexceeded = false;
373    $countanswers = array();
374    foreach ($formanswers as $val) {
375        $countanswers[$val] = 0;
376    }
377    if($choice->limitanswers) {
378        // Find out whether groups are being used and enabled
379        if (groups_get_activity_groupmode($cm) > 0) {
380            $currentgroup = groups_get_activity_group($cm);
381        } else {
382            $currentgroup = 0;
383        }
384
385        list ($insql, $params) = $DB->get_in_or_equal($formanswers, SQL_PARAMS_NAMED);
386
387        if($currentgroup) {
388            // If groups are being used, retrieve responses only for users in
389            // current group
390            global $CFG;
391
392            $params['groupid'] = $currentgroup;
393            $sql = "SELECT ca.*
394                      FROM {choice_answers} ca
395                INNER JOIN {groups_members} gm ON ca.userid=gm.userid
396                     WHERE optionid $insql
397                       AND gm.groupid= :groupid";
398        } else {
399            // Groups are not used, retrieve all answers for this option ID
400            $sql = "SELECT ca.*
401                      FROM {choice_answers} ca
402                     WHERE optionid $insql";
403        }
404
405        $answers = $DB->get_records_sql($sql, $params);
406        if ($answers) {
407            foreach ($answers as $a) { //only return enrolled users.
408                if (is_enrolled($context, $a->userid, 'mod/choice:choose')) {
409                    $countanswers[$a->optionid]++;
410                }
411            }
412        }
413
414        foreach ($countanswers as $opt => $count) {
415            // Ignore the user's existing answers when checking whether an answer count has been exceeded.
416            // A user may wish to update their response with an additional choice option and shouldn't be competing with themself!
417            if (in_array($opt, $existinganswers)) {
418                continue;
419            }
420            if ($count >= $choice->maxanswers[$opt]) {
421                $choicesexceeded = true;
422                break;
423            }
424        }
425    }
426
427    // Check the user hasn't exceeded the maximum selections for the choice(s) they have selected.
428    $answersnapshots = array();
429    $deletedanswersnapshots = array();
430    if (!($choice->limitanswers && $choicesexceeded)) {
431        if ($current) {
432            // Update an existing answer.
433            foreach ($current as $c) {
434                if (in_array($c->optionid, $formanswers)) {
435                    $DB->set_field('choice_answers', 'timemodified', time(), array('id' => $c->id));
436                } else {
437                    $deletedanswersnapshots[] = $c;
438                    $DB->delete_records('choice_answers', array('id' => $c->id));
439                }
440            }
441
442            // Add new ones.
443            foreach ($formanswers as $f) {
444                if (!in_array($f, $existinganswers)) {
445                    $newanswer = new stdClass();
446                    $newanswer->optionid = $f;
447                    $newanswer->choiceid = $choice->id;
448                    $newanswer->userid = $userid;
449                    $newanswer->timemodified = time();
450                    $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
451                    $answersnapshots[] = $newanswer;
452                }
453            }
454        } else {
455            // Add new answer.
456            foreach ($formanswers as $answer) {
457                $newanswer = new stdClass();
458                $newanswer->choiceid = $choice->id;
459                $newanswer->userid = $userid;
460                $newanswer->optionid = $answer;
461                $newanswer->timemodified = time();
462                $newanswer->id = $DB->insert_record("choice_answers", $newanswer);
463                $answersnapshots[] = $newanswer;
464            }
465
466            // Update completion state
467            $completion = new completion_info($course);
468            if ($completion->is_enabled($cm) && $choice->completionsubmit) {
469                $completion->update_state($cm, COMPLETION_COMPLETE);
470            }
471        }
472    } else {
473        // This is a choice with limited options, and one of the options selected has just run over its limit.
474        $choicelock->release();
475        print_error('choicefull', 'choice', $continueurl);
476    }
477
478    // Release lock.
479    if (isset($choicelock)) {
480        $choicelock->release();
481    }
482
483    // Trigger events.
484    foreach ($deletedanswersnapshots as $answer) {
485        \mod_choice\event\answer_deleted::create_from_object($answer, $choice, $cm, $course)->trigger();
486    }
487    foreach ($answersnapshots as $answer) {
488        \mod_choice\event\answer_created::create_from_object($answer, $choice, $cm, $course)->trigger();
489    }
490}
491
492/**
493 * @param array $user
494 * @param object $cm
495 * @return void Output is echo'd
496 */
497function choice_show_reportlink($user, $cm) {
498    $userschosen = array();
499    foreach($user as $optionid => $userlist) {
500        if ($optionid) {
501            $userschosen = array_merge($userschosen, array_keys($userlist));
502        }
503    }
504    $responsecount = count(array_unique($userschosen));
505
506    echo '<div class="reportlink">';
507    echo "<a href=\"report.php?id=$cm->id\">".get_string("viewallresponses", "choice", $responsecount)."</a>";
508    echo '</div>';
509}
510
511/**
512 * @global object
513 * @param object $choice
514 * @param object $course
515 * @param object $coursemodule
516 * @param array $allresponses
517
518 *  * @param bool $allresponses
519 * @return object
520 */
521function prepare_choice_show_results($choice, $course, $cm, $allresponses) {
522    global $OUTPUT;
523
524    $display = clone($choice);
525    $display->coursemoduleid = $cm->id;
526    $display->courseid = $course->id;
527
528    if (!empty($choice->showunanswered)) {
529        $choice->option[0] = get_string('notanswered', 'choice');
530        $choice->maxanswers[0] = 0;
531    }
532
533    // Remove from the list of non-respondents the users who do not have access to this activity.
534    if (!empty($display->showunanswered) && $allresponses[0]) {
535        $info = new \core_availability\info_module(cm_info::create($cm));
536        $allresponses[0] = $info->filter_user_list($allresponses[0]);
537    }
538
539    //overwrite options value;
540    $display->options = array();
541    $allusers = [];
542    foreach ($choice->option as $optionid => $optiontext) {
543        $display->options[$optionid] = new stdClass;
544        $display->options[$optionid]->text = format_string($optiontext, true,
545            ['context' => context_module::instance($cm->id)]);
546        $display->options[$optionid]->maxanswer = $choice->maxanswers[$optionid];
547
548        if (array_key_exists($optionid, $allresponses)) {
549            $display->options[$optionid]->user = $allresponses[$optionid];
550            $allusers = array_merge($allusers, array_keys($allresponses[$optionid]));
551        }
552    }
553    unset($display->option);
554    unset($display->maxanswers);
555
556    $display->numberofuser = count(array_unique($allusers));
557    $context = context_module::instance($cm->id);
558    $display->viewresponsecapability = has_capability('mod/choice:readresponses', $context);
559    $display->deleterepsonsecapability = has_capability('mod/choice:deleteresponses',$context);
560    $display->fullnamecapability = has_capability('moodle/site:viewfullnames', $context);
561
562    if (empty($allresponses)) {
563        echo $OUTPUT->heading(get_string("nousersyet"), 3, null);
564        return false;
565    }
566
567    return $display;
568}
569
570/**
571 * @global object
572 * @param array $attemptids
573 * @param object $choice Choice main table row
574 * @param object $cm Course-module object
575 * @param object $course Course object
576 * @return bool
577 */
578function choice_delete_responses($attemptids, $choice, $cm, $course) {
579    global $DB, $CFG, $USER;
580    require_once($CFG->libdir.'/completionlib.php');
581
582    if(!is_array($attemptids) || empty($attemptids)) {
583        return false;
584    }
585
586    foreach($attemptids as $num => $attemptid) {
587        if(empty($attemptid)) {
588            unset($attemptids[$num]);
589        }
590    }
591
592    $completion = new completion_info($course);
593    foreach($attemptids as $attemptid) {
594        if ($todelete = $DB->get_record('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid))) {
595            // Trigger the event answer deleted.
596            \mod_choice\event\answer_deleted::create_from_object($todelete, $choice, $cm, $course)->trigger();
597            $DB->delete_records('choice_answers', array('choiceid' => $choice->id, 'id' => $attemptid));
598        }
599    }
600
601    // Update completion state.
602    if ($completion->is_enabled($cm) && $choice->completionsubmit) {
603        $completion->update_state($cm, COMPLETION_INCOMPLETE);
604    }
605
606    return true;
607}
608
609
610/**
611 * Given an ID of an instance of this module,
612 * this function will permanently delete the instance
613 * and any data that depends on it.
614 *
615 * @global object
616 * @param int $id
617 * @return bool
618 */
619function choice_delete_instance($id) {
620    global $DB;
621
622    if (! $choice = $DB->get_record("choice", array("id"=>"$id"))) {
623        return false;
624    }
625
626    $result = true;
627
628    if (! $DB->delete_records("choice_answers", array("choiceid"=>"$choice->id"))) {
629        $result = false;
630    }
631
632    if (! $DB->delete_records("choice_options", array("choiceid"=>"$choice->id"))) {
633        $result = false;
634    }
635
636    if (! $DB->delete_records("choice", array("id"=>"$choice->id"))) {
637        $result = false;
638    }
639    // Remove old calendar events.
640    if (! $DB->delete_records('event', array('modulename' => 'choice', 'instance' => $choice->id))) {
641        $result = false;
642    }
643
644    return $result;
645}
646
647/**
648 * Returns text string which is the answer that matches the id
649 *
650 * @global object
651 * @param object $choice
652 * @param int $id
653 * @return string
654 */
655function choice_get_option_text($choice, $id) {
656    global $DB;
657
658    if ($result = $DB->get_record("choice_options", array("id" => $id))) {
659        return $result->text;
660    } else {
661        return get_string("notanswered", "choice");
662    }
663}
664
665/**
666 * Gets a full choice record
667 *
668 * @global object
669 * @param int $choiceid
670 * @return object|bool The choice or false
671 */
672function choice_get_choice($choiceid) {
673    global $DB;
674
675    if ($choice = $DB->get_record("choice", array("id" => $choiceid))) {
676        if ($options = $DB->get_records("choice_options", array("choiceid" => $choiceid), "id")) {
677            foreach ($options as $option) {
678                $choice->option[$option->id] = $option->text;
679                $choice->maxanswers[$option->id] = $option->maxanswers;
680            }
681            return $choice;
682        }
683    }
684    return false;
685}
686
687/**
688 * List the actions that correspond to a view of this module.
689 * This is used by the participation report.
690 *
691 * Note: This is not used by new logging system. Event with
692 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
693 *       be considered as view action.
694 *
695 * @return array
696 */
697function choice_get_view_actions() {
698    return array('view','view all','report');
699}
700
701/**
702 * List the actions that correspond to a post of this module.
703 * This is used by the participation report.
704 *
705 * Note: This is not used by new logging system. Event with
706 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
707 *       will be considered as post action.
708 *
709 * @return array
710 */
711function choice_get_post_actions() {
712    return array('choose','choose again');
713}
714
715
716/**
717 * Implementation of the function for printing the form elements that control
718 * whether the course reset functionality affects the choice.
719 *
720 * @param object $mform form passed by reference
721 */
722function choice_reset_course_form_definition(&$mform) {
723    $mform->addElement('header', 'choiceheader', get_string('modulenameplural', 'choice'));
724    $mform->addElement('advcheckbox', 'reset_choice', get_string('removeresponses','choice'));
725}
726
727/**
728 * Course reset form defaults.
729 *
730 * @return array
731 */
732function choice_reset_course_form_defaults($course) {
733    return array('reset_choice'=>1);
734}
735
736/**
737 * Actual implementation of the reset course functionality, delete all the
738 * choice responses for course $data->courseid.
739 *
740 * @global object
741 * @global object
742 * @param object $data the data submitted from the reset course.
743 * @return array status array
744 */
745function choice_reset_userdata($data) {
746    global $CFG, $DB;
747
748    $componentstr = get_string('modulenameplural', 'choice');
749    $status = array();
750
751    if (!empty($data->reset_choice)) {
752        $choicessql = "SELECT ch.id
753                       FROM {choice} ch
754                       WHERE ch.course=?";
755
756        $DB->delete_records_select('choice_answers', "choiceid IN ($choicessql)", array($data->courseid));
757        $status[] = array('component'=>$componentstr, 'item'=>get_string('removeresponses', 'choice'), 'error'=>false);
758    }
759
760    /// updating dates - shift may be negative too
761    if ($data->timeshift) {
762        // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
763        // See MDL-9367.
764        shift_course_mod_dates('choice', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
765        $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
766    }
767
768    return $status;
769}
770
771/**
772 * @global object
773 * @global object
774 * @global object
775 * @uses CONTEXT_MODULE
776 * @param object $choice
777 * @param object $cm
778 * @param int $groupmode
779 * @param bool $onlyactive Whether to get response data for active users only.
780 * @return array
781 */
782function choice_get_response_data($choice, $cm, $groupmode, $onlyactive) {
783    global $CFG, $USER, $DB;
784
785    $context = context_module::instance($cm->id);
786
787/// Get the current group
788    if ($groupmode > 0) {
789        $currentgroup = groups_get_activity_group($cm);
790    } else {
791        $currentgroup = 0;
792    }
793
794/// Initialise the returned array, which is a matrix:  $allresponses[responseid][userid] = responseobject
795    $allresponses = array();
796
797/// First get all the users who have access here
798/// To start with we assume they are all "unanswered" then move them later
799    $extrafields = get_extra_user_fields($context);
800    $allresponses[0] = get_enrolled_users($context, 'mod/choice:choose', $currentgroup,
801            user_picture::fields('u', $extrafields), null, 0, 0, $onlyactive);
802
803/// Get all the recorded responses for this choice
804    $rawresponses = $DB->get_records('choice_answers', array('choiceid' => $choice->id));
805
806/// Use the responses to move users into the correct column
807
808    if ($rawresponses) {
809        $answeredusers = array();
810        foreach ($rawresponses as $response) {
811            if (isset($allresponses[0][$response->userid])) {   // This person is enrolled and in correct group
812                $allresponses[0][$response->userid]->timemodified = $response->timemodified;
813                $allresponses[$response->optionid][$response->userid] = clone($allresponses[0][$response->userid]);
814                $allresponses[$response->optionid][$response->userid]->answerid = $response->id;
815                $answeredusers[] = $response->userid;
816            }
817        }
818        foreach ($answeredusers as $answereduser) {
819            unset($allresponses[0][$answereduser]);
820        }
821    }
822    return $allresponses;
823}
824
825/**
826 * @uses FEATURE_GROUPS
827 * @uses FEATURE_GROUPINGS
828 * @uses FEATURE_MOD_INTRO
829 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
830 * @uses FEATURE_GRADE_HAS_GRADE
831 * @uses FEATURE_GRADE_OUTCOMES
832 * @param string $feature FEATURE_xx constant for requested feature
833 * @return mixed True if module supports feature, null if doesn't know
834 */
835function choice_supports($feature) {
836    switch($feature) {
837        case FEATURE_GROUPS:                  return true;
838        case FEATURE_GROUPINGS:               return true;
839        case FEATURE_MOD_INTRO:               return true;
840        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
841        case FEATURE_COMPLETION_HAS_RULES:    return true;
842        case FEATURE_GRADE_HAS_GRADE:         return false;
843        case FEATURE_GRADE_OUTCOMES:          return false;
844        case FEATURE_BACKUP_MOODLE2:          return true;
845        case FEATURE_SHOW_DESCRIPTION:        return true;
846
847        default: return null;
848    }
849}
850
851/**
852 * Adds module specific settings to the settings block
853 *
854 * @param settings_navigation $settings The settings navigation object
855 * @param navigation_node $choicenode The node to add module settings to
856 */
857function choice_extend_settings_navigation(settings_navigation $settings, navigation_node $choicenode) {
858    global $PAGE;
859
860    if (has_capability('mod/choice:readresponses', $PAGE->cm->context)) {
861
862        $groupmode = groups_get_activity_groupmode($PAGE->cm);
863        if ($groupmode) {
864            groups_get_activity_group($PAGE->cm, true);
865        }
866
867        $choice = choice_get_choice($PAGE->cm->instance);
868
869        // Check if we want to include responses from inactive users.
870        $onlyactive = $choice->includeinactive ? false : true;
871
872        // Big function, approx 6 SQL calls per user.
873        $allresponses = choice_get_response_data($choice, $PAGE->cm, $groupmode, $onlyactive);
874
875        $allusers = [];
876        foreach($allresponses as $optionid => $userlist) {
877            if ($optionid) {
878                $allusers = array_merge($allusers, array_keys($userlist));
879            }
880        }
881        $responsecount = count(array_unique($allusers));
882        $choicenode->add(get_string("viewallresponses", "choice", $responsecount), new moodle_url('/mod/choice/report.php', array('id'=>$PAGE->cm->id)));
883    }
884}
885
886/**
887 * Obtains the automatic completion state for this choice based on any conditions
888 * in forum settings.
889 *
890 * @param object $course Course
891 * @param object $cm Course-module
892 * @param int $userid User ID
893 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
894 * @return bool True if completed, false if not, $type if conditions not set.
895 */
896function choice_get_completion_state($course, $cm, $userid, $type) {
897    global $CFG,$DB;
898
899    // Get choice details
900    $choice = $DB->get_record('choice', array('id'=>$cm->instance), '*',
901            MUST_EXIST);
902
903    // If completion option is enabled, evaluate it and return true/false
904    if($choice->completionsubmit) {
905        return $DB->record_exists('choice_answers', array(
906                'choiceid'=>$choice->id, 'userid'=>$userid));
907    } else {
908        // Completion option is not enabled so just return $type
909        return $type;
910    }
911}
912
913/**
914 * Return a list of page types
915 * @param string $pagetype current page type
916 * @param stdClass $parentcontext Block's parent context
917 * @param stdClass $currentcontext Current context of block
918 */
919function choice_page_type_list($pagetype, $parentcontext, $currentcontext) {
920    $module_pagetype = array('mod-choice-*'=>get_string('page-mod-choice-x', 'choice'));
921    return $module_pagetype;
922}
923
924/**
925 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
926 */
927function choice_print_overview() {
928    throw new coding_exception('choice_print_overview() can not be used any more and is obsolete.');
929}
930
931
932/**
933 * Get responses of a given user on a given choice.
934 *
935 * @param stdClass $choice Choice record
936 * @param int $userid User id
937 * @return array of choice answers records
938 * @since  Moodle 3.6
939 */
940function choice_get_user_response($choice, $userid) {
941    global $DB;
942    return $DB->get_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $userid), 'optionid');
943}
944
945/**
946 * Get my responses on a given choice.
947 *
948 * @param stdClass $choice Choice record
949 * @return array of choice answers records
950 * @since  Moodle 3.0
951 */
952function choice_get_my_response($choice) {
953    global $USER;
954    return choice_get_user_response($choice, $USER->id);
955}
956
957
958/**
959 * Get all the responses on a given choice.
960 *
961 * @param stdClass $choice Choice record
962 * @return array of choice answers records
963 * @since  Moodle 3.0
964 */
965function choice_get_all_responses($choice) {
966    global $DB;
967    return $DB->get_records('choice_answers', array('choiceid' => $choice->id));
968}
969
970
971/**
972 * Return true if we are allowd to view the choice results.
973 *
974 * @param stdClass $choice Choice record
975 * @param rows|null $current my choice responses
976 * @param bool|null $choiceopen if the choice is open
977 * @return bool true if we can view the results, false otherwise.
978 * @since  Moodle 3.0
979 */
980function choice_can_view_results($choice, $current = null, $choiceopen = null) {
981
982    if (is_null($choiceopen)) {
983        $timenow = time();
984
985        if ($choice->timeopen != 0 && $timenow < $choice->timeopen) {
986            // If the choice is not available, we can't see the results.
987            return false;
988        }
989
990        if ($choice->timeclose != 0 && $timenow > $choice->timeclose) {
991            $choiceopen = false;
992        } else {
993            $choiceopen = true;
994        }
995    }
996    if (empty($current)) {
997        $current = choice_get_my_response($choice);
998    }
999
1000    if ($choice->showresults == CHOICE_SHOWRESULTS_ALWAYS or
1001       ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_ANSWER and !empty($current)) or
1002       ($choice->showresults == CHOICE_SHOWRESULTS_AFTER_CLOSE and !$choiceopen)) {
1003        return true;
1004    }
1005    return false;
1006}
1007
1008/**
1009 * Mark the activity completed (if required) and trigger the course_module_viewed event.
1010 *
1011 * @param  stdClass $choice     choice object
1012 * @param  stdClass $course     course object
1013 * @param  stdClass $cm         course module object
1014 * @param  stdClass $context    context object
1015 * @since Moodle 3.0
1016 */
1017function choice_view($choice, $course, $cm, $context) {
1018
1019    // Trigger course_module_viewed event.
1020    $params = array(
1021        'context' => $context,
1022        'objectid' => $choice->id
1023    );
1024
1025    $event = \mod_choice\event\course_module_viewed::create($params);
1026    $event->add_record_snapshot('course_modules', $cm);
1027    $event->add_record_snapshot('course', $course);
1028    $event->add_record_snapshot('choice', $choice);
1029    $event->trigger();
1030
1031    // Completion.
1032    $completion = new completion_info($course);
1033    $completion->set_module_viewed($cm);
1034}
1035
1036/**
1037 * Check if a choice is available for the current user.
1038 *
1039 * @param  stdClass  $choice            choice record
1040 * @return array                       status (available or not and possible warnings)
1041 */
1042function choice_get_availability_status($choice) {
1043    $available = true;
1044    $warnings = array();
1045
1046    $timenow = time();
1047
1048    if (!empty($choice->timeopen) && ($choice->timeopen > $timenow)) {
1049        $available = false;
1050        $warnings['notopenyet'] = userdate($choice->timeopen);
1051    } else if (!empty($choice->timeclose) && ($timenow > $choice->timeclose)) {
1052        $available = false;
1053        $warnings['expired'] = userdate($choice->timeclose);
1054    }
1055    if (!$choice->allowupdate && choice_get_my_response($choice)) {
1056        $available = false;
1057        $warnings['choicesaved'] = '';
1058    }
1059
1060    // Choice is available.
1061    return array($available, $warnings);
1062}
1063
1064/**
1065 * This standard function will check all instances of this module
1066 * and make sure there are up-to-date events created for each of them.
1067 * If courseid = 0, then every choice event in the site is checked, else
1068 * only choice events belonging to the course specified are checked.
1069 * This function is used, in its new format, by restore_refresh_events()
1070 *
1071 * @param int $courseid
1072 * @param int|stdClass $instance Choice module instance or ID.
1073 * @param int|stdClass $cm Course module object or ID (not used in this module).
1074 * @return bool
1075 */
1076function choice_refresh_events($courseid = 0, $instance = null, $cm = null) {
1077    global $DB, $CFG;
1078    require_once($CFG->dirroot.'/mod/choice/locallib.php');
1079
1080    // If we have instance information then we can just update the one event instead of updating all events.
1081    if (isset($instance)) {
1082        if (!is_object($instance)) {
1083            $instance = $DB->get_record('choice', array('id' => $instance), '*', MUST_EXIST);
1084        }
1085        choice_set_events($instance);
1086        return true;
1087    }
1088
1089    if ($courseid) {
1090        if (! $choices = $DB->get_records("choice", array("course" => $courseid))) {
1091            return true;
1092        }
1093    } else {
1094        if (! $choices = $DB->get_records("choice")) {
1095            return true;
1096        }
1097    }
1098
1099    foreach ($choices as $choice) {
1100        choice_set_events($choice);
1101    }
1102    return true;
1103}
1104
1105/**
1106 * Check if the module has any update that affects the current user since a given time.
1107 *
1108 * @param  cm_info $cm course module data
1109 * @param  int $from the time to check updates from
1110 * @param  array $filter  if we need to check only specific updates
1111 * @return stdClass an object with the different type of areas indicating if they were updated or not
1112 * @since Moodle 3.2
1113 */
1114function choice_check_updates_since(cm_info $cm, $from, $filter = array()) {
1115    global $DB;
1116
1117    $updates = new stdClass();
1118    $choice = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
1119    list($available, $warnings) = choice_get_availability_status($choice);
1120    if (!$available) {
1121        return $updates;
1122    }
1123
1124    $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1125
1126    if (!choice_can_view_results($choice)) {
1127        return $updates;
1128    }
1129    // Check if there are new responses in the choice.
1130    $updates->answers = (object) array('updated' => false);
1131    $select = 'choiceid = :id AND timemodified > :since';
1132    $params = array('id' => $choice->id, 'since' => $from);
1133    $answers = $DB->get_records_select('choice_answers', $select, $params, '', 'id');
1134    if (!empty($answers)) {
1135        $updates->answers->updated = true;
1136        $updates->answers->itemids = array_keys($answers);
1137    }
1138
1139    return $updates;
1140}
1141
1142/**
1143 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1144 *
1145 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1146 * is not displayed on the block.
1147 *
1148 * @param calendar_event $event
1149 * @param \core_calendar\action_factory $factory
1150 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1151 * @return \core_calendar\local\event\entities\action_interface|null
1152 */
1153function mod_choice_core_calendar_provide_event_action(calendar_event $event,
1154                                                       \core_calendar\action_factory $factory,
1155                                                       int $userid = 0) {
1156    global $USER;
1157
1158    if (!$userid) {
1159        $userid = $USER->id;
1160    }
1161
1162    $cm = get_fast_modinfo($event->courseid, $userid)->instances['choice'][$event->instance];
1163
1164    if (!$cm->uservisible) {
1165        // The module is not visible to the user for any reason.
1166        return null;
1167    }
1168
1169    $completion = new \completion_info($cm->get_course());
1170
1171    $completiondata = $completion->get_data($cm, false, $userid);
1172
1173    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1174        return null;
1175    }
1176
1177    $now = time();
1178
1179    if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < $now) {
1180        // The choice has closed so the user can no longer submit anything.
1181        return null;
1182    }
1183
1184    // The choice is actionable if we don't have a start time or the start time is
1185    // in the past.
1186    $actionable = (empty($cm->customdata['timeopen']) || $cm->customdata['timeopen'] <= $now);
1187
1188    if ($actionable && choice_get_user_response((object)['id' => $event->instance], $userid)) {
1189        // There is no action if the user has already submitted their choice.
1190        return null;
1191    }
1192
1193    return $factory->create_instance(
1194        get_string('viewchoices', 'choice'),
1195        new \moodle_url('/mod/choice/view.php', array('id' => $cm->id)),
1196        1,
1197        $actionable
1198    );
1199}
1200
1201/**
1202 * This function calculates the minimum and maximum cutoff values for the timestart of
1203 * the given event.
1204 *
1205 * It will return an array with two values, the first being the minimum cutoff value and
1206 * the second being the maximum cutoff value. Either or both values can be null, which
1207 * indicates there is no minimum or maximum, respectively.
1208 *
1209 * If a cutoff is required then the function must return an array containing the cutoff
1210 * timestamp and error string to display to the user if the cutoff value is violated.
1211 *
1212 * A minimum and maximum cutoff return value will look like:
1213 * [
1214 *     [1505704373, 'The date must be after this date'],
1215 *     [1506741172, 'The date must be before this date']
1216 * ]
1217 *
1218 * @param calendar_event $event The calendar event to get the time range for
1219 * @param stdClass $choice The module instance to get the range from
1220 */
1221function mod_choice_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $choice) {
1222    $mindate = null;
1223    $maxdate = null;
1224
1225    if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1226        if (!empty($choice->timeclose)) {
1227            $maxdate = [
1228                $choice->timeclose,
1229                get_string('openafterclose', 'choice')
1230            ];
1231        }
1232    } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1233        if (!empty($choice->timeopen)) {
1234            $mindate = [
1235                $choice->timeopen,
1236                get_string('closebeforeopen', 'choice')
1237            ];
1238        }
1239    }
1240
1241    return [$mindate, $maxdate];
1242}
1243
1244/**
1245 * This function will update the choice module according to the
1246 * event that has been modified.
1247 *
1248 * It will set the timeopen or timeclose value of the choice instance
1249 * according to the type of event provided.
1250 *
1251 * @throws \moodle_exception
1252 * @param \calendar_event $event
1253 * @param stdClass $choice The module instance to get the range from
1254 */
1255function mod_choice_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $choice) {
1256    global $DB;
1257
1258    if (!in_array($event->eventtype, [CHOICE_EVENT_TYPE_OPEN, CHOICE_EVENT_TYPE_CLOSE])) {
1259        return;
1260    }
1261
1262    $courseid = $event->courseid;
1263    $modulename = $event->modulename;
1264    $instanceid = $event->instance;
1265    $modified = false;
1266
1267    // Something weird going on. The event is for a different module so
1268    // we should ignore it.
1269    if ($modulename != 'choice') {
1270        return;
1271    }
1272
1273    if ($choice->id != $instanceid) {
1274        return;
1275    }
1276
1277    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1278    $context = context_module::instance($coursemodule->id);
1279
1280    // The user does not have the capability to modify this activity.
1281    if (!has_capability('moodle/course:manageactivities', $context)) {
1282        return;
1283    }
1284
1285    if ($event->eventtype == CHOICE_EVENT_TYPE_OPEN) {
1286        // If the event is for the choice activity opening then we should
1287        // set the start time of the choice activity to be the new start
1288        // time of the event.
1289        if ($choice->timeopen != $event->timestart) {
1290            $choice->timeopen = $event->timestart;
1291            $modified = true;
1292        }
1293    } else if ($event->eventtype == CHOICE_EVENT_TYPE_CLOSE) {
1294        // If the event is for the choice activity closing then we should
1295        // set the end time of the choice activity to be the new start
1296        // time of the event.
1297        if ($choice->timeclose != $event->timestart) {
1298            $choice->timeclose = $event->timestart;
1299            $modified = true;
1300        }
1301    }
1302
1303    if ($modified) {
1304        $choice->timemodified = time();
1305        // Persist the instance changes.
1306        $DB->update_record('choice', $choice);
1307        $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1308        $event->trigger();
1309    }
1310}
1311
1312/**
1313 * Get icon mapping for font-awesome.
1314 */
1315function mod_choice_get_fontawesome_icon_map() {
1316    return [
1317        'mod_choice:row' => 'fa-info',
1318        'mod_choice:column' => 'fa-columns',
1319    ];
1320}
1321
1322/**
1323 * Add a get_coursemodule_info function in case any choice type wants to add 'extra' information
1324 * for the course (see resource).
1325 *
1326 * Given a course_module object, this function returns any "extra" information that may be needed
1327 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1328 *
1329 * @param stdClass $coursemodule The coursemodule object (record).
1330 * @return cached_cm_info An object on information that the courses
1331 *                        will know about (most noticeably, an icon).
1332 */
1333function choice_get_coursemodule_info($coursemodule) {
1334    global $DB;
1335
1336    $dbparams = ['id' => $coursemodule->instance];
1337    $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose';
1338    if (!$choice = $DB->get_record('choice', $dbparams, $fields)) {
1339        return false;
1340    }
1341
1342    $result = new cached_cm_info();
1343    $result->name = $choice->name;
1344
1345    if ($coursemodule->showdescription) {
1346        // Convert intro to html. Do not filter cached version, filters run at display time.
1347        $result->content = format_module_intro('choice', $choice, $coursemodule->id, false);
1348    }
1349
1350    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1351    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1352        $result->customdata['customcompletionrules']['completionsubmit'] = $choice->completionsubmit;
1353    }
1354    // Populate some other values that can be used in calendar or on dashboard.
1355    if ($choice->timeopen) {
1356        $result->customdata['timeopen'] = $choice->timeopen;
1357    }
1358    if ($choice->timeclose) {
1359        $result->customdata['timeclose'] = $choice->timeclose;
1360    }
1361
1362    return $result;
1363}
1364
1365/**
1366 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1367 *
1368 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1369 * @return array $descriptions the array of descriptions for the custom rules.
1370 */
1371function mod_choice_get_completion_active_rule_descriptions($cm) {
1372    // Values will be present in cm_info, and we assume these are up to date.
1373    if (empty($cm->customdata['customcompletionrules'])
1374        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1375        return [];
1376    }
1377
1378    $descriptions = [];
1379    foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1380        switch ($key) {
1381            case 'completionsubmit':
1382                if (!empty($val)) {
1383                    $descriptions[] = get_string('completionsubmit', 'choice');
1384                }
1385                break;
1386            default:
1387                break;
1388        }
1389    }
1390    return $descriptions;
1391}
1392