MDL-77564 Quiz display options: Hide or show the grade information
[moodle.git] / mod / quiz / lib.php
blobf64b5f147d556b9e04fb06e9c15f03ed05ddec5c
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.
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/>.
17 /**
18 * Library of functions for the quiz module.
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}
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
29 defined('MOODLE_INTERNAL') || die();
31 use mod_quiz\access_manager;
32 use mod_quiz\form\add_random_form;
33 use mod_quiz\grade_calculator;
34 use mod_quiz\question\bank\custom_view;
35 use mod_quiz\question\bank\qbank_helper;
36 use mod_quiz\question\display_options;
37 use mod_quiz\question\qubaids_for_quiz;
38 use mod_quiz\question\qubaids_for_users_attempts;
39 use core_question\statistics\questions\all_calculated_for_qubaid_condition;
40 use mod_quiz\quiz_attempt;
41 use mod_quiz\quiz_settings;
43 require_once($CFG->dirroot . '/calendar/lib.php');
45 /**#@+
46 * Option controlling what options are offered on the quiz settings form.
48 define('QUIZ_MAX_ATTEMPT_OPTION', 10);
49 define('QUIZ_MAX_QPP_OPTION', 50);
50 define('QUIZ_MAX_DECIMAL_OPTION', 5);
51 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
52 /**#@-*/
54 /**#@+
55 * Options determining how the grades from individual attempts are combined to give
56 * the overall grade for a user
58 define('QUIZ_GRADEHIGHEST', '1');
59 define('QUIZ_GRADEAVERAGE', '2');
60 define('QUIZ_ATTEMPTFIRST', '3');
61 define('QUIZ_ATTEMPTLAST', '4');
62 /**#@-*/
64 /**
65 * @var int If start and end date for the quiz are more than this many seconds apart
66 * they will be represented by two separate events in the calendar
68 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
70 /**#@+
71 * Options for navigation method within quizzes.
73 define('QUIZ_NAVMETHOD_FREE', 'free');
74 define('QUIZ_NAVMETHOD_SEQ', 'sequential');
75 /**#@-*/
77 /**
78 * Event types.
80 define('QUIZ_EVENT_TYPE_OPEN', 'open');
81 define('QUIZ_EVENT_TYPE_CLOSE', 'close');
83 require_once(__DIR__ . '/deprecatedlib.php');
85 /**
86 * Given an object containing all the necessary data,
87 * (defined by the form in mod_form.php) this function
88 * will create a new instance and return the id number
89 * of the new instance.
91 * @param stdClass $quiz the data that came from the form.
92 * @return mixed the id of the new instance on success,
93 * false or a string error message on failure.
95 function quiz_add_instance($quiz) {
96 global $DB;
97 $cmid = $quiz->coursemodule;
99 // Process the options from the form.
100 $quiz->timecreated = time();
101 $result = quiz_process_options($quiz);
102 if ($result && is_string($result)) {
103 return $result;
106 // Try to store it in the database.
107 $quiz->id = $DB->insert_record('quiz', $quiz);
109 // Create the first section for this quiz.
110 $DB->insert_record('quiz_sections', ['quizid' => $quiz->id,
111 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0]);
113 // Do the processing required after an add or an update.
114 quiz_after_add_or_update($quiz);
116 return $quiz->id;
120 * Given an object containing all the necessary data,
121 * (defined by the form in mod_form.php) this function
122 * will update an existing instance with new data.
124 * @param stdClass $quiz the data that came from the form.
125 * @param stdClass $mform no longer used.
126 * @return mixed true on success, false or a string error message on failure.
128 function quiz_update_instance($quiz, $mform) {
129 global $CFG, $DB;
130 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
132 // Process the options from the form.
133 $result = quiz_process_options($quiz);
134 if ($result && is_string($result)) {
135 return $result;
138 // Get the current value, so we can see what changed.
139 $oldquiz = $DB->get_record('quiz', ['id' => $quiz->instance]);
141 // We need two values from the existing DB record that are not in the form,
142 // in some of the function calls below.
143 $quiz->sumgrades = $oldquiz->sumgrades;
144 $quiz->grade = $oldquiz->grade;
146 // Update the database.
147 $quiz->id = $quiz->instance;
148 $DB->update_record('quiz', $quiz);
150 // Do the processing required after an add or an update.
151 quiz_after_add_or_update($quiz);
153 if ($oldquiz->grademethod != $quiz->grademethod) {
154 $gradecalculator = quiz_settings::create($quiz->id)->get_grade_calculator();
155 $gradecalculator->recompute_all_final_grades();
156 quiz_update_grades($quiz);
159 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
160 || $oldquiz->timeclose != $quiz->timeclose
161 || $oldquiz->graceperiod != $quiz->graceperiod;
162 if ($quizdateschanged) {
163 quiz_update_open_attempts(['quizid' => $quiz->id]);
166 // Delete any previous preview attempts.
167 quiz_delete_previews($quiz);
169 // Repaginate, if asked to.
170 if (!empty($quiz->repaginatenow) && !quiz_has_attempts($quiz->id)) {
171 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
174 return true;
178 * Given an ID of an instance of this module,
179 * this function will permanently delete the instance
180 * and any data that depends on it.
182 * @param int $id the id of the quiz to delete.
183 * @return bool success or failure.
185 function quiz_delete_instance($id) {
186 global $DB;
188 $quiz = $DB->get_record('quiz', ['id' => $id], '*', MUST_EXIST);
190 quiz_delete_all_attempts($quiz);
191 quiz_delete_all_overrides($quiz);
192 quiz_delete_references($quiz->id);
194 // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'.
195 $DB->delete_records('quiz_slots', ['quizid' => $quiz->id]);
196 $DB->delete_records('quiz_sections', ['quizid' => $quiz->id]);
198 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
200 access_manager::delete_settings($quiz);
202 $events = $DB->get_records('event', ['modulename' => 'quiz', 'instance' => $quiz->id]);
203 foreach ($events as $event) {
204 $event = calendar_event::load($event);
205 $event->delete();
208 quiz_grade_item_delete($quiz);
209 // We must delete the module record after we delete the grade item.
210 $DB->delete_records('quiz', ['id' => $quiz->id]);
212 return true;
216 * Deletes a quiz override from the database and clears any corresponding calendar events
218 * @param stdClass $quiz The quiz object.
219 * @param int $overrideid The id of the override being deleted
220 * @param bool $log Whether to trigger logs.
221 * @return bool true on success
223 function quiz_delete_override($quiz, $overrideid, $log = true) {
224 global $DB;
226 if (!isset($quiz->cmid)) {
227 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
228 $quiz->cmid = $cm->id;
231 $override = $DB->get_record('quiz_overrides', ['id' => $overrideid], '*', MUST_EXIST);
233 // Delete the events.
234 if (isset($override->groupid)) {
235 // Create the search array for a group override.
236 $eventsearcharray = ['modulename' => 'quiz',
237 'instance' => $quiz->id, 'groupid' => (int)$override->groupid];
238 $cachekey = "{$quiz->id}_g_{$override->groupid}";
239 } else {
240 // Create the search array for a user override.
241 $eventsearcharray = ['modulename' => 'quiz',
242 'instance' => $quiz->id, 'userid' => (int)$override->userid];
243 $cachekey = "{$quiz->id}_u_{$override->userid}";
245 $events = $DB->get_records('event', $eventsearcharray);
246 foreach ($events as $event) {
247 $eventold = calendar_event::load($event);
248 $eventold->delete();
251 $DB->delete_records('quiz_overrides', ['id' => $overrideid]);
252 cache::make('mod_quiz', 'overrides')->delete($cachekey);
254 if ($log) {
255 // Set the common parameters for one of the events we will be triggering.
256 $params = [
257 'objectid' => $override->id,
258 'context' => context_module::instance($quiz->cmid),
259 'other' => [
260 'quizid' => $override->quiz
263 // Determine which override deleted event to fire.
264 if (!empty($override->userid)) {
265 $params['relateduserid'] = $override->userid;
266 $event = \mod_quiz\event\user_override_deleted::create($params);
267 } else {
268 $params['other']['groupid'] = $override->groupid;
269 $event = \mod_quiz\event\group_override_deleted::create($params);
272 // Trigger the override deleted event.
273 $event->add_record_snapshot('quiz_overrides', $override);
274 $event->trigger();
277 return true;
281 * Deletes all quiz overrides from the database and clears any corresponding calendar events
283 * @param stdClass $quiz The quiz object.
284 * @param bool $log Whether to trigger logs.
286 function quiz_delete_all_overrides($quiz, $log = true) {
287 global $DB;
289 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id');
290 foreach ($overrides as $override) {
291 quiz_delete_override($quiz, $override->id, $log);
296 * Updates a quiz object with override information for a user.
298 * Algorithm: For each quiz setting, if there is a matching user-specific override,
299 * then use that otherwise, if there are group-specific overrides, return the most
300 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
302 * Special case: if there is more than one password that applies to the user, then
303 * quiz->extrapasswords will contain an array of strings giving the remaining
304 * passwords.
306 * @param stdClass $quiz The quiz object.
307 * @param int $userid The userid.
308 * @return stdClass $quiz The updated quiz object.
310 function quiz_update_effective_access($quiz, $userid) {
311 global $DB;
313 // Check for user override.
314 $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id, 'userid' => $userid]);
316 if (!$override) {
317 $override = new stdClass();
318 $override->timeopen = null;
319 $override->timeclose = null;
320 $override->timelimit = null;
321 $override->attempts = null;
322 $override->password = null;
325 // Check for group overrides.
326 $groupings = groups_get_user_groups($quiz->course, $userid);
328 if (!empty($groupings[0])) {
329 // Select all overrides that apply to the User's groups.
330 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
331 $sql = "SELECT * FROM {quiz_overrides}
332 WHERE groupid $extra AND quiz = ?";
333 $params[] = $quiz->id;
334 $records = $DB->get_records_sql($sql, $params);
336 // Combine the overrides.
337 $opens = [];
338 $closes = [];
339 $limits = [];
340 $attempts = [];
341 $passwords = [];
343 foreach ($records as $gpoverride) {
344 if (isset($gpoverride->timeopen)) {
345 $opens[] = $gpoverride->timeopen;
347 if (isset($gpoverride->timeclose)) {
348 $closes[] = $gpoverride->timeclose;
350 if (isset($gpoverride->timelimit)) {
351 $limits[] = $gpoverride->timelimit;
353 if (isset($gpoverride->attempts)) {
354 $attempts[] = $gpoverride->attempts;
356 if (isset($gpoverride->password)) {
357 $passwords[] = $gpoverride->password;
360 // If there is a user override for a setting, ignore the group override.
361 if (is_null($override->timeopen) && count($opens)) {
362 $override->timeopen = min($opens);
364 if (is_null($override->timeclose) && count($closes)) {
365 if (in_array(0, $closes)) {
366 $override->timeclose = 0;
367 } else {
368 $override->timeclose = max($closes);
371 if (is_null($override->timelimit) && count($limits)) {
372 if (in_array(0, $limits)) {
373 $override->timelimit = 0;
374 } else {
375 $override->timelimit = max($limits);
378 if (is_null($override->attempts) && count($attempts)) {
379 if (in_array(0, $attempts)) {
380 $override->attempts = 0;
381 } else {
382 $override->attempts = max($attempts);
385 if (is_null($override->password) && count($passwords)) {
386 $override->password = array_shift($passwords);
387 if (count($passwords)) {
388 $override->extrapasswords = $passwords;
394 // Merge with quiz defaults.
395 $keys = ['timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords'];
396 foreach ($keys as $key) {
397 if (isset($override->{$key})) {
398 $quiz->{$key} = $override->{$key};
402 return $quiz;
406 * Delete all the attempts belonging to a quiz.
408 * @param stdClass $quiz The quiz object.
410 function quiz_delete_all_attempts($quiz) {
411 global $CFG, $DB;
412 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
413 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
414 $DB->delete_records('quiz_attempts', ['quiz' => $quiz->id]);
415 $DB->delete_records('quiz_grades', ['quiz' => $quiz->id]);
419 * Delete all the attempts belonging to a user in a particular quiz.
421 * @param \mod_quiz\quiz_settings $quiz The quiz object.
422 * @param stdClass $user The user object.
424 function quiz_delete_user_attempts($quiz, $user) {
425 global $CFG, $DB;
426 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
427 question_engine::delete_questions_usage_by_activities(new qubaids_for_users_attempts(
428 $quiz->get_quizid(), $user->id, 'all'));
429 $params = [
430 'quiz' => $quiz->get_quizid(),
431 'userid' => $user->id,
433 $DB->delete_records('quiz_attempts', $params);
434 $DB->delete_records('quiz_grades', $params);
438 * Get the best current grade for a particular user in a quiz.
440 * @param stdClass $quiz the quiz settings.
441 * @param int $userid the id of the user.
442 * @return float the user's current grade for this quiz, or null if this user does
443 * not have a grade on this quiz.
445 function quiz_get_best_grade($quiz, $userid) {
446 global $DB;
447 $grade = $DB->get_field('quiz_grades', 'grade',
448 ['quiz' => $quiz->id, 'userid' => $userid]);
450 // Need to detect errors/no result, without catching 0 grades.
451 if ($grade === false) {
452 return null;
455 return $grade + 0; // Convert to number.
459 * Is this a graded quiz? If this method returns true, you can assume that
460 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
461 * divide by them).
463 * @param stdClass $quiz a row from the quiz table.
464 * @return bool whether this is a graded quiz.
466 function quiz_has_grades($quiz) {
467 return $quiz->grade >= grade_calculator::ALMOST_ZERO && $quiz->sumgrades >= grade_calculator::ALMOST_ZERO;
471 * Does this quiz allow multiple tries?
473 * @return bool
475 function quiz_allows_multiple_tries($quiz) {
476 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
477 return $bt->allows_multiple_submitted_responses();
481 * Return a small object with summary information about what a
482 * user has done with a given particular instance of this module
483 * Used for user activity reports.
484 * $return->time = the time they did it
485 * $return->info = a short text description
487 * @param stdClass $course
488 * @param stdClass $user
489 * @param stdClass $mod
490 * @param stdClass $quiz
491 * @return stdClass|null
493 function quiz_user_outline($course, $user, $mod, $quiz) {
494 global $DB, $CFG;
495 require_once($CFG->libdir . '/gradelib.php');
496 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
498 if (empty($grades->items[0]->grades)) {
499 return null;
500 } else {
501 $grade = reset($grades->items[0]->grades);
504 $result = new stdClass();
505 // If the user can't see hidden grades, don't return that information.
506 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
507 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
508 $result->info = get_string('gradenoun') . ': ' . $grade->str_long_grade;
509 } else {
510 $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
513 $result->time = grade_get_date_for_user_grade($grade, $user);
515 return $result;
519 * Print a detailed representation of what a user has done with
520 * a given particular instance of this module, for user activity reports.
522 * @param stdClass $course
523 * @param stdClass $user
524 * @param stdClass $mod
525 * @param stdClass $quiz
526 * @return bool
528 function quiz_user_complete($course, $user, $mod, $quiz) {
529 global $DB, $CFG, $OUTPUT;
530 require_once($CFG->libdir . '/gradelib.php');
531 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
533 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
534 if (!empty($grades->items[0]->grades)) {
535 $grade = reset($grades->items[0]->grades);
536 // If the user can't see hidden grades, don't return that information.
537 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
538 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
539 echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade);
540 if ($grade->str_feedback) {
541 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
543 } else {
544 echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
545 if ($grade->str_feedback) {
546 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades'));
551 if ($attempts = $DB->get_records('quiz_attempts',
552 ['userid' => $user->id, 'quiz' => $quiz->id], 'attempt')) {
553 foreach ($attempts as $attempt) {
554 echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
555 if ($attempt->state != quiz_attempt::FINISHED) {
556 echo quiz_attempt_state_name($attempt->state);
557 } else {
558 if (!isset($gitem)) {
559 if (!empty($grades->items[0]->grades)) {
560 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]);
561 } else {
562 $gitem = new stdClass();
563 $gitem->hidden = true;
566 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
567 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades);
568 } else {
569 echo get_string('hidden', 'grades');
571 echo ' - '.userdate($attempt->timefinish).'<br />';
574 } else {
575 print_string('noattempts', 'quiz');
578 return true;
583 * @param int|array $quizids A quiz ID, or an array of quiz IDs.
584 * @param int $userid the userid.
585 * @param string $status 'all', 'finished' or 'unfinished' to control
586 * @param bool $includepreviews
587 * @return array of all the user's attempts at this quiz. Returns an empty
588 * array if there are none.
590 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) {
591 global $DB;
593 $params = [];
594 switch ($status) {
595 case 'all':
596 $statuscondition = '';
597 break;
599 case 'finished':
600 $statuscondition = ' AND state IN (:state1, :state2)';
601 $params['state1'] = quiz_attempt::FINISHED;
602 $params['state2'] = quiz_attempt::ABANDONED;
603 break;
605 case 'unfinished':
606 $statuscondition = ' AND state IN (:state1, :state2)';
607 $params['state1'] = quiz_attempt::IN_PROGRESS;
608 $params['state2'] = quiz_attempt::OVERDUE;
609 break;
612 $quizids = (array) $quizids;
613 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED);
614 $params += $inparams;
615 $params['userid'] = $userid;
617 $previewclause = '';
618 if (!$includepreviews) {
619 $previewclause = ' AND preview = 0';
622 return $DB->get_records_select('quiz_attempts',
623 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition,
624 $params, 'quiz, attempt ASC');
628 * Return grade for given user or all users.
630 * @param int $quizid id of quiz
631 * @param int $userid optional user id, 0 means all users
632 * @return array array of grades, false if none. These are raw grades. They should
633 * be processed with quiz_format_grade for display.
635 function quiz_get_user_grades($quiz, $userid = 0) {
636 global $CFG, $DB;
638 $params = [$quiz->id];
639 $usertest = '';
640 if ($userid) {
641 $params[] = $userid;
642 $usertest = 'AND u.id = ?';
644 return $DB->get_records_sql("
645 SELECT
646 u.id,
647 u.id AS userid,
648 qg.grade AS rawgrade,
649 qg.timemodified AS dategraded,
650 MAX(qa.timefinish) AS datesubmitted
652 FROM {user} u
653 JOIN {quiz_grades} qg ON u.id = qg.userid
654 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
656 WHERE qg.quiz = ?
657 $usertest
658 GROUP BY u.id, qg.grade, qg.timemodified", $params);
662 * Round a grade to the correct number of decimal places, and format it for display.
664 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
665 * @param float $grade The grade to round.
666 * @return string
668 function quiz_format_grade($quiz, $grade) {
669 if (is_null($grade)) {
670 return get_string('notyetgraded', 'quiz');
672 return format_float($grade, $quiz->decimalpoints);
676 * Determine the correct number of decimal places required to format a grade.
678 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints and
679 * ->questiondecimalpoints are used.
680 * @return integer
682 function quiz_get_grade_format($quiz) {
683 if (empty($quiz->questiondecimalpoints)) {
684 $quiz->questiondecimalpoints = -1;
687 if ($quiz->questiondecimalpoints == -1) {
688 return $quiz->decimalpoints;
691 return $quiz->questiondecimalpoints;
695 * Round a grade to the correct number of decimal places, and format it for display.
697 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used.
698 * @param float $grade The grade to round.
699 * @return string
701 function quiz_format_question_grade($quiz, $grade) {
702 return format_float($grade, quiz_get_grade_format($quiz));
706 * Update grades in central gradebook
708 * @category grade
709 * @param stdClass $quiz the quiz settings.
710 * @param int $userid specific user only, 0 means all users.
711 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
713 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
714 global $CFG, $DB;
715 require_once($CFG->libdir . '/gradelib.php');
717 if ($quiz->grade == 0) {
718 quiz_grade_item_update($quiz);
720 } else if ($grades = quiz_get_user_grades($quiz, $userid)) {
721 quiz_grade_item_update($quiz, $grades);
723 } else if ($userid && $nullifnone) {
724 $grade = new stdClass();
725 $grade->userid = $userid;
726 $grade->rawgrade = null;
727 quiz_grade_item_update($quiz, $grade);
729 } else {
730 quiz_grade_item_update($quiz);
735 * Create or update the grade item for given quiz
737 * @category grade
738 * @param stdClass $quiz object with extra cmidnumber
739 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
740 * @return int 0 if ok, error code otherwise
742 function quiz_grade_item_update($quiz, $grades = null) {
743 global $CFG, $OUTPUT;
744 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
745 require_once($CFG->libdir . '/gradelib.php');
747 if (property_exists($quiz, 'cmidnumber')) { // May not be always present.
748 $params = ['itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber];
749 } else {
750 $params = ['itemname' => $quiz->name];
753 if ($quiz->grade > 0) {
754 $params['gradetype'] = GRADE_TYPE_VALUE;
755 $params['grademax'] = $quiz->grade;
756 $params['grademin'] = 0;
758 } else {
759 $params['gradetype'] = GRADE_TYPE_NONE;
762 // What this is trying to do:
763 // 1. If the quiz is set to not show grades while the quiz is still open,
764 // and is set to show grades after the quiz is closed, then create the
765 // grade_item with a show-after date that is the quiz close date.
766 // 2. If the quiz is set to not show grades at either of those times,
767 // create the grade_item as hidden.
768 // 3. If the quiz is set to show grades, create the grade_item visible.
769 $openreviewoptions = display_options::make_from_quiz($quiz,
770 display_options::LATER_WHILE_OPEN);
771 $closedreviewoptions = display_options::make_from_quiz($quiz,
772 display_options::AFTER_CLOSE);
773 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
774 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
775 $params['hidden'] = 1;
777 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
778 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
779 if ($quiz->timeclose) {
780 $params['hidden'] = $quiz->timeclose;
781 } else {
782 $params['hidden'] = 1;
785 } else {
786 // Either
787 // a) both open and closed enabled
788 // b) open enabled, closed disabled - we can not "hide after",
789 // grades are kept visible even after closing.
790 $params['hidden'] = 0;
793 if (!$params['hidden']) {
794 // If the grade item is not hidden by the quiz logic, then we need to
795 // hide it if the quiz is hidden from students.
796 if (property_exists($quiz, 'visible')) {
797 // Saving the quiz form, and cm not yet updated in the database.
798 $params['hidden'] = !$quiz->visible;
799 } else {
800 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
801 $params['hidden'] = !$cm->visible;
805 if ($grades === 'reset') {
806 $params['reset'] = true;
807 $grades = null;
810 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
811 if (!empty($gradebook_grades->items)) {
812 $grade_item = $gradebook_grades->items[0];
813 if ($grade_item->locked) {
814 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
815 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
816 if (!$confirm_regrade) {
817 if (!AJAX_SCRIPT) {
818 $message = get_string('gradeitemislocked', 'grades');
819 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
820 '&amp;mode=overview';
821 $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
822 echo $OUTPUT->box_start('generalbox', 'notice');
823 echo '<p>'. $message .'</p>';
824 echo $OUTPUT->container_start('buttons');
825 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades'));
826 echo $OUTPUT->single_button($back_link, get_string('cancel'));
827 echo $OUTPUT->container_end();
828 echo $OUTPUT->box_end();
830 return GRADE_UPDATE_ITEM_LOCKED;
835 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
839 * Delete grade item for given quiz
841 * @category grade
842 * @param stdClass $quiz object
843 * @return int
845 function quiz_grade_item_delete($quiz) {
846 global $CFG;
847 require_once($CFG->libdir . '/gradelib.php');
849 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0,
850 null, ['deleted' => 1]);
854 * This standard function will check all instances of this module
855 * and make sure there are up-to-date events created for each of them.
856 * If courseid = 0, then every quiz event in the site is checked, else
857 * only quiz events belonging to the course specified are checked.
858 * This function is used, in its new format, by restore_refresh_events()
860 * @param int $courseid
861 * @param int|stdClass $instance Quiz module instance or ID.
862 * @param int|stdClass $cm Course module object or ID (not used in this module).
863 * @return bool
865 function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) {
866 global $DB;
868 // If we have instance information then we can just update the one event instead of updating all events.
869 if (isset($instance)) {
870 if (!is_object($instance)) {
871 $instance = $DB->get_record('quiz', ['id' => $instance], '*', MUST_EXIST);
873 quiz_update_events($instance);
874 return true;
877 if ($courseid == 0) {
878 if (!$quizzes = $DB->get_records('quiz')) {
879 return true;
881 } else {
882 if (!$quizzes = $DB->get_records('quiz', ['course' => $courseid])) {
883 return true;
887 foreach ($quizzes as $quiz) {
888 quiz_update_events($quiz);
891 return true;
895 * Returns all quiz graded users since a given time for specified quiz
897 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart,
898 $courseid, $cmid, $userid = 0, $groupid = 0) {
899 global $CFG, $USER, $DB;
900 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
902 $course = get_course($courseid);
903 $modinfo = get_fast_modinfo($course);
905 $cm = $modinfo->cms[$cmid];
906 $quiz = $DB->get_record('quiz', ['id' => $cm->instance]);
908 if ($userid) {
909 $userselect = "AND u.id = :userid";
910 $params['userid'] = $userid;
911 } else {
912 $userselect = '';
915 if ($groupid) {
916 $groupselect = 'AND gm.groupid = :groupid';
917 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id';
918 $params['groupid'] = $groupid;
919 } else {
920 $groupselect = '';
921 $groupjoin = '';
924 $params['timestart'] = $timestart;
925 $params['quizid'] = $quiz->id;
927 $userfieldsapi = \core_user\fields::for_userpic();
928 $ufields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects;
929 if (!$attempts = $DB->get_records_sql("
930 SELECT qa.*,
931 {$ufields}
932 FROM {quiz_attempts} qa
933 JOIN {user} u ON u.id = qa.userid
934 $groupjoin
935 WHERE qa.timefinish > :timestart
936 AND qa.quiz = :quizid
937 AND qa.preview = 0
938 $userselect
939 $groupselect
940 ORDER BY qa.timefinish ASC", $params)) {
941 return;
944 $context = context_module::instance($cm->id);
945 $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
946 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
947 $grader = has_capability('mod/quiz:viewreports', $context);
948 $groupmode = groups_get_activity_groupmode($cm, $course);
950 $usersgroups = null;
951 $aname = format_string($cm->name, true);
952 foreach ($attempts as $attempt) {
953 if ($attempt->userid != $USER->id) {
954 if (!$grader) {
955 // Grade permission required.
956 continue;
959 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
960 $usersgroups = groups_get_all_groups($course->id,
961 $attempt->userid, $cm->groupingid);
962 $usersgroups = array_keys($usersgroups);
963 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) {
964 continue;
969 $options = quiz_get_review_options($quiz, $attempt, $context);
971 $tmpactivity = new stdClass();
973 $tmpactivity->type = 'quiz';
974 $tmpactivity->cmid = $cm->id;
975 $tmpactivity->name = $aname;
976 $tmpactivity->sectionnum = $cm->sectionnum;
977 $tmpactivity->timestamp = $attempt->timefinish;
979 $tmpactivity->content = new stdClass();
980 $tmpactivity->content->attemptid = $attempt->id;
981 $tmpactivity->content->attempt = $attempt->attempt;
982 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) {
983 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades);
984 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades);
985 } else {
986 $tmpactivity->content->sumgrades = null;
987 $tmpactivity->content->maxgrade = null;
990 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain');
991 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames);
993 $activities[$index++] = $tmpactivity;
997 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
998 global $CFG, $OUTPUT;
1000 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
1002 echo '<tr><td class="userpicture" valign="top">';
1003 echo $OUTPUT->user_picture($activity->user, ['courseid' => $courseid]);
1004 echo '</td><td>';
1006 if ($detail) {
1007 $modname = $modnames[$activity->type];
1008 echo '<div class="title">';
1009 echo $OUTPUT->image_icon('monologo', $modname, $activity->type);
1010 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' .
1011 $activity->cmid . '">' . $activity->name . '</a>';
1012 echo '</div>';
1015 echo '<div class="grade">';
1016 echo get_string('attempt', 'quiz', $activity->content->attempt);
1017 if (isset($activity->content->maxgrade)) {
1018 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
1019 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' .
1020 $activity->content->attemptid . '">' . $grades . '</a>)';
1022 echo '</div>';
1024 echo '<div class="user">';
1025 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id .
1026 '&amp;course=' . $courseid . '">' . $activity->user->fullname .
1027 '</a> - ' . userdate($activity->timestamp);
1028 echo '</div>';
1030 echo '</td></tr></table>';
1032 return;
1036 * Pre-process the quiz options form data, making any necessary adjustments.
1037 * Called by add/update instance in this file.
1039 * @param stdClass $quiz The variables set on the form.
1041 function quiz_process_options($quiz) {
1042 global $CFG;
1043 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1044 require_once($CFG->libdir . '/questionlib.php');
1046 $quiz->timemodified = time();
1048 // Quiz name.
1049 if (!empty($quiz->name)) {
1050 $quiz->name = trim($quiz->name);
1053 // Password field - different in form to stop browsers that remember passwords
1054 // getting confused.
1055 $quiz->password = $quiz->quizpassword;
1056 unset($quiz->quizpassword);
1058 // Quiz feedback.
1059 if (isset($quiz->feedbacktext)) {
1060 // Clean up the boundary text.
1061 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) {
1062 if (empty($quiz->feedbacktext[$i]['text'])) {
1063 $quiz->feedbacktext[$i]['text'] = '';
1064 } else {
1065 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']);
1069 // Check the boundary value is a number or a percentage, and in range.
1070 $i = 0;
1071 while (!empty($quiz->feedbackboundaries[$i])) {
1072 $boundary = trim($quiz->feedbackboundaries[$i]);
1073 if (!is_numeric($boundary)) {
1074 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') {
1075 $boundary = trim(substr($boundary, 0, -1));
1076 if (is_numeric($boundary)) {
1077 $boundary = $boundary * $quiz->grade / 100.0;
1078 } else {
1079 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1);
1083 if ($boundary <= 0 || $boundary >= $quiz->grade) {
1084 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1);
1086 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) {
1087 return get_string('feedbackerrororder', 'quiz', $i + 1);
1089 $quiz->feedbackboundaries[$i] = $boundary;
1090 $i += 1;
1092 $numboundaries = $i;
1094 // Check there is nothing in the remaining unused fields.
1095 if (!empty($quiz->feedbackboundaries)) {
1096 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) {
1097 if (!empty($quiz->feedbackboundaries[$i]) &&
1098 trim($quiz->feedbackboundaries[$i]) != '') {
1099 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1);
1103 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) {
1104 if (!empty($quiz->feedbacktext[$i]['text']) &&
1105 trim($quiz->feedbacktext[$i]['text']) != '') {
1106 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1);
1109 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade().
1110 $quiz->feedbackboundaries[-1] = $quiz->grade + 1;
1111 $quiz->feedbackboundaries[$numboundaries] = 0;
1112 $quiz->feedbackboundarycount = $numboundaries;
1113 } else {
1114 $quiz->feedbackboundarycount = -1;
1117 // Combing the individual settings into the review columns.
1118 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt');
1119 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness');
1120 $quiz->reviewmaxmarks = quiz_review_option_form_to_db($quiz, 'maxmarks');
1121 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks');
1122 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback');
1123 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback');
1124 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer');
1125 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback');
1126 $quiz->reviewattempt |= display_options::DURING;
1127 $quiz->reviewoverallfeedback &= ~display_options::DURING;
1129 // Ensure that disabled checkboxes in completion settings are set to 0.
1130 // But only if the completion settinsg are unlocked.
1131 if (!empty($quiz->completionunlocked)) {
1132 if (empty($quiz->completionusegrade)) {
1133 $quiz->completionpassgrade = 0;
1135 if (empty($quiz->completionpassgrade)) {
1136 $quiz->completionattemptsexhausted = 0;
1138 if (empty($quiz->completionminattemptsenabled)) {
1139 $quiz->completionminattempts = 0;
1145 * Helper function for {@link quiz_process_options()}.
1146 * @param stdClass $fromform the sumbitted form date.
1147 * @param string $field one of the review option field names.
1149 function quiz_review_option_form_to_db($fromform, $field) {
1150 static $times = [
1151 'during' => display_options::DURING,
1152 'immediately' => display_options::IMMEDIATELY_AFTER,
1153 'open' => display_options::LATER_WHILE_OPEN,
1154 'closed' => display_options::AFTER_CLOSE,
1157 $review = 0;
1158 foreach ($times as $whenname => $when) {
1159 $fieldname = $field . $whenname;
1160 if (!empty($fromform->$fieldname)) {
1161 $review |= $when;
1162 unset($fromform->$fieldname);
1166 return $review;
1170 * In place editable callback for slot displaynumber.
1172 * @param string $itemtype slotdisplarnumber
1173 * @param int $itemid the id of the slot in the quiz_slots table
1174 * @param string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table
1175 * @return \core\output\inplace_editable|void
1177 function mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue): \core\output\inplace_editable {
1178 global $DB;
1180 if ($itemtype === 'slotdisplaynumber') {
1181 // Work out which quiz and slot this is.
1182 $slot = $DB->get_record('quiz_slots', ['id' => $itemid], '*', MUST_EXIST);
1183 $quizobj = quiz_settings::create($slot->quizid);
1185 // Validate the context, and check the required capability.
1186 $context = $quizobj->get_context();
1187 \core_external\external_api::validate_context($context);
1188 require_capability('mod/quiz:manage', $context);
1190 // Update the value - truncating the size of the DB column.
1191 $structure = $quizobj->get_structure();
1192 $structure->update_slot_display_number($itemid, core_text::substr($newvalue, 0, 16));
1194 // Prepare the element for the output.
1195 return $structure->make_slot_display_number_in_place_editable($itemid, $context);
1200 * This function is called at the end of quiz_add_instance
1201 * and quiz_update_instance, to do the common processing.
1203 * @param stdClass $quiz the quiz object.
1205 function quiz_after_add_or_update($quiz) {
1206 global $DB;
1207 $cmid = $quiz->coursemodule;
1209 // We need to use context now, so we need to make sure all needed info is already in db.
1210 $DB->set_field('course_modules', 'instance', $quiz->id, ['id' => $cmid]);
1211 $context = context_module::instance($cmid);
1213 // Save the feedback.
1214 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]);
1216 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) {
1217 $feedback = new stdClass();
1218 $feedback->quizid = $quiz->id;
1219 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text'];
1220 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format'];
1221 $feedback->mingrade = $quiz->feedbackboundaries[$i];
1222 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1];
1223 $feedback->id = $DB->insert_record('quiz_feedback', $feedback);
1224 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'],
1225 $context->id, 'mod_quiz', 'feedback', $feedback->id,
1226 ['subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0],
1227 $quiz->feedbacktext[$i]['text']);
1228 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext,
1229 ['id' => $feedback->id]);
1232 // Store any settings belonging to the access rules.
1233 access_manager::save_settings($quiz);
1235 // Update the events relating to this quiz.
1236 quiz_update_events($quiz);
1237 $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null;
1238 \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected);
1240 // Update related grade item.
1241 quiz_grade_item_update($quiz);
1245 * This function updates the events associated to the quiz.
1246 * If $override is non-zero, then it updates only the events
1247 * associated with the specified override.
1249 * @param stdClass $quiz the quiz object.
1250 * @param stdClass|null $override limit to a specific override
1252 function quiz_update_events($quiz, $override = null) {
1253 global $DB;
1255 // Load the old events relating to this quiz.
1256 $conds = ['modulename' => 'quiz',
1257 'instance' => $quiz->id];
1258 if (!empty($override)) {
1259 // Only load events for this override.
1260 if (isset($override->userid)) {
1261 $conds['userid'] = $override->userid;
1262 } else {
1263 $conds['groupid'] = $override->groupid;
1266 $oldevents = $DB->get_records('event', $conds, 'id ASC');
1268 // Now make a to-do list of all that needs to be updated.
1269 if (empty($override)) {
1270 // We are updating the primary settings for the quiz, so we need to add all the overrides.
1271 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id ASC');
1272 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
1273 // list contains the original (non-override) event for the module. If this is not included
1274 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
1275 // list against the $oldevents list.
1276 array_unshift($overrides, new stdClass());
1277 } else {
1278 // Just do the one override.
1279 $overrides = [$override];
1282 // Get group override priorities.
1283 $grouppriorities = quiz_get_group_override_priorities($quiz->id);
1285 foreach ($overrides as $current) {
1286 $groupid = isset($current->groupid)? $current->groupid : 0;
1287 $userid = isset($current->userid)? $current->userid : 0;
1288 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen;
1289 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose;
1291 // Only add open/close events for an override if they differ from the quiz default.
1292 $addopen = empty($current->id) || !empty($current->timeopen);
1293 $addclose = empty($current->id) || !empty($current->timeclose);
1295 if (!empty($quiz->coursemodule)) {
1296 $cmid = $quiz->coursemodule;
1297 } else {
1298 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id;
1301 $event = new stdClass();
1302 $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
1303 $event->description = format_module_intro('quiz', $quiz, $cmid, false);
1304 $event->format = FORMAT_HTML;
1305 // Events module won't show user events when the courseid is nonzero.
1306 $event->courseid = ($userid) ? 0 : $quiz->course;
1307 $event->groupid = $groupid;
1308 $event->userid = $userid;
1309 $event->modulename = 'quiz';
1310 $event->instance = $quiz->id;
1311 $event->timestart = $timeopen;
1312 $event->timeduration = max($timeclose - $timeopen, 0);
1313 $event->timesort = $timeopen;
1314 $event->visible = instance_is_visible('quiz', $quiz);
1315 $event->eventtype = QUIZ_EVENT_TYPE_OPEN;
1316 $event->priority = null;
1318 // Determine the event name and priority.
1319 if ($groupid) {
1320 // Group override event.
1321 $params = new stdClass();
1322 $params->quiz = $quiz->name;
1323 $params->group = groups_get_group_name($groupid);
1324 if ($params->group === false) {
1325 // Group doesn't exist, just skip it.
1326 continue;
1328 $eventname = get_string('overridegroupeventname', 'quiz', $params);
1329 // Set group override priority.
1330 if ($grouppriorities !== null) {
1331 $openpriorities = $grouppriorities['open'];
1332 if (isset($openpriorities[$timeopen])) {
1333 $event->priority = $openpriorities[$timeopen];
1336 } else if ($userid) {
1337 // User override event.
1338 $params = new stdClass();
1339 $params->quiz = $quiz->name;
1340 $eventname = get_string('overrideusereventname', 'quiz', $params);
1341 // Set user override priority.
1342 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
1343 } else {
1344 // The parent event.
1345 $eventname = $quiz->name;
1348 if ($addopen or $addclose) {
1349 // Separate start and end events.
1350 $event->timeduration = 0;
1351 if ($timeopen && $addopen) {
1352 if ($oldevent = array_shift($oldevents)) {
1353 $event->id = $oldevent->id;
1354 } else {
1355 unset($event->id);
1357 $event->name = get_string('quizeventopens', 'quiz', $eventname);
1358 // The method calendar_event::create will reuse a db record if the id field is set.
1359 calendar_event::create($event, false);
1361 if ($timeclose && $addclose) {
1362 if ($oldevent = array_shift($oldevents)) {
1363 $event->id = $oldevent->id;
1364 } else {
1365 unset($event->id);
1367 $event->type = CALENDAR_EVENT_TYPE_ACTION;
1368 $event->name = get_string('quizeventcloses', 'quiz', $eventname);
1369 $event->timestart = $timeclose;
1370 $event->timesort = $timeclose;
1371 $event->eventtype = QUIZ_EVENT_TYPE_CLOSE;
1372 if ($groupid && $grouppriorities !== null) {
1373 $closepriorities = $grouppriorities['close'];
1374 if (isset($closepriorities[$timeclose])) {
1375 $event->priority = $closepriorities[$timeclose];
1378 calendar_event::create($event, false);
1383 // Delete any leftover events.
1384 foreach ($oldevents as $badevent) {
1385 $badevent = calendar_event::load($badevent);
1386 $badevent->delete();
1391 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz.
1393 * @param int $quizid The quiz ID.
1394 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
1396 function quiz_get_group_override_priorities($quizid) {
1397 global $DB;
1399 // Fetch group overrides.
1400 $where = 'quiz = :quiz AND groupid IS NOT NULL';
1401 $params = ['quiz' => $quizid];
1402 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose');
1403 if (!$overrides) {
1404 return null;
1407 $grouptimeopen = [];
1408 $grouptimeclose = [];
1409 foreach ($overrides as $override) {
1410 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) {
1411 $grouptimeopen[] = $override->timeopen;
1413 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) {
1414 $grouptimeclose[] = $override->timeclose;
1418 // Sort open times in ascending manner. The earlier open time gets higher priority.
1419 sort($grouptimeopen);
1420 // Set priorities.
1421 $opengrouppriorities = [];
1422 $openpriority = 1;
1423 foreach ($grouptimeopen as $timeopen) {
1424 $opengrouppriorities[$timeopen] = $openpriority++;
1427 // Sort close times in descending manner. The later close time gets higher priority.
1428 rsort($grouptimeclose);
1429 // Set priorities.
1430 $closegrouppriorities = [];
1431 $closepriority = 1;
1432 foreach ($grouptimeclose as $timeclose) {
1433 $closegrouppriorities[$timeclose] = $closepriority++;
1436 return [
1437 'open' => $opengrouppriorities,
1438 'close' => $closegrouppriorities
1443 * List the actions that correspond to a view of this module.
1444 * This is used by the participation report.
1446 * Note: This is not used by new logging system. Event with
1447 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1448 * be considered as view action.
1450 * @return array
1452 function quiz_get_view_actions() {
1453 return ['view', 'view all', 'report', 'review'];
1457 * List the actions that correspond to a post of this module.
1458 * This is used by the participation report.
1460 * Note: This is not used by new logging system. Event with
1461 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1462 * will be considered as post action.
1464 * @return array
1466 function quiz_get_post_actions() {
1467 return ['attempt', 'close attempt', 'preview', 'editquestions',
1468 'delete attempt', 'manualgrade'];
1472 * Standard callback used by questions_in_use.
1474 * @param array $questionids of question ids.
1475 * @return bool whether any of these questions are used by any instance of this module.
1477 function quiz_questions_in_use($questionids) {
1478 return question_engine::questions_in_use($questionids,
1479 new qubaid_join('{quiz_attempts} quiza', 'quiza.uniqueid',
1480 'quiza.preview = 0'));
1484 * Implementation of the function for printing the form elements that control
1485 * whether the course reset functionality affects the quiz.
1487 * @param MoodleQuickForm $mform the course reset form that is being built.
1489 function quiz_reset_course_form_definition($mform) {
1490 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz'));
1491 $mform->addElement('advcheckbox', 'reset_quiz_attempts',
1492 get_string('removeallquizattempts', 'quiz'));
1493 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides',
1494 get_string('removealluseroverrides', 'quiz'));
1495 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides',
1496 get_string('removeallgroupoverrides', 'quiz'));
1500 * Course reset form defaults.
1501 * @return array the defaults.
1503 function quiz_reset_course_form_defaults($course) {
1504 return ['reset_quiz_attempts' => 1,
1505 'reset_quiz_group_overrides' => 1,
1506 'reset_quiz_user_overrides' => 1];
1510 * Removes all grades from gradebook
1512 * @param int $courseid
1513 * @param string optional type
1515 function quiz_reset_gradebook($courseid, $type='') {
1516 global $CFG, $DB;
1518 $quizzes = $DB->get_records_sql("
1519 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid
1520 FROM {modules} m
1521 JOIN {course_modules} cm ON m.id = cm.module
1522 JOIN {quiz} q ON cm.instance = q.id
1523 WHERE m.name = 'quiz' AND cm.course = ?", [$courseid]);
1525 foreach ($quizzes as $quiz) {
1526 quiz_grade_item_update($quiz, 'reset');
1531 * Actual implementation of the reset course functionality, delete all the
1532 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is
1533 * set and true.
1535 * Also, move the quiz open and close dates, if the course start date is changing.
1537 * @param stdClass $data the data submitted from the reset course.
1538 * @return array status array
1540 function quiz_reset_userdata($data) {
1541 global $CFG, $DB;
1542 require_once($CFG->libdir . '/questionlib.php');
1544 $componentstr = get_string('modulenameplural', 'quiz');
1545 $status = [];
1547 // Delete attempts.
1548 if (!empty($data->reset_quiz_attempts)) {
1549 question_engine::delete_questions_usage_by_activities(new qubaid_join(
1550 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id',
1551 'quiza.uniqueid', 'quiz.course = :quizcourseid',
1552 ['quizcourseid' => $data->courseid]));
1554 $DB->delete_records_select('quiz_attempts',
1555 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1556 $status[] = [
1557 'component' => $componentstr,
1558 'item' => get_string('attemptsdeleted', 'quiz'),
1559 'error' => false];
1561 // Remove all grades from gradebook.
1562 $DB->delete_records_select('quiz_grades',
1563 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]);
1564 if (empty($data->reset_gradebook_grades)) {
1565 quiz_reset_gradebook($data->courseid);
1567 $status[] = [
1568 'component' => $componentstr,
1569 'item' => get_string('gradesdeleted', 'quiz'),
1570 'error' => false];
1573 $purgeoverrides = false;
1575 // Remove user overrides.
1576 if (!empty($data->reset_quiz_user_overrides)) {
1577 $DB->delete_records_select('quiz_overrides',
1578 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid]);
1579 $status[] = [
1580 'component' => $componentstr,
1581 'item' => get_string('useroverridesdeleted', 'quiz'),
1582 'error' => false];
1583 $purgeoverrides = true;
1585 // Remove group overrides.
1586 if (!empty($data->reset_quiz_group_overrides)) {
1587 $DB->delete_records_select('quiz_overrides',
1588 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid]);
1589 $status[] = [
1590 'component' => $componentstr,
1591 'item' => get_string('groupoverridesdeleted', 'quiz'),
1592 'error' => false];
1593 $purgeoverrides = true;
1596 // Updating dates - shift may be negative too.
1597 if ($data->timeshift) {
1598 $DB->execute("UPDATE {quiz_overrides}
1599 SET timeopen = timeopen + ?
1600 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1601 AND timeopen <> 0", [$data->timeshift, $data->courseid]);
1602 $DB->execute("UPDATE {quiz_overrides}
1603 SET timeclose = timeclose + ?
1604 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?)
1605 AND timeclose <> 0", [$data->timeshift, $data->courseid]);
1607 $purgeoverrides = true;
1609 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1610 // See MDL-9367.
1611 shift_course_mod_dates('quiz', ['timeopen', 'timeclose'],
1612 $data->timeshift, $data->courseid);
1614 $status[] = [
1615 'component' => $componentstr,
1616 'item' => get_string('openclosedatesupdated', 'quiz'),
1617 'error' => false];
1620 if ($purgeoverrides) {
1621 cache::make('mod_quiz', 'overrides')->purge();
1624 return $status;
1628 * Return a textual summary of the number of attempts that have been made at a particular quiz,
1629 * returns '' if no attempts have been made yet, unless $returnzero is passed as true.
1631 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1632 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1633 * $cm->groupingid fields are used at the moment.
1634 * @param bool $returnzero if false (default), when no attempts have been
1635 * made '' is returned instead of 'Attempts: 0'.
1636 * @param int $currentgroup if there is a concept of current group where this method is being called
1637 * (e.g. a report) pass it in here. Default 0 which means no current group.
1638 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or
1639 * "Attemtps 123 (45 from this group)".
1641 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) {
1642 global $DB, $USER;
1643 $numattempts = $DB->count_records('quiz_attempts', ['quiz' => $quiz->id, 'preview' => 0]);
1644 if ($numattempts || $returnzero) {
1645 if (groups_get_activity_groupmode($cm)) {
1646 $a = new stdClass();
1647 $a->total = $numattempts;
1648 if ($currentgroup) {
1649 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1650 '{quiz_attempts} qa JOIN ' .
1651 '{groups_members} gm ON qa.userid = gm.userid ' .
1652 'WHERE quiz = ? AND preview = 0 AND groupid = ?',
1653 [$quiz->id, $currentgroup]);
1654 return get_string('attemptsnumthisgroup', 'quiz', $a);
1655 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) {
1656 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups));
1657 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' .
1658 '{quiz_attempts} qa JOIN ' .
1659 '{groups_members} gm ON qa.userid = gm.userid ' .
1660 'WHERE quiz = ? AND preview = 0 AND ' .
1661 "groupid $usql", array_merge([$quiz->id], $params));
1662 return get_string('attemptsnumyourgroups', 'quiz', $a);
1665 return get_string('attemptsnum', 'quiz', $numattempts);
1667 return '';
1671 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link
1672 * to the quiz reports.
1674 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment.
1675 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
1676 * $cm->groupingid fields are used at the moment.
1677 * @param stdClass $context the quiz context.
1678 * @param bool $returnzero if false (default), when no attempts have been made
1679 * '' is returned instead of 'Attempts: 0'.
1680 * @param int $currentgroup if there is a concept of current group where this method is being called
1681 * (e.g. a report) pass it in here. Default 0 which means no current group.
1682 * @return string HTML fragment for the link.
1684 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false,
1685 $currentgroup = 0) {
1686 global $PAGE;
1688 return $PAGE->get_renderer('mod_quiz')->quiz_attempt_summary_link_to_reports(
1689 $quiz, $cm, $context, $returnzero, $currentgroup);
1693 * @param string $feature FEATURE_xx constant for requested feature
1694 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1696 function quiz_supports($feature) {
1697 switch($feature) {
1698 case FEATURE_GROUPS: return true;
1699 case FEATURE_GROUPINGS: return true;
1700 case FEATURE_MOD_INTRO: return true;
1701 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
1702 case FEATURE_COMPLETION_HAS_RULES: return true;
1703 case FEATURE_GRADE_HAS_GRADE: return true;
1704 case FEATURE_GRADE_OUTCOMES: return true;
1705 case FEATURE_BACKUP_MOODLE2: return true;
1706 case FEATURE_SHOW_DESCRIPTION: return true;
1707 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true;
1708 case FEATURE_USES_QUESTIONS: return true;
1709 case FEATURE_PLAGIARISM: return true;
1710 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_ASSESSMENT;
1712 default: return null;
1717 * @return array all other caps used in module
1719 function quiz_get_extra_capabilities() {
1720 global $CFG;
1721 require_once($CFG->libdir . '/questionlib.php');
1722 return question_get_all_capabilities();
1726 * This function extends the settings navigation block for the site.
1728 * It is safe to rely on PAGE here as we will only ever be within the module
1729 * context when this is called
1731 * @param settings_navigation $settings
1732 * @param navigation_node $quiznode
1733 * @return void
1735 function quiz_extend_settings_navigation(settings_navigation $settings, navigation_node $quiznode) {
1736 global $CFG;
1738 // Require {@link questionlib.php}
1739 // Included here as we only ever want to include this file if we really need to.
1740 require_once($CFG->libdir . '/questionlib.php');
1742 // We want to add these new nodes after the Edit settings node, and before the
1743 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1744 $keys = $quiznode->get_children_key_list();
1745 $beforekey = null;
1746 $i = array_search('modedit', $keys);
1747 if ($i === false and array_key_exists(0, $keys)) {
1748 $beforekey = $keys[0];
1749 } else if (array_key_exists($i + 1, $keys)) {
1750 $beforekey = $keys[$i + 1];
1753 if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $settings->get_page()->cm->context)) {
1754 $url = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']);
1755 $node = navigation_node::create(get_string('overrides', 'quiz'),
1756 $url, navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides');
1757 $settingsoverride = $quiznode->add_node($node, $beforekey);
1760 if (has_capability('mod/quiz:manage', $settings->get_page()->cm->context)) {
1761 $node = navigation_node::create(get_string('questions', 'quiz'),
1762 new moodle_url('/mod/quiz/edit.php', ['cmid' => $settings->get_page()->cm->id]),
1763 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit', new pix_icon('t/edit', ''));
1764 $quiznode->add_node($node, $beforekey);
1767 if (has_capability('mod/quiz:preview', $settings->get_page()->cm->context)) {
1768 $url = new moodle_url('/mod/quiz/startattempt.php',
1769 ['cmid' => $settings->get_page()->cm->id, 'sesskey' => sesskey()]);
1770 $node = navigation_node::create(get_string('preview', 'quiz'), $url,
1771 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview',
1772 new pix_icon('i/preview', ''));
1773 $previewnode = $quiznode->add_node($node, $beforekey);
1774 $previewnode->set_show_in_secondary_navigation(false);
1777 question_extend_settings_navigation($quiznode, $settings->get_page()->cm->context)->trim_if_empty();
1779 if (has_any_capability(['mod/quiz:viewreports', 'mod/quiz:grade'], $settings->get_page()->cm->context)) {
1780 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
1781 $reportlist = quiz_report_list($settings->get_page()->cm->context);
1783 $url = new moodle_url('/mod/quiz/report.php',
1784 ['id' => $settings->get_page()->cm->id, 'mode' => reset($reportlist)]);
1785 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url,
1786 navigation_node::TYPE_SETTING,
1787 null, 'quiz_report', new pix_icon('i/report', '')));
1789 foreach ($reportlist as $report) {
1790 $url = new moodle_url('/mod/quiz/report.php', ['id' => $settings->get_page()->cm->id, 'mode' => $report]);
1791 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url,
1792 navigation_node::TYPE_SETTING,
1793 null, 'quiz_report_' . $report, new pix_icon('i/item', '')));
1799 * Serves the quiz files.
1801 * @package mod_quiz
1802 * @category files
1803 * @param stdClass $course course object
1804 * @param stdClass $cm course module object
1805 * @param stdClass $context context object
1806 * @param string $filearea file area
1807 * @param array $args extra arguments
1808 * @param bool $forcedownload whether or not force download
1809 * @param array $options additional options affecting the file serving
1810 * @return bool false if file not found, does not return if found - justsend the file
1812 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= []) {
1813 global $CFG, $DB;
1815 if ($context->contextlevel != CONTEXT_MODULE) {
1816 return false;
1819 require_login($course, false, $cm);
1821 if (!$quiz = $DB->get_record('quiz', ['id' => $cm->instance])) {
1822 return false;
1825 // The 'intro' area is served by pluginfile.php.
1826 $fileareas = ['feedback'];
1827 if (!in_array($filearea, $fileareas)) {
1828 return false;
1831 $feedbackid = (int)array_shift($args);
1832 if (!$feedback = $DB->get_record('quiz_feedback', ['id' => $feedbackid])) {
1833 return false;
1836 $fs = get_file_storage();
1837 $relativepath = implode('/', $args);
1838 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath";
1839 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1840 return false;
1842 send_stored_file($file, 0, 0, true, $options);
1846 * Called via pluginfile.php -> question_pluginfile to serve files belonging to
1847 * a question in a question_attempt when that attempt is a quiz attempt.
1849 * @package mod_quiz
1850 * @category files
1851 * @param stdClass $course course settings object
1852 * @param stdClass $context context object
1853 * @param string $component the name of the component we are serving files for.
1854 * @param string $filearea the name of the file area.
1855 * @param int $qubaid the attempt usage id.
1856 * @param int $slot the id of a question in this quiz attempt.
1857 * @param array $args the remaining bits of the file path.
1858 * @param bool $forcedownload whether the user must be forced to download the file.
1859 * @param array $options additional options affecting the file serving
1860 * @return bool false if file not found, does not return if found - justsend the file
1862 function quiz_question_pluginfile($course, $context, $component,
1863 $filearea, $qubaid, $slot, $args, $forcedownload, array $options= []) {
1864 global $CFG;
1865 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1867 $attemptobj = quiz_attempt::create_from_usage_id($qubaid);
1868 require_login($attemptobj->get_course(), false, $attemptobj->get_cm());
1870 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) {
1871 // In the middle of an attempt.
1872 if (!$attemptobj->is_preview_user()) {
1873 $attemptobj->require_capability('mod/quiz:attempt');
1875 $isreviewing = false;
1877 } else {
1878 // Reviewing an attempt.
1879 $attemptobj->check_review_capability();
1880 $isreviewing = true;
1883 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id,
1884 $component, $filearea, $args, $forcedownload)) {
1885 send_file_not_found();
1888 $fs = get_file_storage();
1889 $relativepath = implode('/', $args);
1890 $fullpath = "/$context->id/$component/$filearea/$relativepath";
1891 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1892 send_file_not_found();
1895 send_stored_file($file, 0, 0, $forcedownload, $options);
1899 * Return a list of page types
1900 * @param string $pagetype current page type
1901 * @param stdClass $parentcontext Block's parent context
1902 * @param stdClass $currentcontext Current context of block
1904 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) {
1905 $modulepagetype = [
1906 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'),
1907 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'),
1908 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'),
1909 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'),
1910 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'),
1911 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'),
1912 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'),
1914 return $modulepagetype;
1918 * @return the options for quiz navigation.
1920 function quiz_get_navigation_options() {
1921 return [
1922 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'),
1923 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz')
1928 * Check if the module has any update that affects the current user since a given time.
1930 * @param cm_info $cm course module data
1931 * @param int $from the time to check updates from
1932 * @param array $filter if we need to check only specific updates
1933 * @return stdClass an object with the different type of areas indicating if they were updated or not
1934 * @since Moodle 3.2
1936 function quiz_check_updates_since(cm_info $cm, $from, $filter = []) {
1937 global $DB, $USER, $CFG;
1938 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
1940 $updates = course_check_module_updates_since($cm, $from, [], $filter);
1942 // Check if questions were updated.
1943 $updates->questions = (object) ['updated' => false];
1944 $quizobj = quiz_settings::create($cm->instance, $USER->id);
1945 $quizobj->preload_questions();
1946 $quizobj->load_questions();
1947 $questionids = array_keys($quizobj->get_questions());
1948 if (!empty($questionids)) {
1949 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
1950 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)';
1951 $params['time1'] = $from;
1952 $params['time2'] = $from;
1953 $questions = $DB->get_records_select('question', $select, $params, '', 'id');
1954 if (!empty($questions)) {
1955 $updates->questions->updated = true;
1956 $updates->questions->itemids = array_keys($questions);
1960 // Check for new attempts or grades.
1961 $updates->attempts = (object) ['updated' => false];
1962 $updates->grades = (object) ['updated' => false];
1963 $select = 'quiz = ? AND userid = ? AND timemodified > ?';
1964 $params = [$cm->instance, $USER->id, $from];
1966 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1967 if (!empty($attempts)) {
1968 $updates->attempts->updated = true;
1969 $updates->attempts->itemids = array_keys($attempts);
1971 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
1972 if (!empty($grades)) {
1973 $updates->grades->updated = true;
1974 $updates->grades->itemids = array_keys($grades);
1977 // Now, teachers should see other students updates.
1978 if (has_capability('mod/quiz:viewreports', $cm->context)) {
1979 $select = 'quiz = ? AND timemodified > ?';
1980 $params = [$cm->instance, $from];
1982 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1983 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1984 if (empty($groupusers)) {
1985 return $updates;
1987 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1988 $select .= ' AND userid ' . $insql;
1989 $params = array_merge($params, $inparams);
1992 $updates->userattempts = (object) ['updated' => false];
1993 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id');
1994 if (!empty($attempts)) {
1995 $updates->userattempts->updated = true;
1996 $updates->userattempts->itemids = array_keys($attempts);
1999 $updates->usergrades = (object) ['updated' => false];
2000 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id');
2001 if (!empty($grades)) {
2002 $updates->usergrades->updated = true;
2003 $updates->usergrades->itemids = array_keys($grades);
2006 return $updates;
2010 * Get icon mapping for font-awesome.
2012 function mod_quiz_get_fontawesome_icon_map() {
2013 return [
2014 'mod_quiz:navflagged' => 'fa-flag',
2019 * This function receives a calendar event and returns the action associated with it, or null if there is none.
2021 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
2022 * is not displayed on the block.
2024 * @param calendar_event $event
2025 * @param \core_calendar\action_factory $factory
2026 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
2027 * @return \core_calendar\local\event\entities\action_interface|null
2029 function mod_quiz_core_calendar_provide_event_action(calendar_event $event,
2030 \core_calendar\action_factory $factory,
2031 int $userid = 0) {
2032 global $CFG, $USER;
2034 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2036 if (empty($userid)) {
2037 $userid = $USER->id;
2040 $cm = get_fast_modinfo($event->courseid, $userid)->instances['quiz'][$event->instance];
2041 $quizobj = quiz_settings::create($cm->instance, $userid);
2042 $quiz = $quizobj->get_quiz();
2044 // Check they have capabilities allowing them to view the quiz.
2045 if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) {
2046 return null;
2049 $completion = new \completion_info($cm->get_course());
2051 $completiondata = $completion->get_data($cm, false, $userid);
2053 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
2054 return null;
2057 quiz_update_effective_access($quiz, $userid);
2059 // Check if quiz is closed, if so don't display it.
2060 if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) {
2061 return null;
2064 if (!$quizobj->is_participant($userid)) {
2065 // If the user is not a participant then they have
2066 // no action to take. This will filter out the events for teachers.
2067 return null;
2070 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid);
2071 if (!empty($attempts)) {
2072 // The student's last attempt is finished.
2073 return null;
2076 $name = get_string('attemptquiznow', 'quiz');
2077 $url = new \moodle_url('/mod/quiz/view.php', [
2078 'id' => $cm->id
2080 $itemcount = 1;
2081 $actionable = true;
2083 // Check if the quiz is not currently actionable.
2084 if (!empty($quiz->timeopen) && $quiz->timeopen > time()) {
2085 $actionable = false;
2088 return $factory->create_instance(
2089 $name,
2090 $url,
2091 $itemcount,
2092 $actionable
2097 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information
2098 * for the course (see resource).
2100 * Given a course_module object, this function returns any "extra" information that may be needed
2101 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2103 * @param stdClass $coursemodule The coursemodule object (record).
2104 * @return cached_cm_info|false An object on information that the courses
2105 * will know about (most noticeably, an icon).
2107 function quiz_get_coursemodule_info($coursemodule) {
2108 global $DB;
2110 $dbparams = ['id' => $coursemodule->instance];
2111 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionminattempts,
2112 timeopen, timeclose';
2113 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) {
2114 return false;
2117 $result = new cached_cm_info();
2118 $result->name = $quiz->name;
2120 if ($coursemodule->showdescription) {
2121 // Convert intro to html. Do not filter cached version, filters run at display time.
2122 $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false);
2125 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
2126 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
2127 if ($quiz->completionattemptsexhausted) {
2128 $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [
2129 'completionpassgrade' => $coursemodule->completionpassgrade,
2130 'completionattemptsexhausted' => $quiz->completionattemptsexhausted,
2132 } else {
2133 $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [];
2136 $result->customdata['customcompletionrules']['completionminattempts'] = $quiz->completionminattempts;
2139 // Populate some other values that can be used in calendar or on dashboard.
2140 if ($quiz->timeopen) {
2141 $result->customdata['timeopen'] = $quiz->timeopen;
2143 if ($quiz->timeclose) {
2144 $result->customdata['timeclose'] = $quiz->timeclose;
2147 return $result;
2151 * Sets dynamic information about a course module
2153 * This function is called from cm_info when displaying the module
2155 * @param cm_info $cm
2157 function mod_quiz_cm_info_dynamic(cm_info $cm) {
2158 global $USER;
2160 $cache = cache::make('mod_quiz', 'overrides');
2161 $override = $cache->get("{$cm->instance}_u_{$USER->id}");
2163 if (!$override) {
2164 $override = (object) [
2165 'timeopen' => null,
2166 'timeclose' => null,
2170 // No need to look for group overrides if there are user overrides for both timeopen and timeclose.
2171 if (is_null($override->timeopen) || is_null($override->timeclose)) {
2172 $opens = [];
2173 $closes = [];
2174 $groupings = groups_get_user_groups($cm->course, $USER->id);
2175 foreach ($groupings[0] as $groupid) {
2176 $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
2177 if (isset($groupoverride->timeopen)) {
2178 $opens[] = $groupoverride->timeopen;
2180 if (isset($groupoverride->timeclose)) {
2181 $closes[] = $groupoverride->timeclose;
2184 // If there is a user override for a setting, ignore the group override.
2185 if (is_null($override->timeopen) && count($opens)) {
2186 $override->timeopen = min($opens);
2188 if (is_null($override->timeclose) && count($closes)) {
2189 if (in_array(0, $closes)) {
2190 $override->timeclose = 0;
2191 } else {
2192 $override->timeclose = max($closes);
2197 // Populate some other values that can be used in calendar or on dashboard.
2198 if (!is_null($override->timeopen)) {
2199 $cm->override_customdata('timeopen', $override->timeopen);
2201 if (!is_null($override->timeclose)) {
2202 $cm->override_customdata('timeclose', $override->timeclose);
2207 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
2209 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
2210 * @return array $descriptions the array of descriptions for the custom rules.
2212 function mod_quiz_get_completion_active_rule_descriptions($cm) {
2213 // Values will be present in cm_info, and we assume these are up to date.
2214 if (empty($cm->customdata['customcompletionrules'])
2215 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
2216 return [];
2219 $descriptions = [];
2220 $rules = $cm->customdata['customcompletionrules'];
2222 if (!empty($rules['completionpassorattemptsexhausted'])) {
2223 if (!empty($rules['completionpassorattemptsexhausted']['completionattemptsexhausted'])) {
2224 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2226 } else {
2227 // Fallback.
2228 if (!empty($rules['completionattemptsexhausted'])) {
2229 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz');
2233 if (!empty($rules['completionminattempts'])) {
2234 $descriptions[] = get_string('completionminattemptsdesc', 'quiz', $rules['completionminattempts']);
2237 return $descriptions;
2241 * Returns the min and max values for the timestart property of a quiz
2242 * activity event.
2244 * The min and max values will be the timeopen and timeclose properties
2245 * of the quiz, respectively, if they are set.
2247 * If either value isn't set then null will be returned instead to
2248 * indicate that there is no cutoff for that value.
2250 * If the vent has no valid timestart range then [false, false] will
2251 * be returned. This is the case for overriden events.
2253 * A minimum and maximum cutoff return value will look like:
2255 * [1505704373, 'The date must be after this date'],
2256 * [1506741172, 'The date must be before this date']
2259 * @throws \moodle_exception
2260 * @param \calendar_event $event The calendar event to get the time range for
2261 * @param stdClass $quiz The module instance to get the range from
2262 * @return array
2264 function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) {
2265 global $CFG, $DB;
2266 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2268 // Overrides do not have a valid timestart range.
2269 if (quiz_is_overriden_calendar_event($event)) {
2270 return [false, false];
2273 $mindate = null;
2274 $maxdate = null;
2276 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2277 if (!empty($quiz->timeclose)) {
2278 $maxdate = [
2279 $quiz->timeclose,
2280 get_string('openafterclose', 'quiz')
2283 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2284 if (!empty($quiz->timeopen)) {
2285 $mindate = [
2286 $quiz->timeopen,
2287 get_string('closebeforeopen', 'quiz')
2292 return [$mindate, $maxdate];
2296 * This function will update the quiz module according to the
2297 * event that has been modified.
2299 * It will set the timeopen or timeclose value of the quiz instance
2300 * according to the type of event provided.
2302 * @throws \moodle_exception
2303 * @param \calendar_event $event A quiz activity calendar event
2304 * @param \stdClass $quiz A quiz activity instance
2306 function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) {
2307 global $CFG, $DB;
2308 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2310 if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) {
2311 // This isn't an event that we care about so we can ignore it.
2312 return;
2315 $courseid = $event->courseid;
2316 $modulename = $event->modulename;
2317 $instanceid = $event->instance;
2318 $modified = false;
2319 $closedatechanged = false;
2321 // Something weird going on. The event is for a different module so
2322 // we should ignore it.
2323 if ($modulename != 'quiz') {
2324 return;
2327 if ($quiz->id != $instanceid) {
2328 // The provided quiz instance doesn't match the event so
2329 // there is nothing to do here.
2330 return;
2333 // We don't update the activity if it's an override event that has
2334 // been modified.
2335 if (quiz_is_overriden_calendar_event($event)) {
2336 return;
2339 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
2340 $context = context_module::instance($coursemodule->id);
2342 // The user does not have the capability to modify this activity.
2343 if (!has_capability('moodle/course:manageactivities', $context)) {
2344 return;
2347 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) {
2348 // If the event is for the quiz activity opening then we should
2349 // set the start time of the quiz activity to be the new start
2350 // time of the event.
2351 if ($quiz->timeopen != $event->timestart) {
2352 $quiz->timeopen = $event->timestart;
2353 $modified = true;
2355 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) {
2356 // If the event is for the quiz activity closing then we should
2357 // set the end time of the quiz activity to be the new start
2358 // time of the event.
2359 if ($quiz->timeclose != $event->timestart) {
2360 $quiz->timeclose = $event->timestart;
2361 $modified = true;
2362 $closedatechanged = true;
2366 if ($modified) {
2367 $quiz->timemodified = time();
2368 $DB->update_record('quiz', $quiz);
2370 if ($closedatechanged) {
2371 quiz_update_open_attempts(['quizid' => $quiz->id]);
2374 // Delete any previous preview attempts.
2375 quiz_delete_previews($quiz);
2376 quiz_update_events($quiz);
2377 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
2378 $event->trigger();
2383 * Generates the question bank in a fragment output. This allows
2384 * the question bank to be displayed in a modal.
2386 * The only expected argument provided in the $args array is
2387 * 'querystring'. The value should be the list of parameters
2388 * URL encoded and used to build the question bank page.
2390 * The individual list of parameters expected can be found in
2391 * question_build_edit_resources.
2393 * @param array $args The fragment arguments.
2394 * @return string The rendered mform fragment.
2396 function mod_quiz_output_fragment_quiz_question_bank($args) {
2397 global $CFG, $DB, $PAGE;
2398 require_once($CFG->dirroot . '/mod/quiz/locallib.php');
2399 require_once($CFG->dirroot . '/question/editlib.php');
2401 $querystring = preg_replace('/^\?/', '', $args['querystring']);
2402 $params = [];
2403 parse_str($querystring, $params);
2405 // Build the required resources. The $params are all cleaned as
2406 // part of this process.
2407 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
2408 question_build_edit_resources('editq', '/mod/quiz/edit.php', $params, custom_view::DEFAULT_PAGE_SIZE);
2410 // Get the course object and related bits.
2411 $course = get_course($quiz->course);
2412 require_capability('mod/quiz:manage', $contexts->lowest());
2414 // Create quiz question bank view.
2415 $questionbank = new custom_view($contexts, $thispageurl, $course, $cm, $quiz);
2416 $questionbank->set_quiz_has_attempts(quiz_has_attempts($quiz->id));
2418 // Output.
2419 $renderer = $PAGE->get_renderer('mod_quiz', 'edit');
2420 return $renderer->question_bank_contents($questionbank, $pagevars);
2424 * Generates the add random question in a fragment output. This allows the
2425 * form to be rendered in javascript, for example inside a modal.
2427 * The required arguments as keys in the $args array are:
2428 * cat {string} The category and category context ids comma separated.
2429 * addonpage {int} The page id to add this question to.
2430 * returnurl {string} URL to return to after form submission.
2431 * cmid {int} The course module id the questions are being added to.
2433 * @param array $args The fragment arguments.
2434 * @return string The rendered mform fragment.
2436 function mod_quiz_output_fragment_add_random_question_form($args) {
2437 global $CFG;
2439 $contexts = new \core_question\local\bank\question_edit_contexts($args['context']);
2440 $formoptions = [
2441 'contexts' => $contexts,
2442 'cat' => $args['cat']
2444 $formdata = [
2445 'category' => $args['cat'],
2446 'addonpage' => $args['addonpage'],
2447 'returnurl' => $args['returnurl'],
2448 'cmid' => $args['cmid']
2451 $form = new add_random_form(
2452 new \moodle_url('/mod/quiz/addrandom.php'),
2453 $formoptions,
2454 'post',
2456 null,
2457 true,
2458 $formdata
2460 $form->set_data($formdata);
2462 return $form->render();
2466 * Callback to fetch the activity event type lang string.
2468 * @param string $eventtype The event type.
2469 * @return lang_string The event type lang string.
2471 function mod_quiz_core_calendar_get_event_action_string(string $eventtype): string {
2472 $modulename = get_string('modulename', 'quiz');
2474 switch ($eventtype) {
2475 case QUIZ_EVENT_TYPE_OPEN:
2476 $identifier = 'quizeventopens';
2477 break;
2478 case QUIZ_EVENT_TYPE_CLOSE:
2479 $identifier = 'quizeventcloses';
2480 break;
2481 default:
2482 return get_string('requiresaction', 'calendar', $modulename);
2485 return get_string($identifier, 'quiz', $modulename);
2489 * Delete question reference data.
2491 * @param int $quizid The id of quiz.
2493 function quiz_delete_references($quizid): void {
2494 global $DB;
2495 $slots = $DB->get_records('quiz_slots', ['quizid' => $quizid]);
2496 foreach ($slots as $slot) {
2497 $params = [
2498 'itemid' => $slot->id,
2499 'component' => 'mod_quiz',
2500 'questionarea' => 'slot'
2502 // Delete any set references.
2503 $DB->delete_records('question_set_references', $params);
2504 // Delete any references.
2505 $DB->delete_records('question_references', $params);
2510 * Implement the calculate_question_stats callback.
2512 * This enables quiz statistics to be shown in statistics columns in the database.
2514 * @param context $context return the statistics related to this context (which will be a quiz context).
2515 * @return all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null.
2517 function mod_quiz_calculate_question_stats(context $context): ?all_calculated_for_qubaid_condition {
2518 global $CFG;
2519 require_once($CFG->dirroot . '/mod/quiz/report/statistics/report.php');
2520 $cm = get_coursemodule_from_id('quiz', $context->instanceid);
2521 $report = new quiz_statistics_report();
2522 return $report->calculate_questions_stats_for_question_bank($cm->instance, false);