Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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