Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of functions for the quiz module.
19
 *
20
 * This contains functions that are called also from outside the quiz module
21
 * Functions that are only called by the quiz module itself are in {@link locallib.php}
22
 *
23
 * @package    mod_quiz
24
 * @copyright  1999 onwards Martin Dougiamas {@link http://moodle.com}
25
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
 */
27
 
28
 
29
use qbank_managecategories\helper;
30
 
31
defined('MOODLE_INTERNAL') || die();
32
 
33
use mod_quiz\access_manager;
34
use mod_quiz\grade_calculator;
35
use mod_quiz\question\bank\custom_view;
36
use mod_quiz\question\bank\qbank_helper;
37
use mod_quiz\question\display_options;
38
use mod_quiz\question\qubaids_for_quiz;
39
use mod_quiz\question\qubaids_for_users_attempts;
40
use core_question\statistics\questions\all_calculated_for_qubaid_condition;
41
use mod_quiz\local\override_cache;
42
use mod_quiz\quiz_attempt;
43
use mod_quiz\quiz_settings;
44
 
45
require_once($CFG->dirroot . '/calendar/lib.php');
46
require_once($CFG->dirroot . '/question/editlib.php');
47
 
48
/**#@+
49
 * Option controlling what options are offered on the quiz settings form.
50
 */
51
define('QUIZ_MAX_ATTEMPT_OPTION', 10);
52
define('QUIZ_MAX_QPP_OPTION', 50);
53
define('QUIZ_MAX_DECIMAL_OPTION', 5);
54
define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
55
/**#@-*/
56
 
57
/**#@+
58
 * Options determining how the grades from individual attempts are combined to give
59
 * the overall grade for a user
60
 */
61
define('QUIZ_GRADEHIGHEST', '1');
62
define('QUIZ_GRADEAVERAGE', '2');
63
define('QUIZ_ATTEMPTFIRST', '3');
64
define('QUIZ_ATTEMPTLAST',  '4');
65
/**#@-*/
66
 
67
/**
68
 * @var int If start and end date for the quiz are more than this many seconds apart
69
 * they will be represented by two separate events in the calendar
70
 */
71
define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
72
 
73
/**#@+
74
 * Options for navigation method within quizzes.
75
 */
76
define('QUIZ_NAVMETHOD_FREE', 'free');
77
define('QUIZ_NAVMETHOD_SEQ',  'sequential');
78
/**#@-*/
79
 
80
/**
81
 * Event types.
82
 */
83
define('QUIZ_EVENT_TYPE_OPEN', 'open');
84
define('QUIZ_EVENT_TYPE_CLOSE', 'close');
85
 
86
require_once(__DIR__ . '/deprecatedlib.php');
87
 
88
/**
89
 * Given an object containing all the necessary data,
90
 * (defined by the form in mod_form.php) this function
91
 * will create a new instance and return the id number
92
 * of the new instance.
93
 *
94
 * @param stdClass $quiz the data that came from the form.
95
 * @return mixed the id of the new instance on success,
96
 *          false or a string error message on failure.
97
 */
98
function quiz_add_instance($quiz) {
99
    global $DB;
100
    $cmid = $quiz->coursemodule;
101
 
102
    // Process the options from the form.
103
    $quiz->timecreated = time();
104
    $result = quiz_process_options($quiz);
105
    if ($result && is_string($result)) {
106
        return $result;
107
    }
108
 
109
    // Try to store it in the database.
110
    $quiz->id = $DB->insert_record('quiz', $quiz);
111
 
112
    // Create the first section for this quiz.
113
    $DB->insert_record('quiz_sections', ['quizid' => $quiz->id,
114
            'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0]);
115
 
116
    // Do the processing required after an add or an update.
117
    quiz_after_add_or_update($quiz);
118
 
119
    return $quiz->id;
120
}
121
 
122
/**
123
 * Given an object containing all the necessary data,
124
 * (defined by the form in mod_form.php) this function
125
 * will update an existing instance with new data.
126
 *
127
 * @param stdClass $quiz the data that came from the form.
128
 * @param stdClass $mform no longer used.
129
 * @return mixed true on success, false or a string error message on failure.
130
 */
131
function quiz_update_instance($quiz, $mform) {
132
    global $CFG, $DB;
133
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
134
 
135
    // Process the options from the form.
136
    $result = quiz_process_options($quiz);
137
    if ($result && is_string($result)) {
138
        return $result;
139
    }
140
 
141
    // Get the current value, so we can see what changed.
142
    $oldquiz = $DB->get_record('quiz', ['id' => $quiz->instance]);
143
 
144
    // We need two values from the existing DB record that are not in the form,
145
    // in some of the function calls below.
146
    $quiz->sumgrades = $oldquiz->sumgrades;
147
    $quiz->grade     = $oldquiz->grade;
148
 
149
    // Update the database.
150
    $quiz->id = $quiz->instance;
151
    $DB->update_record('quiz', $quiz);
152
 
153
    // Do the processing required after an add or an update.
154
    quiz_after_add_or_update($quiz);
155
 
156
    if ($oldquiz->grademethod != $quiz->grademethod) {
157
        $gradecalculator = quiz_settings::create($quiz->id)->get_grade_calculator();
158
        $gradecalculator->recompute_all_final_grades();
159
        quiz_update_grades($quiz);
160
    }
161
 
162
    $quizdateschanged = $oldquiz->timelimit   != $quiz->timelimit
163
                     || $oldquiz->timeclose   != $quiz->timeclose
164
                     || $oldquiz->graceperiod != $quiz->graceperiod;
165
    if ($quizdateschanged) {
166
        quiz_update_open_attempts(['quizid' => $quiz->id]);
167
    }
168
 
169
    // Delete any previous preview attempts.
170
    quiz_delete_previews($quiz);
171
 
172
    // Repaginate, if asked to.
173
    if (!empty($quiz->repaginatenow) && !quiz_has_attempts($quiz->id)) {
174
        quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
175
    }
176
 
177
    return true;
178
}
179
 
180
/**
181
 * Given an ID of an instance of this module,
182
 * this function will permanently delete the instance
183
 * and any data that depends on it.
184
 *
185
 * @param int $id the id of the quiz to delete.
186
 * @return bool success or failure.
187
 */
188
function quiz_delete_instance($id) {
189
    global $DB;
190
 
191
    $quiz = $DB->get_record('quiz', ['id' => $id], '*', MUST_EXIST);
192
 
193
    quiz_delete_all_attempts($quiz);
194
 
195
    // Delete all overrides, and for performance do not log or check permissions.
196
    $quizobj = quiz_settings::create($quiz->id);
197
    $quizobj->get_override_manager()->delete_all_overrides(shouldlog: false);
198
 
199
    quiz_delete_references($quiz->id);
200
 
201
    // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'.
202
    $DB->delete_records('quiz_slots', ['quizid' => $quiz->id]);
203
    $DB->delete_records('quiz_sections', ['quizid' => $quiz->id]);
204
 
205
    $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
206
 
207
    access_manager::delete_settings($quiz);
208
 
209
    $events = $DB->get_records('event', ['modulename' => 'quiz', 'instance' => $quiz->id]);
210
    foreach ($events as $event) {
211
        $event = calendar_event::load($event);
212
        $event->delete();
213
    }
214
 
215
    quiz_grade_item_delete($quiz);
216
    // We must delete the module record after we delete the grade item.
217
    $DB->delete_records('quiz', ['id' => $quiz->id]);
218
 
219
    return true;
220
}
221
 
222
/**
223
 * Updates a quiz object with override information for a user.
224
 *
225
 * Algorithm:  For each quiz setting, if there is a matching user-specific override,
226
 *   then use that otherwise, if there are group-specific overrides, return the most
227
 *   lenient combination of them.  If neither applies, leave the quiz setting unchanged.
228
 *
229
 *   Special case: if there is more than one password that applies to the user, then
230
 *   quiz->extrapasswords will contain an array of strings giving the remaining
231
 *   passwords.
232
 *
233
 * @param stdClass $quiz The quiz object.
234
 * @param int $userid The userid.
235
 * @return stdClass $quiz The updated quiz object.
236
 */
237
function quiz_update_effective_access($quiz, $userid) {
238
    global $DB;
239
 
240
    // Check for user override.
241
    $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id, 'userid' => $userid]);
242
 
243
    if (!$override) {
244
        $override = new stdClass();
245
        $override->timeopen = null;
246
        $override->timeclose = null;
247
        $override->timelimit = null;
248
        $override->attempts = null;
249
        $override->password = null;
250
    }
251
 
252
    // Check for group overrides.
253
    $groupings = groups_get_user_groups($quiz->course, $userid);
254
 
255
    if (!empty($groupings[0])) {
256
        // Select all overrides that apply to the User's groups.
257
        list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
258
        $sql = "SELECT * FROM {quiz_overrides}
259
                WHERE groupid $extra AND quiz = ?";
260
        $params[] = $quiz->id;
261
        $records = $DB->get_records_sql($sql, $params);
262
 
263
        // Combine the overrides.
264
        $opens = [];
265
        $closes = [];
266
        $limits = [];
267
        $attempts = [];
268
        $passwords = [];
269
 
270
        foreach ($records as $gpoverride) {
271
            if (isset($gpoverride->timeopen)) {
272
                $opens[] = $gpoverride->timeopen;
273
            }
274
            if (isset($gpoverride->timeclose)) {
275
                $closes[] = $gpoverride->timeclose;
276
            }
277
            if (isset($gpoverride->timelimit)) {
278
                $limits[] = $gpoverride->timelimit;
279
            }
280
            if (isset($gpoverride->attempts)) {
281
                $attempts[] = $gpoverride->attempts;
282
            }
283
            if (isset($gpoverride->password)) {
284
                $passwords[] = $gpoverride->password;
285
            }
286
        }
287
        // If there is a user override for a setting, ignore the group override.
288
        if (is_null($override->timeopen) && count($opens)) {
289
            $override->timeopen = min($opens);
290
        }
291
        if (is_null($override->timeclose) && count($closes)) {
292
            if (in_array(0, $closes)) {
293
                $override->timeclose = 0;
294
            } else {
295
                $override->timeclose = max($closes);
296
            }
297
        }
298
        if (is_null($override->timelimit) && count($limits)) {
299
            if (in_array(0, $limits)) {
300
                $override->timelimit = 0;
301
            } else {
302
                $override->timelimit = max($limits);
303
            }
304
        }
305
        if (is_null($override->attempts) && count($attempts)) {
306
            if (in_array(0, $attempts)) {
307
                $override->attempts = 0;
308
            } else {
309
                $override->attempts = max($attempts);
310
            }
311
        }
312
        if (is_null($override->password) && count($passwords)) {
313
            $override->password = array_shift($passwords);
314
            if (count($passwords)) {
315
                $override->extrapasswords = $passwords;
316
            }
317
        }
318
 
319
    }
320
 
321
    // Merge with quiz defaults.
322
    $keys = ['timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords'];
323
    foreach ($keys as $key) {
324
        if (isset($override->{$key})) {
325
            $quiz->{$key} = $override->{$key};
326
        }
327
    }
328
 
329
    return $quiz;
330
}
331
 
332
/**
333
 * Delete all the attempts belonging to a quiz.
334
 *
335
 * @param stdClass $quiz The quiz object.
336
 */
337
function quiz_delete_all_attempts($quiz) {
338
    global $CFG, $DB;
339
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
340
    question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
341
    $DB->delete_records('quiz_attempts', ['quiz' => $quiz->id]);
342
    $DB->delete_records('quiz_grades', ['quiz' => $quiz->id]);
343
}
344
 
345
/**
346
 * Delete all the attempts belonging to a user in a particular quiz.
347
 *
348
 * @param \mod_quiz\quiz_settings $quiz The quiz object.
349
 * @param stdClass $user The user object.
350
 */
351
function quiz_delete_user_attempts($quiz, $user) {
352
    global $CFG, $DB;
353
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
354
    question_engine::delete_questions_usage_by_activities(new qubaids_for_users_attempts(
355
            $quiz->get_quizid(), $user->id, 'all'));
356
    $params = [
357
        'quiz' => $quiz->get_quizid(),
358
        'userid' => $user->id,
359
    ];
360
    $DB->delete_records('quiz_attempts', $params);
361
    $DB->delete_records('quiz_grades', $params);
362
}
363
 
364
/**
365
 * Get the best current grade for a particular user in a quiz.
366
 *
367
 * @param stdClass $quiz the quiz settings.
368
 * @param int $userid the id of the user.
369
 * @return float the user's current grade for this quiz, or null if this user does
370
 * not have a grade on this quiz.
371
 */
372
function quiz_get_best_grade($quiz, $userid) {
373
    global $DB;
374
    $grade = $DB->get_field('quiz_grades', 'grade',
375
            ['quiz' => $quiz->id, 'userid' => $userid]);
376
 
377
    // Need to detect errors/no result, without catching 0 grades.
378
    if ($grade === false) {
379
        return null;
380
    }
381
 
382
    return $grade + 0; // Convert to number.
383
}
384
 
385
/**
386
 * Is this a graded quiz? If this method returns true, you can assume that
387
 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
388
 * divide by them).
389
 *
390
 * @param stdClass $quiz a row from the quiz table.
391
 * @return bool whether this is a graded quiz.
392
 */
393
function quiz_has_grades($quiz) {
394
    return $quiz->grade >= grade_calculator::ALMOST_ZERO && $quiz->sumgrades >= grade_calculator::ALMOST_ZERO;
395
}
396
 
397
/**
398
 * Does this quiz allow multiple tries?
399
 *
400
 * @return bool
401
 */
402
function quiz_allows_multiple_tries($quiz) {
403
    $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
404
    return $bt->allows_multiple_submitted_responses();
405
}
406
 
407
/**
408
 * Return a small object with summary information about what a
409
 * user has done with a given particular instance of this module
410
 * Used for user activity reports.
411
 * $return->time = the time they did it
412
 * $return->info = a short text description
413
 *
414
 * @param stdClass $course
415
 * @param stdClass $user
416
 * @param stdClass $mod
417
 * @param stdClass $quiz
418
 * @return stdClass|null
419
 */
420
function quiz_user_outline($course, $user, $mod, $quiz) {
421
    global $DB, $CFG;
422
    require_once($CFG->libdir . '/gradelib.php');
423
    $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
424
 
425
    if (empty($grades->items[0]->grades)) {
426
        return null;
427
    } else {
428
        $grade = reset($grades->items[0]->grades);
429
    }
430
 
431
    $result = new stdClass();
432
    // If the user can't see hidden grades, don't return that information.
433
    $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
434
    if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
435
        $result->info = get_string('gradenoun') . ': ' . $grade->str_long_grade;
436
    } else {
437
        $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
438
    }
439
 
440
    $result->time = grade_get_date_for_user_grade($grade, $user);
441
 
442
    return $result;
443
}
444
 
