MDL-76897 quiz: move quiz_update_sumgrades into grade_calculator
[moodle.git] / mod / quiz / locallib.php
blob14d6828ed7b7af424265ed120bc6a1b3755c307f
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 used by the quiz module.
20 * This contains functions that are called from within the quiz module only
21 * Functions that are also called by core Moodle are in {@link lib.php}
22 * This script also loads the code in {@link questionlib.php} which holds
23 * the module-indpendent code for handling questions and which in turn
24 * initialises all the questiontype classes.
26 * @package mod_quiz
27 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 require_once($CFG->dirroot . '/mod/quiz/lib.php');
34 require_once($CFG->libdir . '/completionlib.php');
35 require_once($CFG->libdir . '/filelib.php');
36 require_once($CFG->libdir . '/questionlib.php');
38 use mod_quiz\access_manager;
39 use mod_quiz\question\bank\qbank_helper;
40 use mod_quiz\question\display_options;
41 use mod_quiz\quiz_attempt;
42 use mod_quiz\quiz_settings;
44 /**
45 * @var int We show the countdown timer if there is less than this amount of time left before the
46 * the quiz close date. (1 hour)
48 define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
50 /**
51 * @var int If there are fewer than this many seconds left when the student submits
52 * a page of the quiz, then do not take them to the next page of the quiz. Instead
53 * close the quiz immediately.
55 define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
57 /**
58 * @var int We show no image when user selects No image from dropdown menu in quiz settings.
60 define('QUIZ_SHOWIMAGE_NONE', 0);
62 /**
63 * @var int We show small image when user selects small image from dropdown menu in quiz settings.
65 define('QUIZ_SHOWIMAGE_SMALL', 1);
67 /**
68 * @var int We show Large image when user selects Large image from dropdown menu in quiz settings.
70 define('QUIZ_SHOWIMAGE_LARGE', 2);
73 // Functions related to attempts ///////////////////////////////////////////////
75 /**
76 * Creates an object to represent a new attempt at a quiz
78 * Creates an attempt object to represent an attempt at the quiz by the current
79 * user starting at the current time. The ->id field is not set. The object is
80 * NOT written to the database.
82 * @param quiz_settings $quizobj the quiz object to create an attempt for.
83 * @param int $attemptnumber the sequence number for the attempt.
84 * @param stdClass|false $lastattempt the previous attempt by this user, if any. Only needed
85 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
86 * @param int $timenow the time the attempt was started at.
87 * @param bool $ispreview whether this new attempt is a preview.
88 * @param int|null $userid the id of the user attempting this quiz.
90 * @return stdClass the newly created attempt object.
92 function quiz_create_attempt(quiz_settings $quizobj, $attemptnumber, $lastattempt, $timenow, $ispreview = false, $userid = null) {
93 global $USER;
95 if ($userid === null) {
96 $userid = $USER->id;
99 $quiz = $quizobj->get_quiz();
100 if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
101 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
102 new moodle_url('/mod/quiz/view.php', ['q' => $quiz->id]),
103 ['grade' => quiz_format_grade($quiz, $quiz->grade)]);
106 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
107 // We are not building on last attempt so create a new attempt.
108 $attempt = new stdClass();
109 $attempt->quiz = $quiz->id;
110 $attempt->userid = $userid;
111 $attempt->preview = 0;
112 $attempt->layout = '';
113 } else {
114 // Build on last attempt.
115 if (empty($lastattempt)) {
116 throw new \moodle_exception('cannotfindprevattempt', 'quiz');
118 $attempt = $lastattempt;
121 $attempt->attempt = $attemptnumber;
122 $attempt->timestart = $timenow;
123 $attempt->timefinish = 0;
124 $attempt->timemodified = $timenow;
125 $attempt->timemodifiedoffline = 0;
126 $attempt->state = quiz_attempt::IN_PROGRESS;
127 $attempt->currentpage = 0;
128 $attempt->sumgrades = null;
129 $attempt->gradednotificationsenttime = null;
131 // If this is a preview, mark it as such.
132 if ($ispreview) {
133 $attempt->preview = 1;
136 $timeclose = $quizobj->get_access_manager($timenow)->get_end_time($attempt);
137 if ($timeclose === false || $ispreview) {
138 $attempt->timecheckstate = null;
139 } else {
140 $attempt->timecheckstate = $timeclose;
143 return $attempt;
146 * Start a normal, new, quiz attempt.
148 * @param quiz_settings $quizobj the quiz object to start an attempt for.
149 * @param question_usage_by_activity $quba
150 * @param stdClass $attempt
151 * @param integer $attemptnumber starting from 1
152 * @param integer $timenow the attempt start time
153 * @param array $questionids slot number => question id. Used for random questions, to force the choice
154 * of a particular actual question. Intended for testing purposes only.
155 * @param array $forcedvariantsbyslot slot number => variant. Used for questions with variants,
156 * to force the choice of a particular variant. Intended for testing
157 * purposes only.
158 * @return stdClass modified attempt object
160 function quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,
161 $questionids = [], $forcedvariantsbyslot = []) {
163 // Usages for this user's previous quiz attempts.
164 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
165 $quizobj->get_quizid(), $attempt->userid);
167 // Fully load all the questions in this quiz.
168 $quizobj->preload_questions();
169 $quizobj->load_questions();
171 // First load all the non-random questions.
172 $randomfound = false;
173 $slot = 0;
174 $questions = [];
175 $maxmark = [];
176 $page = [];
177 foreach ($quizobj->get_questions() as $questiondata) {
178 $slot += 1;
179 $maxmark[$slot] = $questiondata->maxmark;
180 $page[$slot] = $questiondata->page;
181 if ($questiondata->qtype == 'random') {
182 $randomfound = true;
183 continue;
185 if (!$quizobj->get_quiz()->shuffleanswers) {
186 $questiondata->options->shuffleanswers = false;
188 $questions[$slot] = question_bank::make_question($questiondata);
191 // Then find a question to go in place of each random question.
192 if ($randomfound) {
193 $slot = 0;
194 $usedquestionids = [];
195 foreach ($questions as $question) {
196 if ($question->id && isset($usedquestions[$question->id])) {
197 $usedquestionids[$question->id] += 1;
198 } else {
199 $usedquestionids[$question->id] = 1;
202 $randomloader = new \core_question\local\bank\random_question_loader($qubaids, $usedquestionids);
204 foreach ($quizobj->get_questions() as $questiondata) {
205 $slot += 1;
206 if ($questiondata->qtype != 'random') {
207 continue;
210 $tagids = qbank_helper::get_tag_ids_for_slot($questiondata);
212 // Deal with fixed random choices for testing.
213 if (isset($questionids[$quba->next_slot_number()])) {
214 if ($randomloader->is_question_available($questiondata->category,
215 (bool) $questiondata->questiontext, $questionids[$quba->next_slot_number()], $tagids)) {
216 $questions[$slot] = question_bank::load_question(
217 $questionids[$quba->next_slot_number()], $quizobj->get_quiz()->shuffleanswers);
218 continue;
219 } else {
220 throw new coding_exception('Forced question id not available.');
224 // Normal case, pick one at random.
225 $questionid = $randomloader->get_next_question_id($questiondata->category,
226 $questiondata->randomrecurse, $tagids);
227 if ($questionid === null) {
228 throw new moodle_exception('notenoughrandomquestions', 'quiz',
229 $quizobj->view_url(), $questiondata);
232 $questions[$slot] = question_bank::load_question($questionid,
233 $quizobj->get_quiz()->shuffleanswers);
237 // Finally add them all to the usage.
238 ksort($questions);
239 foreach ($questions as $slot => $question) {
240 $newslot = $quba->add_question($question, $maxmark[$slot]);
241 if ($newslot != $slot) {
242 throw new coding_exception('Slot numbers have got confused.');
246 // Start all the questions.
247 $variantstrategy = new core_question\engine\variants\least_used_strategy($quba, $qubaids);
249 if (!empty($forcedvariantsbyslot)) {
250 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
251 $forcedvariantsbyslot, $quba);
252 $variantstrategy = new question_variant_forced_choices_selection_strategy(
253 $forcedvariantsbyseed, $variantstrategy);
256 $quba->start_all_questions($variantstrategy, $timenow, $attempt->userid);
258 // Work out the attempt layout.
259 $sections = $quizobj->get_sections();
260 foreach ($sections as $i => $section) {
261 if (isset($sections[$i + 1])) {
262 $sections[$i]->lastslot = $sections[$i + 1]->firstslot - 1;
263 } else {
264 $sections[$i]->lastslot = count($questions);
268 $layout = [];
269 foreach ($sections as $section) {
270 if ($section->shufflequestions) {
271 $questionsinthissection = [];
272 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
273 $questionsinthissection[] = $slot;
275 shuffle($questionsinthissection);
276 $questionsonthispage = 0;
277 foreach ($questionsinthissection as $slot) {
278 if ($questionsonthispage && $questionsonthispage == $quizobj->get_quiz()->questionsperpage) {
279 $layout[] = 0;
280 $questionsonthispage = 0;
282 $layout[] = $slot;
283 $questionsonthispage += 1;
286 } else {
287 $currentpage = $page[$section->firstslot];
288 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
289 if ($currentpage !== null && $page[$slot] != $currentpage) {
290 $layout[] = 0;
292 $layout[] = $slot;
293 $currentpage = $page[$slot];
297 // Each section ends with a page break.
298 $layout[] = 0;
300 $attempt->layout = implode(',', $layout);
302 return $attempt;
306 * Start a subsequent new attempt, in each attempt builds on last mode.
308 * @param question_usage_by_activity $quba this question usage
309 * @param stdClass $attempt this attempt
310 * @param stdClass $lastattempt last attempt
311 * @return stdClass modified attempt object
314 function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
315 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
317 $oldnumberstonew = [];
318 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
319 $newslot = $quba->add_question($oldqa->get_question(false), $oldqa->get_max_mark());
321 $quba->start_question_based_on($newslot, $oldqa);
323 $oldnumberstonew[$oldslot] = $newslot;
326 // Update attempt layout.
327 $newlayout = [];
328 foreach (explode(',', $lastattempt->layout) as $oldslot) {
329 if ($oldslot != 0) {
330 $newlayout[] = $oldnumberstonew[$oldslot];
331 } else {
332 $newlayout[] = 0;
335 $attempt->layout = implode(',', $newlayout);
336 return $attempt;
340 * The save started question usage and quiz attempt in db and log the started attempt.
342 * @param quiz_settings $quizobj
343 * @param question_usage_by_activity $quba
344 * @param stdClass $attempt
345 * @return stdClass attempt object with uniqueid and id set.
347 function quiz_attempt_save_started($quizobj, $quba, $attempt) {
348 global $DB;
349 // Save the attempt in the database.
350 question_engine::save_questions_usage_by_activity($quba);
351 $attempt->uniqueid = $quba->get_id();
352 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
354 // Params used by the events below.
355 $params = [
356 'objectid' => $attempt->id,
357 'relateduserid' => $attempt->userid,
358 'courseid' => $quizobj->get_courseid(),
359 'context' => $quizobj->get_context()
361 // Decide which event we are using.
362 if ($attempt->preview) {
363 $params['other'] = [
364 'quizid' => $quizobj->get_quizid()
366 $event = \mod_quiz\event\attempt_preview_started::create($params);
367 } else {
368 $event = \mod_quiz\event\attempt_started::create($params);
372 // Trigger the event.
373 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
374 $event->add_record_snapshot('quiz_attempts', $attempt);
375 $event->trigger();
377 return $attempt;
381 * Returns an unfinished attempt (if there is one) for the given
382 * user on the given quiz. This function does not return preview attempts.
384 * @param int $quizid the id of the quiz.
385 * @param int $userid the id of the user.
387 * @return mixed the unfinished attempt if there is one, false if not.
389 function quiz_get_user_attempt_unfinished($quizid, $userid) {
390 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
391 if ($attempts) {
392 return array_shift($attempts);
393 } else {
394 return false;
399 * Delete a quiz attempt.
400 * @param mixed $attempt an integer attempt id or an attempt object
401 * (row of the quiz_attempts table).
402 * @param stdClass $quiz the quiz object.
404 function quiz_delete_attempt($attempt, $quiz) {
405 global $DB;
406 if (is_numeric($attempt)) {
407 if (!$attempt = $DB->get_record('quiz_attempts', ['id' => $attempt])) {
408 return;
412 if ($attempt->quiz != $quiz->id) {
413 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
414 "but was passed quiz $quiz->id.");
415 return;
418 if (!isset($quiz->cmid)) {
419 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
420 $quiz->cmid = $cm->id;
423 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
424 $DB->delete_records('quiz_attempts', ['id' => $attempt->id]);
426 // Log the deletion of the attempt if not a preview.
427 if (!$attempt->preview) {
428 $params = [
429 'objectid' => $attempt->id,
430 'relateduserid' => $attempt->userid,
431 'context' => context_module::instance($quiz->cmid),
432 'other' => [
433 'quizid' => $quiz->id
436 $event = \mod_quiz\event\attempt_deleted::create($params);
437 $event->add_record_snapshot('quiz_attempts', $attempt);
438 $event->trigger();
441 // Search quiz_attempts for other instances by this user.
442 // If none, then delete record for this quiz, this user from quiz_grades
443 // else recalculate best grade.
444 $userid = $attempt->userid;
445 if (!$DB->record_exists('quiz_attempts', ['userid' => $userid, 'quiz' => $quiz->id])) {
446 $DB->delete_records('quiz_grades', ['userid' => $userid, 'quiz' => $quiz->id]);
447 } else {
448 quiz_save_best_grade($quiz, $userid);
451 quiz_update_grades($quiz, $userid);
455 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
456 * to one user.
457 * @param stdClass $quiz the quiz object.
458 * @param int $userid (optional) if given, only delete the previews belonging to this user.
460 function quiz_delete_previews($quiz, $userid = null) {
461 global $DB;
462 $conditions = ['quiz' => $quiz->id, 'preview' => 1];
463 if (!empty($userid)) {
464 $conditions['userid'] = $userid;
466 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
467 foreach ($previewattempts as $attempt) {
468 quiz_delete_attempt($attempt, $quiz);
473 * @param int $quizid The quiz id.
474 * @return bool whether this quiz has any (non-preview) attempts.
476 function quiz_has_attempts($quizid) {
477 global $DB;
478 return $DB->record_exists('quiz_attempts', ['quiz' => $quizid, 'preview' => 0]);
481 // Functions to do with quiz layout and pages //////////////////////////////////
484 * Repaginate the questions in a quiz
485 * @param int $quizid the id of the quiz to repaginate.
486 * @param int $slotsperpage number of items to put on each page. 0 means unlimited.
488 function quiz_repaginate_questions($quizid, $slotsperpage) {
489 global $DB;
490 $trans = $DB->start_delegated_transaction();
492 $sections = $DB->get_records('quiz_sections', ['quizid' => $quizid], 'firstslot ASC');
493 $firstslots = [];
494 foreach ($sections as $section) {
495 if ((int)$section->firstslot === 1) {
496 continue;
498 $firstslots[] = $section->firstslot;
501 $slots = $DB->get_records('quiz_slots', ['quizid' => $quizid],
502 'slot');
503 $currentpage = 1;
504 $slotsonthispage = 0;
505 foreach ($slots as $slot) {
506 if (($firstslots && in_array($slot->slot, $firstslots)) ||
507 ($slotsonthispage && $slotsonthispage == $slotsperpage)) {
508 $currentpage += 1;
509 $slotsonthispage = 0;
511 if ($slot->page != $currentpage) {
512 $DB->set_field('quiz_slots', 'page', $currentpage, ['id' => $slot->id]);
514 $slotsonthispage += 1;
517 $trans->allow_commit();
519 // Log quiz re-paginated event.
520 $cm = get_coursemodule_from_instance('quiz', $quizid);
521 $event = \mod_quiz\event\quiz_repaginated::create([
522 'context' => \context_module::instance($cm->id),
523 'objectid' => $quizid,
524 'other' => [
525 'slotsperpage' => $slotsperpage
528 $event->trigger();
532 // Functions to do with quiz grades ////////////////////////////////////////////
533 // Note a lot of logic related to this is now in the grade_calculator class.
536 * Convert the raw grade stored in $attempt into a grade out of the maximum
537 * grade for this quiz.
539 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
540 * @param stdClass $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
541 * @param bool|string $format whether to format the results for display
542 * or 'question' to format a question grade (different number of decimal places.
543 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
544 * if the $grade is null.
546 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
547 if (is_null($rawgrade)) {
548 $grade = null;
549 } else if ($quiz->sumgrades >= 0.000005) {
550 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
551 } else {
552 $grade = 0;
554 if ($format === 'question') {
555 $grade = quiz_format_question_grade($quiz, $grade);
556 } else if ($format) {
557 $grade = quiz_format_grade($quiz, $grade);
559 return $grade;
563 * Get the feedback object for this grade on this quiz.
565 * @param float $grade a grade on this quiz.
566 * @param stdClass $quiz the quiz settings.
567 * @return false|stdClass the record object or false if there is not feedback for the given grade
568 * @since Moodle 3.1
570 function quiz_feedback_record_for_grade($grade, $quiz) {
571 global $DB;
573 // With CBM etc, it is possible to get -ve grades, which would then not match
574 // any feedback. Therefore, we replace -ve grades with 0.
575 $grade = max($grade, 0);
577 $feedback = $DB->get_record_select('quiz_feedback',
578 'quizid = ? AND mingrade <= ? AND ? < maxgrade', [$quiz->id, $grade, $grade]);
580 return $feedback;
584 * Get the feedback text that should be show to a student who
585 * got this grade on this quiz. The feedback is processed ready for diplay.
587 * @param float $grade a grade on this quiz.
588 * @param stdClass $quiz the quiz settings.
589 * @param context_module $context the quiz context.
590 * @return string the comment that corresponds to this grade (empty string if there is not one.
592 function quiz_feedback_for_grade($grade, $quiz, $context) {
594 if (is_null($grade)) {
595 return '';
598 $feedback = quiz_feedback_record_for_grade($grade, $quiz);
600 if (empty($feedback->feedbacktext)) {
601 return '';
604 // Clean the text, ready for display.
605 $formatoptions = new stdClass();
606 $formatoptions->noclean = true;
607 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
608 $context->id, 'mod_quiz', 'feedback', $feedback->id);
609 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
611 return $feedbacktext;
615 * @param stdClass $quiz the quiz database row.
616 * @return bool Whether this quiz has any non-blank feedback text.
618 function quiz_has_feedback($quiz) {
619 global $DB;
620 static $cache = [];
621 if (!array_key_exists($quiz->id, $cache)) {
622 $cache[$quiz->id] = quiz_has_grades($quiz) &&
623 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
624 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
625 [$quiz->id]);
627 return $cache[$quiz->id];
631 * Update the sumgrades field of the attempts at a quiz.
633 * @param stdClass $quiz a quiz.
635 function quiz_update_all_attempt_sumgrades($quiz) {
636 global $DB;
637 $dm = new question_engine_data_mapper();
638 $timenow = time();
640 $sql = "UPDATE {quiz_attempts}
642 timemodified = :timenow,
643 sumgrades = (
644 {$dm->sum_usage_marks_subquery('uniqueid')}
646 WHERE quiz = :quizid AND state = :finishedstate";
647 $DB->execute($sql, ['timenow' => $timenow, 'quizid' => $quiz->id,
648 'finishedstate' => quiz_attempt::FINISHED]);
652 * The quiz grade is the maximum that student's results are marked out of. When it
653 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
654 * rescaled. After calling this function, you probably need to call
655 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
656 * quiz_update_grades.
658 * @param float $newgrade the new maximum grade for the quiz.
659 * @param stdClass $quiz the quiz we are updating. Passed by reference so its
660 * grade field can be updated too.
661 * @return bool indicating success or failure.
663 function quiz_set_grade($newgrade, $quiz) {
664 global $DB;
665 // This is potentially expensive, so only do it if necessary.
666 if (abs($quiz->grade - $newgrade) < 1e-7) {
667 // Nothing to do.
668 return true;
671 $oldgrade = $quiz->grade;
672 $quiz->grade = $newgrade;
674 // Use a transaction, so that on those databases that support it, this is safer.
675 $transaction = $DB->start_delegated_transaction();
677 // Update the quiz table.
678 $DB->set_field('quiz', 'grade', $newgrade, ['id' => $quiz->instance]);
680 if ($oldgrade < 1) {
681 // If the old grade was zero, we cannot rescale, we have to recompute.
682 // We also recompute if the old grade was too small to avoid underflow problems.
683 quiz_update_all_final_grades($quiz);
685 } else {
686 // We can rescale the grades efficiently.
687 $timemodified = time();
688 $DB->execute("
689 UPDATE {quiz_grades}
690 SET grade = ? * grade, timemodified = ?
691 WHERE quiz = ?
692 ", [$newgrade / $oldgrade, $timemodified, $quiz->id]);
695 if ($oldgrade > 1e-7) {
696 // Update the quiz_feedback table.
697 $factor = $newgrade/$oldgrade;
698 $DB->execute("
699 UPDATE {quiz_feedback}
700 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
701 WHERE quizid = ?
702 ", [$factor, $factor, $quiz->id]);
705 // Update grade item and send all grades to gradebook.
706 quiz_grade_item_update($quiz);
707 quiz_update_grades($quiz);
709 $transaction->allow_commit();
711 // Log quiz grade updated event.
712 // We use $num + 0 as a trick to remove the useless 0 digits from decimals.
713 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
714 $event = \mod_quiz\event\quiz_grade_updated::create([
715 'context' => \context_module::instance($cm->id),
716 'objectid' => $quiz->id,
717 'other' => [
718 'oldgrade' => $oldgrade + 0,
719 'newgrade' => $newgrade + 0
722 $event->trigger();
723 return true;
727 * Save the overall grade for a user at a quiz in the quiz_grades table
729 * @param stdClass $quiz The quiz for which the best grade is to be calculated and then saved.
730 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
731 * @param array $attempts The attempts of this user. Useful if you are
732 * looping through many users. Attempts can be fetched in one master query to
733 * avoid repeated querying.
734 * @return bool Indicates success or failure.
736 function quiz_save_best_grade($quiz, $userid = null, $attempts = []) {
737 global $DB, $OUTPUT, $USER;
739 if (empty($userid)) {
740 $userid = $USER->id;
743 if (!$attempts) {
744 // Get all the attempts made by the user.
745 $attempts = quiz_get_user_attempts($quiz->id, $userid);
748 // Calculate the best grade.
749 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
750 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
752 // Save the best grade in the database.
753 if (is_null($bestgrade)) {
754 $DB->delete_records('quiz_grades', ['quiz' => $quiz->id, 'userid' => $userid]);
756 } else if ($grade = $DB->get_record('quiz_grades',
757 ['quiz' => $quiz->id, 'userid' => $userid])) {
758 $grade->grade = $bestgrade;
759 $grade->timemodified = time();
760 $DB->update_record('quiz_grades', $grade);
762 } else {
763 $grade = new stdClass();
764 $grade->quiz = $quiz->id;
765 $grade->userid = $userid;
766 $grade->grade = $bestgrade;
767 $grade->timemodified = time();
768 $DB->insert_record('quiz_grades', $grade);
771 quiz_update_grades($quiz, $userid);
775 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
777 * @param stdClass $quiz the quiz settings object.
778 * @param array $attempts an array of all the user's attempts at this quiz in order.
779 * @return float the overall grade
781 function quiz_calculate_best_grade($quiz, $attempts) {
783 switch ($quiz->grademethod) {
785 case QUIZ_ATTEMPTFIRST:
786 $firstattempt = reset($attempts);
787 return $firstattempt->sumgrades;
789 case QUIZ_ATTEMPTLAST:
790 $lastattempt = end($attempts);
791 return $lastattempt->sumgrades;
793 case QUIZ_GRADEAVERAGE:
794 $sum = 0;
795 $count = 0;
796 foreach ($attempts as $attempt) {
797 if (!is_null($attempt->sumgrades)) {
798 $sum += $attempt->sumgrades;
799 $count++;
802 if ($count == 0) {
803 return null;
805 return $sum / $count;
807 case QUIZ_GRADEHIGHEST:
808 default:
809 $max = null;
810 foreach ($attempts as $attempt) {
811 if ($attempt->sumgrades > $max) {
812 $max = $attempt->sumgrades;
815 return $max;
820 * Update the final grade at this quiz for all students.
822 * This function is equivalent to calling quiz_save_best_grade for all
823 * users, but much more efficient.
825 * @param stdClass $quiz the quiz settings.
827 function quiz_update_all_final_grades($quiz) {
828 global $DB;
830 if (!$quiz->sumgrades) {
831 return;
834 $param = ['iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED];
835 $firstlastattemptjoin = "JOIN (
836 SELECT
837 iquiza.userid,
838 MIN(attempt) AS firstattempt,
839 MAX(attempt) AS lastattempt
841 FROM {quiz_attempts} iquiza
843 WHERE
844 iquiza.state = :istatefinished AND
845 iquiza.preview = 0 AND
846 iquiza.quiz = :iquizid
848 GROUP BY iquiza.userid
849 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
851 switch ($quiz->grademethod) {
852 case QUIZ_ATTEMPTFIRST:
853 // Because of the where clause, there will only be one row, but we
854 // must still use an aggregate function.
855 $select = 'MAX(quiza.sumgrades)';
856 $join = $firstlastattemptjoin;
857 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
858 break;
860 case QUIZ_ATTEMPTLAST:
861 // Because of the where clause, there will only be one row, but we
862 // must still use an aggregate function.
863 $select = 'MAX(quiza.sumgrades)';
864 $join = $firstlastattemptjoin;
865 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
866 break;
868 case QUIZ_GRADEAVERAGE:
869 $select = 'AVG(quiza.sumgrades)';
870 $join = '';
871 $where = '';
872 break;
874 default:
875 case QUIZ_GRADEHIGHEST:
876 $select = 'MAX(quiza.sumgrades)';
877 $join = '';
878 $where = '';
879 break;
882 if ($quiz->sumgrades >= 0.000005) {
883 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
884 } else {
885 $finalgrade = '0';
887 $param['quizid'] = $quiz->id;
888 $param['quizid2'] = $quiz->id;
889 $param['quizid3'] = $quiz->id;
890 $param['quizid4'] = $quiz->id;
891 $param['statefinished'] = quiz_attempt::FINISHED;
892 $param['statefinished2'] = quiz_attempt::FINISHED;
893 $finalgradesubquery = "
894 SELECT quiza.userid, $finalgrade AS newgrade
895 FROM {quiz_attempts} quiza
896 $join
897 WHERE
898 $where
899 quiza.state = :statefinished AND
900 quiza.preview = 0 AND
901 quiza.quiz = :quizid3
902 GROUP BY quiza.userid";
904 $changedgrades = $DB->get_records_sql("
905 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
907 FROM (
908 SELECT userid
909 FROM {quiz_grades} qg
910 WHERE quiz = :quizid
911 UNION
912 SELECT DISTINCT userid
913 FROM {quiz_attempts} quiza2
914 WHERE
915 quiza2.state = :statefinished2 AND
916 quiza2.preview = 0 AND
917 quiza2.quiz = :quizid2
918 ) users
920 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
922 LEFT JOIN (
923 $finalgradesubquery
924 ) newgrades ON newgrades.userid = users.userid
926 WHERE
927 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
928 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
929 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
930 // The mess on the previous line is detecting where the value is
931 // NULL in one column, and NOT NULL in the other, but SQL does
932 // not have an XOR operator, and MS SQL server can't cope with
933 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
934 $param);
936 $timenow = time();
937 $todelete = [];
938 foreach ($changedgrades as $changedgrade) {
940 if (is_null($changedgrade->newgrade)) {
941 $todelete[] = $changedgrade->userid;
943 } else if (is_null($changedgrade->grade)) {
944 $toinsert = new stdClass();
945 $toinsert->quiz = $quiz->id;
946 $toinsert->userid = $changedgrade->userid;
947 $toinsert->timemodified = $timenow;
948 $toinsert->grade = $changedgrade->newgrade;
949 $DB->insert_record('quiz_grades', $toinsert);
951 } else {
952 $toupdate = new stdClass();
953 $toupdate->id = $changedgrade->id;
954 $toupdate->grade = $changedgrade->newgrade;
955 $toupdate->timemodified = $timenow;
956 $DB->update_record('quiz_grades', $toupdate);
960 if (!empty($todelete)) {
961 list($test, $params) = $DB->get_in_or_equal($todelete);
962 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
963 array_merge([$quiz->id], $params));
968 * Return summary of the number of settings override that exist.
970 * To get a nice display of this, see the quiz_override_summary_links()
971 * quiz renderer method.
973 * @param stdClass $quiz the quiz settings. Only $quiz->id is used at the moment.
974 * @param stdClass|cm_info $cm the cm object. Only $cm->course, $cm->groupmode and
975 * $cm->groupingid fields are used at the moment.
976 * @param int $currentgroup if there is a concept of current group where this method is being called
977 * (e.g. a report) pass it in here. Default 0 which means no current group.
978 * @return array like 'group' => 3, 'user' => 12] where 3 is the number of group overrides,
979 * and 12 is the number of user ones.
981 function quiz_override_summary(stdClass $quiz, stdClass $cm, int $currentgroup = 0): array {
982 global $DB;
984 if ($currentgroup) {
985 // Currently only interested in one group.
986 $groupcount = $DB->count_records('quiz_overrides', ['quiz' => $quiz->id, 'groupid' => $currentgroup]);
987 $usercount = $DB->count_records_sql("
988 SELECT COUNT(1)
989 FROM {quiz_overrides} o
990 JOIN {groups_members} gm ON o.userid = gm.userid
991 WHERE o.quiz = ?
992 AND gm.groupid = ?
993 ", [$quiz->id, $currentgroup]);
994 return ['group' => $groupcount, 'user' => $usercount, 'mode' => 'onegroup'];
997 $quizgroupmode = groups_get_activity_groupmode($cm);
998 $accessallgroups = ($quizgroupmode == NOGROUPS) ||
999 has_capability('moodle/site:accessallgroups', context_module::instance($cm->id));
1001 if ($accessallgroups) {
1002 // User can see all groups.
1003 $groupcount = $DB->count_records_select('quiz_overrides',
1004 'quiz = ? AND groupid IS NOT NULL', [$quiz->id]);
1005 $usercount = $DB->count_records_select('quiz_overrides',
1006 'quiz = ? AND userid IS NOT NULL', [$quiz->id]);
1007 return ['group' => $groupcount, 'user' => $usercount, 'mode' => 'allgroups'];
1009 } else {
1010 // User can only see groups they are in.
1011 $groups = groups_get_activity_allowed_groups($cm);
1012 if (!$groups) {
1013 return ['group' => 0, 'user' => 0, 'mode' => 'somegroups'];
1016 list($groupidtest, $params) = $DB->get_in_or_equal(array_keys($groups));
1017 $params[] = $quiz->id;
1019 $groupcount = $DB->count_records_select('quiz_overrides',
1020 "groupid $groupidtest AND quiz = ?", $params);
1021 $usercount = $DB->count_records_sql("
1022 SELECT COUNT(1)
1023 FROM {quiz_overrides} o
1024 JOIN {groups_members} gm ON o.userid = gm.userid
1025 WHERE gm.groupid $groupidtest
1026 AND o.quiz = ?
1027 ", $params);
1029 return ['group' => $groupcount, 'user' => $usercount, 'mode' => 'somegroups'];
1034 * Efficiently update check state time on all open attempts
1036 * @param array $conditions optional restrictions on which attempts to update
1037 * Allowed conditions:
1038 * courseid => (array|int) attempts in given course(s)
1039 * userid => (array|int) attempts for given user(s)
1040 * quizid => (array|int) attempts in given quiz(s)
1041 * groupid => (array|int) quizzes with some override for given group(s)
1044 function quiz_update_open_attempts(array $conditions) {
1045 global $DB;
1047 foreach ($conditions as &$value) {
1048 if (!is_array($value)) {
1049 $value = [$value];
1053 $params = [];
1054 $wheres = ["quiza.state IN ('inprogress', 'overdue')"];
1055 $iwheres = ["iquiza.state IN ('inprogress', 'overdue')"];
1057 if (isset($conditions['courseid'])) {
1058 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
1059 $params = array_merge($params, $inparams);
1060 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
1061 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
1062 $params = array_merge($params, $inparams);
1063 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
1066 if (isset($conditions['userid'])) {
1067 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
1068 $params = array_merge($params, $inparams);
1069 $wheres[] = "quiza.userid $incond";
1070 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
1071 $params = array_merge($params, $inparams);
1072 $iwheres[] = "iquiza.userid $incond";
1075 if (isset($conditions['quizid'])) {
1076 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
1077 $params = array_merge($params, $inparams);
1078 $wheres[] = "quiza.quiz $incond";
1079 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
1080 $params = array_merge($params, $inparams);
1081 $iwheres[] = "iquiza.quiz $incond";
1084 if (isset($conditions['groupid'])) {
1085 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
1086 $params = array_merge($params, $inparams);
1087 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1088 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
1089 $params = array_merge($params, $inparams);
1090 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1093 // SQL to compute timeclose and timelimit for each attempt:
1094 $quizausersql = quiz_get_attempt_usertime_sql(
1095 implode("\n AND ", $iwheres));
1097 // SQL to compute the new timecheckstate
1098 $timecheckstatesql = "
1099 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
1100 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
1101 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
1102 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
1103 ELSE quizauser.usertimeclose END +
1104 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
1106 // SQL to select which attempts to process
1107 $attemptselect = implode("\n AND ", $wheres);
1110 * Each database handles updates with inner joins differently:
1111 * - mysql does not allow a FROM clause
1112 * - postgres and mssql allow FROM but handle table aliases differently
1113 * - oracle requires a subquery
1115 * Different code for each database.
1118 $dbfamily = $DB->get_dbfamily();
1119 if ($dbfamily == 'mysql') {
1120 $updatesql = "UPDATE {quiz_attempts} quiza
1121 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1122 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1123 SET quiza.timecheckstate = $timecheckstatesql
1124 WHERE $attemptselect";
1125 } else if ($dbfamily == 'postgres') {
1126 $updatesql = "UPDATE {quiz_attempts} quiza
1127 SET timecheckstate = $timecheckstatesql
1128 FROM {quiz} quiz, ( $quizausersql ) quizauser
1129 WHERE quiz.id = quiza.quiz
1130 AND quizauser.id = quiza.id
1131 AND $attemptselect";
1132 } else if ($dbfamily == 'mssql') {
1133 $updatesql = "UPDATE quiza
1134 SET timecheckstate = $timecheckstatesql
1135 FROM {quiz_attempts} quiza
1136 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1137 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1138 WHERE $attemptselect";
1139 } else {
1140 // oracle, sqlite and others
1141 $updatesql = "UPDATE {quiz_attempts} quiza
1142 SET timecheckstate = (
1143 SELECT $timecheckstatesql
1144 FROM {quiz} quiz, ( $quizausersql ) quizauser
1145 WHERE quiz.id = quiza.quiz
1146 AND quizauser.id = quiza.id
1148 WHERE $attemptselect";
1151 $DB->execute($updatesql, $params);
1155 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
1156 * The query used herein is very similar to the one in function quiz_get_user_timeclose, so, in case you
1157 * would change either one of them, make sure to apply your changes to both.
1159 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1160 * for performance. These can use the table alias iquiza for the quiz attempts table.
1161 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
1163 function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1164 if ($redundantwhereclauses) {
1165 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1167 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1168 // any other group override
1169 $quizausersql = "
1170 SELECT iquiza.id,
1171 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1172 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1174 FROM {quiz_attempts} iquiza
1175 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1176 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1177 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1178 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1179 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1180 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1181 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
1182 $redundantwhereclauses
1183 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1184 return $quizausersql;
1188 * Return the attempt with the best grade for a quiz
1190 * Which attempt is the best depends on $quiz->grademethod. If the grade
1191 * method is GRADEAVERAGE then this function simply returns the last attempt.
1192 * @return stdClass The attempt with the best grade
1193 * @param stdClass $quiz The quiz for which the best grade is to be calculated
1194 * @param array $attempts An array of all the attempts of the user at the quiz
1196 function quiz_calculate_best_attempt($quiz, $attempts) {
1198 switch ($quiz->grademethod) {
1200 case QUIZ_ATTEMPTFIRST:
1201 foreach ($attempts as $attempt) {
1202 return $attempt;
1204 break;
1206 case QUIZ_GRADEAVERAGE: // We need to do something with it.
1207 case QUIZ_ATTEMPTLAST:
1208 foreach ($attempts as $attempt) {
1209 $final = $attempt;
1211 return $final;
1213 default:
1214 case QUIZ_GRADEHIGHEST:
1215 $max = -1;
1216 foreach ($attempts as $attempt) {
1217 if ($attempt->sumgrades > $max) {
1218 $max = $attempt->sumgrades;
1219 $maxattempt = $attempt;
1222 return $maxattempt;
1227 * @return array int => lang string the options for calculating the quiz grade
1228 * from the individual attempt grades.
1230 function quiz_get_grading_options() {
1231 return [
1232 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1233 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1234 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1235 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1240 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1241 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
1242 * @return the lang string for that option.
1244 function quiz_get_grading_option_name($option) {
1245 $strings = quiz_get_grading_options();
1246 return $strings[$option];
1250 * @return array string => lang string the options for handling overdue quiz
1251 * attempts.
1253 function quiz_get_overdue_handling_options() {
1254 return [
1255 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1256 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1257 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1262 * Get the choices for what size user picture to show.
1263 * @return array string => lang string the options for whether to display the user's picture.
1265 function quiz_get_user_image_options() {
1266 return [
1267 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
1268 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
1269 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'),
1274 * Return an user's timeclose for all quizzes in a course, hereby taking into account group and user overrides.
1276 * @param int $courseid the course id.
1277 * @return stdClass An object with of all quizids and close unixdates in this course, taking into account the most lenient
1278 * overrides, if existing and 0 if no close date is set.
1280 function quiz_get_user_timeclose($courseid) {
1281 global $DB, $USER;
1283 // For teacher and manager/admins return timeclose.
1284 if (has_capability('moodle/course:update', context_course::instance($courseid))) {
1285 $sql = "SELECT quiz.id, quiz.timeclose AS usertimeclose
1286 FROM {quiz} quiz
1287 WHERE quiz.course = :courseid";
1289 $results = $DB->get_records_sql($sql, ['courseid' => $courseid]);
1290 return $results;
1293 $sql = "SELECT q.id,
1294 COALESCE(v.userclose, v.groupclose, q.timeclose, 0) AS usertimeclose
1295 FROM (
1296 SELECT quiz.id as quizid,
1297 MAX(quo.timeclose) AS userclose, MAX(qgo.timeclose) AS groupclose
1298 FROM {quiz} quiz
1299 LEFT JOIN {quiz_overrides} quo on quiz.id = quo.quiz AND quo.userid = :userid
1300 LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
1301 LEFT JOIN {quiz_overrides} qgo on quiz.id = qgo.quiz AND qgo.groupid = gm.groupid
1302 WHERE quiz.course = :courseid
1303 GROUP BY quiz.id) v
1304 JOIN {quiz} q ON q.id = v.quizid";
1306 $results = $DB->get_records_sql($sql, ['userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid]);
1307 return $results;
1312 * Get the choices to offer for the 'Questions per page' option.
1313 * @return array int => string.
1315 function quiz_questions_per_page_options() {
1316 $pageoptions = [];
1317 $pageoptions[0] = get_string('neverallononepage', 'quiz');
1318 $pageoptions[1] = get_string('everyquestion', 'quiz');
1319 for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
1320 $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
1322 return $pageoptions;
1326 * Get the human-readable name for a quiz attempt state.
1327 * @param string $state one of the state constants like {@see quiz_attempt::IN_PROGRESS}.
1328 * @return string The lang string to describe that state.
1330 function quiz_attempt_state_name($state) {
1331 switch ($state) {
1332 case quiz_attempt::IN_PROGRESS:
1333 return get_string('stateinprogress', 'quiz');
1334 case quiz_attempt::OVERDUE:
1335 return get_string('stateoverdue', 'quiz');
1336 case quiz_attempt::FINISHED:
1337 return get_string('statefinished', 'quiz');
1338 case quiz_attempt::ABANDONED:
1339 return get_string('stateabandoned', 'quiz');
1340 default:
1341 throw new coding_exception('Unknown quiz attempt state.');
1345 // Other quiz functions ////////////////////////////////////////////////////////
1348 * @param stdClass $quiz the quiz.
1349 * @param int $cmid the course_module object for this quiz.
1350 * @param stdClass $question the question.
1351 * @param string $returnurl url to return to after action is done.
1352 * @param int $variant which question variant to preview (optional).
1353 * @return string html for a number of icons linked to action pages for a
1354 * question - preview and edit / view icons depending on user capabilities.
1356 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl, $variant = null) {
1357 $html = '';
1358 if ($question->qtype !== 'random') {
1359 $html = quiz_question_preview_button($quiz, $question, false, $variant);
1361 $html .= quiz_question_edit_button($cmid, $question, $returnurl);
1362 return $html;
1366 * @param int $cmid the course_module.id for this quiz.
1367 * @param stdClass $question the question.
1368 * @param string $returnurl url to return to after action is done.
1369 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
1370 * @return the HTML for an edit icon, view icon, or nothing for a question
1371 * (depending on permissions).
1373 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
1374 global $CFG, $OUTPUT;
1376 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
1377 static $stredit = null;
1378 static $strview = null;
1379 if ($stredit === null) {
1380 $stredit = get_string('edit');
1381 $strview = get_string('view');
1384 // What sort of icon should we show?
1385 $action = '';
1386 if (!empty($question->id) &&
1387 (question_has_capability_on($question, 'edit') ||
1388 question_has_capability_on($question, 'move'))) {
1389 $action = $stredit;
1390 $icon = 't/edit';
1391 } else if (!empty($question->id) &&
1392 question_has_capability_on($question, 'view')) {
1393 $action = $strview;
1394 $icon = 'i/info';
1397 // Build the icon.
1398 if ($action) {
1399 if ($returnurl instanceof moodle_url) {
1400 $returnurl = $returnurl->out_as_local_url(false);
1402 $questionparams = ['returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id];
1403 $questionurl = new moodle_url("$CFG->wwwroot/question/bank/editquestion/question.php", $questionparams);
1404 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton">' .
1405 $OUTPUT->pix_icon($icon, $action) . $contentaftericon .
1406 '</a>';
1407 } else if ($contentaftericon) {
1408 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
1409 } else {
1410 return '';
1415 * @param stdClass $quiz the quiz settings
1416 * @param stdClass $question the question
1417 * @param int $variant which question variant to preview (optional).
1418 * @return moodle_url to preview this question with the options from this quiz.
1420 function quiz_question_preview_url($quiz, $question, $variant = null) {
1421 // Get the appropriate display options.
1422 $displayoptions = display_options::make_from_quiz($quiz,
1423 display_options::DURING);
1425 $maxmark = null;
1426 if (isset($question->maxmark)) {
1427 $maxmark = $question->maxmark;
1430 // Work out the correcte preview URL.
1431 return \qbank_previewquestion\helper::question_preview_url($question->id, $quiz->preferredbehaviour,
1432 $maxmark, $displayoptions, $variant);
1436 * @param stdClass $quiz the quiz settings
1437 * @param stdClass $question the question
1438 * @param bool $label if true, show the preview question label after the icon
1439 * @param int $variant which question variant to preview (optional).
1440 * @param bool $random if question is random, true.
1441 * @return the HTML for a preview question icon.
1443 function quiz_question_preview_button($quiz, $question, $label = false, $variant = null, $random = null) {
1444 global $PAGE;
1445 if (!question_has_capability_on($question, 'use')) {
1446 return '';
1448 return $PAGE->get_renderer('mod_quiz', 'edit')->question_preview_icon($quiz, $question, $label, $variant, null);
1452 * @param stdClass $attempt the attempt.
1453 * @param stdClass $context the quiz context.
1454 * @return int whether flags should be shown/editable to the current user for this attempt.
1456 function quiz_get_flag_option($attempt, $context) {
1457 global $USER;
1458 if (!has_capability('moodle/question:flag', $context)) {
1459 return question_display_options::HIDDEN;
1460 } else if ($attempt->userid == $USER->id) {
1461 return question_display_options::EDITABLE;
1462 } else {
1463 return question_display_options::VISIBLE;
1468 * Work out what state this quiz attempt is in - in the sense used by
1469 * quiz_get_review_options, not in the sense of $attempt->state.
1470 * @param stdClass $quiz the quiz settings
1471 * @param stdClass $attempt the quiz_attempt database row.
1472 * @return int one of the display_options::DURING,
1473 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
1475 function quiz_attempt_state($quiz, $attempt) {
1476 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
1477 return display_options::DURING;
1478 } else if ($quiz->timeclose && time() >= $quiz->timeclose) {
1479 return display_options::AFTER_CLOSE;
1480 } else if (time() < $attempt->timefinish + 120) {
1481 return display_options::IMMEDIATELY_AFTER;
1482 } else {
1483 return display_options::LATER_WHILE_OPEN;
1488 * The appropriate display_options object for this attempt at this quiz right now.
1490 * @param stdClass $quiz the quiz instance.
1491 * @param stdClass $attempt the attempt in question.
1492 * @param context $context the quiz context.
1494 * @return display_options
1496 function quiz_get_review_options($quiz, $attempt, $context) {
1497 $options = display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
1499 $options->readonly = true;
1500 $options->flags = quiz_get_flag_option($attempt, $context);
1501 if (!empty($attempt->id)) {
1502 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1503 ['attempt' => $attempt->id]);
1506 // Show a link to the comment box only for closed attempts.
1507 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
1508 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
1509 $options->manualcomment = question_display_options::VISIBLE;
1510 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1511 ['attempt' => $attempt->id]);
1514 if (!is_null($context) && !$attempt->preview &&
1515 has_capability('mod/quiz:viewreports', $context) &&
1516 has_capability('moodle/grade:viewhidden', $context)) {
1517 // People who can see reports and hidden grades should be shown everything,
1518 // except during preview when teachers want to see what students see.
1519 $options->attempt = question_display_options::VISIBLE;
1520 $options->correctness = question_display_options::VISIBLE;
1521 $options->marks = question_display_options::MARK_AND_MAX;
1522 $options->feedback = question_display_options::VISIBLE;
1523 $options->numpartscorrect = question_display_options::VISIBLE;
1524 $options->manualcomment = question_display_options::VISIBLE;
1525 $options->generalfeedback = question_display_options::VISIBLE;
1526 $options->rightanswer = question_display_options::VISIBLE;
1527 $options->overallfeedback = question_display_options::VISIBLE;
1528 $options->history = question_display_options::VISIBLE;
1529 $options->userinfoinhistory = $attempt->userid;
1533 return $options;
1537 * Combines the review options from a number of different quiz attempts.
1538 * Returns an array of two ojects, so the suggested way of calling this
1539 * funciton is:
1540 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1542 * @param stdClass $quiz the quiz instance.
1543 * @param array $attempts an array of attempt objects.
1545 * @return array of two options objects, one showing which options are true for
1546 * at least one of the attempts, the other showing which options are true
1547 * for all attempts.
1549 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1550 $fields = ['feedback', 'generalfeedback', 'rightanswer', 'overallfeedback'];
1551 $someoptions = new stdClass();
1552 $alloptions = new stdClass();
1553 foreach ($fields as $field) {
1554 $someoptions->$field = false;
1555 $alloptions->$field = true;
1557 $someoptions->marks = question_display_options::HIDDEN;
1558 $alloptions->marks = question_display_options::MARK_AND_MAX;
1560 // This shouldn't happen, but we need to prevent reveal information.
1561 if (empty($attempts)) {
1562 return [$someoptions, $someoptions];
1565 foreach ($attempts as $attempt) {
1566 $attemptoptions = display_options::make_from_quiz($quiz,
1567 quiz_attempt_state($quiz, $attempt));
1568 foreach ($fields as $field) {
1569 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1570 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1572 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1573 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1575 return [$someoptions, $alloptions];
1578 // Functions for sending notification messages /////////////////////////////////
1581 * Sends a confirmation message to the student confirming that the attempt was processed.
1583 * @param stdClass $recipient user object for the recipient.
1584 * @param stdClass $a lots of useful information that can be used in the message
1585 * subject and body.
1586 * @param bool $studentisonline is the student currently interacting with Moodle?
1588 * @return int|false as for {@link message_send()}.
1590 function quiz_send_confirmation($recipient, $a, $studentisonline) {
1592 // Add information about the recipient to $a.
1593 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1594 $a->username = fullname($recipient);
1595 $a->userusername = $recipient->username;
1597 // Prepare the message.
1598 $eventdata = new \core\message\message();
1599 $eventdata->courseid = $a->courseid;
1600 $eventdata->component = 'mod_quiz';
1601 $eventdata->name = 'confirmation';
1602 $eventdata->notification = 1;
1604 $eventdata->userfrom = core_user::get_noreply_user();
1605 $eventdata->userto = $recipient;
1606 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1608 if ($studentisonline) {
1609 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1610 } else {
1611 $eventdata->fullmessage = get_string('emailconfirmbodyautosubmit', 'quiz', $a);
1614 $eventdata->fullmessageformat = FORMAT_PLAIN;
1615 $eventdata->fullmessagehtml = '';
1617 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1618 $eventdata->contexturl = $a->quizurl;
1619 $eventdata->contexturlname = $a->quizname;
1620 $eventdata->customdata = [
1621 'cmid' => $a->quizcmid,
1622 'instance' => $a->quizid,
1623 'attemptid' => $a->attemptid,
1626 // ... and send it.
1627 return message_send($eventdata);
1631 * Sends notification messages to the interested parties that assign the role capability
1633 * @param stdClass $recipient user object of the intended recipient
1634 * @param stdClass $submitter user object for the user who submitted the attempt.
1635 * @param stdClass $a associative array of replaceable fields for the templates
1637 * @return int|false as for {@link message_send()}.
1639 function quiz_send_notification($recipient, $submitter, $a) {
1640 global $PAGE;
1642 // Recipient info for template.
1643 $a->useridnumber = $recipient->idnumber;
1644 $a->username = fullname($recipient);
1645 $a->userusername = $recipient->username;
1647 // Prepare the message.
1648 $eventdata = new \core\message\message();
1649 $eventdata->courseid = $a->courseid;
1650 $eventdata->component = 'mod_quiz';
1651 $eventdata->name = 'submission';
1652 $eventdata->notification = 1;
1654 $eventdata->userfrom = $submitter;
1655 $eventdata->userto = $recipient;
1656 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1657 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1658 $eventdata->fullmessageformat = FORMAT_PLAIN;
1659 $eventdata->fullmessagehtml = '';
1661 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1662 $eventdata->contexturl = $a->quizreviewurl;
1663 $eventdata->contexturlname = $a->quizname;
1664 $userpicture = new user_picture($submitter);
1665 $userpicture->size = 1; // Use f1 size.
1666 $userpicture->includetoken = $recipient->id; // Generate an out-of-session token for the user receiving the message.
1667 $eventdata->customdata = [
1668 'cmid' => $a->quizcmid,
1669 'instance' => $a->quizid,
1670 'attemptid' => $a->attemptid,
1671 'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
1674 // ... and send it.
1675 return message_send($eventdata);
1679 * Send all the requried messages when a quiz attempt is submitted.
1681 * @param stdClass $course the course
1682 * @param stdClass $quiz the quiz
1683 * @param stdClass $attempt this attempt just finished
1684 * @param stdClass $context the quiz context
1685 * @param stdClass $cm the coursemodule for this quiz
1686 * @param bool $studentisonline is the student currently interacting with Moodle?
1688 * @return bool true if all necessary messages were sent successfully, else false.
1690 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm, $studentisonline) {
1691 global $CFG, $DB;
1693 // Do nothing if required objects not present.
1694 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1695 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1698 $submitter = $DB->get_record('user', ['id' => $attempt->userid], '*', MUST_EXIST);
1700 // Check for confirmation required.
1701 $sendconfirm = false;
1702 $notifyexcludeusers = '';
1703 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1704 $notifyexcludeusers = $submitter->id;
1705 $sendconfirm = true;
1708 // Check for notifications required.
1709 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang,
1710 u.timezone, u.mailformat, u.maildisplay, u.auth, u.suspended, u.deleted, ';
1711 $userfieldsapi = \core_user\fields::for_name();
1712 $notifyfields .= $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1713 $groups = groups_get_all_groups($course->id, $submitter->id, $cm->groupingid);
1714 if (is_array($groups) && count($groups) > 0) {
1715 $groups = array_keys($groups);
1716 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1717 // If the user is not in a group, and the quiz is set to group mode,
1718 // then set $groups to a non-existant id so that only users with
1719 // 'moodle/site:accessallgroups' get notified.
1720 $groups = -1;
1721 } else {
1722 $groups = '';
1724 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1725 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1727 if (empty($userstonotify) && !$sendconfirm) {
1728 return true; // Nothing to do.
1731 $a = new stdClass();
1732 // Course info.
1733 $a->courseid = $course->id;
1734 $a->coursename = $course->fullname;
1735 $a->courseshortname = $course->shortname;
1736 // Quiz info.
1737 $a->quizname = $quiz->name;
1738 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1739 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1740 format_string($quiz->name) . ' report</a>';
1741 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1742 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1743 $a->quizid = $quiz->id;
1744 $a->quizcmid = $cm->id;
1745 // Attempt info.
1746 $a->submissiontime = userdate($attempt->timefinish);
1747 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1748 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1749 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1750 format_string($quiz->name) . ' review</a>';
1751 $a->attemptid = $attempt->id;
1752 // Student who sat the quiz info.
1753 $a->studentidnumber = $submitter->idnumber;
1754 $a->studentname = fullname($submitter);
1755 $a->studentusername = $submitter->username;
1757 $allok = true;
1759 // Send notifications if required.
1760 if (!empty($userstonotify)) {
1761 foreach ($userstonotify as $recipient) {
1762 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1766 // Send confirmation if required. We send the student confirmation last, so
1767 // that if message sending is being intermittently buggy, which means we send
1768 // some but not all messages, and then try again later, then teachers may get
1769 // duplicate messages, but the student will always get exactly one.
1770 if ($sendconfirm) {
1771 $allok = $allok && quiz_send_confirmation($submitter, $a, $studentisonline);
1774 return $allok;
1778 * Send the notification message when a quiz attempt becomes overdue.
1780 * @param quiz_attempt $attemptobj all the data about the quiz attempt.
1782 function quiz_send_overdue_message($attemptobj) {
1783 global $CFG, $DB;
1785 $submitter = $DB->get_record('user', ['id' => $attemptobj->get_userid()], '*', MUST_EXIST);
1787 if (!$attemptobj->has_capability('mod/quiz:emailwarnoverdue', $submitter->id, false)) {
1788 return; // Message not required.
1791 if (!$attemptobj->has_response_to_at_least_one_graded_question()) {
1792 return; // Message not required.
1795 // Prepare lots of useful information that admins might want to include in
1796 // the email message.
1797 $quizname = format_string($attemptobj->get_quiz_name());
1799 $deadlines = [];
1800 if ($attemptobj->get_quiz()->timelimit) {
1801 $deadlines[] = $attemptobj->get_attempt()->timestart + $attemptobj->get_quiz()->timelimit;
1803 if ($attemptobj->get_quiz()->timeclose) {
1804 $deadlines[] = $attemptobj->get_quiz()->timeclose;
1806 $duedate = min($deadlines);
1807 $graceend = $duedate + $attemptobj->get_quiz()->graceperiod;
1809 $a = new stdClass();
1810 // Course info.
1811 $a->courseid = $attemptobj->get_course()->id;
1812 $a->coursename = format_string($attemptobj->get_course()->fullname);
1813 $a->courseshortname = format_string($attemptobj->get_course()->shortname);
1814 // Quiz info.
1815 $a->quizname = $quizname;
1816 $a->quizurl = $attemptobj->view_url();
1817 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1818 // Attempt info.
1819 $a->attemptduedate = userdate($duedate);
1820 $a->attemptgraceend = userdate($graceend);
1821 $a->attemptsummaryurl = $attemptobj->summary_url()->out(false);
1822 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1823 // Student's info.
1824 $a->studentidnumber = $submitter->idnumber;
1825 $a->studentname = fullname($submitter);
1826 $a->studentusername = $submitter->username;
1828 // Prepare the message.
1829 $eventdata = new \core\message\message();
1830 $eventdata->courseid = $a->courseid;
1831 $eventdata->component = 'mod_quiz';
1832 $eventdata->name = 'attempt_overdue';
1833 $eventdata->notification = 1;
1835 $eventdata->userfrom = core_user::get_noreply_user();
1836 $eventdata->userto = $submitter;
1837 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1838 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1839 $eventdata->fullmessageformat = FORMAT_PLAIN;
1840 $eventdata->fullmessagehtml = '';
1842 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1843 $eventdata->contexturl = $a->quizurl;
1844 $eventdata->contexturlname = $a->quizname;
1845 $eventdata->customdata = [
1846 'cmid' => $attemptobj->get_cmid(),
1847 'instance' => $attemptobj->get_quizid(),
1848 'attemptid' => $attemptobj->get_attemptid(),
1851 // Send the message.
1852 return message_send($eventdata);
1856 * Handle the quiz_attempt_submitted event.
1858 * This sends the confirmation and notification messages, if required.
1860 * @param stdClass $event the event object.
1862 function quiz_attempt_submitted_handler($event) {
1863 global $DB;
1865 $course = $DB->get_record('course', ['id' => $event->courseid]);
1866 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1867 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1868 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1869 $eventdata = $event->get_data();
1871 if (!($course && $quiz && $cm && $attempt)) {
1872 // Something has been deleted since the event was raised. Therefore, the
1873 // event is no longer relevant.
1874 return true;
1877 // Update completion state.
1878 $completion = new completion_info($course);
1879 if ($completion->is_enabled($cm) &&
1880 ($quiz->completionattemptsexhausted || $quiz->completionminattempts)) {
1881 $completion->update_state($cm, COMPLETION_COMPLETE, $event->userid);
1883 return quiz_send_notification_messages($course, $quiz, $attempt,
1884 context_module::instance($cm->id), $cm, $eventdata['other']['studentisonline']);
1888 * Send the notification message when a quiz attempt has been manual graded.
1890 * @param quiz_attempt $attemptobj Some data about the quiz attempt.
1891 * @param stdClass $userto
1892 * @return int|false As for message_send.
1894 function quiz_send_notify_manual_graded_message(quiz_attempt $attemptobj, object $userto): ?int {
1895 global $CFG;
1897 $quizname = format_string($attemptobj->get_quiz_name());
1899 $a = new stdClass();
1900 // Course info.
1901 $a->courseid = $attemptobj->get_courseid();
1902 $a->coursename = format_string($attemptobj->get_course()->fullname);
1903 // Quiz info.
1904 $a->quizname = $quizname;
1905 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $attemptobj->get_cmid();
1907 // Attempt info.
1908 $a->attempttimefinish = userdate($attemptobj->get_attempt()->timefinish);
1909 // Student's info.
1910 $a->studentidnumber = $userto->idnumber;
1911 $a->studentname = fullname($userto);
1913 $eventdata = new \core\message\message();
1914 $eventdata->component = 'mod_quiz';
1915 $eventdata->name = 'attempt_grading_complete';
1916 $eventdata->userfrom = core_user::get_noreply_user();
1917 $eventdata->userto = $userto;
1919 $eventdata->subject = get_string('emailmanualgradedsubject', 'quiz', $a);
1920 $eventdata->fullmessage = get_string('emailmanualgradedbody', 'quiz', $a);
1921 $eventdata->fullmessageformat = FORMAT_PLAIN;
1922 $eventdata->fullmessagehtml = '';
1924 $eventdata->notification = 1;
1925 $eventdata->contexturl = $a->quizurl;
1926 $eventdata->contexturlname = $a->quizname;
1928 // Send the message.
1929 return message_send($eventdata);
1934 * Logic to happen when a/some group(s) has/have been deleted in a course.
1936 * @param int $courseid The course ID.
1937 * @return void
1939 function quiz_process_group_deleted_in_course($courseid) {
1940 global $DB;
1942 // It would be nice if we got the groupid that was deleted.
1943 // Instead, we just update all quizzes with orphaned group overrides.
1944 $sql = "SELECT o.id, o.quiz, o.groupid
1945 FROM {quiz_overrides} o
1946 JOIN {quiz} quiz ON quiz.id = o.quiz
1947 LEFT JOIN {groups} grp ON grp.id = o.groupid
1948 WHERE quiz.course = :courseid
1949 AND o.groupid IS NOT NULL
1950 AND grp.id IS NULL";
1951 $params = ['courseid' => $courseid];
1952 $records = $DB->get_records_sql($sql, $params);
1953 if (!$records) {
1954 return; // Nothing to do.
1956 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
1957 $cache = cache::make('mod_quiz', 'overrides');
1958 foreach ($records as $record) {
1959 $cache->delete("{$record->quiz}_g_{$record->groupid}");
1961 quiz_update_open_attempts(['quizid' => array_unique(array_column($records, 'quiz'))]);
1965 * Get the information about the standard quiz JavaScript module.
1966 * @return array a standard jsmodule structure.
1968 function quiz_get_js_module() {
1969 global $PAGE;
1971 return [
1972 'name' => 'mod_quiz',
1973 'fullpath' => '/mod/quiz/module.js',
1974 'requires' => ['base', 'dom', 'event-delegate', 'event-key',
1975 'core_question_engine'],
1976 'strings' => [
1977 ['cancel', 'moodle'],
1978 ['flagged', 'question'],
1979 ['functiondisabledbysecuremode', 'quiz'],
1980 ['startattempt', 'quiz'],
1981 ['timesup', 'quiz'],
1988 * Creates a textual representation of a question for display.
1990 * @param stdClass $question A question object from the database questions table
1991 * @param bool $showicon If true, show the question's icon with the question. False by default.
1992 * @param bool $showquestiontext If true (default), show question text after question name.
1993 * If false, show only question name.
1994 * @param bool $showidnumber If true, show the question's idnumber, if any. False by default.
1995 * @param core_tag_tag[]|bool $showtags if array passed, show those tags. Else, if true, get and show tags,
1996 * else, don't show tags (which is the default).
1997 * @return string HTML fragment.
1999 function quiz_question_tostring($question, $showicon = false, $showquestiontext = true,
2000 $showidnumber = false, $showtags = false) {
2001 global $OUTPUT;
2002 $result = '';
2004 // Question name.
2005 $name = shorten_text(format_string($question->name), 200);
2006 if ($showicon) {
2007 $name .= print_question_icon($question) . ' ' . $name;
2009 $result .= html_writer::span($name, 'questionname');
2011 // Question idnumber.
2012 if ($showidnumber && $question->idnumber !== null && $question->idnumber !== '') {
2013 $result .= ' ' . html_writer::span(
2014 html_writer::span(get_string('idnumber', 'question'), 'accesshide') .
2015 ' ' . s($question->idnumber), 'badge badge-primary');
2018 // Question tags.
2019 if (is_array($showtags)) {
2020 $tags = $showtags;
2021 } else if ($showtags) {
2022 $tags = core_tag_tag::get_item_tags('core_question', 'question', $question->id);
2023 } else {
2024 $tags = [];
2026 if ($tags) {
2027 $result .= $OUTPUT->tag_list($tags, null, 'd-inline', 0, null, true);
2030 // Question text.
2031 if ($showquestiontext) {
2032 $questiontext = question_utils::to_plain_text($question->questiontext,
2033 $question->questiontextformat, ['noclean' => true, 'para' => false]);
2034 $questiontext = shorten_text($questiontext, 50);
2035 if ($questiontext) {
2036 $result .= ' ' . html_writer::span(s($questiontext), 'questiontext');
2040 return $result;
2044 * Verify that the question exists, and the user has permission to use it.
2045 * Does not return. Throws an exception if the question cannot be used.
2046 * @param int $questionid The id of the question.
2048 function quiz_require_question_use($questionid) {
2049 global $DB;
2050 $question = $DB->get_record('question', ['id' => $questionid], '*', MUST_EXIST);
2051 question_require_capability_on($question, 'use');
2055 * Add a question to a quiz
2057 * Adds a question to a quiz by updating $quiz as well as the
2058 * quiz and quiz_slots tables. It also adds a page break if required.
2059 * @param int $questionid The id of the question to be added
2060 * @param stdClass $quiz The extended quiz object as used by edit.php
2061 * This is updated by this function
2062 * @param int $page Which page in quiz to add the question on. If 0 (default),
2063 * add at the end
2064 * @param float $maxmark The maximum mark to set for this question. (Optional,
2065 * defaults to question.defaultmark.
2066 * @return bool false if the question was already in the quiz
2068 function quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null) {
2069 global $DB;
2071 if (!isset($quiz->cmid)) {
2072 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
2073 $quiz->cmid = $cm->id;
2076 // Make sue the question is not of the "random" type.
2077 $questiontype = $DB->get_field('question', 'qtype', ['id' => $questionid]);
2078 if ($questiontype == 'random') {
2079 throw new coding_exception(
2080 'Adding "random" questions via quiz_add_quiz_question() is deprecated. Please use quiz_add_random_questions().'
2084 $trans = $DB->start_delegated_transaction();
2086 $sql = "SELECT qbe.id
2087 FROM {quiz_slots} slot
2088 JOIN {question_references} qr ON qr.itemid = slot.id
2089 JOIN {question_bank_entries} qbe ON qbe.id = qr.questionbankentryid
2090 WHERE slot.quizid = ?
2091 AND qr.component = ?
2092 AND qr.questionarea = ?";
2094 $questionslots = $DB->get_records_sql($sql, [$quiz->id, 'mod_quiz', 'slot']);
2096 $currententry = get_question_bank_entry($questionid);
2098 if (array_key_exists($currententry->id, $questionslots)) {
2099 $trans->allow_commit();
2100 return false;
2103 $sql = "SELECT slot.slot, slot.page, slot.id
2104 FROM {quiz_slots} slot
2105 WHERE slot.quizid = ?
2106 ORDER BY slot.slot";
2108 $slots = $DB->get_records_sql($sql, [$quiz->id]);
2110 $maxpage = 1;
2111 $numonlastpage = 0;
2112 foreach ($slots as $slot) {
2113 if ($slot->page > $maxpage) {
2114 $maxpage = $slot->page;
2115 $numonlastpage = 1;
2116 } else {
2117 $numonlastpage += 1;
2121 // Add the new instance.
2122 $slot = new stdClass();
2123 $slot->quizid = $quiz->id;
2125 if ($maxmark !== null) {
2126 $slot->maxmark = $maxmark;
2127 } else {
2128 $slot->maxmark = $DB->get_field('question', 'defaultmark', ['id' => $questionid]);
2131 if (is_int($page) && $page >= 1) {
2132 // Adding on a given page.
2133 $lastslotbefore = 0;
2134 foreach (array_reverse($slots) as $otherslot) {
2135 if ($otherslot->page > $page) {
2136 $DB->set_field('quiz_slots', 'slot', $otherslot->slot + 1, ['id' => $otherslot->id]);
2137 } else {
2138 $lastslotbefore = $otherslot->slot;
2139 break;
2142 $slot->slot = $lastslotbefore + 1;
2143 $slot->page = min($page, $maxpage + 1);
2145 quiz_update_section_firstslots($quiz->id, 1, max($lastslotbefore, 1));
2147 } else {
2148 $lastslot = end($slots);
2149 if ($lastslot) {
2150 $slot->slot = $lastslot->slot + 1;
2151 } else {
2152 $slot->slot = 1;
2154 if ($quiz->questionsperpage && $numonlastpage >= $quiz->questionsperpage) {
2155 $slot->page = $maxpage + 1;
2156 } else {
2157 $slot->page = $maxpage;
2161 $slotid = $DB->insert_record('quiz_slots', $slot);
2163 // Update or insert record in question_reference table.
2164 $sql = "SELECT DISTINCT qr.id, qr.itemid
2165 FROM {question} q
2166 JOIN {question_versions} qv ON q.id = qv.questionid
2167 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2168 JOIN {question_references} qr ON qbe.id = qr.questionbankentryid AND qr.version = qv.version
2169 JOIN {quiz_slots} qs ON qs.id = qr.itemid
2170 WHERE q.id = ?
2171 AND qs.id = ?
2172 AND qr.component = ?
2173 AND qr.questionarea = ?";
2174 $qreferenceitem = $DB->get_record_sql($sql, [$questionid, $slotid, 'mod_quiz', 'slot']);
2176 if (!$qreferenceitem) {
2177 // Create a new reference record for questions created already.
2178 $questionreferences = new \StdClass();
2179 $questionreferences->usingcontextid = context_module::instance($quiz->cmid)->id;
2180 $questionreferences->component = 'mod_quiz';
2181 $questionreferences->questionarea = 'slot';
2182 $questionreferences->itemid = $slotid;
2183 $questionreferences->questionbankentryid = get_question_bank_entry($questionid)->id;
2184 $questionreferences->version = null; // Always latest.
2185 $DB->insert_record('question_references', $questionreferences);
2187 } else if ($qreferenceitem->itemid === 0 || $qreferenceitem->itemid === null) {
2188 $questionreferences = new \StdClass();
2189 $questionreferences->id = $qreferenceitem->id;
2190 $questionreferences->itemid = $slotid;
2191 $DB->update_record('question_references', $questionreferences);
2192 } else {
2193 // If the reference record exits for another quiz.
2194 $questionreferences = new \StdClass();
2195 $questionreferences->usingcontextid = context_module::instance($quiz->cmid)->id;
2196 $questionreferences->component = 'mod_quiz';
2197 $questionreferences->questionarea = 'slot';
2198 $questionreferences->itemid = $slotid;
2199 $questionreferences->questionbankentryid = get_question_bank_entry($questionid)->id;
2200 $questionreferences->version = null; // Always latest.
2201 $DB->insert_record('question_references', $questionreferences);
2204 $trans->allow_commit();
2206 // Log slot created event.
2207 $cm = get_coursemodule_from_instance('quiz', $quiz->id);
2208 $event = \mod_quiz\event\slot_created::create([
2209 'context' => context_module::instance($cm->id),
2210 'objectid' => $slotid,
2211 'other' => [
2212 'quizid' => $quiz->id,
2213 'slotnumber' => $slot->slot,
2214 'page' => $slot->page
2217 $event->trigger();
2221 * Move all the section headings in a certain slot range by a certain offset.
2223 * @param int $quizid the id of a quiz
2224 * @param int $direction amount to adjust section heading positions. Normally +1 or -1.
2225 * @param int $afterslot adjust headings that start after this slot.
2226 * @param int|null $beforeslot optionally, only adjust headings before this slot.
2228 function quiz_update_section_firstslots($quizid, $direction, $afterslot, $beforeslot = null) {
2229 global $DB;
2230 $where = 'quizid = ? AND firstslot > ?';
2231 $params = [$direction, $quizid, $afterslot];
2232 if ($beforeslot) {
2233 $where .= ' AND firstslot < ?';
2234 $params[] = $beforeslot;
2236 $firstslotschanges = $DB->get_records_select_menu('quiz_sections',
2237 $where, $params, '', 'firstslot, firstslot + ?');
2238 update_field_with_unique_index('quiz_sections', 'firstslot', $firstslotschanges, ['quizid' => $quizid]);
2242 * Add a random question to the quiz at a given point.
2243 * @param stdClass $quiz the quiz settings.
2244 * @param int $addonpage the page on which to add the question.
2245 * @param int $categoryid the question category to add the question from.
2246 * @param int $number the number of random questions to add.
2247 * @param bool $includesubcategories whether to include questoins from subcategories.
2248 * @param int[] $tagids Array of tagids. The question that will be picked randomly should be tagged with all these tags.
2250 function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,
2251 $includesubcategories, $tagids = []) {
2252 global $DB;
2254 $category = $DB->get_record('question_categories', ['id' => $categoryid]);
2255 if (!$category) {
2256 new moodle_exception('invalidcategoryid');
2259 $catcontext = context::instance_by_id($category->contextid);
2260 require_capability('moodle/question:useall', $catcontext);
2262 // Tags for filter condition.
2263 $tags = \core_tag_tag::get_bulk($tagids, 'id, name');
2264 $tagstrings = [];
2265 foreach ($tags as $tag) {
2266 $tagstrings[] = "{$tag->id},{$tag->name}";
2268 // Create the selected number of random questions.
2269 for ($i = 0; $i < $number; $i++) {
2270 // Set the filter conditions.
2271 $filtercondition = new stdClass();
2272 $filtercondition->questioncategoryid = $categoryid;
2273 $filtercondition->includingsubcategories = $includesubcategories ? 1 : 0;
2274 if (!empty($tagstrings)) {
2275 $filtercondition->tags = $tagstrings;
2278 if (!isset($quiz->cmid)) {
2279 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
2280 $quiz->cmid = $cm->id;
2283 // Slot data.
2284 $randomslotdata = new stdClass();
2285 $randomslotdata->quizid = $quiz->id;
2286 $randomslotdata->usingcontextid = context_module::instance($quiz->cmid)->id;
2287 $randomslotdata->questionscontextid = $category->contextid;
2288 $randomslotdata->maxmark = 1;
2290 $randomslot = new \mod_quiz\local\structure\slot_random($randomslotdata);
2291 $randomslot->set_quiz($quiz);
2292 $randomslot->set_filter_condition($filtercondition);
2293 $randomslot->insert($addonpage);
2298 * Mark the activity completed (if required) and trigger the course_module_viewed event.
2300 * @param stdClass $quiz quiz object
2301 * @param stdClass $course course object
2302 * @param stdClass $cm course module object
2303 * @param stdClass $context context object
2304 * @since Moodle 3.1
2306 function quiz_view($quiz, $course, $cm, $context) {
2308 $params = [
2309 'objectid' => $quiz->id,
2310 'context' => $context
2313 $event = \mod_quiz\event\course_module_viewed::create($params);
2314 $event->add_record_snapshot('quiz', $quiz);
2315 $event->trigger();
2317 // Completion.
2318 $completion = new completion_info($course);
2319 $completion->set_module_viewed($cm);
2323 * Validate permissions for creating a new attempt and start a new preview attempt if required.
2325 * @param quiz_settings $quizobj quiz object
2326 * @param access_manager $accessmanager quiz access manager
2327 * @param bool $forcenew whether was required to start a new preview attempt
2328 * @param int $page page to jump to in the attempt
2329 * @param bool $redirect whether to redirect or throw exceptions (for web or ws usage)
2330 * @return array an array containing the attempt information, access error messages and the page to jump to in the attempt
2331 * @since Moodle 3.1
2333 function quiz_validate_new_attempt(quiz_settings $quizobj, access_manager $accessmanager, $forcenew, $page, $redirect) {
2334 global $DB, $USER;
2335 $timenow = time();
2337 if ($quizobj->is_preview_user() && $forcenew) {
2338 $accessmanager->current_attempt_finished();
2341 // Check capabilities.
2342 if (!$quizobj->is_preview_user()) {
2343 $quizobj->require_capability('mod/quiz:attempt');
2346 // Check to see if a new preview was requested.
2347 if ($quizobj->is_preview_user() && $forcenew) {
2348 // To force the creation of a new preview, we mark the current attempt (if any)
2349 // as abandoned. It will then automatically be deleted below.
2350 $DB->set_field('quiz_attempts', 'state', quiz_attempt::ABANDONED,
2351 ['quiz' => $quizobj->get_quizid(), 'userid' => $USER->id]);
2354 // Look for an existing attempt.
2355 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id, 'all', true);
2356 $lastattempt = end($attempts);
2358 $attemptnumber = null;
2359 // If an in-progress attempt exists, check password then redirect to it.
2360 if ($lastattempt && ($lastattempt->state == quiz_attempt::IN_PROGRESS ||
2361 $lastattempt->state == quiz_attempt::OVERDUE)) {
2362 $currentattemptid = $lastattempt->id;
2363 $messages = $accessmanager->prevent_access();
2365 // If the attempt is now overdue, deal with that.
2366 $quizobj->create_attempt_object($lastattempt)->handle_if_time_expired($timenow, true);
2368 // And, if the attempt is now no longer in progress, redirect to the appropriate place.
2369 if ($lastattempt->state == quiz_attempt::ABANDONED || $lastattempt->state == quiz_attempt::FINISHED) {
2370 if ($redirect) {
2371 redirect($quizobj->review_url($lastattempt->id));
2372 } else {
2373 throw new moodle_exception('attemptalreadyclosed', 'quiz', $quizobj->view_url());
2377 // If the page number was not explicitly in the URL, go to the current page.
2378 if ($page == -1) {
2379 $page = $lastattempt->currentpage;
2382 } else {
2383 while ($lastattempt && $lastattempt->preview) {
2384 $lastattempt = array_pop($attempts);
2387 // Get number for the next or unfinished attempt.
2388 if ($lastattempt) {
2389 $attemptnumber = $lastattempt->attempt + 1;
2390 } else {
2391 $lastattempt = false;
2392 $attemptnumber = 1;
2394 $currentattemptid = null;
2396 $messages = $accessmanager->prevent_access() +
2397 $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
2399 if ($page == -1) {
2400 $page = 0;
2403 return [$currentattemptid, $attemptnumber, $lastattempt, $messages, $page];
2407 * Prepare and start a new attempt deleting the previous preview attempts.
2409 * @param quiz_settings $quizobj quiz object
2410 * @param int $attemptnumber the attempt number
2411 * @param stdClass $lastattempt last attempt object
2412 * @param bool $offlineattempt whether is an offline attempt or not
2413 * @param array $forcedrandomquestions slot number => question id. Used for random questions,
2414 * to force the choice of a particular actual question. Intended for testing purposes only.
2415 * @param array $forcedvariants slot number => variant. Used for questions with variants,
2416 * to force the choice of a particular variant. Intended for testing purposes only.
2417 * @param int $userid Specific user id to create an attempt for that user, null for current logged in user
2418 * @return stdClass the new attempt
2419 * @since Moodle 3.1
2421 function quiz_prepare_and_start_new_attempt(quiz_settings $quizobj, $attemptnumber, $lastattempt,
2422 $offlineattempt = false, $forcedrandomquestions = [], $forcedvariants = [], $userid = null) {
2423 global $DB, $USER;
2425 if ($userid === null) {
2426 $userid = $USER->id;
2427 $ispreviewuser = $quizobj->is_preview_user();
2428 } else {
2429 $ispreviewuser = has_capability('mod/quiz:preview', $quizobj->get_context(), $userid);
2431 // Delete any previous preview attempts belonging to this user.
2432 quiz_delete_previews($quizobj->get_quiz(), $userid);
2434 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
2435 $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
2437 // Create the new attempt and initialize the question sessions
2438 $timenow = time(); // Update time now, in case the server is running really slowly.
2439 $attempt = quiz_create_attempt($quizobj, $attemptnumber, $lastattempt, $timenow, $ispreviewuser, $userid);
2441 if (!($quizobj->get_quiz()->attemptonlast && $lastattempt)) {
2442 $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,
2443 $forcedrandomquestions, $forcedvariants);
2444 } else {
2445 $attempt = quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt);
2448 $transaction = $DB->start_delegated_transaction();
2450 // Init the timemodifiedoffline for offline attempts.
2451 if ($offlineattempt) {
2452 $attempt->timemodifiedoffline = $attempt->timemodified;
2454 $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
2456 $transaction->allow_commit();
2458 return $attempt;
2462 * Check if the given calendar_event is either a user or group override
2463 * event for quiz.
2465 * @param calendar_event $event The calendar event to check
2466 * @return bool
2468 function quiz_is_overriden_calendar_event(\calendar_event $event) {
2469 global $DB;
2471 if (!isset($event->modulename)) {
2472 return false;
2475 if ($event->modulename != 'quiz') {
2476 return false;
2479 if (!isset($event->instance)) {
2480 return false;
2483 if (!isset($event->userid) && !isset($event->groupid)) {
2484 return false;
2487 $overrideparams = [
2488 'quiz' => $event->instance
2491 if (isset($event->groupid)) {
2492 $overrideparams['groupid'] = $event->groupid;
2493 } else if (isset($event->userid)) {
2494 $overrideparams['userid'] = $event->userid;
2497 return $DB->record_exists('quiz_overrides', $overrideparams);
2501 * Get quiz attempt and handling error.
2503 * @param int $attemptid the id of the current attempt.
2504 * @param int|null $cmid the course_module id for this quiz.
2505 * @return quiz_attempt all the data about the quiz attempt.
2507 function quiz_create_attempt_handling_errors($attemptid, $cmid = null) {
2508 try {
2509 $attempobj = quiz_attempt::create($attemptid);
2510 } catch (moodle_exception $e) {
2511 if (!empty($cmid)) {
2512 list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'quiz');
2513 $continuelink = new moodle_url('/mod/quiz/view.php', ['id' => $cmid]);
2514 $context = context_module::instance($cm->id);
2515 if (has_capability('mod/quiz:preview', $context)) {
2516 throw new moodle_exception('attempterrorcontentchange', 'quiz', $continuelink);
2517 } else {
2518 throw new moodle_exception('attempterrorcontentchangeforuser', 'quiz', $continuelink);
2520 } else {
2521 throw new moodle_exception('attempterrorinvalid', 'quiz');
2524 if (!empty($cmid) && $attempobj->get_cmid() != $cmid) {
2525 throw new moodle_exception('invalidcoursemodule');
2526 } else {
2527 return $attempobj;