MDL-49813 quiz: add sections in the right place after page changes
[moodle.git] / mod / quiz / locallib.php
blob85da20afdd75cc1f82f0a6d90b697b92219a72ea
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
32 defined('MOODLE_INTERNAL') || die();
34 require_once($CFG->dirroot . '/mod/quiz/lib.php');
35 require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
36 require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
37 require_once($CFG->dirroot . '/mod/quiz/renderer.php');
38 require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
39 require_once($CFG->libdir . '/eventslib.php');
40 require_once($CFG->libdir . '/filelib.php');
41 require_once($CFG->libdir . '/questionlib.php');
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 object $quizobj the quiz object to create an attempt for.
83 * @param int $attemptnumber the sequence number for the attempt.
84 * @param object $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 $userid the id of the user attempting this quiz.
90 * @return object the newly created attempt object.
92 function quiz_create_attempt(quiz $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', array('q' => $quiz->id)),
103 array('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 print_error('cannotfindprevattempt', 'quiz');
118 $attempt = $lastattempt;
121 $attempt->attempt = $attemptnumber;
122 $attempt->timestart = $timenow;
123 $attempt->timefinish = 0;
124 $attempt->timemodified = $timenow;
125 $attempt->state = quiz_attempt::IN_PROGRESS;
126 $attempt->currentpage = 0;
127 $attempt->sumgrades = null;
129 // If this is a preview, mark it as such.
130 if ($ispreview) {
131 $attempt->preview = 1;
134 $timeclose = $quizobj->get_access_manager($timenow)->get_end_time($attempt);
135 if ($timeclose === false || $ispreview) {
136 $attempt->timecheckstate = null;
137 } else {
138 $attempt->timecheckstate = $timeclose;
141 return $attempt;
144 * Start a normal, new, quiz attempt.
146 * @param quiz $quizobj the quiz object to start an attempt for.
147 * @param question_usage_by_activity $quba
148 * @param object $attempt
149 * @param integer $attemptnumber starting from 1
150 * @param integer $timenow the attempt start time
151 * @param array $questionids slot number => question id. Used for random questions, to force the choice
152 * of a particular actual question. Intended for testing purposes only.
153 * @param array $forcedvariantsbyslot slot number => variant. Used for questions with variants,
154 * to force the choice of a particular variant. Intended for testing
155 * purposes only.
156 * @throws moodle_exception
157 * @return object modified attempt object
159 function quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,
160 $questionids = array(), $forcedvariantsbyslot = array()) {
162 // Usages for this user's previous quiz attempts.
163 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
164 $quizobj->get_quizid(), $attempt->userid);
166 // Fully load all the questions in this quiz.
167 $quizobj->preload_questions();
168 $quizobj->load_questions();
170 // First load all the non-random questions.
171 $randomfound = false;
172 $slot = 0;
173 $questions = array();
174 $maxmark = array();
175 $page = array();
176 foreach ($quizobj->get_questions() as $questiondata) {
177 $slot += 1;
178 $maxmark[$slot] = $questiondata->maxmark;
179 $page[$slot] = $questiondata->page;
180 if ($questiondata->qtype == 'random') {
181 $randomfound = true;
182 continue;
184 if (!$quizobj->get_quiz()->shuffleanswers) {
185 $questiondata->options->shuffleanswers = false;
187 $questions[$slot] = question_bank::make_question($questiondata);
190 // Then find a question to go in place of each random question.
191 if ($randomfound) {
192 $slot = 0;
193 $usedquestionids = array();
194 foreach ($questions as $question) {
195 if (isset($usedquestions[$question->id])) {
196 $usedquestionids[$question->id] += 1;
197 } else {
198 $usedquestionids[$question->id] = 1;
201 $randomloader = new \core_question\bank\random_question_loader($qubaids, $usedquestionids);
203 foreach ($quizobj->get_questions() as $questiondata) {
204 $slot += 1;
205 if ($questiondata->qtype != 'random') {
206 continue;
209 // Deal with fixed random choices for testing.
210 if (isset($questionids[$quba->next_slot_number()])) {
211 if ($randomloader->is_question_available($questiondata->category,
212 (bool) $questiondata->questiontext, $questionids[$quba->next_slot_number()])) {
213 $questions[$slot] = question_bank::load_question(
214 $questionids[$quba->next_slot_number()], $quizobj->get_quiz()->shuffleanswers);
215 continue;
216 } else {
217 throw new coding_exception('Forced question id not available.');
221 // Normal case, pick one at random.
222 $questionid = $randomloader->get_next_question_id($questiondata->category,
223 (bool) $questiondata->questiontext);
224 if ($questionid === null) {
225 throw new moodle_exception('notenoughrandomquestions', 'quiz',
226 $quizobj->view_url(), $questiondata);
229 $questions[$slot] = question_bank::load_question($questionid,
230 $quizobj->get_quiz()->shuffleanswers);
234 // Finally add them all to the usage.
235 ksort($questions);
236 foreach ($questions as $slot => $question) {
237 $newslot = $quba->add_question($question, $maxmark[$slot]);
238 if ($newslot != $slot) {
239 throw new coding_exception('Slot numbers have got confused.');
243 // Start all the questions.
244 $variantstrategy = new core_question\engine\variants\least_used_strategy($quba, $qubaids);
246 if (!empty($forcedvariantsbyslot)) {
247 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
248 $forcedvariantsbyslot, $quba);
249 $variantstrategy = new question_variant_forced_choices_selection_strategy(
250 $forcedvariantsbyseed, $variantstrategy);
253 $quba->start_all_questions($variantstrategy, $timenow);
255 // Work out the attempt layout.
256 $sections = $quizobj->get_sections();
257 foreach ($sections as $i => $section) {
258 if (isset($sections[$i + 1])) {
259 $sections[$i]->lastslot = $sections[$i + 1]->firstslot - 1;
260 } else {
261 $sections[$i]->lastslot = count($questions);
265 $layout = array();
266 foreach ($sections as $section) {
267 if ($section->shufflequestions) {
268 $questionsinthissection = array();
269 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
270 $questionsinthissection[] = $slot;
272 shuffle($questionsinthissection);
273 $questionsonthispage = 0;
274 foreach ($questionsinthissection as $slot) {
275 if ($questionsonthispage && $questionsonthispage == $quizobj->get_quiz()->questionsperpage) {
276 $layout[] = 0;
277 $questionsonthispage = 0;
279 $layout[] = $slot;
280 $questionsonthispage += 1;
283 } else {
284 $currentpage = $page[$section->firstslot];
285 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
286 if ($currentpage !== null && $page[$slot] != $currentpage) {
287 $layout[] = 0;
289 $layout[] = $slot;
290 $currentpage = $page[$slot];
294 // Each section ends with a page break.
295 $layout[] = 0;
297 $attempt->layout = implode(',', $layout);
299 return $attempt;
303 * Start a subsequent new attempt, in each attempt builds on last mode.
305 * @param question_usage_by_activity $quba this question usage
306 * @param object $attempt this attempt
307 * @param object $lastattempt last attempt
308 * @return object modified attempt object
311 function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
312 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
314 $oldnumberstonew = array();
315 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
316 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
318 $quba->start_question_based_on($newslot, $oldqa);
320 $oldnumberstonew[$oldslot] = $newslot;
323 // Update attempt layout.
324 $newlayout = array();
325 foreach (explode(',', $lastattempt->layout) as $oldslot) {
326 if ($oldslot != 0) {
327 $newlayout[] = $oldnumberstonew[$oldslot];
328 } else {
329 $newlayout[] = 0;
332 $attempt->layout = implode(',', $newlayout);
333 return $attempt;
337 * The save started question usage and quiz attempt in db and log the started attempt.
339 * @param quiz $quizobj
340 * @param question_usage_by_activity $quba
341 * @param object $attempt
342 * @return object attempt object with uniqueid and id set.
344 function quiz_attempt_save_started($quizobj, $quba, $attempt) {
345 global $DB;
346 // Save the attempt in the database.
347 question_engine::save_questions_usage_by_activity($quba);
348 $attempt->uniqueid = $quba->get_id();
349 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
351 // Params used by the events below.
352 $params = array(
353 'objectid' => $attempt->id,
354 'relateduserid' => $attempt->userid,
355 'courseid' => $quizobj->get_courseid(),
356 'context' => $quizobj->get_context()
358 // Decide which event we are using.
359 if ($attempt->preview) {
360 $params['other'] = array(
361 'quizid' => $quizobj->get_quizid()
363 $event = \mod_quiz\event\attempt_preview_started::create($params);
364 } else {
365 $event = \mod_quiz\event\attempt_started::create($params);
369 // Trigger the event.
370 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
371 $event->add_record_snapshot('quiz_attempts', $attempt);
372 $event->trigger();
374 return $attempt;
378 * Returns an unfinished attempt (if there is one) for the given
379 * user on the given quiz. This function does not return preview attempts.
381 * @param int $quizid the id of the quiz.
382 * @param int $userid the id of the user.
384 * @return mixed the unfinished attempt if there is one, false if not.
386 function quiz_get_user_attempt_unfinished($quizid, $userid) {
387 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
388 if ($attempts) {
389 return array_shift($attempts);
390 } else {
391 return false;
396 * Delete a quiz attempt.
397 * @param mixed $attempt an integer attempt id or an attempt object
398 * (row of the quiz_attempts table).
399 * @param object $quiz the quiz object.
401 function quiz_delete_attempt($attempt, $quiz) {
402 global $DB;
403 if (is_numeric($attempt)) {
404 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
405 return;
409 if ($attempt->quiz != $quiz->id) {
410 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
411 "but was passed quiz $quiz->id.");
412 return;
415 if (!isset($quiz->cmid)) {
416 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
417 $quiz->cmid = $cm->id;
420 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
421 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
423 // Log the deletion of the attempt.
424 $params = array(
425 'objectid' => $attempt->id,
426 'relateduserid' => $attempt->userid,
427 'context' => context_module::instance($quiz->cmid),
428 'other' => array(
429 'quizid' => $quiz->id
432 $event = \mod_quiz\event\attempt_deleted::create($params);
433 $event->add_record_snapshot('quiz_attempts', $attempt);
434 $event->trigger();
436 // Search quiz_attempts for other instances by this user.
437 // If none, then delete record for this quiz, this user from quiz_grades
438 // else recalculate best grade.
439 $userid = $attempt->userid;
440 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
441 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
442 } else {
443 quiz_save_best_grade($quiz, $userid);
446 quiz_update_grades($quiz, $userid);
450 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
451 * to one user.
452 * @param object $quiz the quiz object.
453 * @param int $userid (optional) if given, only delete the previews belonging to this user.
455 function quiz_delete_previews($quiz, $userid = null) {
456 global $DB;
457 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
458 if (!empty($userid)) {
459 $conditions['userid'] = $userid;
461 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
462 foreach ($previewattempts as $attempt) {
463 quiz_delete_attempt($attempt, $quiz);
468 * @param int $quizid The quiz id.
469 * @return bool whether this quiz has any (non-preview) attempts.
471 function quiz_has_attempts($quizid) {
472 global $DB;
473 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
476 // Functions to do with quiz layout and pages //////////////////////////////////
479 * Repaginate the questions in a quiz
480 * @param int $quizid the id of the quiz to repaginate.
481 * @param int $slotsperpage number of items to put on each page. 0 means unlimited.
483 function quiz_repaginate_questions($quizid, $slotsperpage) {
484 global $DB;
485 $trans = $DB->start_delegated_transaction();
487 $sections = $DB->get_records('quiz_sections', array('quizid' => $quizid), 'firstslot ASC');
488 $firstslots = array();
489 foreach ($sections as $section) {
490 if ((int)$section->firstslot === 1) {
491 continue;
493 $firstslots[] = $section->firstslot;
496 $slots = $DB->get_records('quiz_slots', array('quizid' => $quizid),
497 'slot');
498 $currentpage = 1;
499 $slotsonthispage = 0;
500 foreach ($slots as $slot) {
501 if (($firstslots && in_array($slot->slot, $firstslots)) ||
502 ($slotsonthispage && $slotsonthispage == $slotsperpage)) {
503 $currentpage += 1;
504 $slotsonthispage = 0;
506 if ($slot->page != $currentpage) {
507 $DB->set_field('quiz_slots', 'page', $currentpage, array('id' => $slot->id));
509 $slotsonthispage += 1;
512 $trans->allow_commit();
515 // Functions to do with quiz grades ////////////////////////////////////////////
518 * Convert the raw grade stored in $attempt into a grade out of the maximum
519 * grade for this quiz.
521 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
522 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
523 * @param bool|string $format whether to format the results for display
524 * or 'question' to format a question grade (different number of decimal places.
525 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
526 * if the $grade is null.
528 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
529 if (is_null($rawgrade)) {
530 $grade = null;
531 } else if ($quiz->sumgrades >= 0.000005) {
532 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
533 } else {
534 $grade = 0;
536 if ($format === 'question') {
537 $grade = quiz_format_question_grade($quiz, $grade);
538 } else if ($format) {
539 $grade = quiz_format_grade($quiz, $grade);
541 return $grade;
545 * Get the feedback text that should be show to a student who
546 * got this grade on this quiz. The feedback is processed ready for diplay.
548 * @param float $grade a grade on this quiz.
549 * @param object $quiz the quiz settings.
550 * @param object $context the quiz context.
551 * @return string the comment that corresponds to this grade (empty string if there is not one.
553 function quiz_feedback_for_grade($grade, $quiz, $context) {
554 global $DB;
556 if (is_null($grade)) {
557 return '';
560 // With CBM etc, it is possible to get -ve grades, which would then not match
561 // any feedback. Therefore, we replace -ve grades with 0.
562 $grade = max($grade, 0);
564 $feedback = $DB->get_record_select('quiz_feedback',
565 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
567 if (empty($feedback->feedbacktext)) {
568 return '';
571 // Clean the text, ready for display.
572 $formatoptions = new stdClass();
573 $formatoptions->noclean = true;
574 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
575 $context->id, 'mod_quiz', 'feedback', $feedback->id);
576 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
578 return $feedbacktext;
582 * @param object $quiz the quiz database row.
583 * @return bool Whether this quiz has any non-blank feedback text.
585 function quiz_has_feedback($quiz) {
586 global $DB;
587 static $cache = array();
588 if (!array_key_exists($quiz->id, $cache)) {
589 $cache[$quiz->id] = quiz_has_grades($quiz) &&
590 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
591 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
592 array($quiz->id));
594 return $cache[$quiz->id];
598 * Update the sumgrades field of the quiz. This needs to be called whenever
599 * the grading structure of the quiz is changed. For example if a question is
600 * added or removed, or a question weight is changed.
602 * You should call {@link quiz_delete_previews()} before you call this function.
604 * @param object $quiz a quiz.
606 function quiz_update_sumgrades($quiz) {
607 global $DB;
609 $sql = 'UPDATE {quiz}
610 SET sumgrades = COALESCE((
611 SELECT SUM(maxmark)
612 FROM {quiz_slots}
613 WHERE quizid = {quiz}.id
614 ), 0)
615 WHERE id = ?';
616 $DB->execute($sql, array($quiz->id));
617 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
619 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
620 // If the quiz has been attempted, and the sumgrades has been
621 // set to 0, then we must also set the maximum possible grade to 0, or
622 // we will get a divide by zero error.
623 quiz_set_grade(0, $quiz);
628 * Update the sumgrades field of the attempts at a quiz.
630 * @param object $quiz a quiz.
632 function quiz_update_all_attempt_sumgrades($quiz) {
633 global $DB;
634 $dm = new question_engine_data_mapper();
635 $timenow = time();
637 $sql = "UPDATE {quiz_attempts}
639 timemodified = :timenow,
640 sumgrades = (
641 {$dm->sum_usage_marks_subquery('uniqueid')}
643 WHERE quiz = :quizid AND state = :finishedstate";
644 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
645 'finishedstate' => quiz_attempt::FINISHED));
649 * The quiz grade is the maximum that student's results are marked out of. When it
650 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
651 * rescaled. After calling this function, you probably need to call
652 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
653 * quiz_update_grades.
655 * @param float $newgrade the new maximum grade for the quiz.
656 * @param object $quiz the quiz we are updating. Passed by reference so its
657 * grade field can be updated too.
658 * @return bool indicating success or failure.
660 function quiz_set_grade($newgrade, $quiz) {
661 global $DB;
662 // This is potentially expensive, so only do it if necessary.
663 if (abs($quiz->grade - $newgrade) < 1e-7) {
664 // Nothing to do.
665 return true;
668 $oldgrade = $quiz->grade;
669 $quiz->grade = $newgrade;
671 // Use a transaction, so that on those databases that support it, this is safer.
672 $transaction = $DB->start_delegated_transaction();
674 // Update the quiz table.
675 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
677 if ($oldgrade < 1) {
678 // If the old grade was zero, we cannot rescale, we have to recompute.
679 // We also recompute if the old grade was too small to avoid underflow problems.
680 quiz_update_all_final_grades($quiz);
682 } else {
683 // We can rescale the grades efficiently.
684 $timemodified = time();
685 $DB->execute("
686 UPDATE {quiz_grades}
687 SET grade = ? * grade, timemodified = ?
688 WHERE quiz = ?
689 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
692 if ($oldgrade > 1e-7) {
693 // Update the quiz_feedback table.
694 $factor = $newgrade/$oldgrade;
695 $DB->execute("
696 UPDATE {quiz_feedback}
697 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
698 WHERE quizid = ?
699 ", array($factor, $factor, $quiz->id));
702 // Update grade item and send all grades to gradebook.
703 quiz_grade_item_update($quiz);
704 quiz_update_grades($quiz);
706 $transaction->allow_commit();
707 return true;
711 * Save the overall grade for a user at a quiz in the quiz_grades table
713 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
714 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
715 * @param array $attempts The attempts of this user. Useful if you are
716 * looping through many users. Attempts can be fetched in one master query to
717 * avoid repeated querying.
718 * @return bool Indicates success or failure.
720 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
721 global $DB, $OUTPUT, $USER;
723 if (empty($userid)) {
724 $userid = $USER->id;
727 if (!$attempts) {
728 // Get all the attempts made by the user.
729 $attempts = quiz_get_user_attempts($quiz->id, $userid);
732 // Calculate the best grade.
733 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
734 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
736 // Save the best grade in the database.
737 if (is_null($bestgrade)) {
738 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
740 } else if ($grade = $DB->get_record('quiz_grades',
741 array('quiz' => $quiz->id, 'userid' => $userid))) {
742 $grade->grade = $bestgrade;
743 $grade->timemodified = time();
744 $DB->update_record('quiz_grades', $grade);
746 } else {
747 $grade = new stdClass();
748 $grade->quiz = $quiz->id;
749 $grade->userid = $userid;
750 $grade->grade = $bestgrade;
751 $grade->timemodified = time();
752 $DB->insert_record('quiz_grades', $grade);
755 quiz_update_grades($quiz, $userid);
759 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
761 * @param object $quiz the quiz settings object.
762 * @param array $attempts an array of all the user's attempts at this quiz in order.
763 * @return float the overall grade
765 function quiz_calculate_best_grade($quiz, $attempts) {
767 switch ($quiz->grademethod) {
769 case QUIZ_ATTEMPTFIRST:
770 $firstattempt = reset($attempts);
771 return $firstattempt->sumgrades;
773 case QUIZ_ATTEMPTLAST:
774 $lastattempt = end($attempts);
775 return $lastattempt->sumgrades;
777 case QUIZ_GRADEAVERAGE:
778 $sum = 0;
779 $count = 0;
780 foreach ($attempts as $attempt) {
781 if (!is_null($attempt->sumgrades)) {
782 $sum += $attempt->sumgrades;
783 $count++;
786 if ($count == 0) {
787 return null;
789 return $sum / $count;
791 case QUIZ_GRADEHIGHEST:
792 default:
793 $max = null;
794 foreach ($attempts as $attempt) {
795 if ($attempt->sumgrades > $max) {
796 $max = $attempt->sumgrades;
799 return $max;
804 * Update the final grade at this quiz for all students.
806 * This function is equivalent to calling quiz_save_best_grade for all
807 * users, but much more efficient.
809 * @param object $quiz the quiz settings.
811 function quiz_update_all_final_grades($quiz) {
812 global $DB;
814 if (!$quiz->sumgrades) {
815 return;
818 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
819 $firstlastattemptjoin = "JOIN (
820 SELECT
821 iquiza.userid,
822 MIN(attempt) AS firstattempt,
823 MAX(attempt) AS lastattempt
825 FROM {quiz_attempts} iquiza
827 WHERE
828 iquiza.state = :istatefinished AND
829 iquiza.preview = 0 AND
830 iquiza.quiz = :iquizid
832 GROUP BY iquiza.userid
833 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
835 switch ($quiz->grademethod) {
836 case QUIZ_ATTEMPTFIRST:
837 // Because of the where clause, there will only be one row, but we
838 // must still use an aggregate function.
839 $select = 'MAX(quiza.sumgrades)';
840 $join = $firstlastattemptjoin;
841 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
842 break;
844 case QUIZ_ATTEMPTLAST:
845 // Because of the where clause, there will only be one row, but we
846 // must still use an aggregate function.
847 $select = 'MAX(quiza.sumgrades)';
848 $join = $firstlastattemptjoin;
849 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
850 break;
852 case QUIZ_GRADEAVERAGE:
853 $select = 'AVG(quiza.sumgrades)';
854 $join = '';
855 $where = '';
856 break;
858 default:
859 case QUIZ_GRADEHIGHEST:
860 $select = 'MAX(quiza.sumgrades)';
861 $join = '';
862 $where = '';
863 break;
866 if ($quiz->sumgrades >= 0.000005) {
867 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
868 } else {
869 $finalgrade = '0';
871 $param['quizid'] = $quiz->id;
872 $param['quizid2'] = $quiz->id;
873 $param['quizid3'] = $quiz->id;
874 $param['quizid4'] = $quiz->id;
875 $param['statefinished'] = quiz_attempt::FINISHED;
876 $param['statefinished2'] = quiz_attempt::FINISHED;
877 $finalgradesubquery = "
878 SELECT quiza.userid, $finalgrade AS newgrade
879 FROM {quiz_attempts} quiza
880 $join
881 WHERE
882 $where
883 quiza.state = :statefinished AND
884 quiza.preview = 0 AND
885 quiza.quiz = :quizid3
886 GROUP BY quiza.userid";
888 $changedgrades = $DB->get_records_sql("
889 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
891 FROM (
892 SELECT userid
893 FROM {quiz_grades} qg
894 WHERE quiz = :quizid
895 UNION
896 SELECT DISTINCT userid
897 FROM {quiz_attempts} quiza2
898 WHERE
899 quiza2.state = :statefinished2 AND
900 quiza2.preview = 0 AND
901 quiza2.quiz = :quizid2
902 ) users
904 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
906 LEFT JOIN (
907 $finalgradesubquery
908 ) newgrades ON newgrades.userid = users.userid
910 WHERE
911 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
912 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
913 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
914 // The mess on the previous line is detecting where the value is
915 // NULL in one column, and NOT NULL in the other, but SQL does
916 // not have an XOR operator, and MS SQL server can't cope with
917 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
918 $param);
920 $timenow = time();
921 $todelete = array();
922 foreach ($changedgrades as $changedgrade) {
924 if (is_null($changedgrade->newgrade)) {
925 $todelete[] = $changedgrade->userid;
927 } else if (is_null($changedgrade->grade)) {
928 $toinsert = new stdClass();
929 $toinsert->quiz = $quiz->id;
930 $toinsert->userid = $changedgrade->userid;
931 $toinsert->timemodified = $timenow;
932 $toinsert->grade = $changedgrade->newgrade;
933 $DB->insert_record('quiz_grades', $toinsert);
935 } else {
936 $toupdate = new stdClass();
937 $toupdate->id = $changedgrade->id;
938 $toupdate->grade = $changedgrade->newgrade;
939 $toupdate->timemodified = $timenow;
940 $DB->update_record('quiz_grades', $toupdate);
944 if (!empty($todelete)) {
945 list($test, $params) = $DB->get_in_or_equal($todelete);
946 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
947 array_merge(array($quiz->id), $params));
952 * Efficiently update check state time on all open attempts
954 * @param array $conditions optional restrictions on which attempts to update
955 * Allowed conditions:
956 * courseid => (array|int) attempts in given course(s)
957 * userid => (array|int) attempts for given user(s)
958 * quizid => (array|int) attempts in given quiz(s)
959 * groupid => (array|int) quizzes with some override for given group(s)
962 function quiz_update_open_attempts(array $conditions) {
963 global $DB;
965 foreach ($conditions as &$value) {
966 if (!is_array($value)) {
967 $value = array($value);
971 $params = array();
972 $wheres = array("quiza.state IN ('inprogress', 'overdue')");
973 $iwheres = array("iquiza.state IN ('inprogress', 'overdue')");
975 if (isset($conditions['courseid'])) {
976 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
977 $params = array_merge($params, $inparams);
978 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
979 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
980 $params = array_merge($params, $inparams);
981 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
984 if (isset($conditions['userid'])) {
985 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
986 $params = array_merge($params, $inparams);
987 $wheres[] = "quiza.userid $incond";
988 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
989 $params = array_merge($params, $inparams);
990 $iwheres[] = "iquiza.userid $incond";
993 if (isset($conditions['quizid'])) {
994 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
995 $params = array_merge($params, $inparams);
996 $wheres[] = "quiza.quiz $incond";
997 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
998 $params = array_merge($params, $inparams);
999 $iwheres[] = "iquiza.quiz $incond";
1002 if (isset($conditions['groupid'])) {
1003 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
1004 $params = array_merge($params, $inparams);
1005 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1006 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
1007 $params = array_merge($params, $inparams);
1008 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1011 // SQL to compute timeclose and timelimit for each attempt:
1012 $quizausersql = quiz_get_attempt_usertime_sql(
1013 implode("\n AND ", $iwheres));
1015 // SQL to compute the new timecheckstate
1016 $timecheckstatesql = "
1017 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
1018 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
1019 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
1020 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
1021 ELSE quizauser.usertimeclose END +
1022 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
1024 // SQL to select which attempts to process
1025 $attemptselect = implode("\n AND ", $wheres);
1028 * Each database handles updates with inner joins differently:
1029 * - mysql does not allow a FROM clause
1030 * - postgres and mssql allow FROM but handle table aliases differently
1031 * - oracle requires a subquery
1033 * Different code for each database.
1036 $dbfamily = $DB->get_dbfamily();
1037 if ($dbfamily == 'mysql') {
1038 $updatesql = "UPDATE {quiz_attempts} quiza
1039 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1040 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1041 SET quiza.timecheckstate = $timecheckstatesql
1042 WHERE $attemptselect";
1043 } else if ($dbfamily == 'postgres') {
1044 $updatesql = "UPDATE {quiz_attempts} quiza
1045 SET timecheckstate = $timecheckstatesql
1046 FROM {quiz} quiz, ( $quizausersql ) quizauser
1047 WHERE quiz.id = quiza.quiz
1048 AND quizauser.id = quiza.id
1049 AND $attemptselect";
1050 } else if ($dbfamily == 'mssql') {
1051 $updatesql = "UPDATE quiza
1052 SET timecheckstate = $timecheckstatesql
1053 FROM {quiz_attempts} quiza
1054 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1055 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1056 WHERE $attemptselect";
1057 } else {
1058 // oracle, sqlite and others
1059 $updatesql = "UPDATE {quiz_attempts} quiza
1060 SET timecheckstate = (
1061 SELECT $timecheckstatesql
1062 FROM {quiz} quiz, ( $quizausersql ) quizauser
1063 WHERE quiz.id = quiza.quiz
1064 AND quizauser.id = quiza.id
1066 WHERE $attemptselect";
1069 $DB->execute($updatesql, $params);
1073 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
1075 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1076 * for performance. These can use the table alias iquiza for the quiz attempts table.
1077 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
1079 function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1080 if ($redundantwhereclauses) {
1081 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1083 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1084 // any other group override
1085 $quizausersql = "
1086 SELECT iquiza.id,
1087 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1088 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1090 FROM {quiz_attempts} iquiza
1091 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1092 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1093 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1094 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1095 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1096 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1097 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
1098 $redundantwhereclauses
1099 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1100 return $quizausersql;
1104 * Return the attempt with the best grade for a quiz
1106 * Which attempt is the best depends on $quiz->grademethod. If the grade
1107 * method is GRADEAVERAGE then this function simply returns the last attempt.
1108 * @return object The attempt with the best grade
1109 * @param object $quiz The quiz for which the best grade is to be calculated
1110 * @param array $attempts An array of all the attempts of the user at the quiz
1112 function quiz_calculate_best_attempt($quiz, $attempts) {
1114 switch ($quiz->grademethod) {
1116 case QUIZ_ATTEMPTFIRST:
1117 foreach ($attempts as $attempt) {
1118 return $attempt;
1120 break;
1122 case QUIZ_GRADEAVERAGE: // We need to do something with it.
1123 case QUIZ_ATTEMPTLAST:
1124 foreach ($attempts as $attempt) {
1125 $final = $attempt;
1127 return $final;
1129 default:
1130 case QUIZ_GRADEHIGHEST:
1131 $max = -1;
1132 foreach ($attempts as $attempt) {
1133 if ($attempt->sumgrades > $max) {
1134 $max = $attempt->sumgrades;
1135 $maxattempt = $attempt;
1138 return $maxattempt;
1143 * @return array int => lang string the options for calculating the quiz grade
1144 * from the individual attempt grades.
1146 function quiz_get_grading_options() {
1147 return array(
1148 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1149 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1150 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1151 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1156 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1157 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
1158 * @return the lang string for that option.
1160 function quiz_get_grading_option_name($option) {
1161 $strings = quiz_get_grading_options();
1162 return $strings[$option];
1166 * @return array string => lang string the options for handling overdue quiz
1167 * attempts.
1169 function quiz_get_overdue_handling_options() {
1170 return array(
1171 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1172 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1173 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1178 * Get the choices for what size user picture to show.
1179 * @return array string => lang string the options for whether to display the user's picture.
1181 function quiz_get_user_image_options() {
1182 return array(
1183 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
1184 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
1185 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'),
1190 * Get the choices to offer for the 'Questions per page' option.
1191 * @return array int => string.
1193 function quiz_questions_per_page_options() {
1194 $pageoptions = array();
1195 $pageoptions[0] = get_string('neverallononepage', 'quiz');
1196 $pageoptions[1] = get_string('everyquestion', 'quiz');
1197 for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
1198 $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
1200 return $pageoptions;
1204 * Get the human-readable name for a quiz attempt state.
1205 * @param string $state one of the state constants like {@link quiz_attempt::IN_PROGRESS}.
1206 * @return string The lang string to describe that state.
1208 function quiz_attempt_state_name($state) {
1209 switch ($state) {
1210 case quiz_attempt::IN_PROGRESS:
1211 return get_string('stateinprogress', 'quiz');
1212 case quiz_attempt::OVERDUE:
1213 return get_string('stateoverdue', 'quiz');
1214 case quiz_attempt::FINISHED:
1215 return get_string('statefinished', 'quiz');
1216 case quiz_attempt::ABANDONED:
1217 return get_string('stateabandoned', 'quiz');
1218 default:
1219 throw new coding_exception('Unknown quiz attempt state.');
1223 // Other quiz functions ////////////////////////////////////////////////////////
1226 * @param object $quiz the quiz.
1227 * @param int $cmid the course_module object for this quiz.
1228 * @param object $question the question.
1229 * @param string $returnurl url to return to after action is done.
1230 * @return string html for a number of icons linked to action pages for a
1231 * question - preview and edit / view icons depending on user capabilities.
1233 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
1234 $html = quiz_question_preview_button($quiz, $question) . ' ' .
1235 quiz_question_edit_button($cmid, $question, $returnurl);
1236 return $html;
1240 * @param int $cmid the course_module.id for this quiz.
1241 * @param object $question the question.
1242 * @param string $returnurl url to return to after action is done.
1243 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
1244 * @return the HTML for an edit icon, view icon, or nothing for a question
1245 * (depending on permissions).
1247 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
1248 global $CFG, $OUTPUT;
1250 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
1251 static $stredit = null;
1252 static $strview = null;
1253 if ($stredit === null) {
1254 $stredit = get_string('edit');
1255 $strview = get_string('view');
1258 // What sort of icon should we show?
1259 $action = '';
1260 if (!empty($question->id) &&
1261 (question_has_capability_on($question, 'edit', $question->category) ||
1262 question_has_capability_on($question, 'move', $question->category))) {
1263 $action = $stredit;
1264 $icon = '/t/edit';
1265 } else if (!empty($question->id) &&
1266 question_has_capability_on($question, 'view', $question->category)) {
1267 $action = $strview;
1268 $icon = '/i/info';
1271 // Build the icon.
1272 if ($action) {
1273 if ($returnurl instanceof moodle_url) {
1274 $returnurl = $returnurl->out_as_local_url(false);
1276 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
1277 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
1278 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
1279 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
1280 '</a>';
1281 } else if ($contentaftericon) {
1282 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
1283 } else {
1284 return '';
1289 * @param object $quiz the quiz settings
1290 * @param object $question the question
1291 * @return moodle_url to preview this question with the options from this quiz.
1293 function quiz_question_preview_url($quiz, $question) {
1294 // Get the appropriate display options.
1295 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
1296 mod_quiz_display_options::DURING);
1298 $maxmark = null;
1299 if (isset($question->maxmark)) {
1300 $maxmark = $question->maxmark;
1303 // Work out the correcte preview URL.
1304 return question_preview_url($question->id, $quiz->preferredbehaviour,
1305 $maxmark, $displayoptions);
1309 * @param object $quiz the quiz settings
1310 * @param object $question the question
1311 * @param bool $label if true, show the preview question label after the icon
1312 * @return the HTML for a preview question icon.
1314 function quiz_question_preview_button($quiz, $question, $label = false) {
1315 global $PAGE;
1316 if (!question_has_capability_on($question, 'use', $question->category)) {
1317 return '';
1320 return $PAGE->get_renderer('mod_quiz', 'edit')->question_preview_icon($quiz, $question, $label);
1324 * @param object $attempt the attempt.
1325 * @param object $context the quiz context.
1326 * @return int whether flags should be shown/editable to the current user for this attempt.
1328 function quiz_get_flag_option($attempt, $context) {
1329 global $USER;
1330 if (!has_capability('moodle/question:flag', $context)) {
1331 return question_display_options::HIDDEN;
1332 } else if ($attempt->userid == $USER->id) {
1333 return question_display_options::EDITABLE;
1334 } else {
1335 return question_display_options::VISIBLE;
1340 * Work out what state this quiz attempt is in - in the sense used by
1341 * quiz_get_review_options, not in the sense of $attempt->state.
1342 * @param object $quiz the quiz settings
1343 * @param object $attempt the quiz_attempt database row.
1344 * @return int one of the mod_quiz_display_options::DURING,
1345 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
1347 function quiz_attempt_state($quiz, $attempt) {
1348 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
1349 return mod_quiz_display_options::DURING;
1350 } else if (time() < $attempt->timefinish + 120) {
1351 return mod_quiz_display_options::IMMEDIATELY_AFTER;
1352 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
1353 return mod_quiz_display_options::LATER_WHILE_OPEN;
1354 } else {
1355 return mod_quiz_display_options::AFTER_CLOSE;
1360 * The the appropraite mod_quiz_display_options object for this attempt at this
1361 * quiz right now.
1363 * @param object $quiz the quiz instance.
1364 * @param object $attempt the attempt in question.
1365 * @param $context the quiz context.
1367 * @return mod_quiz_display_options
1369 function quiz_get_review_options($quiz, $attempt, $context) {
1370 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
1372 $options->readonly = true;
1373 $options->flags = quiz_get_flag_option($attempt, $context);
1374 if (!empty($attempt->id)) {
1375 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1376 array('attempt' => $attempt->id));
1379 // Show a link to the comment box only for closed attempts.
1380 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
1381 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
1382 $options->manualcomment = question_display_options::VISIBLE;
1383 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1384 array('attempt' => $attempt->id));
1387 if (!is_null($context) && !$attempt->preview &&
1388 has_capability('mod/quiz:viewreports', $context) &&
1389 has_capability('moodle/grade:viewhidden', $context)) {
1390 // People who can see reports and hidden grades should be shown everything,
1391 // except during preview when teachers want to see what students see.
1392 $options->attempt = question_display_options::VISIBLE;
1393 $options->correctness = question_display_options::VISIBLE;
1394 $options->marks = question_display_options::MARK_AND_MAX;
1395 $options->feedback = question_display_options::VISIBLE;
1396 $options->numpartscorrect = question_display_options::VISIBLE;
1397 $options->manualcomment = question_display_options::VISIBLE;
1398 $options->generalfeedback = question_display_options::VISIBLE;
1399 $options->rightanswer = question_display_options::VISIBLE;
1400 $options->overallfeedback = question_display_options::VISIBLE;
1401 $options->history = question_display_options::VISIBLE;
1405 return $options;
1409 * Combines the review options from a number of different quiz attempts.
1410 * Returns an array of two ojects, so the suggested way of calling this
1411 * funciton is:
1412 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1414 * @param object $quiz the quiz instance.
1415 * @param array $attempts an array of attempt objects.
1416 * @param $context the roles and permissions context,
1417 * normally the context for the quiz module instance.
1419 * @return array of two options objects, one showing which options are true for
1420 * at least one of the attempts, the other showing which options are true
1421 * for all attempts.
1423 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1424 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1425 $someoptions = new stdClass();
1426 $alloptions = new stdClass();
1427 foreach ($fields as $field) {
1428 $someoptions->$field = false;
1429 $alloptions->$field = true;
1431 $someoptions->marks = question_display_options::HIDDEN;
1432 $alloptions->marks = question_display_options::MARK_AND_MAX;
1434 foreach ($attempts as $attempt) {
1435 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1436 quiz_attempt_state($quiz, $attempt));
1437 foreach ($fields as $field) {
1438 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1439 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1441 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1442 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1444 return array($someoptions, $alloptions);
1447 // Functions for sending notification messages /////////////////////////////////
1450 * Sends a confirmation message to the student confirming that the attempt was processed.
1452 * @param object $a lots of useful information that can be used in the message
1453 * subject and body.
1455 * @return int|false as for {@link message_send()}.
1457 function quiz_send_confirmation($recipient, $a) {
1459 // Add information about the recipient to $a.
1460 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1461 $a->username = fullname($recipient);
1462 $a->userusername = $recipient->username;
1464 // Prepare the message.
1465 $eventdata = new stdClass();
1466 $eventdata->component = 'mod_quiz';
1467 $eventdata->name = 'confirmation';
1468 $eventdata->notification = 1;
1470 $eventdata->userfrom = core_user::get_noreply_user();
1471 $eventdata->userto = $recipient;
1472 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1473 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1474 $eventdata->fullmessageformat = FORMAT_PLAIN;
1475 $eventdata->fullmessagehtml = '';
1477 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1478 $eventdata->contexturl = $a->quizurl;
1479 $eventdata->contexturlname = $a->quizname;
1481 // ... and send it.
1482 return message_send($eventdata);
1486 * Sends notification messages to the interested parties that assign the role capability
1488 * @param object $recipient user object of the intended recipient
1489 * @param object $a associative array of replaceable fields for the templates
1491 * @return int|false as for {@link message_send()}.
1493 function quiz_send_notification($recipient, $submitter, $a) {
1495 // Recipient info for template.
1496 $a->useridnumber = $recipient->idnumber;
1497 $a->username = fullname($recipient);
1498 $a->userusername = $recipient->username;
1500 // Prepare the message.
1501 $eventdata = new stdClass();
1502 $eventdata->component = 'mod_quiz';
1503 $eventdata->name = 'submission';
1504 $eventdata->notification = 1;
1506 $eventdata->userfrom = $submitter;
1507 $eventdata->userto = $recipient;
1508 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1509 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1510 $eventdata->fullmessageformat = FORMAT_PLAIN;
1511 $eventdata->fullmessagehtml = '';
1513 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1514 $eventdata->contexturl = $a->quizreviewurl;
1515 $eventdata->contexturlname = $a->quizname;
1517 // ... and send it.
1518 return message_send($eventdata);
1522 * Send all the requried messages when a quiz attempt is submitted.
1524 * @param object $course the course
1525 * @param object $quiz the quiz
1526 * @param object $attempt this attempt just finished
1527 * @param object $context the quiz context
1528 * @param object $cm the coursemodule for this quiz
1530 * @return bool true if all necessary messages were sent successfully, else false.
1532 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1533 global $CFG, $DB;
1535 // Do nothing if required objects not present.
1536 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1537 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1540 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1542 // Check for confirmation required.
1543 $sendconfirm = false;
1544 $notifyexcludeusers = '';
1545 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1546 $notifyexcludeusers = $submitter->id;
1547 $sendconfirm = true;
1550 // Check for notifications required.
1551 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang, u.timezone, u.mailformat, u.maildisplay, ';
1552 $notifyfields .= get_all_user_name_fields(true, 'u');
1553 $groups = groups_get_all_groups($course->id, $submitter->id);
1554 if (is_array($groups) && count($groups) > 0) {
1555 $groups = array_keys($groups);
1556 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1557 // If the user is not in a group, and the quiz is set to group mode,
1558 // then set $groups to a non-existant id so that only users with
1559 // 'moodle/site:accessallgroups' get notified.
1560 $groups = -1;
1561 } else {
1562 $groups = '';
1564 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1565 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1567 if (empty($userstonotify) && !$sendconfirm) {
1568 return true; // Nothing to do.
1571 $a = new stdClass();
1572 // Course info.
1573 $a->coursename = $course->fullname;
1574 $a->courseshortname = $course->shortname;
1575 // Quiz info.
1576 $a->quizname = $quiz->name;
1577 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1578 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1579 format_string($quiz->name) . ' report</a>';
1580 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1581 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1582 // Attempt info.
1583 $a->submissiontime = userdate($attempt->timefinish);
1584 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1585 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1586 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1587 format_string($quiz->name) . ' review</a>';
1588 // Student who sat the quiz info.
1589 $a->studentidnumber = $submitter->idnumber;
1590 $a->studentname = fullname($submitter);
1591 $a->studentusername = $submitter->username;
1593 $allok = true;
1595 // Send notifications if required.
1596 if (!empty($userstonotify)) {
1597 foreach ($userstonotify as $recipient) {
1598 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1602 // Send confirmation if required. We send the student confirmation last, so
1603 // that if message sending is being intermittently buggy, which means we send
1604 // some but not all messages, and then try again later, then teachers may get
1605 // duplicate messages, but the student will always get exactly one.
1606 if ($sendconfirm) {
1607 $allok = $allok && quiz_send_confirmation($submitter, $a);
1610 return $allok;
1614 * Send the notification message when a quiz attempt becomes overdue.
1616 * @param quiz_attempt $attemptobj all the data about the quiz attempt.
1618 function quiz_send_overdue_message($attemptobj) {
1619 global $CFG, $DB;
1621 $submitter = $DB->get_record('user', array('id' => $attemptobj->get_userid()), '*', MUST_EXIST);
1623 if (!$attemptobj->has_capability('mod/quiz:emailwarnoverdue', $submitter->id, false)) {
1624 return; // Message not required.
1627 if (!$attemptobj->has_response_to_at_least_one_graded_question()) {
1628 return; // Message not required.
1631 // Prepare lots of useful information that admins might want to include in
1632 // the email message.
1633 $quizname = format_string($attemptobj->get_quiz_name());
1635 $deadlines = array();
1636 if ($attemptobj->get_quiz()->timelimit) {
1637 $deadlines[] = $attemptobj->get_attempt()->timestart + $attemptobj->get_quiz()->timelimit;
1639 if ($attemptobj->get_quiz()->timeclose) {
1640 $deadlines[] = $attemptobj->get_quiz()->timeclose;
1642 $duedate = min($deadlines);
1643 $graceend = $duedate + $attemptobj->get_quiz()->graceperiod;
1645 $a = new stdClass();
1646 // Course info.
1647 $a->coursename = format_string($attemptobj->get_course()->fullname);
1648 $a->courseshortname = format_string($attemptobj->get_course()->shortname);
1649 // Quiz info.
1650 $a->quizname = $quizname;
1651 $a->quizurl = $attemptobj->view_url();
1652 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1653 // Attempt info.
1654 $a->attemptduedate = userdate($duedate);
1655 $a->attemptgraceend = userdate($graceend);
1656 $a->attemptsummaryurl = $attemptobj->summary_url()->out(false);
1657 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1658 // Student's info.
1659 $a->studentidnumber = $submitter->idnumber;
1660 $a->studentname = fullname($submitter);
1661 $a->studentusername = $submitter->username;
1663 // Prepare the message.
1664 $eventdata = new stdClass();
1665 $eventdata->component = 'mod_quiz';
1666 $eventdata->name = 'attempt_overdue';
1667 $eventdata->notification = 1;
1669 $eventdata->userfrom = core_user::get_noreply_user();
1670 $eventdata->userto = $submitter;
1671 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1672 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1673 $eventdata->fullmessageformat = FORMAT_PLAIN;
1674 $eventdata->fullmessagehtml = '';
1676 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1677 $eventdata->contexturl = $a->quizurl;
1678 $eventdata->contexturlname = $a->quizname;
1680 // Send the message.
1681 return message_send($eventdata);
1685 * Handle the quiz_attempt_submitted event.
1687 * This sends the confirmation and notification messages, if required.
1689 * @param object $event the event object.
1691 function quiz_attempt_submitted_handler($event) {
1692 global $DB;
1694 $course = $DB->get_record('course', array('id' => $event->courseid));
1695 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1696 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1697 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1699 if (!($course && $quiz && $cm && $attempt)) {
1700 // Something has been deleted since the event was raised. Therefore, the
1701 // event is no longer relevant.
1702 return true;
1705 // Update completion state.
1706 $completion = new completion_info($course);
1707 if ($completion->is_enabled($cm) && ($quiz->completionattemptsexhausted || $quiz->completionpass)) {
1708 $completion->update_state($cm, COMPLETION_COMPLETE, $event->userid);
1710 return quiz_send_notification_messages($course, $quiz, $attempt,
1711 context_module::instance($cm->id), $cm);
1715 * Handle groups_member_added event
1717 * @param object $event the event object.
1718 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_added()}.
1720 function quiz_groups_member_added_handler($event) {
1721 debugging('quiz_groups_member_added_handler() is deprecated, please use ' .
1722 '\mod_quiz\group_observers::group_member_added() instead.', DEBUG_DEVELOPER);
1723 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1727 * Handle groups_member_removed event
1729 * @param object $event the event object.
1730 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1732 function quiz_groups_member_removed_handler($event) {
1733 debugging('quiz_groups_member_removed_handler() is deprecated, please use ' .
1734 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1735 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1739 * Handle groups_group_deleted event
1741 * @param object $event the event object.
1742 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_deleted()}.
1744 function quiz_groups_group_deleted_handler($event) {
1745 global $DB;
1746 debugging('quiz_groups_group_deleted_handler() is deprecated, please use ' .
1747 '\mod_quiz\group_observers::group_deleted() instead.', DEBUG_DEVELOPER);
1748 quiz_process_group_deleted_in_course($event->courseid);
1752 * Logic to happen when a/some group(s) has/have been deleted in a course.
1754 * @param int $courseid The course ID.
1755 * @return void
1757 function quiz_process_group_deleted_in_course($courseid) {
1758 global $DB;
1760 // It would be nice if we got the groupid that was deleted.
1761 // Instead, we just update all quizzes with orphaned group overrides.
1762 $sql = "SELECT o.id, o.quiz
1763 FROM {quiz_overrides} o
1764 JOIN {quiz} quiz ON quiz.id = o.quiz
1765 LEFT JOIN {groups} grp ON grp.id = o.groupid
1766 WHERE quiz.course = :courseid
1767 AND o.groupid IS NOT NULL
1768 AND grp.id IS NULL";
1769 $params = array('courseid' => $courseid);
1770 $records = $DB->get_records_sql_menu($sql, $params);
1771 if (!$records) {
1772 return; // Nothing to do.
1774 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
1775 quiz_update_open_attempts(array('quizid' => array_unique(array_values($records))));
1779 * Handle groups_members_removed event
1781 * @param object $event the event object.
1782 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1784 function quiz_groups_members_removed_handler($event) {
1785 debugging('quiz_groups_members_removed_handler() is deprecated, please use ' .
1786 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1787 if ($event->userid == 0) {
1788 quiz_update_open_attempts(array('courseid'=>$event->courseid));
1789 } else {
1790 quiz_update_open_attempts(array('courseid'=>$event->courseid, 'userid'=>$event->userid));
1795 * Get the information about the standard quiz JavaScript module.
1796 * @return array a standard jsmodule structure.
1798 function quiz_get_js_module() {
1799 global $PAGE;
1801 return array(
1802 'name' => 'mod_quiz',
1803 'fullpath' => '/mod/quiz/module.js',
1804 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1805 'core_question_engine', 'moodle-core-formchangechecker'),
1806 'strings' => array(
1807 array('cancel', 'moodle'),
1808 array('flagged', 'question'),
1809 array('functiondisabledbysecuremode', 'quiz'),
1810 array('startattempt', 'quiz'),
1811 array('timesup', 'quiz'),
1812 array('changesmadereallygoaway', 'moodle'),
1819 * An extension of question_display_options that includes the extra options used
1820 * by the quiz.
1822 * @copyright 2010 The Open University
1823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1825 class mod_quiz_display_options extends question_display_options {
1826 /**#@+
1827 * @var integer bits used to indicate various times in relation to a
1828 * quiz attempt.
1830 const DURING = 0x10000;
1831 const IMMEDIATELY_AFTER = 0x01000;
1832 const LATER_WHILE_OPEN = 0x00100;
1833 const AFTER_CLOSE = 0x00010;
1834 /**#@-*/
1837 * @var boolean if this is false, then the student is not allowed to review
1838 * anything about the attempt.
1840 public $attempt = true;
1843 * @var boolean if this is false, then the student is not allowed to review
1844 * anything about the attempt.
1846 public $overallfeedback = self::VISIBLE;
1849 * Set up the various options from the quiz settings, and a time constant.
1850 * @param object $quiz the quiz settings.
1851 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1852 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1853 * @return mod_quiz_display_options set up appropriately.
1855 public static function make_from_quiz($quiz, $when) {
1856 $options = new self();
1858 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1859 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
1860 $options->marks = self::extract($quiz->reviewmarks, $when,
1861 self::MARK_AND_MAX, self::MAX_ONLY);
1862 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1863 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1864 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1865 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1867 $options->numpartscorrect = $options->feedback;
1868 $options->manualcomment = $options->feedback;
1870 if ($quiz->questiondecimalpoints != -1) {
1871 $options->markdp = $quiz->questiondecimalpoints;
1872 } else {
1873 $options->markdp = $quiz->decimalpoints;
1876 return $options;
1879 protected static function extract($bitmask, $bit,
1880 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
1881 if ($bitmask & $bit) {
1882 return $whenset;
1883 } else {
1884 return $whennotset;
1891 * A {@link qubaid_condition} for finding all the question usages belonging to
1892 * a particular quiz.
1894 * @copyright 2010 The Open University
1895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1897 class qubaids_for_quiz extends qubaid_join {
1898 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1899 $where = 'quiza.quiz = :quizaquiz';
1900 $params = array('quizaquiz' => $quizid);
1902 if (!$includepreviews) {
1903 $where .= ' AND preview = 0';
1906 if ($onlyfinished) {
1907 $where .= ' AND state == :statefinished';
1908 $params['statefinished'] = quiz_attempt::FINISHED;
1911 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
1916 * Creates a textual representation of a question for display.
1918 * @param object $question A question object from the database questions table
1919 * @param bool $showicon If true, show the question's icon with the question. False by default.
1920 * @param bool $showquestiontext If true (default), show question text after question name.
1921 * If false, show only question name.
1922 * @return string
1924 function quiz_question_tostring($question, $showicon = false, $showquestiontext = true) {
1925 $result = '';
1927 $name = shorten_text(format_string($question->name), 200);
1928 if ($showicon) {
1929 $name .= print_question_icon($question) . ' ' . $name;
1931 $result .= html_writer::span($name, 'questionname');
1933 if ($showquestiontext) {
1934 $questiontext = question_utils::to_plain_text($question->questiontext,
1935 $question->questiontextformat, array('noclean' => true, 'para' => false));
1936 $questiontext = shorten_text($questiontext, 200);
1937 if ($questiontext) {
1938 $result .= ' ' . html_writer::span(s($questiontext), 'questiontext');
1942 return $result;
1946 * Verify that the question exists, and the user has permission to use it.
1947 * Does not return. Throws an exception if the question cannot be used.
1948 * @param int $questionid The id of the question.
1950 function quiz_require_question_use($questionid) {
1951 global $DB;
1952 $question = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
1953 question_require_capability_on($question, 'use');
1957 * Verify that the question exists, and the user has permission to use it.
1958 * @param object $quiz the quiz settings.
1959 * @param int $slot which question in the quiz to test.
1960 * @return bool whether the user can use this question.
1962 function quiz_has_question_use($quiz, $slot) {
1963 global $DB;
1964 $question = $DB->get_record_sql("
1965 SELECT q.*
1966 FROM {quiz_slots} slot
1967 JOIN {question} q ON q.id = slot.questionid
1968 WHERE slot.quizid = ? AND slot.slot = ?", array($quiz->id, $slot));
1969 if (!$question) {
1970 return false;
1972 return question_has_capability_on($question, 'use');
1976 * Add a question to a quiz
1978 * Adds a question to a quiz by updating $quiz as well as the
1979 * quiz and quiz_slots tables. It also adds a page break if required.
1980 * @param int $questionid The id of the question to be added
1981 * @param object $quiz The extended quiz object as used by edit.php
1982 * This is updated by this function
1983 * @param int $page Which page in quiz to add the question on. If 0 (default),
1984 * add at the end
1985 * @param float $maxmark The maximum mark to set for this question. (Optional,
1986 * defaults to question.defaultmark.
1987 * @return bool false if the question was already in the quiz
1989 function quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null) {
1990 global $DB;
1991 $slots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id),
1992 'slot', 'questionid, slot, page, id');
1993 if (array_key_exists($questionid, $slots)) {
1994 return false;
1997 $trans = $DB->start_delegated_transaction();
1999 $maxpage = 1;
2000 $numonlastpage = 0;
2001 foreach ($slots as $slot) {
2002 if ($slot->page > $maxpage) {
2003 $maxpage = $slot->page;
2004 $numonlastpage = 1;
2005 } else {
2006 $numonlastpage += 1;
2010 // Add the new question instance.
2011 $slot = new stdClass();
2012 $slot->quizid = $quiz->id;
2013 $slot->questionid = $questionid;
2015 if ($maxmark !== null) {
2016 $slot->maxmark = $maxmark;
2017 } else {
2018 $slot->maxmark = $DB->get_field('question', 'defaultmark', array('id' => $questionid));
2021 if (is_int($page) && $page >= 1) {
2022 // Adding on a given page.
2023 $lastslotbefore = 0;
2024 foreach (array_reverse($slots) as $otherslot) {
2025 if ($otherslot->page > $page) {
2026 $DB->set_field('quiz_slots', 'slot', $otherslot->slot + 1, array('id' => $otherslot->id));
2027 } else {
2028 $lastslotbefore = $otherslot->slot;
2029 break;
2032 $slot->slot = $lastslotbefore + 1;
2033 $slot->page = min($page, $maxpage + 1);
2035 $DB->execute("
2036 UPDATE {quiz_sections}
2037 SET firstslot = firstslot + 1
2038 WHERE quizid = ?
2039 AND firstslot > ?
2040 ", array($quiz->id, max($lastslotbefore, 1)));
2042 } else {
2043 $lastslot = end($slots);
2044 if ($lastslot) {
2045 $slot->slot = $lastslot->slot + 1;
2046 } else {
2047 $slot->slot = 1;
2049 if ($quiz->questionsperpage && $numonlastpage >= $quiz->questionsperpage) {
2050 $slot->page = $maxpage + 1;
2051 } else {
2052 $slot->page = $maxpage;
2056 $DB->insert_record('quiz_slots', $slot);
2057 $trans->allow_commit();
2061 * Add a random question to the quiz at a given point.
2062 * @param object $quiz the quiz settings.
2063 * @param int $addonpage the page on which to add the question.
2064 * @param int $categoryid the question category to add the question from.
2065 * @param int $number the number of random questions to add.
2066 * @param bool $includesubcategories whether to include questoins from subcategories.
2068 function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,
2069 $includesubcategories) {
2070 global $DB;
2072 $category = $DB->get_record('question_categories', array('id' => $categoryid));
2073 if (!$category) {
2074 print_error('invalidcategoryid', 'error');
2077 $catcontext = context::instance_by_id($category->contextid);
2078 require_capability('moodle/question:useall', $catcontext);
2080 // Find existing random questions in this category that are
2081 // not used by any quiz.
2082 if ($existingquestions = $DB->get_records_sql(
2083 "SELECT q.id, q.qtype FROM {question} q
2084 WHERE qtype = 'random'
2085 AND category = ?
2086 AND " . $DB->sql_compare_text('questiontext') . " = ?
2087 AND NOT EXISTS (
2088 SELECT *
2089 FROM {quiz_slots}
2090 WHERE questionid = q.id)
2091 ORDER BY id", array($category->id, ($includesubcategories ? '1' : '0')))) {
2092 // Take as many of these as needed.
2093 while (($existingquestion = array_shift($existingquestions)) && $number > 0) {
2094 quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage);
2095 $number -= 1;
2099 if ($number <= 0) {
2100 return;
2103 // More random questions are needed, create them.
2104 for ($i = 0; $i < $number; $i += 1) {
2105 $form = new stdClass();
2106 $form->questiontext = array('text' => ($includesubcategories ? '1' : '0'), 'format' => 0);
2107 $form->category = $category->id . ',' . $category->contextid;
2108 $form->defaultmark = 1;
2109 $form->hidden = 1;
2110 $form->stamp = make_unique_id_code(); // Set the unique code (not to be changed).
2111 $question = new stdClass();
2112 $question->qtype = 'random';
2113 $question = question_bank::get_qtype('random')->save_question($question, $form);
2114 if (!isset($question->id)) {
2115 print_error('cannotinsertrandomquestion', 'quiz');
2117 quiz_add_quiz_question($question->id, $quiz, $addonpage);