445
/**
446
 * Print a detailed representation of what a  user has done with
447
 * a given particular instance of this module, for user activity reports.
448
 *
449
 * @param stdClass $course
450
 * @param stdClass $user
451
 * @param stdClass $mod
452
 * @param stdClass $quiz
453
 * @return bool
454
 */
455
function quiz_user_complete($course, $user, $mod, $quiz) {
456
    global $DB, $CFG, $OUTPUT;
457
    require_once($CFG->libdir . '/gradelib.php');
458
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
459
 
460
    $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
461
    if (!empty($grades->items[0]->grades)) {
462
        $grade = reset($grades->items[0]->grades);
463
        // If the user can't see hidden grades, don't return that information.
464
        $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
465
        if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
466
            echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
467
            if ($grade->str_feedback) {
468
                echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
469
            }
470
        } else {
471
            echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
472
            if ($grade->str_feedback) {
473
                echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
474
            }
475
        }
476
    }
477
 
478
    if ($attempts = $DB->get_records('quiz_attempts',
479
            ['userid' => $user->id, 'quiz' => $quiz->id], 'attempt')) {
480
        foreach ($attempts as $attempt) {
481
            echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
482
            if ($attempt->state != quiz_attempt::FINISHED) {
483
                echo quiz_attempt_state_name($attempt->state);
484
            } else {
485
                if (!isset($gitem)) {
486
                    if (!empty($grades->items[0]->grades)) {
487
                        $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
488
                    } else {
489
                        $gitem = new stdClass();
490
                        $gitem->hidden = true;
491
                    }
492
                }
493
                if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
494
                    echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
495
                } else {
496
                    echo get_string('hidden', 'grades');
497
                }
498
                echo ' - '.userdate($attempt->timefinish).'<br />';
499
            }
500
        }
501
    } else {
502
        print_string('noattempts', 'quiz');
503
    }
504
 
505
    return true;
506
}
507
 
508
 
509
/**
510
 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
511
 * @param int $userid the userid.
512
 * @param string $status 'all', 'finished' or 'unfinished' to control
513
 * @param bool $includepreviews
514
 * @return array of all the user's attempts at this quiz. Returns an empty
515
 *      array if there are none.
516
 */
517
function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
518
    global $DB;
519
 
520
    $params = [];
521
    switch ($status) {
522
        case 'all':
523
            $statuscondition = '';
524
            break;
525
 
526
        case 'finished':
527
            $statuscondition = ' AND state IN (:state1, :state2)';
528
            $params['state1'] = quiz_attempt::FINISHED;
529
            $params['state2'] = quiz_attempt::ABANDONED;
530
            break;
531
 
532
        case 'unfinished':
533
            $statuscondition = ' AND state IN (:state1, :state2)';
534
            $params['state1'] = quiz_attempt::IN_PROGRESS;
535
            $params['state2'] = quiz_attempt::OVERDUE;
536
            break;
537
    }
538
 
539
    $quizids = (array) $quizids;
540
    list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
541
    $params += $inparams;
542
    $params['userid'] = $userid;
543
 
544
    $previewclause = '';
545
    if (!$includepreviews) {
546
        $previewclause = ' AND preview = 0';
547
    }
548
 
549
    return $DB->get_records_select('quiz_attempts',
550
            "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
551
            $params, 'quiz, attempt ASC');
552
}
553
 
554
/**
555
 * Return grade for given user or all users.
556
 *
557
 * @param int $quizid id of quiz
558
 * @param int $userid optional user id, 0 means all users
559
 * @return array array of grades, false if none. These are raw grades. They should
560
 * be processed with quiz_format_grade for display.
561
 */
562
function quiz_get_user_grades($quiz, $userid = 0) {
563
    global $CFG, $DB;
564
 
565
    $params = [$quiz->id];
566
    $usertest = '';
567
    if ($userid) {
568
        $params[] = $userid;
569
        $usertest = 'AND u.id = ?';
570
    }
571
    return $DB->get_records_sql("
572
            SELECT
573
                u.id,
574
                u.id AS userid,
575
                qg.grade AS rawgrade,
576
                qg.timemodified AS dategraded,
577
                MAX(qa.timefinish) AS datesubmitted
578
 
579
            FROM {user} u
580
            JOIN {quiz_grades} qg ON u.id = qg.userid
581
            JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
582
 
583
            WHERE qg.quiz = ?
584
            $usertest
585
            GROUP BY u.id, qg.grade, qg.timemodified", $params);
586
}
587
 
588
/**
589
 * Round a grade to the correct number of decimal places, and format it for display.
590
 *
591
 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
592
 * @param float|null $grade The grade to round and display (or null meaning no grade).
593
 * @return string
594
 */
595
function quiz_format_grade($quiz, $grade) {
596
    if (is_null($grade)) {
597
        return get_string('notyetgraded', 'quiz');
598
    }
599
    return format_float($grade, $quiz->decimalpoints);
600
}
601
 
602
/**
603
 * Determine the correct number of decimal places required to format a grade.
604
 *
605
 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints and
606
 *      ->questiondecimalpoints are used.
607
 * @return integer
608
 */
609
function quiz_get_grade_format($quiz) {
610
    if (empty($quiz->questiondecimalpoints)) {
611
        $quiz->questiondecimalpoints = -1;
612
    }
613
 
614
    if ($quiz->questiondecimalpoints == -1) {
615
        return $quiz->decimalpoints;
616
    }
617
 
618
    return $quiz->questiondecimalpoints;
619
}
620
 
621
/**
622
 * Round a grade to the correct number of decimal places, and format it for display.
623
 *
624
 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
625
 * @param float $grade The grade to round.
626
 * @return string
627
 */
628
function quiz_format_question_grade($quiz, $grade) {
629
    return format_float($grade, quiz_get_grade_format($quiz));
630
}
631
 
632
/**
633
 * Update grades in central gradebook
634
 *
635
 * @category grade
636
 * @param stdClass $quiz the quiz settings.
637
 * @param int $userid specific user only, 0 means all users.
638
 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
639
 */
640
function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
641
    global $CFG, $DB;
642
    require_once($CFG->libdir . '/gradelib.php');
643
 
644
    if ($quiz->grade == 0) {
645
        quiz_grade_item_update($quiz);
646
 
647
    } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
648
        quiz_grade_item_update($quiz, $grades);
649
 
650
    } else if ($userid && $nullifnone) {
651
        $grade = new stdClass();
652
        $grade->userid = $userid;
653
        $grade->rawgrade = null;
654
        quiz_grade_item_update($quiz, $grade);
655
 
656
    } else {
657
        quiz_grade_item_update($quiz);
658
    }
659
}
660
 
661
/**
662
 * Create or update the grade item for given quiz
663
 *
664
 * @category grade
665
 * @param stdClass $quiz object with extra cmidnumber
666
 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
667
 * @return int 0 if ok, error code otherwise
668
 */
669
function quiz_grade_item_update($quiz, $grades = null) {
670
    global $CFG, $OUTPUT;
671
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
672
    require_once($CFG->libdir . '/gradelib.php');
673
 
674
    if (property_exists($quiz, 'cmidnumber')) { // May not be always present.
675
        $params = ['itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber];
676
    } else {
677
        $params = ['itemname' => $quiz->name];
678
    }
679
 
680
    if ($quiz->grade > 0) {
681
        $params['gradetype'] = GRADE_TYPE_VALUE;
682
        $params['grademax']  = $quiz->grade;
683
        $params['grademin']  = 0;
684
 
685
    } else {
686
        $params['gradetype'] = GRADE_TYPE_NONE;
687
    }
688
 
689
    // What this is trying to do:
690
    // 1. If the quiz is set to not show grades while the quiz is still open,
691
    //    and is set to show grades after the quiz is closed, then create the
692
    //    grade_item with a show-after date that is the quiz close date.
693
    // 2. If the quiz is set to not show grades at either of those times,
694
    //    create the grade_item as hidden.
695
    // 3. If the quiz is set to show grades, create the grade_item visible.
696
    $openreviewoptions = display_options::make_from_quiz($quiz,
697
            display_options::LATER_WHILE_OPEN);
698
    $closedreviewoptions = display_options::make_from_quiz($quiz,
699
            display_options::AFTER_CLOSE);
700
    if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
701
            $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
702
        $params['hidden'] = 1;
703
 
704
    } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
705
            $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
706
        if ($quiz->timeclose) {
707
            $params['hidden'] = $quiz->timeclose;
708
        } else {
709
            $params['hidden'] = 1;
710
        }
711
 
712
    } else {
713
        // Either
714
        // a) both open and closed enabled
715
        // b) open enabled, closed disabled - we can not "hide after",
716
        //    grades are kept visible even after closing.
717
        $params['hidden'] = 0;
718
    }
