2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
28 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 defined('MOODLE_INTERNAL') || die();
35 require_once($CFG->dirroot . '/mod/quiz/lib.php');
36 require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
37 require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
38 require_once($CFG->dirroot . '/mod/quiz/renderer.php');
39 require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
40 require_once($CFG->dirroot . '/question/editlib.php');
41 require_once($CFG->libdir . '/eventslib.php');
42 require_once($CFG->libdir . '/filelib.php');
46 * @var int We show the countdown timer if there is less than this amount of time left before the
47 * the quiz close date. (1 hour)
49 define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
52 * @var int If there are fewer than this many seconds left when the student submits
53 * a page of the quiz, then do not take them to the next page of the quiz. Instead
54 * close the quiz immediately.
56 define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
59 * @var int We show no image when user selects No image from dropdown menu in quiz settings.
61 define('QUIZ_SHOWIMAGE_NONE', 0);
64 * @var int We show small image when user selects small image from dropdown menu in quiz settings.
66 define('QUIZ_SHOWIMAGE_SMALL', 1);
69 * @var int We show Large image when user selects Large image from dropdown menu in quiz settings.
71 define('QUIZ_SHOWIMAGE_LARGE', 2);
74 // Functions related to attempts ///////////////////////////////////////////////
77 * Creates an object to represent a new attempt at a quiz
79 * Creates an attempt object to represent an attempt at the quiz by the current
80 * user starting at the current time. The ->id field is not set. The object is
81 * NOT written to the database.
83 * @param object $quizobj the quiz object to create an attempt for.
84 * @param int $attemptnumber the sequence number for the attempt.
85 * @param object $lastattempt the previous attempt by this user, if any. Only needed
86 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
87 * @param int $timenow the time the attempt was started at.
88 * @param bool $ispreview whether this new attempt is a preview.
89 * @param int $userid the id of the user attempting this quiz.
91 * @return object the newly created attempt object.
93 function quiz_create_attempt(quiz $quizobj, $attemptnumber, $lastattempt, $timenow, $ispreview = false, $userid = null) {
96 if ($userid === null) {
100 $quiz = $quizobj->get_quiz();
101 if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
102 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
103 new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
104 array('grade' => quiz_format_grade($quiz, $quiz->grade)));
107 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
108 // We are not building on last attempt so create a new attempt.
109 $attempt = new stdClass();
110 $attempt->quiz = $quiz->id;
111 $attempt->userid = $userid;
112 $attempt->preview = 0;
113 $attempt->layout = quiz_clean_layout($quiz->questions, true);
114 if ($quiz->shufflequestions) {
115 $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
118 // Build on last attempt.
119 if (empty($lastattempt)) {
120 print_error('cannotfindprevattempt', 'quiz');
122 $attempt = $lastattempt;
125 $attempt->attempt = $attemptnumber;
126 $attempt->timestart = $timenow;
127 $attempt->timefinish = 0;
128 $attempt->timemodified = $timenow;
129 $attempt->state = quiz_attempt::IN_PROGRESS;
131 // If this is a preview, mark it as such.
133 $attempt->preview = 1;
136 $timeclose = $quizobj->get_access_manager($timenow)->get_end_time($attempt);
137 if ($timeclose === false || $ispreview) {
138 $attempt->timecheckstate = null;
140 $attempt->timecheckstate = $timeclose;
146 * Start a normal, new, quiz attempt.
148 * @param quiz $quizobj the quiz object to start an attempt for.
149 * @param question_usage_by_activity $quba
150 * @param object $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
158 * @throws moodle_exception
159 * @return object modified attempt object
161 function quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,
162 $questionids = array(), $forcedvariantsbyslot = array()) {
163 // Fully load all the questions in this quiz.
164 $quizobj->preload_questions();
165 $quizobj->load_questions();
167 // Add them all to the $quba.
168 $idstoslots = array();
169 $questionsinuse = array_keys($quizobj->get_questions());
170 foreach ($quizobj->get_questions() as $i => $questiondata) {
171 if ($questiondata->qtype != 'random') {
172 if (!$quizobj->get_quiz()->shuffleanswers) {
173 $questiondata->options->shuffleanswers = false;
175 $question = question_bank::make_question($questiondata);
178 if (!isset($questionids[$quba->next_slot_number()])) {
179 $forcequestionid = null;
181 $forcequestionid = $questionids[$quba->next_slot_number()];
184 $question = question_bank::get_qtype('random')->choose_other_question(
185 $questiondata, $questionsinuse, $quizobj->get_quiz()->shuffleanswers, $forcequestionid);
186 if (is_null($question)) {
187 throw new moodle_exception('notenoughrandomquestions', 'quiz',
188 $quizobj->view_url(), $questiondata);
192 $idstoslots[$i] = $quba->add_question($question, $questiondata->maxmark);
193 $questionsinuse[] = $question->id;
196 // Start all the questions.
197 if ($attempt->preview) {
198 $variantoffset = rand(1, 100);
200 $variantoffset = $attemptnumber;
202 $variantstrategy = new question_variant_pseudorandom_no_repeats_strategy(
203 $variantoffset, $attempt->userid, $quizobj->get_quizid());
205 if (!empty($forcedvariantsbyslot)) {
206 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
207 $forcedvariantsbyslot, $quba);
208 $variantstrategy = new question_variant_forced_choices_selection_strategy(
209 $forcedvariantsbyseed, $variantstrategy);
212 $quba->start_all_questions($variantstrategy, $timenow);
214 // Update attempt layout.
215 $newlayout = array();
216 foreach (explode(',', $attempt->layout) as $qid) {
218 $newlayout[] = $idstoslots[$qid];
223 $attempt->layout = implode(',', $newlayout);
228 * Start a subsequent new attempt, in each attempt builds on last mode.
230 * @param question_usage_by_activity $quba this question usage
231 * @param object $attempt this attempt
232 * @param object $lastattempt last attempt
233 * @return object modified attempt object
236 function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
237 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
239 $oldnumberstonew = array();
240 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
241 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
243 $quba->start_question_based_on($newslot, $oldqa);
245 $oldnumberstonew[$oldslot] = $newslot;
248 // Update attempt layout.
249 $newlayout = array();
250 foreach (explode(',', $lastattempt->layout) as $oldslot) {
252 $newlayout[] = $oldnumberstonew[$oldslot];
257 $attempt->layout = implode(',', $newlayout);
262 * The save started question usage and quiz attempt in db and log the started attempt.
264 * @param quiz $quizobj
265 * @param question_usage_by_activity $quba
266 * @param object $attempt
267 * @return object attempt object with uniqueid and id set.
269 function quiz_attempt_save_started($quizobj, $quba, $attempt) {
271 // Save the attempt in the database.
272 question_engine::save_questions_usage_by_activity($quba);
273 $attempt->uniqueid = $quba->get_id();
274 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
275 // Log the new attempt.
276 if ($attempt->preview) {
277 add_to_log($quizobj->get_courseid(), 'quiz', 'preview', 'view.php?id='.$quizobj->get_cmid(),
278 $quizobj->get_quizid(), $quizobj->get_cmid());
280 add_to_log($quizobj->get_courseid(), 'quiz', 'attempt', 'review.php?attempt='.$attempt->id,
281 $quizobj->get_quizid(), $quizobj->get_cmid());
287 * Fire an event to tell the rest of Moodle a quiz attempt has started.
289 * @param object $attempt
290 * @param quiz $quizobj
292 function quiz_fire_attempt_started_event($attempt, $quizobj) {
294 $eventdata = array();
295 $eventdata['context'] = $quizobj->get_context();
296 $eventdata['courseid'] = $quizobj->get_courseid();
297 $eventdata['relateduserid'] = $attempt->userid;
298 $eventdata['objectid'] = $attempt->id;
299 $event = \mod_quiz\event\attempt_started::create($eventdata);
300 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
301 $event->add_record_snapshot('quiz_attempts', $attempt);
306 * Returns an unfinished attempt (if there is one) for the given
307 * user on the given quiz. This function does not return preview attempts.
309 * @param int $quizid the id of the quiz.
310 * @param int $userid the id of the user.
312 * @return mixed the unfinished attempt if there is one, false if not.
314 function quiz_get_user_attempt_unfinished($quizid, $userid) {
315 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
317 return array_shift($attempts);
324 * Delete a quiz attempt.
325 * @param mixed $attempt an integer attempt id or an attempt object
326 * (row of the quiz_attempts table).
327 * @param object $quiz the quiz object.
329 function quiz_delete_attempt($attempt, $quiz) {
331 if (is_numeric($attempt)) {
332 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
337 if ($attempt->quiz != $quiz->id) {
338 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
339 "but was passed quiz $quiz->id.");
343 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
344 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
346 // Search quiz_attempts for other instances by this user.
347 // If none, then delete record for this quiz, this user from quiz_grades
348 // else recalculate best grade.
349 $userid = $attempt->userid;
350 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
351 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
353 quiz_save_best_grade($quiz, $userid);
356 quiz_update_grades($quiz, $userid);
360 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
362 * @param object $quiz the quiz object.
363 * @param int $userid (optional) if given, only delete the previews belonging to this user.
365 function quiz_delete_previews($quiz, $userid = null) {
367 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
368 if (!empty($userid)) {
369 $conditions['userid'] = $userid;
371 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
372 foreach ($previewattempts as $attempt) {
373 quiz_delete_attempt($attempt, $quiz);
378 * @param int $quizid The quiz id.
379 * @return bool whether this quiz has any (non-preview) attempts.
381 function quiz_has_attempts($quizid) {
383 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
386 // Functions to do with quiz layout and pages //////////////////////////////////
389 * Returns a comma separated list of question ids for the quiz
391 * @param string $layout The string representing the quiz layout. Each page is
392 * represented as a comma separated list of question ids and 0 indicating
393 * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
395 * @return string comma separated list of question ids, without page breaks.
397 function quiz_questions_in_quiz($layout) {
398 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
399 if ($questions === '0') {
407 * Returns the number of pages in a quiz layout
409 * @param string $layout The string representing the quiz layout. Always ends in ,0
410 * @return int The number of pages in the quiz.
412 function quiz_number_of_pages($layout) {
413 return substr_count(',' . $layout, ',0');
417 * Returns the number of questions in the quiz layout
419 * @param string $layout the string representing the quiz layout.
420 * @return int The number of questions in the quiz.
422 function quiz_number_of_questions_in_quiz($layout) {
423 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
424 $count = substr_count($layout, ',');
425 if ($layout !== '') {
432 * Re-paginates the quiz layout
434 * @param string $layout The string representing the quiz layout. If there is
435 * if there is any doubt about the quality of the input data, call
436 * quiz_clean_layout before you call this function.
437 * @param int $perpage The number of questions per page
438 * @param bool $shuffle Should the questions be reordered randomly?
439 * @return string the new layout string
441 function quiz_repaginate($layout, $perpage, $shuffle = false) {
442 $questions = quiz_questions_in_quiz($layout);
447 $questions = explode(',', quiz_questions_in_quiz($layout));
454 foreach ($questions as $question) {
455 if ($perpage and $onthispage >= $perpage) {
459 $layout[] = $question;
464 return implode(',', $layout);
467 // Functions to do with quiz grades ////////////////////////////////////////////
470 * Creates an array of maximum grades for a quiz
472 * The grades are extracted from the quiz_question_instances table.
473 * @param object $quiz The quiz settings.
474 * @return array of grades indexed by question id. These are the maximum
475 * possible grades that students can achieve for each of the questions.
477 function quiz_get_all_question_grades($quiz) {
480 $questionlist = quiz_questions_in_quiz($quiz->questions);
481 if (empty($questionlist)) {
485 $params = array($quiz->id);
487 if (!is_null($questionlist)) {
488 list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
489 $wheresql = ' AND questionid ' . $usql;
490 $params = array_merge($params, $question_params);
493 $instances = $DB->get_records_sql("SELECT questionid, maxmark, id
494 FROM {quiz_question_instances}
495 WHERE quizid = ?{$wheresql}", $params);
497 $list = explode(',', $questionlist);
500 foreach ($list as $qid) {
501 if (isset($instances[$qid])) {
502 $grades[$qid] = $instances[$qid]->maxmark;
511 * Convert the raw grade stored in $attempt into a grade out of the maximum
512 * grade for this quiz.
514 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
515 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
516 * @param bool|string $format whether to format the results for display
517 * or 'question' to format a question grade (different number of decimal places.
518 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
519 * if the $grade is null.
521 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
522 if (is_null($rawgrade)) {
524 } else if ($quiz->sumgrades >= 0.000005) {
525 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
529 if ($format === 'question') {
530 $grade = quiz_format_question_grade($quiz, $grade);
531 } else if ($format) {
532 $grade = quiz_format_grade($quiz, $grade);
538 * Get the feedback text that should be show to a student who
539 * got this grade on this quiz. The feedback is processed ready for diplay.
541 * @param float $grade a grade on this quiz.
542 * @param object $quiz the quiz settings.
543 * @param object $context the quiz context.
544 * @return string the comment that corresponds to this grade (empty string if there is not one.
546 function quiz_feedback_for_grade($grade, $quiz, $context) {
549 if (is_null($grade)) {
553 // With CBM etc, it is possible to get -ve grades, which would then not match
554 // any feedback. Therefore, we replace -ve grades with 0.
555 $grade = max($grade, 0);
557 $feedback = $DB->get_record_select('quiz_feedback',
558 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
560 if (empty($feedback->feedbacktext)) {
564 // Clean the text, ready for display.
565 $formatoptions = new stdClass();
566 $formatoptions->noclean = true;
567 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
568 $context->id, 'mod_quiz', 'feedback', $feedback->id);
569 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
571 return $feedbacktext;
575 * @param object $quiz the quiz database row.
576 * @return bool Whether this quiz has any non-blank feedback text.
578 function quiz_has_feedback($quiz) {
580 static $cache = array();
581 if (!array_key_exists($quiz->id, $cache)) {
582 $cache[$quiz->id] = quiz_has_grades($quiz) &&
583 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
584 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
587 return $cache[$quiz->id];
591 * Update the sumgrades field of the quiz. This needs to be called whenever
592 * the grading structure of the quiz is changed. For example if a question is
593 * added or removed, or a question weight is changed.
595 * You should call {@link quiz_delete_previews()} before you call this function.
597 * @param object $quiz a quiz.
599 function quiz_update_sumgrades($quiz) {
602 $sql = 'UPDATE {quiz}
603 SET sumgrades = COALESCE((
605 FROM {quiz_question_instances}
606 WHERE quizid = {quiz}.id
609 $DB->execute($sql, array($quiz->id));
610 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
612 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
613 // If the quiz has been attempted, and the sumgrades has been
614 // set to 0, then we must also set the maximum possible grade to 0, or
615 // we will get a divide by zero error.
616 quiz_set_grade(0, $quiz);
621 * Update the sumgrades field of the attempts at a quiz.
623 * @param object $quiz a quiz.
625 function quiz_update_all_attempt_sumgrades($quiz) {
627 $dm = new question_engine_data_mapper();
630 $sql = "UPDATE {quiz_attempts}
632 timemodified = :timenow,
634 {$dm->sum_usage_marks_subquery('uniqueid')}
636 WHERE quiz = :quizid AND state = :finishedstate";
637 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
638 'finishedstate' => quiz_attempt::FINISHED));
642 * The quiz grade is the maximum that student's results are marked out of. When it
643 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
644 * rescaled. After calling this function, you probably need to call
645 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
646 * quiz_update_grades.
648 * @param float $newgrade the new maximum grade for the quiz.
649 * @param object $quiz the quiz we are updating. Passed by reference so its
650 * grade field can be updated too.
651 * @return bool indicating success or failure.
653 function quiz_set_grade($newgrade, $quiz) {
655 // This is potentially expensive, so only do it if necessary.
656 if (abs($quiz->grade - $newgrade) < 1e-7) {
661 $oldgrade = $quiz->grade;
662 $quiz->grade = $newgrade;
664 // Use a transaction, so that on those databases that support it, this is safer.
665 $transaction = $DB->start_delegated_transaction();
667 // Update the quiz table.
668 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
671 // If the old grade was zero, we cannot rescale, we have to recompute.
672 // We also recompute if the old grade was too small to avoid underflow problems.
673 quiz_update_all_final_grades($quiz);
676 // We can rescale the grades efficiently.
677 $timemodified = time();
680 SET grade = ? * grade, timemodified = ?
682 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
685 if ($oldgrade > 1e-7) {
686 // Update the quiz_feedback table.
687 $factor = $newgrade/$oldgrade;
689 UPDATE {quiz_feedback}
690 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
692 ", array($factor, $factor, $quiz->id));
695 // Update grade item and send all grades to gradebook.
696 quiz_grade_item_update($quiz);
697 quiz_update_grades($quiz);
699 $transaction->allow_commit();
704 * Save the overall grade for a user at a quiz in the quiz_grades table
706 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
707 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
708 * @param array $attempts The attempts of this user. Useful if you are
709 * looping through many users. Attempts can be fetched in one master query to
710 * avoid repeated querying.
711 * @return bool Indicates success or failure.
713 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
714 global $DB, $OUTPUT, $USER;
716 if (empty($userid)) {
721 // Get all the attempts made by the user.
722 $attempts = quiz_get_user_attempts($quiz->id, $userid);
725 // Calculate the best grade.
726 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
727 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
729 // Save the best grade in the database.
730 if (is_null($bestgrade)) {
731 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
733 } else if ($grade = $DB->get_record('quiz_grades',
734 array('quiz' => $quiz->id, 'userid' => $userid))) {
735 $grade->grade = $bestgrade;
736 $grade->timemodified = time();
737 $DB->update_record('quiz_grades', $grade);
740 $grade = new stdClass();
741 $grade->quiz = $quiz->id;
742 $grade->userid = $userid;
743 $grade->grade = $bestgrade;
744 $grade->timemodified = time();
745 $DB->insert_record('quiz_grades', $grade);
748 quiz_update_grades($quiz, $userid);
752 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
754 * @param object $quiz the quiz settings object.
755 * @param array $attempts an array of all the user's attempts at this quiz in order.
756 * @return float the overall grade
758 function quiz_calculate_best_grade($quiz, $attempts) {
760 switch ($quiz->grademethod) {
762 case QUIZ_ATTEMPTFIRST:
763 $firstattempt = reset($attempts);
764 return $firstattempt->sumgrades;
766 case QUIZ_ATTEMPTLAST:
767 $lastattempt = end($attempts);
768 return $lastattempt->sumgrades;
770 case QUIZ_GRADEAVERAGE:
773 foreach ($attempts as $attempt) {
774 if (!is_null($attempt->sumgrades)) {
775 $sum += $attempt->sumgrades;
782 return $sum / $count;
784 case QUIZ_GRADEHIGHEST:
787 foreach ($attempts as $attempt) {
788 if ($attempt->sumgrades > $max) {
789 $max = $attempt->sumgrades;
797 * Update the final grade at this quiz for all students.
799 * This function is equivalent to calling quiz_save_best_grade for all
800 * users, but much more efficient.
802 * @param object $quiz the quiz settings.
804 function quiz_update_all_final_grades($quiz) {
807 if (!$quiz->sumgrades) {
811 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
812 $firstlastattemptjoin = "JOIN (
815 MIN(attempt) AS firstattempt,
816 MAX(attempt) AS lastattempt
818 FROM {quiz_attempts} iquiza
821 iquiza.state = :istatefinished AND
822 iquiza.preview = 0 AND
823 iquiza.quiz = :iquizid
825 GROUP BY iquiza.userid
826 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
828 switch ($quiz->grademethod) {
829 case QUIZ_ATTEMPTFIRST:
830 // Because of the where clause, there will only be one row, but we
831 // must still use an aggregate function.
832 $select = 'MAX(quiza.sumgrades)';
833 $join = $firstlastattemptjoin;
834 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
837 case QUIZ_ATTEMPTLAST:
838 // Because of the where clause, there will only be one row, but we
839 // must still use an aggregate function.
840 $select = 'MAX(quiza.sumgrades)';
841 $join = $firstlastattemptjoin;
842 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
845 case QUIZ_GRADEAVERAGE:
846 $select = 'AVG(quiza.sumgrades)';
852 case QUIZ_GRADEHIGHEST:
853 $select = 'MAX(quiza.sumgrades)';
859 if ($quiz->sumgrades >= 0.000005) {
860 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
864 $param['quizid'] = $quiz->id;
865 $param['quizid2'] = $quiz->id;
866 $param['quizid3'] = $quiz->id;
867 $param['quizid4'] = $quiz->id;
868 $param['statefinished'] = quiz_attempt::FINISHED;
869 $param['statefinished2'] = quiz_attempt::FINISHED;
870 $finalgradesubquery = "
871 SELECT quiza.userid, $finalgrade AS newgrade
872 FROM {quiz_attempts} quiza
876 quiza.state = :statefinished AND
877 quiza.preview = 0 AND
878 quiza.quiz = :quizid3
879 GROUP BY quiza.userid";
881 $changedgrades = $DB->get_records_sql("
882 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
886 FROM {quiz_grades} qg
889 SELECT DISTINCT userid
890 FROM {quiz_attempts} quiza2
892 quiza2.state = :statefinished2 AND
893 quiza2.preview = 0 AND
894 quiza2.quiz = :quizid2
897 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
901 ) newgrades ON newgrades.userid = users.userid
904 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
905 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
906 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
907 // The mess on the previous line is detecting where the value is
908 // NULL in one column, and NOT NULL in the other, but SQL does
909 // not have an XOR operator, and MS SQL server can't cope with
910 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
915 foreach ($changedgrades as $changedgrade) {
917 if (is_null($changedgrade->newgrade)) {
918 $todelete[] = $changedgrade->userid;
920 } else if (is_null($changedgrade->grade)) {
921 $toinsert = new stdClass();
922 $toinsert->quiz = $quiz->id;
923 $toinsert->userid = $changedgrade->userid;
924 $toinsert->timemodified = $timenow;
925 $toinsert->grade = $changedgrade->newgrade;
926 $DB->insert_record('quiz_grades', $toinsert);
929 $toupdate = new stdClass();
930 $toupdate->id = $changedgrade->id;
931 $toupdate->grade = $changedgrade->newgrade;
932 $toupdate->timemodified = $timenow;
933 $DB->update_record('quiz_grades', $toupdate);
937 if (!empty($todelete)) {
938 list($test, $params) = $DB->get_in_or_equal($todelete);
939 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
940 array_merge(array($quiz->id), $params));
945 * Efficiently update check state time on all open attempts
947 * @param array $conditions optional restrictions on which attempts to update
948 * Allowed conditions:
949 * courseid => (array|int) attempts in given course(s)
950 * userid => (array|int) attempts for given user(s)
951 * quizid => (array|int) attempts in given quiz(s)
952 * groupid => (array|int) quizzes with some override for given group(s)
955 function quiz_update_open_attempts(array $conditions) {
958 foreach ($conditions as &$value) {
959 if (!is_array($value)) {
960 $value = array($value);
965 $wheres = array("quiza.state IN ('inprogress', 'overdue')");
966 $iwheres = array("iquiza.state IN ('inprogress', 'overdue')");
968 if (isset($conditions['courseid'])) {
969 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
970 $params = array_merge($params, $inparams);
971 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
972 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
973 $params = array_merge($params, $inparams);
974 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
977 if (isset($conditions['userid'])) {
978 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
979 $params = array_merge($params, $inparams);
980 $wheres[] = "quiza.userid $incond";
981 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
982 $params = array_merge($params, $inparams);
983 $iwheres[] = "iquiza.userid $incond";
986 if (isset($conditions['quizid'])) {
987 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
988 $params = array_merge($params, $inparams);
989 $wheres[] = "quiza.quiz $incond";
990 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
991 $params = array_merge($params, $inparams);
992 $iwheres[] = "iquiza.quiz $incond";
995 if (isset($conditions['groupid'])) {
996 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
997 $params = array_merge($params, $inparams);
998 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
999 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
1000 $params = array_merge($params, $inparams);
1001 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1004 // SQL to compute timeclose and timelimit for each attempt:
1005 $quizausersql = quiz_get_attempt_usertime_sql(
1006 implode("\n AND ", $iwheres));
1008 // SQL to compute the new timecheckstate
1009 $timecheckstatesql = "
1010 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
1011 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
1012 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
1013 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
1014 ELSE quizauser.usertimeclose END +
1015 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
1017 // SQL to select which attempts to process
1018 $attemptselect = implode("\n AND ", $wheres);
1021 * Each database handles updates with inner joins differently:
1022 * - mysql does not allow a FROM clause
1023 * - postgres and mssql allow FROM but handle table aliases differently
1024 * - oracle requires a subquery
1026 * Different code for each database.
1029 $dbfamily = $DB->get_dbfamily();
1030 if ($dbfamily == 'mysql') {
1031 $updatesql = "UPDATE {quiz_attempts} quiza
1032 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1033 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1034 SET quiza.timecheckstate = $timecheckstatesql
1035 WHERE $attemptselect";
1036 } else if ($dbfamily == 'postgres') {
1037 $updatesql = "UPDATE {quiz_attempts} quiza
1038 SET timecheckstate = $timecheckstatesql
1039 FROM {quiz} quiz, ( $quizausersql ) quizauser
1040 WHERE quiz.id = quiza.quiz
1041 AND quizauser.id = quiza.id
1042 AND $attemptselect";
1043 } else if ($dbfamily == 'mssql') {
1044 $updatesql = "UPDATE quiza
1045 SET timecheckstate = $timecheckstatesql
1046 FROM {quiz_attempts} quiza
1047 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1048 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1049 WHERE $attemptselect";
1051 // oracle, sqlite and others
1052 $updatesql = "UPDATE {quiz_attempts} quiza
1053 SET timecheckstate = (
1054 SELECT $timecheckstatesql
1055 FROM {quiz} quiz, ( $quizausersql ) quizauser
1056 WHERE quiz.id = quiza.quiz
1057 AND quizauser.id = quiza.id
1059 WHERE $attemptselect";
1062 $DB->execute($updatesql, $params);
1066 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
1068 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1069 * for performance. These can use the table alias iquiza for the quiz attempts table.
1070 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
1072 function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1073 if ($redundantwhereclauses) {
1074 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1076 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1077 // any other group override
1080 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1081 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1083 FROM {quiz_attempts} iquiza
1084 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1085 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1086 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1087 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1088 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1089 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1090 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
1091 $redundantwhereclauses
1092 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1093 return $quizausersql;
1097 * Return the attempt with the best grade for a quiz
1099 * Which attempt is the best depends on $quiz->grademethod. If the grade
1100 * method is GRADEAVERAGE then this function simply returns the last attempt.
1101 * @return object The attempt with the best grade
1102 * @param object $quiz The quiz for which the best grade is to be calculated
1103 * @param array $attempts An array of all the attempts of the user at the quiz
1105 function quiz_calculate_best_attempt($quiz, $attempts) {
1107 switch ($quiz->grademethod) {
1109 case QUIZ_ATTEMPTFIRST:
1110 foreach ($attempts as $attempt) {
1115 case QUIZ_GRADEAVERAGE: // We need to do something with it.
1116 case QUIZ_ATTEMPTLAST:
1117 foreach ($attempts as $attempt) {
1123 case QUIZ_GRADEHIGHEST:
1125 foreach ($attempts as $attempt) {
1126 if ($attempt->sumgrades > $max) {
1127 $max = $attempt->sumgrades;
1128 $maxattempt = $attempt;
1136 * @return array int => lang string the options for calculating the quiz grade
1137 * from the individual attempt grades.
1139 function quiz_get_grading_options() {
1141 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1142 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1143 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1144 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1149 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1150 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
1151 * @return the lang string for that option.
1153 function quiz_get_grading_option_name($option) {
1154 $strings = quiz_get_grading_options();
1155 return $strings[$option];
1159 * @return array string => lang string the options for handling overdue quiz
1162 function quiz_get_overdue_handling_options() {
1164 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1165 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1166 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1171 * @param string $state one of the state constants like IN_PROGRESS.
1172 * @return string the human-readable state name.
1174 function quiz_attempt_state_name($state) {
1176 case quiz_attempt::IN_PROGRESS:
1177 return get_string('stateinprogress', 'quiz');
1178 case quiz_attempt::OVERDUE:
1179 return get_string('stateoverdue', 'quiz');
1180 case quiz_attempt::FINISHED:
1181 return get_string('statefinished', 'quiz');
1182 case quiz_attempt::ABANDONED:
1183 return get_string('stateabandoned', 'quiz');
1185 throw new coding_exception('Unknown quiz attempt state.');
1189 // Other quiz functions ////////////////////////////////////////////////////////
1192 * @param object $quiz the quiz.
1193 * @param int $cmid the course_module object for this quiz.
1194 * @param object $question the question.
1195 * @param string $returnurl url to return to after action is done.
1196 * @return string html for a number of icons linked to action pages for a
1197 * question - preview and edit / view icons depending on user capabilities.
1199 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
1200 $html = quiz_question_preview_button($quiz, $question) . ' ' .
1201 quiz_question_edit_button($cmid, $question, $returnurl);
1206 * @param int $cmid the course_module.id for this quiz.
1207 * @param object $question the question.
1208 * @param string $returnurl url to return to after action is done.
1209 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
1210 * @return the HTML for an edit icon, view icon, or nothing for a question
1211 * (depending on permissions).
1213 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
1214 global $CFG, $OUTPUT;
1216 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
1217 static $stredit = null;
1218 static $strview = null;
1219 if ($stredit === null) {
1220 $stredit = get_string('edit');
1221 $strview = get_string('view');
1224 // What sort of icon should we show?
1226 if (!empty($question->id) &&
1227 (question_has_capability_on($question, 'edit', $question->category) ||
1228 question_has_capability_on($question, 'move', $question->category))) {
1231 } else if (!empty($question->id) &&
1232 question_has_capability_on($question, 'view', $question->category)) {
1239 if ($returnurl instanceof moodle_url) {
1240 $returnurl = $returnurl->out_as_local_url(false);
1242 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
1243 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
1244 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
1245 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
1247 } else if ($contentaftericon) {
1248 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
1255 * @param object $quiz the quiz settings
1256 * @param object $question the question
1257 * @return moodle_url to preview this question with the options from this quiz.
1259 function quiz_question_preview_url($quiz, $question) {
1260 // Get the appropriate display options.
1261 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
1262 mod_quiz_display_options::DURING);
1265 if (isset($question->maxmark)) {
1266 $maxmark = $question->maxmark;
1269 // Work out the correcte preview URL.
1270 return question_preview_url($question->id, $quiz->preferredbehaviour,
1271 $maxmark, $displayoptions);
1275 * @param object $quiz the quiz settings
1276 * @param object $question the question
1277 * @param bool $label if true, show the preview question label after the icon
1278 * @return the HTML for a preview question icon.
1280 function quiz_question_preview_button($quiz, $question, $label = false) {
1281 global $CFG, $OUTPUT;
1282 if (!question_has_capability_on($question, 'use', $question->category)) {
1286 $url = quiz_question_preview_url($quiz, $question);
1288 // Do we want a label?
1289 $strpreviewlabel = '';
1291 $strpreviewlabel = get_string('preview', 'quiz');
1295 $strpreviewquestion = get_string('previewquestion', 'quiz');
1296 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
1298 $action = new popup_action('click', $url, 'questionpreview',
1299 question_preview_popup_params());
1301 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
1305 * @param object $attempt the attempt.
1306 * @param object $context the quiz context.
1307 * @return int whether flags should be shown/editable to the current user for this attempt.
1309 function quiz_get_flag_option($attempt, $context) {
1311 if (!has_capability('moodle/question:flag', $context)) {
1312 return question_display_options::HIDDEN;
1313 } else if ($attempt->userid == $USER->id) {
1314 return question_display_options::EDITABLE;
1316 return question_display_options::VISIBLE;
1321 * Work out what state this quiz attempt is in - in the sense used by
1322 * quiz_get_review_options, not in the sense of $attempt->state.
1323 * @param object $quiz the quiz settings
1324 * @param object $attempt the quiz_attempt database row.
1325 * @return int one of the mod_quiz_display_options::DURING,
1326 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
1328 function quiz_attempt_state($quiz, $attempt) {
1329 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
1330 return mod_quiz_display_options::DURING;
1331 } else if (time() < $attempt->timefinish + 120) {
1332 return mod_quiz_display_options::IMMEDIATELY_AFTER;
1333 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
1334 return mod_quiz_display_options::LATER_WHILE_OPEN;
1336 return mod_quiz_display_options::AFTER_CLOSE;
1341 * The the appropraite mod_quiz_display_options object for this attempt at this
1344 * @param object $quiz the quiz instance.
1345 * @param object $attempt the attempt in question.
1346 * @param $context the quiz context.
1348 * @return mod_quiz_display_options
1350 function quiz_get_review_options($quiz, $attempt, $context) {
1351 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
1353 $options->readonly = true;
1354 $options->flags = quiz_get_flag_option($attempt, $context);
1355 if (!empty($attempt->id)) {
1356 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1357 array('attempt' => $attempt->id));
1360 // Show a link to the comment box only for closed attempts.
1361 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
1362 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
1363 $options->manualcomment = question_display_options::VISIBLE;
1364 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1365 array('attempt' => $attempt->id));
1368 if (!is_null($context) && !$attempt->preview &&
1369 has_capability('mod/quiz:viewreports', $context) &&
1370 has_capability('moodle/grade:viewhidden', $context)) {
1371 // People who can see reports and hidden grades should be shown everything,
1372 // except during preview when teachers want to see what students see.
1373 $options->attempt = question_display_options::VISIBLE;
1374 $options->correctness = question_display_options::VISIBLE;
1375 $options->marks = question_display_options::MARK_AND_MAX;
1376 $options->feedback = question_display_options::VISIBLE;
1377 $options->numpartscorrect = question_display_options::VISIBLE;
1378 $options->generalfeedback = question_display_options::VISIBLE;
1379 $options->rightanswer = question_display_options::VISIBLE;
1380 $options->overallfeedback = question_display_options::VISIBLE;
1381 $options->history = question_display_options::VISIBLE;
1389 * Combines the review options from a number of different quiz attempts.
1390 * Returns an array of two ojects, so the suggested way of calling this
1392 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1394 * @param object $quiz the quiz instance.
1395 * @param array $attempts an array of attempt objects.
1396 * @param $context the roles and permissions context,
1397 * normally the context for the quiz module instance.
1399 * @return array of two options objects, one showing which options are true for
1400 * at least one of the attempts, the other showing which options are true
1403 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1404 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1405 $someoptions = new stdClass();
1406 $alloptions = new stdClass();
1407 foreach ($fields as $field) {
1408 $someoptions->$field = false;
1409 $alloptions->$field = true;
1411 $someoptions->marks = question_display_options::HIDDEN;
1412 $alloptions->marks = question_display_options::MARK_AND_MAX;
1414 foreach ($attempts as $attempt) {
1415 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1416 quiz_attempt_state($quiz, $attempt));
1417 foreach ($fields as $field) {
1418 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1419 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1421 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1422 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1424 return array($someoptions, $alloptions);
1428 * Clean the question layout from various possible anomalies:
1429 * - Remove consecutive ","'s
1430 * - Remove duplicate question id's
1431 * - Remove extra "," from beginning and end
1432 * - Finally, add a ",0" in the end if there is none
1434 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
1435 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
1436 * @return $string the cleaned-up layout
1438 function quiz_clean_layout($layout, $removeemptypages = false) {
1439 // Remove repeated ','s. This can happen when a restore fails to find the right
1441 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1443 // Remove duplicate question ids.
1444 $layout = explode(',', $layout);
1445 $cleanerlayout = array();
1447 foreach ($layout as $item) {
1449 $cleanerlayout[] = '0';
1450 } else if (!in_array($item, $seen)) {
1451 $cleanerlayout[] = $item;
1456 if ($removeemptypages) {
1457 // Avoid duplicate page breaks.
1458 $layout = $cleanerlayout;
1459 $cleanerlayout = array();
1460 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1461 foreach ($layout as $item) {
1462 if ($stripfollowingbreaks && $item == 0) {
1465 $cleanerlayout[] = $item;
1466 $stripfollowingbreaks = $item == 0;
1470 // Add a page break at the end if there is none.
1471 if (end($cleanerlayout) !== '0') {
1472 $cleanerlayout[] = '0';
1475 return implode(',', $cleanerlayout);
1479 * Get the slot for a question with a particular id.
1480 * @param object $quiz the quiz settings.
1481 * @param int $questionid the of a question in the quiz.
1482 * @return int the corresponding slot. Null if the question is not in the quiz.
1484 function quiz_get_slot_for_question($quiz, $questionid) {
1485 $questionids = quiz_questions_in_quiz($quiz->questions);
1486 foreach (explode(',', $questionids) as $key => $id) {
1487 if ($id == $questionid) {
1494 // Functions for sending notification messages /////////////////////////////////
1497 * Sends a confirmation message to the student confirming that the attempt was processed.
1499 * @param object $a lots of useful information that can be used in the message
1502 * @return int|false as for {@link message_send()}.
1504 function quiz_send_confirmation($recipient, $a) {
1506 // Add information about the recipient to $a.
1507 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1508 $a->username = fullname($recipient);
1509 $a->userusername = $recipient->username;
1511 // Prepare the message.
1512 $eventdata = new stdClass();
1513 $eventdata->component = 'mod_quiz';
1514 $eventdata->name = 'confirmation';
1515 $eventdata->notification = 1;
1517 $eventdata->userfrom = core_user::get_noreply_user();
1518 $eventdata->userto = $recipient;
1519 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1520 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1521 $eventdata->fullmessageformat = FORMAT_PLAIN;
1522 $eventdata->fullmessagehtml = '';
1524 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1525 $eventdata->contexturl = $a->quizurl;
1526 $eventdata->contexturlname = $a->quizname;
1529 return message_send($eventdata);
1533 * Sends notification messages to the interested parties that assign the role capability
1535 * @param object $recipient user object of the intended recipient
1536 * @param object $a associative array of replaceable fields for the templates
1538 * @return int|false as for {@link message_send()}.
1540 function quiz_send_notification($recipient, $submitter, $a) {
1542 // Recipient info for template.
1543 $a->useridnumber = $recipient->idnumber;
1544 $a->username = fullname($recipient);
1545 $a->userusername = $recipient->username;
1547 // Prepare the message.
1548 $eventdata = new stdClass();
1549 $eventdata->component = 'mod_quiz';
1550 $eventdata->name = 'submission';
1551 $eventdata->notification = 1;
1553 $eventdata->userfrom = $submitter;
1554 $eventdata->userto = $recipient;
1555 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1556 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1557 $eventdata->fullmessageformat = FORMAT_PLAIN;
1558 $eventdata->fullmessagehtml = '';
1560 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1561 $eventdata->contexturl = $a->quizreviewurl;
1562 $eventdata->contexturlname = $a->quizname;
1565 return message_send($eventdata);
1569 * Send all the requried messages when a quiz attempt is submitted.
1571 * @param object $course the course
1572 * @param object $quiz the quiz
1573 * @param object $attempt this attempt just finished
1574 * @param object $context the quiz context
1575 * @param object $cm the coursemodule for this quiz
1577 * @return bool true if all necessary messages were sent successfully, else false.
1579 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1582 // Do nothing if required objects not present.
1583 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1584 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1587 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1589 // Check for confirmation required.
1590 $sendconfirm = false;
1591 $notifyexcludeusers = '';
1592 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1593 $notifyexcludeusers = $submitter->id;
1594 $sendconfirm = true;
1597 // Check for notifications required.
1598 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang, u.timezone, u.mailformat, u.maildisplay, ';
1599 $notifyfields .= get_all_user_name_fields(true, 'u');
1600 $groups = groups_get_all_groups($course->id, $submitter->id);
1601 if (is_array($groups) && count($groups) > 0) {
1602 $groups = array_keys($groups);
1603 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1604 // If the user is not in a group, and the quiz is set to group mode,
1605 // then set $groups to a non-existant id so that only users with
1606 // 'moodle/site:accessallgroups' get notified.
1611 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1612 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1614 if (empty($userstonotify) && !$sendconfirm) {
1615 return true; // Nothing to do.
1618 $a = new stdClass();
1620 $a->coursename = $course->fullname;
1621 $a->courseshortname = $course->shortname;
1623 $a->quizname = $quiz->name;
1624 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1625 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1626 format_string($quiz->name) . ' report</a>';
1627 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1628 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1630 $a->submissiontime = userdate($attempt->timefinish);
1631 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1632 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1633 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1634 format_string($quiz->name) . ' review</a>';
1635 // Student who sat the quiz info.
1636 $a->studentidnumber = $submitter->idnumber;
1637 $a->studentname = fullname($submitter);
1638 $a->studentusername = $submitter->username;
1642 // Send notifications if required.
1643 if (!empty($userstonotify)) {
1644 foreach ($userstonotify as $recipient) {
1645 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1649 // Send confirmation if required. We send the student confirmation last, so
1650 // that if message sending is being intermittently buggy, which means we send
1651 // some but not all messages, and then try again later, then teachers may get
1652 // duplicate messages, but the student will always get exactly one.
1654 $allok = $allok && quiz_send_confirmation($submitter, $a);
1661 * Send the notification message when a quiz attempt becomes overdue.
1663 * @param object $course the course
1664 * @param object $quiz the quiz
1665 * @param object $attempt this attempt just finished
1666 * @param object $context the quiz context
1667 * @param object $cm the coursemodule for this quiz
1669 function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
1672 // Do nothing if required objects not present.
1673 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1674 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1677 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1679 if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
1680 return; // Message not required.
1683 // Prepare lots of useful information that admins might want to include in
1684 // the email message.
1685 $quizname = format_string($quiz->name);
1687 $deadlines = array();
1688 if ($quiz->timelimit) {
1689 $deadlines[] = $attempt->timestart + $quiz->timelimit;
1691 if ($quiz->timeclose) {
1692 $deadlines[] = $quiz->timeclose;
1694 $duedate = min($deadlines);
1695 $graceend = $duedate + $quiz->graceperiod;
1697 $a = new stdClass();
1699 $a->coursename = $course->fullname;
1700 $a->courseshortname = $course->shortname;
1702 $a->quizname = $quizname;
1703 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1704 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1706 $a->attemptduedate = userdate($duedate);
1707 $a->attemptgraceend = userdate($graceend);
1708 $a->attemptsummaryurl = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
1709 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1711 $a->studentidnumber = $submitter->idnumber;
1712 $a->studentname = fullname($submitter);
1713 $a->studentusername = $submitter->username;
1715 // Prepare the message.
1716 $eventdata = new stdClass();
1717 $eventdata->component = 'mod_quiz';
1718 $eventdata->name = 'attempt_overdue';
1719 $eventdata->notification = 1;
1721 $eventdata->userfrom = core_user::get_noreply_user();
1722 $eventdata->userto = $submitter;
1723 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1724 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1725 $eventdata->fullmessageformat = FORMAT_PLAIN;
1726 $eventdata->fullmessagehtml = '';
1728 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1729 $eventdata->contexturl = $a->quizurl;
1730 $eventdata->contexturlname = $a->quizname;
1732 // Send the message.
1733 return message_send($eventdata);
1737 * Handle the quiz_attempt_submitted event.
1739 * This sends the confirmation and notification messages, if required.
1741 * @param object $event the event object.
1743 function quiz_attempt_submitted_handler($event) {
1746 $course = $DB->get_record('course', array('id' => $event->courseid));
1747 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1748 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1749 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1751 if (!($course && $quiz && $cm && $attempt)) {
1752 // Something has been deleted since the event was raised. Therefore, the
1753 // event is no longer relevant.
1757 return quiz_send_notification_messages($course, $quiz, $attempt,
1758 context_module::instance($cm->id), $cm);
1762 * Handle the quiz_attempt_overdue event.
1764 * For quizzes with applicable settings, this sends a message to the user, reminding
1765 * them that they forgot to submit, and that they have another chance to do so.
1767 * @param object $event the event object.
1769 function quiz_attempt_overdue_handler($event) {
1772 $course = $DB->get_record('course', array('id' => $event->courseid));
1773 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1774 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1775 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1777 if (!($course && $quiz && $cm && $attempt)) {
1778 // Something has been deleted since the event was raised. Therefore, the
1779 // event is no longer relevant.
1783 return quiz_send_overdue_message($course, $quiz, $attempt,
1784 context_module::instance($cm->id), $cm);
1788 * Handle groups_member_added event
1790 * @param object $event the event object.
1791 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_added()}.
1793 function quiz_groups_member_added_handler($event) {
1794 debugging('quiz_groups_member_added_handler() is deprecated, please use ' .
1795 '\mod_quiz\group_observers::group_member_added() instead.', DEBUG_DEVELOPER);
1796 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1800 * Handle groups_member_removed event
1802 * @param object $event the event object.
1803 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1805 function quiz_groups_member_removed_handler($event) {
1806 debugging('quiz_groups_member_removed_handler() is deprecated, please use ' .
1807 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1808 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1812 * Handle groups_group_deleted event
1814 * @param object $event the event object.
1815 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_deleted()}.
1817 function quiz_groups_group_deleted_handler($event) {
1819 debugging('quiz_groups_group_deleted_handler() is deprecated, please use ' .
1820 '\mod_quiz\group_observers::group_deleted() instead.', DEBUG_DEVELOPER);
1821 quiz_process_group_deleted_in_course($event->courseid);
1825 * Logic to happen when a/some group(s) has/have been deleted in a course.
1827 * @param int $courseid The course ID.
1830 function quiz_process_group_deleted_in_course($courseid) {
1833 // It would be nice if we got the groupid that was deleted.
1834 // Instead, we just update all quizzes with orphaned group overrides.
1835 $sql = "SELECT o.id, o.quiz
1836 FROM {quiz_overrides} o
1837 JOIN {quiz} quiz ON quiz.id = o.quiz
1838 LEFT JOIN {groups} grp ON grp.id = o.groupid
1839 WHERE quiz.course = :courseid AND grp.id IS NULL";
1840 $params = array('courseid' => $courseid);
1841 $records = $DB->get_records_sql_menu($sql, $params);
1843 return; // Nothing to do.
1845 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
1846 quiz_update_open_attempts(array('quizid' => array_unique(array_values($records))));
1850 * Handle groups_members_removed event
1852 * @param object $event the event object.
1853 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1855 function quiz_groups_members_removed_handler($event) {
1856 debugging('quiz_groups_members_removed_handler() is deprecated, please use ' .
1857 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1858 if ($event->userid == 0) {
1859 quiz_update_open_attempts(array('courseid'=>$event->courseid));
1861 quiz_update_open_attempts(array('courseid'=>$event->courseid, 'userid'=>$event->userid));
1866 * Get the information about the standard quiz JavaScript module.
1867 * @return array a standard jsmodule structure.
1869 function quiz_get_js_module() {
1873 'name' => 'mod_quiz',
1874 'fullpath' => '/mod/quiz/module.js',
1875 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1876 'core_question_engine', 'moodle-core-formchangechecker'),
1878 array('cancel', 'moodle'),
1879 array('flagged', 'question'),
1880 array('functiondisabledbysecuremode', 'quiz'),
1881 array('startattempt', 'quiz'),
1882 array('timesup', 'quiz'),
1883 array('changesmadereallygoaway', 'moodle'),
1890 * An extension of question_display_options that includes the extra options used
1893 * @copyright 2010 The Open University
1894 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1896 class mod_quiz_display_options extends question_display_options {
1898 * @var integer bits used to indicate various times in relation to a
1901 const DURING = 0x10000;
1902 const IMMEDIATELY_AFTER = 0x01000;
1903 const LATER_WHILE_OPEN = 0x00100;
1904 const AFTER_CLOSE = 0x00010;
1908 * @var boolean if this is false, then the student is not allowed to review
1909 * anything about the attempt.
1911 public $attempt = true;
1914 * @var boolean if this is false, then the student is not allowed to review
1915 * anything about the attempt.
1917 public $overallfeedback = self::VISIBLE;
1920 * Set up the various options from the quiz settings, and a time constant.
1921 * @param object $quiz the quiz settings.
1922 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1923 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1924 * @return mod_quiz_display_options set up appropriately.
1926 public static function make_from_quiz($quiz, $when) {
1927 $options = new self();
1929 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1930 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
1931 $options->marks = self::extract($quiz->reviewmarks, $when,
1932 self::MARK_AND_MAX, self::MAX_ONLY);
1933 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1934 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1935 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1936 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1938 $options->numpartscorrect = $options->feedback;
1940 if ($quiz->questiondecimalpoints != -1) {
1941 $options->markdp = $quiz->questiondecimalpoints;
1943 $options->markdp = $quiz->decimalpoints;
1949 protected static function extract($bitmask, $bit,
1950 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
1951 if ($bitmask & $bit) {
1961 * A {@link qubaid_condition} for finding all the question usages belonging to
1962 * a particular quiz.
1964 * @copyright 2010 The Open University
1965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1967 class qubaids_for_quiz extends qubaid_join {
1968 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1969 $where = 'quiza.quiz = :quizaquiz';
1970 $params = array('quizaquiz' => $quizid);
1972 if (!$includepreviews) {
1973 $where .= ' AND preview = 0';
1976 if ($onlyfinished) {
1977 $where .= ' AND state == :statefinished';
1978 $params['statefinished'] = quiz_attempt::FINISHED;
1981 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);