719
 
720
    if (!$params['hidden']) {
721
        // If the grade item is not hidden by the quiz logic, then we need to
722
        // hide it if the quiz is hidden from students.
723
        if (property_exists($quiz, 'visible')) {
724
            // Saving the quiz form, and cm not yet updated in the database.
725
            $params['hidden'] = !$quiz->visible;
726
        } else {
727
            $cm = get_coursemodule_from_instance('quiz', $quiz->id);
728
            $params['hidden'] = !$cm->visible;
729
        }
730
    }
731
 
732
    if ($grades  === 'reset') {
733
        $params['reset'] = true;
734
        $grades = null;
735
    }
736
 
737
    $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
738
    if (!empty($gradebook_grades->items)) {
739
        $grade_item = $gradebook_grades->items[0];
740
        if ($grade_item->locked) {
741
            // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
742
            $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
743
            if (!$confirm_regrade) {
744
                if (!AJAX_SCRIPT) {
745
                    $message = get_string('gradeitemislocked', 'grades');
746
                    $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
747
                            '&amp;mode=overview';
748
                    $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
749
                    echo $OUTPUT->box_start('generalbox', 'notice');
750
                    echo '<p>'. $message .'</p>';
751
                    echo $OUTPUT->container_start('buttons');
752
                    echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
753
                    echo $OUTPUT->single_button($back_link,  get_string('cancel'));
754
                    echo $OUTPUT->container_end();
755
                    echo $OUTPUT->box_end();
756
                }
757
                return GRADE_UPDATE_ITEM_LOCKED;
758
            }
759
        }
760
    }
761
 
762
    return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
763
}
764
 
765
/**
766
 * Delete grade item for given quiz
767
 *
768
 * @category grade
769
 * @param stdClass $quiz object
770
 * @return int
771
 */
772
function quiz_grade_item_delete($quiz) {
773
    global $CFG;
774
    require_once($CFG->libdir . '/gradelib.php');
775
 
776
    return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
777
            null, ['deleted' => 1]);
778
}
779
 
780
/**
781
 * This standard function will check all instances of this module
782
 * and make sure there are up-to-date events created for each of them.
783
 * If courseid = 0, then every quiz event in the site is checked, else
784
 * only quiz events belonging to the course specified are checked.
785
 * This function is used, in its new format, by restore_refresh_events()
786
 *
787
 * @param int $courseid
788
 * @param int|stdClass $instance Quiz module instance or ID.
789
 * @param int|stdClass $cm Course module object or ID (not used in this module).
790
 * @return bool
791
 */
792
function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
793
    global $DB;
794
 
795
    // If we have instance information then we can just update the one event instead of updating all events.
796
    if (isset($instance)) {
797
        if (!is_object($instance)) {
798
            $instance = $DB->get_record('quiz', ['id' => $instance], '*', MUST_EXIST);
799
        }
800
        quiz_update_events($instance);
801
        return true;
802
    }
803
 
804
    if ($courseid == 0) {
805
        if (!$quizzes = $DB->get_records('quiz')) {
806
            return true;
807
        }
808
    } else {
809
        if (!$quizzes = $DB->get_records('quiz', ['course' => $courseid])) {
810
            return true;
811
        }
812
    }
813
 
814
    foreach ($quizzes as $quiz) {
815
        quiz_update_events($quiz);
816
    }
817
 
818
    return true;
819
}
820
 
821
/**
822
 * Returns all quiz graded users since a given time for specified quiz
823
 */
824
function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
825
        $courseid, $cmid, $userid = 0, $groupid = 0) {
826
    global $CFG, $USER, $DB;
827
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
828
 
829
    $course = get_course($courseid);
830
    $modinfo = get_fast_modinfo($course);
831
 
832
    $cm = $modinfo->cms[$cmid];
833
    $quiz = $DB->get_record('quiz', ['id' => $cm->instance]);
834
 
835
    if ($userid) {
836
        $userselect = "AND u.id = :userid";
837
        $params['userid'] = $userid;
838
    } else {
839
        $userselect = '';
840
    }
841
 
842
    if ($groupid) {
843
        $groupselect = 'AND gm.groupid = :groupid';
844
        $groupjoin   = 'JOIN {groups_members} gm ON  gm.userid=u.id';
845
        $params['groupid'] = $groupid;
846
    } else {
847
        $groupselect = '';
848
        $groupjoin   = '';
849
    }
850
 
851
    $params['timestart'] = $timestart;
852
    $params['quizid'] = $quiz->id;
853
 
854
    $userfieldsapi = \core_user\fields::for_userpic();
855
    $ufields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects;
856
    if (!$attempts = $DB->get_records_sql("
857
              SELECT qa.*,
858
                     {$ufields}
859
                FROM {quiz_attempts} qa
860
                     JOIN {user} u ON u.id = qa.userid
861
                     $groupjoin
862
               WHERE qa.timefinish > :timestart
863
                 AND qa.quiz = :quizid
864
                 AND qa.preview = 0
865
                     $userselect
866
                     $groupselect
867
            ORDER BY qa.timefinish ASC", $params)) {
868
        return;
869
    }
870
 
871
    $context         = context_module::instance($cm->id);
872
    $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
873
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $context);
874
    $grader          = has_capability('mod/quiz:viewreports', $context);
875
    $groupmode       = groups_get_activity_groupmode($cm, $course);
876
 
877
    $usersgroups = null;
878
    $aname = format_string($cm->name, true);
879
    foreach ($attempts as $attempt) {
880
        if ($attempt->userid != $USER->id) {
881
            if (!$grader) {
882
                // Grade permission required.
883
                continue;
884
            }
885
 
886
            if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
887
                $usersgroups = groups_get_all_groups($course->id,
888
                        $attempt->userid, $cm->groupingid);
889
                $usersgroups = array_keys($usersgroups);
890
                if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
891
                    continue;
892
                }
893
            }
894
        }
895
 
896
        $options = quiz_get_review_options($quiz, $attempt, $context);
897
 
898
        $tmpactivity = new stdClass();
899
 
900
        $tmpactivity->type       = 'quiz';
901
        $tmpactivity->cmid       = $cm->id;
902
        $tmpactivity->name       = $aname;
903
        $tmpactivity->sectionnum = $cm->sectionnum;
904
        $tmpactivity->timestamp  = $attempt->timefinish;
905
 
906
        $tmpactivity->content = new stdClass();
907
        $tmpactivity->content->attemptid = $attempt->id;
908
        $tmpactivity->content->attempt   = $attempt->attempt;
909
        if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
910
            $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
911
            $tmpactivity->content->maxgrade  = quiz_format_grade($quiz, $quiz->sumgrades);
912
        } else {
913
            $tmpactivity->content->sumgrades = null;
914
            $tmpactivity->content->maxgrade  = null;
915
        }
916
 
917
        $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
918
        $tmpactivity->user->fullname  = fullname($tmpactivity->user, $viewfullnames);
919
 
920
        $activities[$index++] = $tmpactivity;
921
    }
922
}
923
 
924
function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
925
    global $CFG, $OUTPUT;
926
 
927
    echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
928
 
929
    echo '<tr><td class="userpicture" valign="top">';
930
    echo $OUTPUT->user_picture($activity->user, ['courseid' => $courseid]);
931
    echo '</td><td>';
932
 
933
    if ($detail) {
934
        $modname = $modnames[$activity->type];
935
        echo '<div class="title">';
936
        echo $OUTPUT->image_icon('monologo', $modname, $activity->type);
937
        echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
938
                $activity->cmid . '">' . $activity->name . '</a>';
939
        echo '</div>';
940
    }
941
 
942
    echo '<div class="grade">';
943
    echo  get_string('attempt', 'quiz', $activity->content->attempt);
944
    if (isset($activity->content->maxgrade)) {
945
        $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
946
        echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
947
                $activity->content->attemptid . '">' . $grades . '</a>)';
948
    }
949
    echo '</div>';
950
 
951
    echo '<div class="user">';
952
    echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
953
            '&amp;course=' . $courseid . '">' . $activity->user->fullname .
954
            '</a> - ' . userdate($activity->timestamp);
955
    echo '</div>';
956
 
957
    echo '</td></tr></table>';
958
 
959
    return;
960
}
961
 
962
/**
963
 * Pre-process the quiz options form data, making any necessary adjustments.
964
 * Called by add/update instance in this file.
965
 *
966
 * @param stdClass $quiz The variables set on the form.
967
 */
968
function quiz_process_options($quiz) {
969
    global $CFG;
970
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
971
    require_once($CFG->libdir . '/questionlib.php');
972
 
973
    $quiz->timemodified = time();
974
 
975
    // Quiz name.
976
    if (!empty($quiz->name)) {
977
        $quiz->name = trim($quiz->name);
978
    }
979
 
980
    // Password field - different in form to stop browsers that remember passwords
981
    // getting confused.
982
    $quiz->password = $quiz->quizpassword;
983
    unset($quiz->quizpassword);
984
 
985
    // Quiz feedback.
986
    if (isset($quiz->feedbacktext)) {
987
        // Clean up the boundary text.
988
        for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
989
            if (empty($quiz->feedbacktext[$i]['text'])) {
990
                $quiz->feedbacktext[$i]['text'] = '';
991
            } else {
992
                $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
993
            }
994
        }
995
 
996
        // Check the boundary value is a number or a percentage, and in range.
997
        $i = 0;
998
        while (!empty($quiz->feedbackboundaries[$i])) {
999
            $boundary = trim($quiz->feedbackboundaries[$i]);
1000
            if (!is_numeric($boundary)) {
1001
                if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1002
                    $boundary = trim(substr($boundary, 0, -1));
1003
                    if (is_numeric($boundary)) {
1004
                        $boundary = $boundary * $quiz->grade / 100.0;
1005
                    } else {
1006
                        return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1007
                    }
1008
                }
1009
            }
1010
            if ($boundary <= 0 || $boundary >= $quiz->grade) {
1011
                return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1012
            }
1013
            if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1014
                return get_string('feedbackerrororder', 'quiz', $i + 1);
1015
            }
1016
            $quiz->feedbackboundaries[$i] = $boundary;
1017
            $i += 1;
1018
        }
1019
        $numboundaries = $i;
1020
 
1021
        // Check there is nothing in the remaining unused fields.
1022
        if (!empty($quiz->feedbackboundaries)) {
1023
            for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1024
                if (!empty($quiz->feedbackboundaries[$i]) &&
1025
                        trim($quiz->feedbackboundaries[$i]) != '') {
1026
                    return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1027
                }
1028
            }
1029
        }
1030
        for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1031
            if (!empty($quiz->feedbacktext[$i]['text']) &&
1032
                    trim($quiz->feedbacktext[$i]['text']) != '') {
1033
                return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1034
            }
1035
        }
1036
        // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1037
        $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1038
        $quiz->feedbackboundaries[$numboundaries] = 0;
1039
        $quiz->feedbackboundarycount = $numboundaries;
1040
    } else {
1041
        $quiz->feedbackboundarycount = -1;
1042
    }
1043
 
1044
    // Combing the individual settings into the review columns.
1045
    $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1046
    $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1047
    $quiz->reviewmaxmarks = quiz_review_option_form_to_db($quiz, 'maxmarks');
1048
    $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1049
    $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1050
    $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1051
    $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1052
    $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1053
    $quiz->reviewattempt |= display_options::DURING;
1054
    $quiz->reviewoverallfeedback &= ~display_options::DURING;
1055
 
1056
    // Ensure that disabled checkboxes in completion settings are set to 0.
1057
    // But only if the completion settinsg are unlocked.
1058
    if (!empty($quiz->completionunlocked)) {
1059
        if (empty($quiz->completionusegrade)) {
1060
            $quiz->completionpassgrade = 0;
1061
        }
1062
        if (empty($quiz->completionpassgrade)) {
1063
            $quiz->completionattemptsexhausted = 0;
1064
        }
1065
        if (empty($quiz->completionminattemptsenabled)) {
1066
            $quiz->completionminattempts = 0;
1067
        }
1068
    }
1069
}
1070
 
1071
/**
1072
 * Helper function for {@link quiz_process_options()}.
1073
 * @param stdClass $fromform the sumbitted form date.
1074
 * @param string $field one of the review option field names.
1075
 */
1076
function quiz_review_option_form_to_db($fromform, $field) {
1077
    static $times = [
1078
        'during' => display_options::DURING,
1079
        'immediately' => display_options::IMMEDIATELY_AFTER,
1080
        'open' => display_options::LATER_WHILE_OPEN,
1081
        'closed' => display_options::AFTER_CLOSE,
1082
    ];
1083
 
1084
    $review = 0;
1085
    foreach ($times as $whenname => $when) {
1086
        $fieldname = $field . $whenname;
1087
        if (!empty($fromform->$fieldname)) {
1088
            $review |= $when;
1089
            unset($fromform->$fieldname);
1090
        }
1091
    }
1092
 
1093
    return $review;
1094
}
1095
 
1096
/**
1097
 * In place editable callback for slot displaynumber.
1098
 *
1099
 * @param string $itemtype slotdisplarnumber
1100
 * @param int $itemid the id of the slot in the quiz_slots table
1101
 * @param string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table
1102
 * @return \core\output\inplace_editable|void
1103
 */
1104
function mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue): \core\output\inplace_editable {
1105
    global $DB;
1106
 
1107
    if ($itemtype === 'slotdisplaynumber') {
1108
        // Work out which quiz and slot this is.
1109
        $slot = $DB->get_record('quiz_slots', ['id' => $itemid], '*', MUST_EXIST);
1110
        $quizobj = quiz_settings::create($slot->quizid);
1111
 
1112
        // Validate the context, and check the required capability.
1113
        $context = $quizobj->get_context();
1114
        \core_external\external_api::validate_context($context);
1115
        require_capability('mod/quiz:manage', $context);
1116
 
1117
        // Update the value - truncating the size of the DB column.
1118
        $structure = $quizobj->get_structure();
1119
        $structure->update_slot_display_number($itemid, core_text::substr($newvalue, 0, 16));
1120
 
1121
        // Prepare the element for the output.
1122
        return $structure->make_slot_display_number_in_place_editable($itemid, $context);
1123
    }
1124
}
1125
 
1126
/**
1127
 * This function is called at the end of quiz_add_instance
1128
 * and quiz_update_instance, to do the common processing.
1129
 *
1130
 * @param stdClass $quiz the quiz object.
1131
 */
1132
function quiz_after_add_or_update($quiz) {
1133
    global $DB;
1134
    $cmid = $quiz->coursemodule;
1135
 
1136
    // We need to use context now, so we need to make sure all needed info is already in db.
1137
    $DB->set_field('course_modules', 'instance', $quiz->id, ['id' => $cmid]);
1138
    $context = context_module::instance($cmid);
1139
 
1140
    // Save the feedback.
1141
    $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
1142
 
1143
    for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1144
        $feedback = new stdClass();
1145
        $feedback->quizid = $quiz->id;
1146
        $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1147
        $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1148
        $feedback->mingrade = $quiz->feedbackboundaries[$i];
1149
        $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1150
        $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1151
        $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1152
                $context->id, 'mod_quiz', 'feedback', $feedback->id,
1153
                ['subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0],
1154
                $quiz->feedbacktext[$i]['text']);
1155
        $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1156
                ['id' => $feedback->id]);
1157
    }
1158
 
1159
    // Store any settings belonging to the access rules.
1160
    access_manager::save_settings($quiz);
1161
 
1162
    // Update the events relating to this quiz.
1163
    quiz_update_events($quiz);
1164
    $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1165
    \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
1166
 
1167
    // Update related grade item.
1168
    quiz_grade_item_update($quiz);
1169
}
1170
 
1171
/**
1172
 * This function updates the events associated to the quiz.
1173
 * If $override is non-zero, then it updates only the events
1174
 * associated with the specified override.
1175
 *
1176
 * @param stdClass $quiz the quiz object.
1177
 * @param stdClass|null $override limit to a specific override
1178
 */
1179
function quiz_update_events($quiz, $override = null) {
1180
    global $DB;
1181
 
1182
    // Load the old events relating to this quiz.
1183
    $conds = ['modulename' => 'quiz',
1184
                   'instance' => $quiz->id];
1185
    if (!empty($override)) {
1186
        // Only load events for this override.
1187
        if (isset($override->userid)) {
1188
            $conds['userid'] = $override->userid;
1189
        } else {
1190
            $conds['groupid'] = $override->groupid;
1191
        }
1192
    }
1193
    $oldevents = $DB->get_records('event', $conds, 'id ASC');
1194
 
1195
    // Now make a to-do list of all that needs to be updated.
1196
    if (empty($override)) {
1197
        // We are updating the primary settings for the quiz, so we need to add all the overrides.
1198
        $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id ASC');
1199
        // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1200
        // list contains the original (non-override) event for the module. If this is not included
1201
        // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1202
        // list against the $oldevents list.
1203
        array_unshift($overrides, new stdClass());
1204
    } else {
1205
        // Just do the one override.
1206
        $overrides = [$override];
1207
    }
1208
 
1209
    // Get group override priorities.
1210
    $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1211
 
1212
    foreach ($overrides as $current) {
1213
        $groupid   = isset($current->groupid)?  $current->groupid : 0;
1214
        $userid    = isset($current->userid)? $current->userid : 0;
1215
        $timeopen  = isset($current->timeopen)?  $current->timeopen : $quiz->timeopen;
1216
        $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1217
 
1218
        // Only add open/close events for an override if they differ from the quiz default.
1219
        $addopen  = empty($current->id) || !empty($current->timeopen);
1220
        $addclose = empty($current->id) || !empty($current->timeclose);
1221
 
1222
        if (!empty($quiz->coursemodule)) {
1223
            $cmid = $quiz->coursemodule;
1224
        } else {
1225
            $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1226
        }
1227
 
1228
        $event = new stdClass();
1229
        $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
1230
        $event->description = format_module_intro('quiz', $quiz, $cmid, false);
1231
        $event->format = FORMAT_HTML;
1232
        // Events module won't show user events when the courseid is nonzero.
1233
        $event->courseid    = ($userid) ? 0 : $quiz->course;
1234
        $event->groupid     = $groupid;
1235
        $event->userid      = $userid;
1236
        $event->modulename  = 'quiz';
1237
        $event->instance    = $quiz->id;
1238
        $event->timestart   = $timeopen;
1239
        $event->timeduration = max($timeclose - $timeopen, 0);
1240
        $event->timesort    = $timeopen;
1241
        $event->visible     = instance_is_visible('quiz', $quiz);
1242
        $event->eventtype   = QUIZ_EVENT_TYPE_OPEN;
1243
        $event->priority    = null;
1244
 
1245
        // Determine the event name and priority.
1246
        if ($groupid) {
1247
            // Group override event.
1248
            $params = new stdClass();
1249
            $params->quiz = $quiz->name;
1250
            $params->group = groups_get_group_name($groupid);
1251
            if ($params->group === false) {
1252
                // Group doesn't exist, just skip it.
1253
                continue;
1254
            }
1255
            $eventname = get_string('overridegroupeventname', 'quiz', $params);
1256
            // Set group override priority.
1257
            if ($grouppriorities !== null) {
1258
                $openpriorities = $grouppriorities['open'];
1259
                if (isset($openpriorities[$timeopen])) {
1260
                    $event->priority = $openpriorities[$timeopen];
1261
                }
1262
            }
1263
        } else if ($userid) {
1264
            // User override event.
1265
            $params = new stdClass();
1266
            $params->quiz = $quiz->name;
1267
            $eventname = get_string('overrideusereventname', 'quiz', $params);
1268
            // Set user override priority.
1269
            $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
1270
        } else {
1271
            // The parent event.
1272
            $eventname = $quiz->name;
1273
        }
1274
 
1275
        if ($addopen or $addclose) {
1276
            // Separate start and end events.
1277
            $event->timeduration  = 0;
1278
            if ($timeopen && $addopen) {
1279
                if ($oldevent = array_shift($oldevents)) {
1280
                    $event->id = $oldevent->id;
1281
                } else {
1282
                    unset($event->id);
1283
                }
1284
                $event->name = get_string('quizeventopens', 'quiz', $eventname);
1285
                // The method calendar_event::create will reuse a db record if the id field is set.
1286
                calendar_event::create($event, false);
1287
            }
1288
            if ($timeclose && $addclose) {
1289
                if ($oldevent = array_shift($oldevents)) {
1290
                    $event->id = $oldevent->id;
1291
                } else {
1292
                    unset($event->id);
1293
                }
1294
                $event->type      = CALENDAR_EVENT_TYPE_ACTION;
1295
                $event->name      = get_string('quizeventcloses', 'quiz', $eventname);
1296
                $event->timestart = $timeclose;
1297
                $event->timesort  = $timeclose;
1298
                $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
1299
                if ($groupid && $grouppriorities !== null) {
1300
                    $closepriorities = $grouppriorities['close'];
1301
                    if (isset($closepriorities[$timeclose])) {
1302
                        $event->priority = $closepriorities[$timeclose];
1303
                    }
1304
                }
1305
                calendar_event::create($event, false);
1306
            }
1307
        }
1308
    }
1309
 
1310
    // Delete any leftover events.
1311
    foreach ($oldevents as $badevent) {
1312
        $badevent = calendar_event::load($badevent);
1313
        $badevent->delete();
1314
    }
1315
}
1316
 
1317
/**
1318
 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1319
 *
1320
 * @param int $quizid The quiz ID.
1321
 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1322
 */
1323
function quiz_get_group_override_priorities($quizid) {
1324
    global $DB;
1325
 
1326
    // Fetch group overrides.
1327
    $where = 'quiz = :quiz AND groupid IS NOT NULL';
1328
    $params = ['quiz' => $quizid];
1329
    $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1330
    if (!$overrides) {
1331
        return null;
1332
    }
1333
 
1334
    $grouptimeopen = [];
1335
    $grouptimeclose = [];
1336
    foreach ($overrides as $override) {
1337
        if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1338
            $grouptimeopen[] = $override->timeopen;
1339
        }
1340
        if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1341
            $grouptimeclose[] = $override->timeclose;
1342
        }
1343
    }
1344
 
1345
    // Sort open times in ascending manner. The earlier open time gets higher priority.
1346
    sort($grouptimeopen);
1347
    // Set priorities.
1348
    $opengrouppriorities = [];
1349
    $openpriority = 1;
1350
    foreach ($grouptimeopen as $timeopen) {
1351
        $opengrouppriorities[$timeopen] = $openpriority++;
1352
    }
1353
 
1354
    // Sort close times in descending manner. The later close time gets higher priority.
1355
    rsort($grouptimeclose);
1356
    // Set priorities.
1357
    $closegrouppriorities = [];
1358
    $closepriority = 1;
1359
    foreach ($grouptimeclose as $timeclose) {
1360
        $closegrouppriorities[$timeclose] = $closepriority++;
1361
    }
1362
 
1363
    return [
1364
        'open' => $opengrouppriorities,
1365
        'close' => $closegrouppriorities
1366
    ];
1367
}
1368
 
1369
/**
1370
 * List the actions that correspond to a view of this module.
1371
 * This is used by the participation report.
1372
 *
1373
 * Note: This is not used by new logging system. Event with
1374
 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1375
 *       be considered as view action.
1376
 *
1377
 * @return array
1378
 */
1379
function quiz_get_view_actions() {
1380
    return ['view', 'view all', 'report', 'review'];
1381
}
1382
 
1383
/**
1384
 * List the actions that correspond to a post of this module.
1385
 * This is used by the participation report.
1386
 *
1387
 * Note: This is not used by new logging system. Event with
1388
 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1389
 *       will be considered as post action.
1390
 *
1391
 * @return array
1392
 */
1393
function quiz_get_post_actions() {
1394
    return ['attempt', 'close attempt', 'preview', 'editquestions',
1395
            'delete attempt', 'manualgrade'];
1396
}
1397
 
1398
/**
1399
 * Standard callback used by questions_in_use.
1400
 *
1401
 * @param array $questionids of question ids.
1402
 * @return bool whether any of these questions are used by any instance of this module.
1403
 */
1404
function quiz_questions_in_use($questionids) {
1405
    return question_engine::questions_in_use($questionids,
1406
            new qubaid_join('{quiz_attempts} quiza', 'quiza.uniqueid',
1407
                'quiza.preview = 0'));
1408
}
1409
 
1410
/**
1411
 * Implementation of the function for printing the form elements that control
1412
 * whether the course reset functionality affects the quiz.
1413
 *
1414
 * @param MoodleQuickForm $mform the course reset form that is being built.
1415
 */
1416
function quiz_reset_course_form_definition($mform) {
1417
    $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1418
    $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1419
            get_string('removeallquizattempts', 'quiz'));
1420
    $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1421
            get_string('removealluseroverrides', 'quiz'));
1422
    $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1423
            get_string('removeallgroupoverrides', 'quiz'));
1424
}
1425
 
1426
/**
1427
 * Course reset form defaults.
1428
 * @return array the defaults.
1429
 */
1430
function quiz_reset_course_form_defaults($course) {
1431
    return ['reset_quiz_attempts' => 1,
1432
                 'reset_quiz_group_overrides' => 1,
1433
                 'reset_quiz_user_overrides' => 1];
1434
}
1435
 
1436
/**
1437
 * Removes all grades from gradebook
1438
 *
1439
 * @param int $courseid
1440
 * @param string optional type
1441
 */
1442
function quiz_reset_gradebook($courseid, $type='') {
1443
    global $CFG, $DB;
1444
 
1445
    $quizzes = $DB->get_records_sql("
1446
            SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1447
            FROM {modules} m
1448
            JOIN {course_modules} cm ON m.id = cm.module
1449
            JOIN {quiz} q ON cm.instance = q.id
1450
            WHERE m.name = 'quiz' AND cm.course = ?", [$courseid]);
1451
 
1452
    foreach ($quizzes as $quiz) {
1453
        quiz_grade_item_update($quiz, 'reset');
1454
    }
1455
}
1456
 
1457
/**
1458
 * Actual implementation of the reset course functionality, delete all the
1459
 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1460
 * set and true.
1461
 *
1462
 * Also, move the quiz open and close dates, if the course start date is changing.
1463
 *
1464
 * @param stdClass $data the data submitted from the reset course.
1465
 * @return array status array
1466
 */
1467
function quiz_reset_userdata($data) {
1468
    global $CFG, $DB;
1469
    require_once($CFG->libdir . '/questionlib.php');
1470
 
1471
    $componentstr = get_string('modulenameplural', 'quiz');
1472
    $status = [];
1473
 
1474
    // Delete attempts.
1475
    if (!empty($data->reset_quiz_attempts)) {
1476
        question_engine::delete_questions_usage_by_activities(new qubaid_join(
1477
                '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1478
                'quiza.uniqueid', 'quiz.course = :quizcourseid',
1479
                ['quizcourseid' => $data->courseid]));
1480
 
1481
        $DB->delete_records_select('quiz_attempts',
1482
                'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1483
        $status[] = [
1484
            'component' => $componentstr,
1485
            'item' => get_string('attemptsdeleted', 'quiz'),
1486
            'error' => false];
1487
 
1488
        // Remove all grades from gradebook.
1489
        $DB->delete_records_select('quiz_grades',
1490
                'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1491
        if (empty($data->reset_gradebook_grades)) {
1492
            quiz_reset_gradebook($data->courseid);
1493
        }
1494
        $status[] = [
1495
            'component' => $componentstr,
1496
            'item' => get_string('gradesdeleted', 'quiz'),
1497
            'error' => false];
1498
    }
1499
 
1500
    $purgeoverrides = false;
1501
 
1502
    // Remove user overrides.
1503
    if (!empty($data->reset_quiz_user_overrides)) {
1504
        $DB->delete_records_select('quiz_overrides',
1505
                'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid]);
1506
        $status[] = [
1507
            'component' => $componentstr,
1508
            'item' => get_string('useroverridesdeleted', 'quiz'),
1509
            'error' => false];
1510
        $purgeoverrides = true;
1511
    }
1512
    // Remove group overrides.
1513
    if (!empty($data->reset_quiz_group_overrides)) {
1514
        $DB->delete_records_select('quiz_overrides',
1515
                'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid]);
1516
        $status[] = [
1517
            'component' => $componentstr,
1518
            'item' => get_string('groupoverridesdeleted', 'quiz'),
1519
            'error' => false];
1520
        $purgeoverrides = true;
1521
    }
1522
 
1523
    // Updating dates - shift may be negative too.
1524
    if ($data->timeshift) {
1525
        $DB->execute("UPDATE {quiz_overrides}
1526
                         SET timeopen = timeopen + ?
1527
                       WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1528
                         AND timeopen <> 0", [$data->timeshift, $data->courseid]);
1529
        $DB->execute("UPDATE {quiz_overrides}
1530
                         SET timeclose = timeclose + ?
1531
                       WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1532
                         AND timeclose <> 0", [$data->timeshift, $data->courseid]);
1533
 
1534
        $purgeoverrides = true;
1535
 
1536
        // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1537
        // See MDL-9367.
1538
        shift_course_mod_dates('quiz', ['timeopen', 'timeclose'],
1539
                $data->timeshift, $data->courseid);
1540
 
1541
        $status[] = [
1542
            'component' => $componentstr,
1543
            'item' => get_string('openclosedatesupdated', 'quiz'),
1544
            'error' => false];
1545
    }
1546
 
1547
    if ($purgeoverrides) {
1548
        \cache_helper::purge_by_event(\mod_quiz\local\override_cache::INVALIDATION_USERDATARESET);
1549
    }
1550
 
1551
    return $status;
1552
}
1553
 
1554
/**
1555
 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1556
 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1557
 *
1558
 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1559
 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1560
 *      $cm->groupingid fields are used at the moment.
1561
 * @param bool $returnzero if false (default), when no attempts have been
1562
 *      made '' is returned instead of 'Attempts: 0'.
1563
 * @param int $currentgroup if there is a concept of current group where this method is being called
1564
 *         (e.g. a report) pass it in here. Default 0 which means no current group.
1565
 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1566
 *          "Attemtps 123 (45 from this group)".
1567
 */
1568
function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1569
    global $DB, $USER;
1570
    $numattempts = $DB->count_records('quiz_attempts', ['quiz' => $quiz->id, 'preview' => 0]);
1571
    if ($numattempts || $returnzero) {
1572
        if (groups_get_activity_groupmode($cm)) {
1573
            $a = new stdClass();
1574
            $a->total = $numattempts;
1575
            if ($currentgroup) {
1576
                $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1577
                        '{quiz_attempts} qa JOIN ' .
1578
                        '{groups_members} gm ON qa.userid = gm.userid ' .
1579
                        'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1580
                        [$quiz->id, $currentgroup]);
1581
                return get_string('attemptsnumthisgroup', 'quiz', $a);
1582
            } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1583
                list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1584
                $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1585
                        '{quiz_attempts} qa JOIN ' .
1586
                        '{groups_members} gm ON qa.userid = gm.userid ' .
1587
                        'WHERE quiz = ? AND preview = 0 AND ' .
1588
                        "groupid $usql", array_merge([$quiz->id], $params));
1589
                return get_string('attemptsnumyourgroups', 'quiz', $a);
1590
            }
1591
        }
1592
        return get_string('attemptsnum', 'quiz', $numattempts);
1593
    }
1594
    return '';
1595
}
1596
 
1597
/**
1598
 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1599
 * to the quiz reports.
1600
 *
1601
 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1602
 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1603
 *      $cm->groupingid fields are used at the moment.
1604
 * @param stdClass $context the quiz context.
1605
 * @param bool $returnzero if false (default), when no attempts have been made
1606
 *      '' is returned instead of 'Attempts: 0'.
1607
 * @param int $currentgroup if there is a concept of current group where this method is being called
1608
 *         (e.g. a report) pass it in here. Default 0 which means no current group.
1609
 * @return string HTML fragment for the link.
1610
 */
1611
function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1612
        $currentgroup = 0) {
1613
    global $PAGE;
1614
 
1615
    return $PAGE->get_renderer('mod_quiz')->quiz_attempt_summary_link_to_reports(
1616
            $quiz, $cm, $context, $returnzero, $currentgroup);
1617
}
1618
 
1619
/**
1620
 * @param string $feature FEATURE_xx constant for requested feature
1621
 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1622
 */
1623
function quiz_supports($feature) {
1624
    switch($feature) {
1625
        case FEATURE_GROUPS:                    return true;
1626
        case FEATURE_GROUPINGS:                 return true;
1627
        case FEATURE_MOD_INTRO:                 return true;
1628
        case FEATURE_COMPLETION_TRACKS_VIEWS:   return true;
1629
        case FEATURE_COMPLETION_HAS_RULES:      return true;
1630
        case FEATURE_GRADE_HAS_GRADE:           return true;
1631
        case FEATURE_GRADE_OUTCOMES:            return true;
1632
        case FEATURE_BACKUP_MOODLE2:            return true;
1633
        case FEATURE_SHOW_DESCRIPTION:          return true;
1634
        case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1635
        case FEATURE_USES_QUESTIONS:            return true;
1636
        case FEATURE_PLAGIARISM:                return true;
1637
        case FEATURE_MOD_PURPOSE:               return MOD_PURPOSE_ASSESSMENT;
1638
 
1639
        default: return null;
1640
    }
1641
}
1642
 
1643
/**
1644
 * @return array all other caps used in module
1645
 */
1646
function quiz_get_extra_capabilities() {
1647
    global $CFG;
1648
    require_once($CFG->libdir . '/questionlib.php');
1649
    return question_get_all_capabilities();
1650
}
1651
 
1652
/**
1653
 * This function extends the settings navigation block for the site.
1654
 *
1655
 * It is safe to rely on PAGE here as we will only ever be within the module
1656
 * context when this is called
1657
 *
1658
 * @param settings_navigation $settings
1659
 * @param navigation_node $quiznode
1660
 * @return void
1661
 */
1662
function quiz_extend_settings_navigation(settings_navigation $settings, navigation_node $quiznode) {
1663
    global $CFG;
1664
 
1665
    // Require {@link questionlib.php}
1666
    // Included here as we only ever want to include this file if we really need to.
1667
    require_once($CFG->libdir . '/questionlib.php');
1668
 
1669
    // We want to add these new nodes after the Edit settings node, and before the
1670
    // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1671
    $keys = $quiznode->get_children_key_list();
1672
    $beforekey = null;
1673
    $i = array_search('modedit', $keys);
1674
    if ($i === false and array_key_exists(0, $keys)) {
1675
        $beforekey = $keys[0];
1676
    } else if (array_key_exists($i + 1, $keys)) {
1677
        $beforekey = $keys[$i + 1];
1678
    }
1679
 
1680
    if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $settings->get_page()->cm->context)) {
1681
        $url = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']);
1682
        $node = navigation_node::create(get_string('overrides', 'quiz'),
1683
                    $url, navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1684
        $settingsoverride = $quiznode->add_node($node, $beforekey);
1685
    }
1686
 
1687
    if (has_capability('mod/quiz:manage', $settings->get_page()->cm->context)) {
1688
        $node = navigation_node::create(get_string('questions', 'quiz'),
1689
            new moodle_url('/mod/quiz/edit.php', ['cmid' => $settings->get_page()->cm->id]),
1690
            navigation_node::TYPE_SETTING, null, 'mod_quiz_edit', new pix_icon('t/edit', ''));
1691
        $quiznode->add_node($node, $beforekey);
1692
    }
1693
 
1694
    if (has_capability('mod/quiz:preview', $settings->get_page()->cm->context)) {
1695
        $url = new moodle_url('/mod/quiz/startattempt.php',
1696
                ['cmid' => $settings->get_page()->cm->id, 'sesskey' => sesskey()]);
1697
        $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1698
                navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1699
                new pix_icon('i/preview', ''));
1700
        $previewnode = $quiznode->add_node($node, $beforekey);
1701
        $previewnode->set_show_in_secondary_navigation(false);
1702
    }
1703
 
1704
    question_extend_settings_navigation($quiznode, $settings->get_page()->cm->context)->trim_if_empty();
1705
 
1706
    if (has_any_capability(['mod/quiz:viewreports', 'mod/quiz:grade'], $settings->get_page()->cm->context)) {
1707
        require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1708
        $reportlist = quiz_report_list($settings->get_page()->cm->context);
1709
 
1710
        $url = new moodle_url('/mod/quiz/report.php',
1711
                ['id' => $settings->get_page()->cm->id, 'mode' => reset($reportlist)]);
1712
        $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1713
                navigation_node::TYPE_SETTING,
1714
                null, 'quiz_report', new pix_icon('i/report', '')));
1715
 
1716
        foreach ($reportlist as $report) {
1717
            $url = new moodle_url('/mod/quiz/report.php', ['id' => $settings->get_page()->cm->id, 'mode' => $report]);
1718
            $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1719
                    navigation_node::TYPE_SETTING,
1720
                    null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1721
        }
1722
    }
1723
}
1724
 
1725
/**
1726
 * Serves the quiz files.
1727
 *
1728
 * @package  mod_quiz
1729
 * @category files
1730
 * @param stdClass $course course object
1731
 * @param stdClass $cm course module object
1732
 * @param stdClass $context context object
1733
 * @param string $filearea file area
1734
 * @param array $args extra arguments
1735
 * @param bool $forcedownload whether or not force download
1736
 * @param array $options additional options affecting the file serving
1737
 * @return bool false if file not found, does not return if found - justsend the file
1738
 */
1739
function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= []) {
1740
    global $CFG, $DB;
1741
 
1742
    if ($context->contextlevel != CONTEXT_MODULE) {
1743
        return false;
1744
    }
1745
 
1746
    require_login($course, false, $cm);
1747
 
1748
    if (!$quiz = $DB->get_record('quiz', ['id' => $cm->instance])) {
1749
        return false;
1750
    }
1751
 
1752
    // The 'intro' area is served by pluginfile.php.
1753
    $fileareas = ['feedback'];
1754
    if (!in_array($filearea, $fileareas)) {
1755
        return false;
1756
    }
1757
 
1758
    $feedbackid = (int)array_shift($args);
1759
    if (!$feedback = $DB->get_record('quiz_feedback', ['id' => $feedbackid])) {
1760
        return false;
1761
    }
1762
 
1763
    $fs = get_file_storage();
1764
    $relativepath = implode('/', $args);
1765
    $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1766
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1767
        return false;
1768
    }
1769
    send_stored_file($file, 0, 0, true, $options);
1770
}
1771
 
1772
/**
1773
 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1774
 * a question in a question_attempt when that attempt is a quiz attempt.
1775
 *
1776
 * @package  mod_quiz
1777
 * @category files
1778
 * @param stdClass $course course settings object
1779
 * @param stdClass $context context object
1780
 * @param string $component the name of the component we are serving files for.
1781
 * @param string $filearea the name of the file area.
1782
 * @param int $qubaid the attempt usage id.
1783
 * @param int $slot the id of a question in this quiz attempt.
1784
 * @param array $args the remaining bits of the file path.
1785
 * @param bool $forcedownload whether the user must be forced to download the file.
1786
 * @param array $options additional options affecting the file serving
1787
 * @return bool false if file not found, does not return if found - justsend the file
1788
 */
1789
function quiz_question_pluginfile($course, $context, $component,
1790
        $filearea, $qubaid, $slot, $args, $forcedownload, array $options= []) {
1791
    global $CFG;
1792
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1793
 
1794
    $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1795
    require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1796
 
1797
    if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1798
        // In the middle of an attempt.
1799
        if (!$attemptobj->is_preview_user()) {
1800
            $attemptobj->require_capability('mod/quiz:attempt');
1801
        }
1802
        $isreviewing = false;
1803
 
1804
    } else {
1805
        // Reviewing an attempt.
1806
        $attemptobj->check_review_capability();
1807
        $isreviewing = true;
1808
    }
1809
 
1810
    if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1811
            $component, $filearea, $args, $forcedownload)) {
1812
        send_file_not_found();
1813
    }
1814
 
1815
    $fs = get_file_storage();
1816
    $relativepath = implode('/', $args);
1817
    $fullpath = "/$context->id/$component/$filearea/$relativepath";
1818
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1819
        send_file_not_found();
1820
    }
1821
 
1822
    send_stored_file($file, 0, 0, $forcedownload, $options);
1823
}
1824
 
1825
/**
1826
 * Return a list of page types
1827
 * @param string $pagetype current page type
1828
 * @param stdClass $parentcontext Block's parent context
1829
 * @param stdClass $currentcontext Current context of block
1830
 */
1831
function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1832
    $modulepagetype = [
1833
        'mod-quiz-*'       => get_string('page-mod-quiz-x', 'quiz'),
1834
        'mod-quiz-view'    => get_string('page-mod-quiz-view', 'quiz'),
1835
        'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1836
        'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1837
        'mod-quiz-review'  => get_string('page-mod-quiz-review', 'quiz'),
1838
        'mod-quiz-edit'    => get_string('page-mod-quiz-edit', 'quiz'),
1839
        'mod-quiz-report'  => get_string('page-mod-quiz-report', 'quiz'),
1840
    ];
1841
    return $modulepagetype;
1842
}
1843
 
1844
/**
1845
 * @return the options for quiz navigation.
1846
 */
1847
function quiz_get_navigation_options() {
1848
    return [
1849
        QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1850
        QUIZ_NAVMETHOD_SEQ  => get_string('navmethod_seq', 'quiz')
1851
    ];
1852
}
1853
 
1854
/**
1855
 * Check if the module has any update that affects the current user since a given time.
1856
 *
1857
 * @param  cm_info $cm course module data
1858
 * @param  int $from the time to check updates from
1859
 * @param  array $filter  if we need to check only specific updates
1860
 * @return stdClass an object with the different type of areas indicating if they were updated or not
1861
 * @since Moodle 3.2
1862
 */
1863
function quiz_check_updates_since(cm_info $cm, $from, $filter = []) {
1864
    global $DB, $USER, $CFG;
1865
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1866
 
1867
    $updates = course_check_module_updates_since($cm, $from, [], $filter);
1868
 
1869
    // Check if questions were updated.
1870
    $updates->questions = (object) ['updated' => false];
1871
    $quizobj = quiz_settings::create($cm->instance, $USER->id);
1872
    $quizobj->preload_questions();
1873
    $questionids = array_keys($quizobj->get_questions(null, false));
1874
    if (!empty($questionids)) {
1875
        list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
1876
        $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
1877
        $params['time1'] = $from;
1878
        $params['time2'] = $from;
1879
        $questions = $DB->get_records_select('question', $select, $params, '', 'id');
1880
        if (!empty($questions)) {
1881
            $updates->questions->updated = true;
1882
            $updates->questions->itemids = array_keys($questions);
1883
        }
1884
    }
1885
 
1886
    // Check for new attempts or grades.
1887
    $updates->attempts = (object) ['updated' => false];
1888
    $updates->grades = (object) ['updated' => false];
1889
    $select = 'quiz = ? AND userid = ? AND timemodified > ?';
1890
    $params = [$cm->instance, $USER->id, $from];
1891
 
1892
    $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1893
    if (!empty($attempts)) {
1894
        $updates->attempts->updated = true;
1895
        $updates->attempts->itemids = array_keys($attempts);
1896
    }
1897
    $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
1898
    if (!empty($grades)) {
1899
        $updates->grades->updated = true;
1900
        $updates->grades->itemids = array_keys($grades);
1901
    }
1902
 
1903
    // Now, teachers should see other students updates.
1904
    if (has_capability('mod/quiz:viewreports', $cm->context)) {
1905
        $select = 'quiz = ? AND timemodified > ?';
1906
        $params = [$cm->instance, $from];
1907
 
1908
        if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1909
            $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1910
            if (empty($groupusers)) {
1911
                return $updates;
1912
            }
1913
            list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1914
            $select .= ' AND userid ' . $insql;
1915
            $params = array_merge($params, $inparams);
1916
        }
1917
 
1918
        $updates->userattempts = (object) ['updated' => false];
1919
        $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1920
        if (!empty($attempts)) {
1921
            $updates->userattempts->updated = true;
1922
            $updates->userattempts->itemids = array_keys($attempts);
1923
        }
1924
 
1925
        $updates->usergrades = (object) ['updated' => false];
1926
        $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
1927
        if (!empty($grades)) {
1928
            $updates->usergrades->updated = true;
1929
            $updates->usergrades->itemids = array_keys($grades);
1930
        }
1931
    }
1932
    return $updates;
1933
}
1934
 
1935
/**
1936
 * Get icon mapping for font-awesome.
1937
 */
1938
function mod_quiz_get_fontawesome_icon_map() {
1939
    return [
1940
        'mod_quiz:navflagged' => 'fa-flag',
1941
    ];
1942
}
1943
 
1944
/**
1945
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1946
 *
1947
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1948
 * is not displayed on the block.
1949
 *
1950
 * @param calendar_event $event
1951
 * @param \core_calendar\action_factory $factory
1952
 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1953
 * @return \core_calendar\local\event\entities\action_interface|null
1954
 */
1955
function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
1956
                                                     \core_calendar\action_factory $factory,
1957
                                                     int $userid = 0) {
1958
    global $CFG, $USER;
1959
 
1960
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1961
 
1962
    if (empty($userid)) {
1963
        $userid = $USER->id;
1964
    }
1965
 
1966
    $cm = get_fast_modinfo($event->courseid, $userid)->instances['quiz'][$event->instance];
1967
    $quizobj = quiz_settings::create($cm->instance, $userid);
1968
    $quiz = $quizobj->get_quiz();
1969
 
1970
    // Check they have capabilities allowing them to view the quiz.
1971
    if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) {
1972
        return null;
1973
    }
1974
 
1975
    $completion = new \completion_info($cm->get_course());
1976
 
1977
    $completiondata = $completion->get_data($cm, false, $userid);
1978
 
1979
    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1980
        return null;
1981
    }
1982
 
1983
    quiz_update_effective_access($quiz, $userid);
1984
 
1985
    // Check if quiz is closed, if so don't display it.
1986
    if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
1987
        return null;
1988
    }
1989
 
1990
    if (!$quizobj->is_participant($userid)) {
1991
        // If the user is not a participant then they have
1992
        // no action to take. This will filter out the events for teachers.
1993
        return null;
1994
    }
1995
 
1996
    $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid);
1997
    if (!empty($attempts)) {
1998
        // The student's last attempt is finished.
1999
        return null;
2000
    }
2001
 
2002
    $name = get_string('attemptquiznow', 'quiz');
2003
    $url = new \moodle_url('/mod/quiz/view.php', [
2004
        'id' => $cm->id
2005
    ]);
2006
    $itemcount = 1;
2007
    $actionable = true;
2008
 
2009
    // Check if the quiz is not currently actionable.
2010
    if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2011
        $actionable = false;
2012
    }
2013
 
2014
    return $factory->create_instance(
2015
        $name,
2016
        $url,
2017
        $itemcount,
2018
        $actionable
2019
    );
2020
}
2021
 
2022
/**
2023
 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2024
 * for the course (see resource).
2025
 *
2026
 * Given a course_module object, this function returns any "extra" information that may be needed
2027
 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
2028
 *
2029
 * @param stdClass $coursemodule The coursemodule object (record).
2030
 * @return cached_cm_info|false An object on information that the courses
2031
 *                        will know about (most noticeably, an icon).
2032
 */
2033
function quiz_get_coursemodule_info($coursemodule) {
2034
    global $DB;
2035
 
2036
    $dbparams = ['id' => $coursemodule->instance];
2037
    $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionminattempts,
2038
        timeopen, timeclose';
2039
    if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2040
        return false;
2041
    }
2042
 
2043
    $result = new cached_cm_info();
2044
    $result->name = $quiz->name;
2045
 
2046
    if ($coursemodule->showdescription) {
2047
        // Convert intro to html. Do not filter cached version, filters run at display time.
2048
        $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2049
    }
2050
 
2051
    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2052
    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2053
        if ($quiz->completionattemptsexhausted) {
2054
            $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [
2055
                'completionpassgrade' => $coursemodule->completionpassgrade,
2056
                'completionattemptsexhausted' => $quiz->completionattemptsexhausted,
2057
            ];
2058
        } else {
2059
            $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [];
2060
        }
2061
 
2062
        $result->customdata['customcompletionrules']['completionminattempts'] = $quiz->completionminattempts;
2063
    }
2064
 
2065
    // Populate some other values that can be used in calendar or on dashboard.
2066
    if ($quiz->timeopen) {
2067
        $result->customdata['timeopen'] = $quiz->timeopen;
2068
    }
2069
    if ($quiz->timeclose) {
2070
        $result->customdata['timeclose'] = $quiz->timeclose;
2071
    }
2072
 
2073
    return $result;
2074
}
2075
 
2076
/**
2077
 * Sets dynamic information about a course module
2078
 *
2079
 * This function is called from cm_info when displaying the module
2080
 *
2081
 * @param cm_info $cm
2082
 */
2083
function mod_quiz_cm_info_dynamic(cm_info $cm) {
2084
    global $USER;
2085
 
2086
    $cache = new override_cache($cm->instance);
2087
    $override = $cache->get_cached_user_override($USER->id);
2088
 
2089
    if (!$override) {
2090
        $override = (object) [
2091
            'timeopen' => null,
2092
            'timeclose' => null,
2093
        ];
2094
    }
2095
 
2096
    // No need to look for group overrides if there are user overrides for both timeopen and timeclose.
2097
    if (is_null($override->timeopen) || is_null($override->timeclose)) {
2098
        $opens = [];
2099
        $closes = [];
2100
        $groupings = groups_get_user_groups($cm->course, $USER->id);
2101
        foreach ($groupings[0] as $groupid) {
2102
            $groupoverride = $cache->get_cached_group_override($groupid);
2103
            if (isset($groupoverride->timeopen)) {
2104
                $opens[] = $groupoverride->timeopen;
2105
            }
2106
            if (isset($groupoverride->timeclose)) {
2107
                $closes[] = $groupoverride->timeclose;
2108
            }
2109
        }
2110
        // If there is a user override for a setting, ignore the group override.
2111
        if (is_null($override->timeopen) && count($opens)) {
2112
            $override->timeopen = min($opens);
2113
        }
2114
        if (is_null($override->timeclose) && count($closes)) {
2115
            if (in_array(0, $closes)) {
2116
                $override->timeclose = 0;
2117
            } else {
2118
                $override->timeclose = max($closes);
2119
            }
2120
        }
2121
    }
2122
 
2123
    // Populate some other values that can be used in calendar or on dashboard.
2124
    if (!is_null($override->timeopen)) {
2125
        $cm->override_customdata('timeopen', $override->timeopen);
2126
    }
2127
    if (!is_null($override->timeclose)) {
2128
        $cm->override_customdata('timeclose', $override->timeclose);
2129
    }
2130
}
2131
 
2132
/**
2133
 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2134
 *
2135
 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2136
 * @return array $descriptions the array of descriptions for the custom rules.
2137
 */
2138
function mod_quiz_get_completion_active_rule_descriptions($cm) {
2139
    // Values will be present in cm_info, and we assume these are up to date.
2140
    if (empty($cm->customdata['customcompletionrules'])
2141
        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2142
        return [];
2143
    }
2144
 
2145
    $descriptions = [];
2146
    $rules = $cm->customdata['customcompletionrules'];
2147
 
2148
    if (!empty($rules['completionpassorattemptsexhausted'])) {
2149
        if (!empty($rules['completionpassorattemptsexhausted']['completionattemptsexhausted'])) {
2150
            $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2151
        }
2152
    } else {
2153
        // Fallback.
2154
        if (!empty($rules['completionattemptsexhausted'])) {
2155
            $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2156
        }
2157
    }
2158
 
2159
    if (!empty($rules['completionminattempts'])) {
2160
        $descriptions[] = get_string('completionminattemptsdesc', 'quiz', $rules['completionminattempts']);
2161
    }
2162
 
2163
    return $descriptions;
2164
}
2165
 
2166
/**
2167
 * Returns the min and max values for the timestart property of a quiz
2168
 * activity event.
2169
 *
2170
 * The min and max values will be the timeopen and timeclose properties
2171
 * of the quiz, respectively, if they are set.
2172
 *
2173
 * If either value isn't set then null will be returned instead to
2174
 * indicate that there is no cutoff for that value.
2175
 *
2176
 * If the vent has no valid timestart range then [false, false] will
2177
 * be returned. This is the case for overriden events.
2178
 *
2179
 * A minimum and maximum cutoff return value will look like:
2180
 * [
2181
 *     [1505704373, 'The date must be after this date'],
2182
 *     [1506741172, 'The date must be before this date']
2183
 * ]
2184
 *
2185
 * @throws \moodle_exception
2186
 * @param \calendar_event $event The calendar event to get the time range for
2187
 * @param stdClass $quiz The module instance to get the range from
2188
 * @return array
2189
 */
2190
function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) {
2191
    global $CFG, $DB;
2192
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2193
 
2194
    // Overrides do not have a valid timestart range.
2195
    if (quiz_is_overriden_calendar_event($event)) {
2196
        return [false, false];
2197
    }
2198
 
2199
    $mindate = null;
2200
    $maxdate = null;
2201
 
2202
    if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2203
        if (!empty($quiz->timeclose)) {
2204
            $maxdate = [
2205
                $quiz->timeclose,
2206
                get_string('openafterclose', 'quiz')
2207
            ];
2208
        }
2209
    } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2210
        if (!empty($quiz->timeopen)) {
2211
            $mindate = [
2212
                $quiz->timeopen,
2213
                get_string('closebeforeopen', 'quiz')
2214
            ];
2215
        }
2216
    }
2217
 
2218
    return [$mindate, $maxdate];
2219
}
2220
 
2221
/**
2222
 * This function will update the quiz module according to the
2223
 * event that has been modified.
2224
 *
2225
 * It will set the timeopen or timeclose value of the quiz instance
2226
 * according to the type of event provided.
2227
 *
2228
 * @throws \moodle_exception
2229
 * @param \calendar_event $event A quiz activity calendar event
2230
 * @param \stdClass $quiz A quiz activity instance
2231
 */
2232
function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) {
2233
    global $CFG, $DB;
2234
    require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2235
 
2236
    if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) {
2237
        // This isn't an event that we care about so we can ignore it.
2238
        return;
2239
    }
2240
 
2241
    $courseid = $event->courseid;
2242
    $modulename = $event->modulename;
2243
    $instanceid = $event->instance;
2244
    $modified = false;
2245
    $closedatechanged = false;
2246
 
2247
    // Something weird going on. The event is for a different module so
2248
    // we should ignore it.
2249
    if ($modulename != 'quiz') {
2250
        return;
2251
    }
2252
 
2253
    if ($quiz->id != $instanceid) {
2254
        // The provided quiz instance doesn't match the event so
2255
        // there is nothing to do here.
2256
        return;
2257
    }
2258
 
2259
    // We don't update the activity if it's an override event that has
2260
    // been modified.
2261
    if (quiz_is_overriden_calendar_event($event)) {
2262
        return;
2263
    }
2264
 
2265
    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2266
    $context = context_module::instance($coursemodule->id);
2267
 
2268
    // The user does not have the capability to modify this activity.
2269
    if (!has_capability('moodle/course:manageactivities', $context)) {
2270
        return;
2271
    }
2272
 
2273
    if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2274
        // If the event is for the quiz activity opening then we should
2275
        // set the start time of the quiz activity to be the new start
2276
        // time of the event.
2277
        if ($quiz->timeopen != $event->timestart) {
2278
            $quiz->timeopen = $event->timestart;
2279
            $modified = true;
2280
        }
2281
    } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2282
        // If the event is for the quiz activity closing then we should
2283
        // set the end time of the quiz activity to be the new start
2284
        // time of the event.
2285
        if ($quiz->timeclose != $event->timestart) {
2286
            $quiz->timeclose = $event->timestart;
2287
            $modified = true;
2288
            $closedatechanged = true;
2289
        }
2290
    }
2291
 
2292
    if ($modified) {
2293
        $quiz->timemodified = time();
2294
        $DB->update_record('quiz', $quiz);
2295
 
2296
        if ($closedatechanged) {
2297
            quiz_update_open_attempts(['quizid' => $quiz->id]);
2298
        }
2299
 
2300
        // Delete any previous preview attempts.
2301
        quiz_delete_previews($quiz);
2302
        quiz_update_events($quiz);
2303
        $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2304
        $event->trigger();
2305
    }
2306
}
2307
 
2308
/**
2309
 * Generates the question bank in a fragment output. This allows
2310
 * the question bank to be displayed in a modal.
2311
 *
2312
 * The only expected argument provided in the $args array is
2313
 * 'querystring'. The value should be the list of parameters
2314
 * URL encoded and used to build the question bank page.
2315
 *
2316
 * The individual list of parameters expected can be found in
2317
 * question_build_edit_resources.
2318
 *
2319
 * @param array $args The fragment arguments.
2320
 * @return string The rendered mform fragment.
2321
 */
2322
function mod_quiz_output_fragment_quiz_question_bank($args): string {
2323
    global $PAGE;
2324
 
2325
    // Retrieve params.
2326
    $params = [];
2327
    $extraparams = [];
2328
    $querystring = parse_url($args['querystring'], PHP_URL_QUERY);
2329
    parse_str($querystring, $params);
2330
 
2331
    $viewclass = \mod_quiz\question\bank\custom_view::class;
2332
    $extraparams['view'] = $viewclass;
2333
 
2334
    // Build required parameters.
2335
    [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2336
            build_required_parameters_for_custom_view($params, $extraparams);
2337
 
2338
    $course = get_course($cm->course);
2339
    require_capability('mod/quiz:manage', $contexts->lowest());
2340
 
2341
    // Custom View.
2342
    $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2343
 
2344
    // Output.
2345
    $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2346
    return $renderer->question_bank_contents($questionbank, $pagevars);
2347
}
2348
 
2349
/**
2350
 * Generates the add random question in a fragment output. This allows the
2351
 * form to be rendered in javascript, for example inside a modal.
2352
 *
2353
 * The required arguments as keys in the $args array are:
2354
 *      cat {string} The category and category context ids comma separated.
2355
 *      addonpage {int} The page id to add this question to.
2356
 *      returnurl {string} URL to return to after form submission.
2357
 *      cmid {int} The course module id the questions are being added to.
2358
 *
2359
 * @param array $args The fragment arguments.
2360
 * @return string The rendered mform fragment.
2361
 */
2362
function mod_quiz_output_fragment_add_random_question_form($args) {
2363
    global $PAGE, $OUTPUT;
2364
 
2365
    $extraparams = [];
2366
 
2367
    // Build required parameters.
2368
    [$contexts, $thispageurl, $cm, $pagevars, $extraparams] =
2369
            build_required_parameters_for_custom_view($args, $extraparams);
2370
 
2371
    // Additional param to differentiate with other question bank view.
2372
    $extraparams['view'] = mod_quiz\question\bank\random_question_view::class;
2373
 
2374
    $course = get_course($cm->course);
2375
    require_capability('mod/quiz:manage', $contexts->lowest());
2376
 
2377
    // Custom View.
2378
    $questionbank = new mod_quiz\question\bank\random_question_view($contexts, $thispageurl, $course, $cm, $pagevars, $extraparams);
2379
 
2380
    $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2381
    $questionbankoutput = $renderer->question_bank_contents($questionbank, $pagevars);
2382
 
2383
    $maxrand = 100;
2384
    for ($i = 1; $i <= min(100, $maxrand); $i++) {
2385
        $randomcount[] = ['value' => $i, 'name' => $i];
2386
    }
2387
 
2388
    // Parent category select.
2389
    $usablecontexts = $contexts->having_cap('moodle/question:useall');
2390
    $categoriesarray = helper::question_category_options($usablecontexts);
2391
    $catoptions = [];
2392
    foreach ($categoriesarray as $group => $opts) {
2393
        // Options for each category group.
2394
        $categories = [];
2395
        foreach ($opts as $context => $name) {
2396
            $categories[] = ['value' => $context, 'name' => $name];
2397
        }
2398
        $catoptions[] = ['label' => $group, 'options' => $categories];
2399
    }
2400
 
2401
    // Template data.
2402
    $data = [
2403
        'questionbank' => $questionbankoutput,
2404
        'randomoptions' => $randomcount,
2405
        'questioncategoryoptions' => $catoptions,
2406
    ];
2407
 
2408
    $helpicon = new \help_icon('parentcategory', 'question');
2409
    $data['questioncategoryhelp'] = $helpicon->export_for_template($renderer);
2410
 
2411
    $result = $OUTPUT->render_from_template('mod_quiz/add_random_question_form', $data);
2412
 
2413
    return $result;
2414
}
2415
 
2416
/**
2417
 * Callback to fetch the activity event type lang string.
2418
 *
2419
 * @param string $eventtype The event type.
2420
 * @return lang_string The event type lang string.
2421
 */
2422
function mod_quiz_core_calendar_get_event_action_string(string $eventtype): string {
2423
    $modulename = get_string('modulename', 'quiz');
2424
 
2425
    switch ($eventtype) {
2426
        case QUIZ_EVENT_TYPE_OPEN:
2427
            $identifier = 'quizeventopens';
2428
            break;
2429
        case QUIZ_EVENT_TYPE_CLOSE:
2430
            $identifier = 'quizeventcloses';
2431
            break;
2432
        default:
2433
            return get_string('requiresaction', 'calendar', $modulename);
2434
    }
2435
 
2436
    return get_string($identifier, 'quiz', $modulename);
2437
}
2438
 
2439
/**
2440
 * Delete all question references for a quiz.
2441
 *
2442
 * @param int $quizid The id of quiz.
2443
 */
2444
function quiz_delete_references($quizid): void {
2445
    global $DB;
2446
 
2447
    $cm = get_coursemodule_from_instance('quiz', $quizid);
2448
    $context = context_module::instance($cm->id);
2449
 
2450
    $conditions = [
2451
        'usingcontextid' => $context->id,
2452
        'component' => 'mod_quiz',
2453
        'questionarea' => 'slot',
2454
    ];
2455
 
2456
    $DB->delete_records('question_references', $conditions);
2457
    $DB->delete_records('question_set_references', $conditions);
2458
}
2459
 
2460
/**
2461
 * Question data fragment to get the question html via ajax call.
2462
 *
2463
 * @param array $args
2464
 * @return string
2465
 */
2466
function mod_quiz_output_fragment_question_data(array $args): string {
2467
    // Return if there is no args.
2468
    if (empty($args)) {
2469
        return '';
2470
    }
2471
 
2472
    // Retrieve params from query string.
2473
    [$params, $extraparams] = \core_question\local\bank\filter_condition_manager::extract_parameters_from_fragment_args($args);
2474
 
2475
    // Build required parameters.
2476
    $cmid = clean_param($args['cmid'], PARAM_INT);
2477
    $thispageurl = new \moodle_url('/mod/quiz/edit.php', ['cmid' => $cmid]);
2478
    $thiscontext = \context_module::instance($cmid);
2479
    $contexts = new \core_question\local\bank\question_edit_contexts($thiscontext);
2480
    $defaultcategory = question_make_default_categories($contexts->all());
2481
    $params['cat'] = implode(',', [$defaultcategory->id, $defaultcategory->contextid]);
2482
 
2483
    $course = get_course($params['courseid']);
2484
    [, $cm] = get_module_from_cmid($cmid);
2485
    $params['tabname'] = 'questions';
2486
 
2487
    // Custom question bank View.
2488
    $viewclass = clean_param($args['view'], PARAM_NOTAGS);
2489
    $questionbank = new $viewclass($contexts, $thispageurl, $course, $cm, $params, $extraparams);
2490
 
2491
    // Question table.
2492
    $questionbank->add_standard_search_conditions();
2493
    ob_start();
2494
    $questionbank->display_question_list();
2495
    return ob_get_clean();
2496
}
2497
 
2498
/**
2499
 * Build required parameters for question bank custom view
2500
 *
2501
 * @param array $params the page parameters
2502
 * @param array $extraparams additional parameters
2503
 * @return array
2504
 */
2505
function build_required_parameters_for_custom_view(array $params, array $extraparams): array {
2506
    // Retrieve questions per page.
2507
    $viewclass = $extraparams['view'] ?? null;
2508
    $defaultpagesize = $viewclass ? $viewclass::DEFAULT_PAGE_SIZE : DEFAULT_QUESTIONS_PER_PAGE;
2509
    // Build the required params.
2510
    [$thispageurl, $contexts, $cmid, $cm, , $pagevars] = question_build_edit_resources(
2511
            'editq',
2512
            '/mod/quiz/edit.php',
2513
            array_merge($params, $extraparams),
2514
            $defaultpagesize);
2515
 
2516
    // Add cmid so we can retrieve later in extra params.
2517
    $extraparams['cmid'] = $cmid;
2518
 
2519
    return [$contexts, $thispageurl, $cm, $pagevars, $extraparams];
2520
}
2521
 
2522
/**
2523
 * Implement the calculate_question_stats callback.
2524
 *
2525
 * This enables quiz statistics to be shown in statistics columns in the database.
2526
 *
2527
 * @param context $context return the statistics related to this context (which will be a quiz context).
2528
 * @return all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null.
2529
 */
2530
function mod_quiz_calculate_question_stats(context $context): ?all_calculated_for_qubaid_condition {
2531
    global $CFG;
2532
    require_once($CFG->dirroot . '/mod/quiz/report/statistics/report.php');
2533
    $cm = get_coursemodule_from_id('quiz', $context->instanceid);
2534
    $report = new quiz_statistics_report();
2535
    return $report->calculate_questions_stats_for_question_bank($cm->instance, false, false);
2536
}
2537
 
2538
/**
2539
 * Return a list of all the user preferences used by mod_quiz.
2540
 *
2541
 * @uses core_user::is_current_user
2542
 *
2543
 * @return array[]
2544
 */
2545
function mod_quiz_user_preferences(): array {
2546
    $preferences = [];
2547
    $preferences['quiz_timerhidden'] = [
2548
        'type' => PARAM_INT,
2549
        'null' => NULL_NOT_ALLOWED,
2550
        'default' => '0',
2551
        'permissioncallback' => [core_user::class, 'is_current_user'],
2552
    ];
2553
    return $preferences;
2554
}