Merge branch 'MDL-48795_27' of https://github.com/apsdehal/moodle into MOODLE_27_STABLE
[moodle.git] / mod / quiz / locallib.php
blobffa7f86cfe5885534bb494f3dca8db063c3d2c8b
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->dirroot . '/question/editlib.php');
40 require_once($CFG->libdir . '/eventslib.php');
41 require_once($CFG->libdir . '/filelib.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()) {
161 // Fully load all the questions in this quiz.
162 $quizobj->preload_questions();
163 $quizobj->load_questions();
165 // Add them all to the $quba.
166 $questionsinuse = array_keys($quizobj->get_questions());
167 foreach ($quizobj->get_questions() as $questiondata) {
168 if ($questiondata->qtype != 'random') {
169 if (!$quizobj->get_quiz()->shuffleanswers) {
170 $questiondata->options->shuffleanswers = false;
172 $question = question_bank::make_question($questiondata);
174 } else {
175 if (!isset($questionids[$quba->next_slot_number()])) {
176 $forcequestionid = null;
177 } else {
178 $forcequestionid = $questionids[$quba->next_slot_number()];
181 $question = question_bank::get_qtype('random')->choose_other_question(
182 $questiondata, $questionsinuse, $quizobj->get_quiz()->shuffleanswers, $forcequestionid);
183 if (is_null($question)) {
184 throw new moodle_exception('notenoughrandomquestions', 'quiz',
185 $quizobj->view_url(), $questiondata);
189 $quba->add_question($question, $questiondata->maxmark);
190 $questionsinuse[] = $question->id;
193 // Start all the questions.
194 if ($attempt->preview) {
195 $variantoffset = rand(1, 100);
196 } else {
197 $variantoffset = $attemptnumber;
199 $variantstrategy = new question_variant_pseudorandom_no_repeats_strategy(
200 $variantoffset, $attempt->userid, $quizobj->get_quizid());
202 if (!empty($forcedvariantsbyslot)) {
203 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
204 $forcedvariantsbyslot, $quba);
205 $variantstrategy = new question_variant_forced_choices_selection_strategy(
206 $forcedvariantsbyseed, $variantstrategy);
209 $quba->start_all_questions($variantstrategy, $timenow);
211 // Work out the attempt layout.
212 $layout = array();
213 if ($quizobj->get_quiz()->shufflequestions) {
214 $slots = $quba->get_slots();
215 shuffle($slots);
217 $questionsonthispage = 0;
218 foreach ($slots as $slot) {
219 if ($questionsonthispage && $questionsonthispage == $quizobj->get_quiz()->questionsperpage) {
220 $layout[] = 0;
221 $questionsonthispage = 0;
223 $layout[] = $slot;
224 $questionsonthispage += 1;
227 } else {
228 $currentpage = null;
229 foreach ($quizobj->get_questions() as $slot) {
230 if ($currentpage !== null && $slot->page != $currentpage) {
231 $layout[] = 0;
233 $layout[] = $slot->slot;
234 $currentpage = $slot->page;
238 $layout[] = 0;
239 $attempt->layout = implode(',', $layout);
241 return $attempt;
245 * Start a subsequent new attempt, in each attempt builds on last mode.
247 * @param question_usage_by_activity $quba this question usage
248 * @param object $attempt this attempt
249 * @param object $lastattempt last attempt
250 * @return object modified attempt object
253 function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
254 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
256 $oldnumberstonew = array();
257 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
258 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
260 $quba->start_question_based_on($newslot, $oldqa);
262 $oldnumberstonew[$oldslot] = $newslot;
265 // Update attempt layout.
266 $newlayout = array();
267 foreach (explode(',', $lastattempt->layout) as $oldslot) {
268 if ($oldslot != 0) {
269 $newlayout[] = $oldnumberstonew[$oldslot];
270 } else {
271 $newlayout[] = 0;
274 $attempt->layout = implode(',', $newlayout);
275 return $attempt;
279 * The save started question usage and quiz attempt in db and log the started attempt.
281 * @param quiz $quizobj
282 * @param question_usage_by_activity $quba
283 * @param object $attempt
284 * @return object attempt object with uniqueid and id set.
286 function quiz_attempt_save_started($quizobj, $quba, $attempt) {
287 global $DB;
288 // Save the attempt in the database.
289 question_engine::save_questions_usage_by_activity($quba);
290 $attempt->uniqueid = $quba->get_id();
291 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
293 // Params used by the events below.
294 $params = array(
295 'objectid' => $attempt->id,
296 'relateduserid' => $attempt->userid,
297 'courseid' => $quizobj->get_courseid(),
298 'context' => $quizobj->get_context()
300 // Decide which event we are using.
301 if ($attempt->preview) {
302 $params['other'] = array(
303 'quizid' => $quizobj->get_quizid()
305 $event = \mod_quiz\event\attempt_preview_started::create($params);
306 } else {
307 $event = \mod_quiz\event\attempt_started::create($params);
311 // Trigger the event.
312 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
313 $event->add_record_snapshot('quiz_attempts', $attempt);
314 $event->trigger();
316 return $attempt;
320 * Returns an unfinished attempt (if there is one) for the given
321 * user on the given quiz. This function does not return preview attempts.
323 * @param int $quizid the id of the quiz.
324 * @param int $userid the id of the user.
326 * @return mixed the unfinished attempt if there is one, false if not.
328 function quiz_get_user_attempt_unfinished($quizid, $userid) {
329 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
330 if ($attempts) {
331 return array_shift($attempts);
332 } else {
333 return false;
338 * Delete a quiz attempt.
339 * @param mixed $attempt an integer attempt id or an attempt object
340 * (row of the quiz_attempts table).
341 * @param object $quiz the quiz object.
343 function quiz_delete_attempt($attempt, $quiz) {
344 global $DB;
345 if (is_numeric($attempt)) {
346 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
347 return;
351 if ($attempt->quiz != $quiz->id) {
352 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
353 "but was passed quiz $quiz->id.");
354 return;
357 if (!isset($quiz->cmid)) {
358 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
359 $quiz->cmid = $cm->id;
362 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
363 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
365 // Log the deletion of the attempt.
366 $params = array(
367 'objectid' => $attempt->id,
368 'relateduserid' => $attempt->userid,
369 'context' => context_module::instance($quiz->cmid),
370 'other' => array(
371 'quizid' => $quiz->id
374 $event = \mod_quiz\event\attempt_deleted::create($params);
375 $event->add_record_snapshot('quiz_attempts', $attempt);
376 $event->trigger();
378 // Search quiz_attempts for other instances by this user.
379 // If none, then delete record for this quiz, this user from quiz_grades
380 // else recalculate best grade.
381 $userid = $attempt->userid;
382 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
383 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
384 } else {
385 quiz_save_best_grade($quiz, $userid);
388 quiz_update_grades($quiz, $userid);
392 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
393 * to one user.
394 * @param object $quiz the quiz object.
395 * @param int $userid (optional) if given, only delete the previews belonging to this user.
397 function quiz_delete_previews($quiz, $userid = null) {
398 global $DB;
399 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
400 if (!empty($userid)) {
401 $conditions['userid'] = $userid;
403 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
404 foreach ($previewattempts as $attempt) {
405 quiz_delete_attempt($attempt, $quiz);
410 * @param int $quizid The quiz id.
411 * @return bool whether this quiz has any (non-preview) attempts.
413 function quiz_has_attempts($quizid) {
414 global $DB;
415 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
418 // Functions to do with quiz layout and pages //////////////////////////////////
421 * Repaginate the questions in a quiz
422 * @param int $quizid the id of the quiz to repaginate.
423 * @param int $slotsperpage number of items to put on each page. 0 means unlimited.
425 function quiz_repaginate_questions($quizid, $slotsperpage) {
426 global $DB;
427 $trans = $DB->start_delegated_transaction();
429 $slots = $DB->get_records('quiz_slots', array('quizid' => $quizid),
430 'slot');
432 $currentpage = 1;
433 $slotsonthispage = 0;
434 foreach ($slots as $slot) {
435 if ($slotsonthispage && $slotsonthispage == $slotsperpage) {
436 $currentpage += 1;
437 $slotsonthispage = 0;
439 if ($slot->page != $currentpage) {
440 $DB->set_field('quiz_slots', 'page', $currentpage, array('id' => $slot->id));
442 $slotsonthispage += 1;
445 $trans->allow_commit();
448 // Functions to do with quiz grades ////////////////////////////////////////////
451 * Convert the raw grade stored in $attempt into a grade out of the maximum
452 * grade for this quiz.
454 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
455 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
456 * @param bool|string $format whether to format the results for display
457 * or 'question' to format a question grade (different number of decimal places.
458 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
459 * if the $grade is null.
461 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
462 if (is_null($rawgrade)) {
463 $grade = null;
464 } else if ($quiz->sumgrades >= 0.000005) {
465 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
466 } else {
467 $grade = 0;
469 if ($format === 'question') {
470 $grade = quiz_format_question_grade($quiz, $grade);
471 } else if ($format) {
472 $grade = quiz_format_grade($quiz, $grade);
474 return $grade;
478 * Get the feedback text that should be show to a student who
479 * got this grade on this quiz. The feedback is processed ready for diplay.
481 * @param float $grade a grade on this quiz.
482 * @param object $quiz the quiz settings.
483 * @param object $context the quiz context.
484 * @return string the comment that corresponds to this grade (empty string if there is not one.
486 function quiz_feedback_for_grade($grade, $quiz, $context) {
487 global $DB;
489 if (is_null($grade)) {
490 return '';
493 // With CBM etc, it is possible to get -ve grades, which would then not match
494 // any feedback. Therefore, we replace -ve grades with 0.
495 $grade = max($grade, 0);
497 $feedback = $DB->get_record_select('quiz_feedback',
498 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
500 if (empty($feedback->feedbacktext)) {
501 return '';
504 // Clean the text, ready for display.
505 $formatoptions = new stdClass();
506 $formatoptions->noclean = true;
507 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
508 $context->id, 'mod_quiz', 'feedback', $feedback->id);
509 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
511 return $feedbacktext;
515 * @param object $quiz the quiz database row.
516 * @return bool Whether this quiz has any non-blank feedback text.
518 function quiz_has_feedback($quiz) {
519 global $DB;
520 static $cache = array();
521 if (!array_key_exists($quiz->id, $cache)) {
522 $cache[$quiz->id] = quiz_has_grades($quiz) &&
523 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
524 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
525 array($quiz->id));
527 return $cache[$quiz->id];
531 * Update the sumgrades field of the quiz. This needs to be called whenever
532 * the grading structure of the quiz is changed. For example if a question is
533 * added or removed, or a question weight is changed.
535 * You should call {@link quiz_delete_previews()} before you call this function.
537 * @param object $quiz a quiz.
539 function quiz_update_sumgrades($quiz) {
540 global $DB;
542 $sql = 'UPDATE {quiz}
543 SET sumgrades = COALESCE((
544 SELECT SUM(maxmark)
545 FROM {quiz_slots}
546 WHERE quizid = {quiz}.id
547 ), 0)
548 WHERE id = ?';
549 $DB->execute($sql, array($quiz->id));
550 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
552 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
553 // If the quiz has been attempted, and the sumgrades has been
554 // set to 0, then we must also set the maximum possible grade to 0, or
555 // we will get a divide by zero error.
556 quiz_set_grade(0, $quiz);
561 * Update the sumgrades field of the attempts at a quiz.
563 * @param object $quiz a quiz.
565 function quiz_update_all_attempt_sumgrades($quiz) {
566 global $DB;
567 $dm = new question_engine_data_mapper();
568 $timenow = time();
570 $sql = "UPDATE {quiz_attempts}
572 timemodified = :timenow,
573 sumgrades = (
574 {$dm->sum_usage_marks_subquery('uniqueid')}
576 WHERE quiz = :quizid AND state = :finishedstate";
577 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
578 'finishedstate' => quiz_attempt::FINISHED));
582 * The quiz grade is the maximum that student's results are marked out of. When it
583 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
584 * rescaled. After calling this function, you probably need to call
585 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
586 * quiz_update_grades.
588 * @param float $newgrade the new maximum grade for the quiz.
589 * @param object $quiz the quiz we are updating. Passed by reference so its
590 * grade field can be updated too.
591 * @return bool indicating success or failure.
593 function quiz_set_grade($newgrade, $quiz) {
594 global $DB;
595 // This is potentially expensive, so only do it if necessary.
596 if (abs($quiz->grade - $newgrade) < 1e-7) {
597 // Nothing to do.
598 return true;
601 $oldgrade = $quiz->grade;
602 $quiz->grade = $newgrade;
604 // Use a transaction, so that on those databases that support it, this is safer.
605 $transaction = $DB->start_delegated_transaction();
607 // Update the quiz table.
608 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
610 if ($oldgrade < 1) {
611 // If the old grade was zero, we cannot rescale, we have to recompute.
612 // We also recompute if the old grade was too small to avoid underflow problems.
613 quiz_update_all_final_grades($quiz);
615 } else {
616 // We can rescale the grades efficiently.
617 $timemodified = time();
618 $DB->execute("
619 UPDATE {quiz_grades}
620 SET grade = ? * grade, timemodified = ?
621 WHERE quiz = ?
622 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
625 if ($oldgrade > 1e-7) {
626 // Update the quiz_feedback table.
627 $factor = $newgrade/$oldgrade;
628 $DB->execute("
629 UPDATE {quiz_feedback}
630 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
631 WHERE quizid = ?
632 ", array($factor, $factor, $quiz->id));
635 // Update grade item and send all grades to gradebook.
636 quiz_grade_item_update($quiz);
637 quiz_update_grades($quiz);
639 $transaction->allow_commit();
640 return true;
644 * Save the overall grade for a user at a quiz in the quiz_grades table
646 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
647 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
648 * @param array $attempts The attempts of this user. Useful if you are
649 * looping through many users. Attempts can be fetched in one master query to
650 * avoid repeated querying.
651 * @return bool Indicates success or failure.
653 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
654 global $DB, $OUTPUT, $USER;
656 if (empty($userid)) {
657 $userid = $USER->id;
660 if (!$attempts) {
661 // Get all the attempts made by the user.
662 $attempts = quiz_get_user_attempts($quiz->id, $userid);
665 // Calculate the best grade.
666 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
667 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
669 // Save the best grade in the database.
670 if (is_null($bestgrade)) {
671 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
673 } else if ($grade = $DB->get_record('quiz_grades',
674 array('quiz' => $quiz->id, 'userid' => $userid))) {
675 $grade->grade = $bestgrade;
676 $grade->timemodified = time();
677 $DB->update_record('quiz_grades', $grade);
679 } else {
680 $grade = new stdClass();
681 $grade->quiz = $quiz->id;
682 $grade->userid = $userid;
683 $grade->grade = $bestgrade;
684 $grade->timemodified = time();
685 $DB->insert_record('quiz_grades', $grade);
688 quiz_update_grades($quiz, $userid);
692 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
694 * @param object $quiz the quiz settings object.
695 * @param array $attempts an array of all the user's attempts at this quiz in order.
696 * @return float the overall grade
698 function quiz_calculate_best_grade($quiz, $attempts) {
700 switch ($quiz->grademethod) {
702 case QUIZ_ATTEMPTFIRST:
703 $firstattempt = reset($attempts);
704 return $firstattempt->sumgrades;
706 case QUIZ_ATTEMPTLAST:
707 $lastattempt = end($attempts);
708 return $lastattempt->sumgrades;
710 case QUIZ_GRADEAVERAGE:
711 $sum = 0;
712 $count = 0;
713 foreach ($attempts as $attempt) {
714 if (!is_null($attempt->sumgrades)) {
715 $sum += $attempt->sumgrades;
716 $count++;
719 if ($count == 0) {
720 return null;
722 return $sum / $count;
724 case QUIZ_GRADEHIGHEST:
725 default:
726 $max = null;
727 foreach ($attempts as $attempt) {
728 if ($attempt->sumgrades > $max) {
729 $max = $attempt->sumgrades;
732 return $max;
737 * Update the final grade at this quiz for all students.
739 * This function is equivalent to calling quiz_save_best_grade for all
740 * users, but much more efficient.
742 * @param object $quiz the quiz settings.
744 function quiz_update_all_final_grades($quiz) {
745 global $DB;
747 if (!$quiz->sumgrades) {
748 return;
751 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
752 $firstlastattemptjoin = "JOIN (
753 SELECT
754 iquiza.userid,
755 MIN(attempt) AS firstattempt,
756 MAX(attempt) AS lastattempt
758 FROM {quiz_attempts} iquiza
760 WHERE
761 iquiza.state = :istatefinished AND
762 iquiza.preview = 0 AND
763 iquiza.quiz = :iquizid
765 GROUP BY iquiza.userid
766 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
768 switch ($quiz->grademethod) {
769 case QUIZ_ATTEMPTFIRST:
770 // Because of the where clause, there will only be one row, but we
771 // must still use an aggregate function.
772 $select = 'MAX(quiza.sumgrades)';
773 $join = $firstlastattemptjoin;
774 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
775 break;
777 case QUIZ_ATTEMPTLAST:
778 // Because of the where clause, there will only be one row, but we
779 // must still use an aggregate function.
780 $select = 'MAX(quiza.sumgrades)';
781 $join = $firstlastattemptjoin;
782 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
783 break;
785 case QUIZ_GRADEAVERAGE:
786 $select = 'AVG(quiza.sumgrades)';
787 $join = '';
788 $where = '';
789 break;
791 default:
792 case QUIZ_GRADEHIGHEST:
793 $select = 'MAX(quiza.sumgrades)';
794 $join = '';
795 $where = '';
796 break;
799 if ($quiz->sumgrades >= 0.000005) {
800 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
801 } else {
802 $finalgrade = '0';
804 $param['quizid'] = $quiz->id;
805 $param['quizid2'] = $quiz->id;
806 $param['quizid3'] = $quiz->id;
807 $param['quizid4'] = $quiz->id;
808 $param['statefinished'] = quiz_attempt::FINISHED;
809 $param['statefinished2'] = quiz_attempt::FINISHED;
810 $finalgradesubquery = "
811 SELECT quiza.userid, $finalgrade AS newgrade
812 FROM {quiz_attempts} quiza
813 $join
814 WHERE
815 $where
816 quiza.state = :statefinished AND
817 quiza.preview = 0 AND
818 quiza.quiz = :quizid3
819 GROUP BY quiza.userid";
821 $changedgrades = $DB->get_records_sql("
822 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
824 FROM (
825 SELECT userid
826 FROM {quiz_grades} qg
827 WHERE quiz = :quizid
828 UNION
829 SELECT DISTINCT userid
830 FROM {quiz_attempts} quiza2
831 WHERE
832 quiza2.state = :statefinished2 AND
833 quiza2.preview = 0 AND
834 quiza2.quiz = :quizid2
835 ) users
837 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
839 LEFT JOIN (
840 $finalgradesubquery
841 ) newgrades ON newgrades.userid = users.userid
843 WHERE
844 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
845 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
846 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
847 // The mess on the previous line is detecting where the value is
848 // NULL in one column, and NOT NULL in the other, but SQL does
849 // not have an XOR operator, and MS SQL server can't cope with
850 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
851 $param);
853 $timenow = time();
854 $todelete = array();
855 foreach ($changedgrades as $changedgrade) {
857 if (is_null($changedgrade->newgrade)) {
858 $todelete[] = $changedgrade->userid;
860 } else if (is_null($changedgrade->grade)) {
861 $toinsert = new stdClass();
862 $toinsert->quiz = $quiz->id;
863 $toinsert->userid = $changedgrade->userid;
864 $toinsert->timemodified = $timenow;
865 $toinsert->grade = $changedgrade->newgrade;
866 $DB->insert_record('quiz_grades', $toinsert);
868 } else {
869 $toupdate = new stdClass();
870 $toupdate->id = $changedgrade->id;
871 $toupdate->grade = $changedgrade->newgrade;
872 $toupdate->timemodified = $timenow;
873 $DB->update_record('quiz_grades', $toupdate);
877 if (!empty($todelete)) {
878 list($test, $params) = $DB->get_in_or_equal($todelete);
879 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
880 array_merge(array($quiz->id), $params));
885 * Efficiently update check state time on all open attempts
887 * @param array $conditions optional restrictions on which attempts to update
888 * Allowed conditions:
889 * courseid => (array|int) attempts in given course(s)
890 * userid => (array|int) attempts for given user(s)
891 * quizid => (array|int) attempts in given quiz(s)
892 * groupid => (array|int) quizzes with some override for given group(s)
895 function quiz_update_open_attempts(array $conditions) {
896 global $DB;
898 foreach ($conditions as &$value) {
899 if (!is_array($value)) {
900 $value = array($value);
904 $params = array();
905 $wheres = array("quiza.state IN ('inprogress', 'overdue')");
906 $iwheres = array("iquiza.state IN ('inprogress', 'overdue')");
908 if (isset($conditions['courseid'])) {
909 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
910 $params = array_merge($params, $inparams);
911 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
912 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
913 $params = array_merge($params, $inparams);
914 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
917 if (isset($conditions['userid'])) {
918 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
919 $params = array_merge($params, $inparams);
920 $wheres[] = "quiza.userid $incond";
921 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
922 $params = array_merge($params, $inparams);
923 $iwheres[] = "iquiza.userid $incond";
926 if (isset($conditions['quizid'])) {
927 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
928 $params = array_merge($params, $inparams);
929 $wheres[] = "quiza.quiz $incond";
930 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
931 $params = array_merge($params, $inparams);
932 $iwheres[] = "iquiza.quiz $incond";
935 if (isset($conditions['groupid'])) {
936 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
937 $params = array_merge($params, $inparams);
938 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
939 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
940 $params = array_merge($params, $inparams);
941 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
944 // SQL to compute timeclose and timelimit for each attempt:
945 $quizausersql = quiz_get_attempt_usertime_sql(
946 implode("\n AND ", $iwheres));
948 // SQL to compute the new timecheckstate
949 $timecheckstatesql = "
950 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
951 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
952 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
953 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
954 ELSE quizauser.usertimeclose END +
955 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
957 // SQL to select which attempts to process
958 $attemptselect = implode("\n AND ", $wheres);
961 * Each database handles updates with inner joins differently:
962 * - mysql does not allow a FROM clause
963 * - postgres and mssql allow FROM but handle table aliases differently
964 * - oracle requires a subquery
966 * Different code for each database.
969 $dbfamily = $DB->get_dbfamily();
970 if ($dbfamily == 'mysql') {
971 $updatesql = "UPDATE {quiz_attempts} quiza
972 JOIN {quiz} quiz ON quiz.id = quiza.quiz
973 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
974 SET quiza.timecheckstate = $timecheckstatesql
975 WHERE $attemptselect";
976 } else if ($dbfamily == 'postgres') {
977 $updatesql = "UPDATE {quiz_attempts} quiza
978 SET timecheckstate = $timecheckstatesql
979 FROM {quiz} quiz, ( $quizausersql ) quizauser
980 WHERE quiz.id = quiza.quiz
981 AND quizauser.id = quiza.id
982 AND $attemptselect";
983 } else if ($dbfamily == 'mssql') {
984 $updatesql = "UPDATE quiza
985 SET timecheckstate = $timecheckstatesql
986 FROM {quiz_attempts} quiza
987 JOIN {quiz} quiz ON quiz.id = quiza.quiz
988 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
989 WHERE $attemptselect";
990 } else {
991 // oracle, sqlite and others
992 $updatesql = "UPDATE {quiz_attempts} quiza
993 SET timecheckstate = (
994 SELECT $timecheckstatesql
995 FROM {quiz} quiz, ( $quizausersql ) quizauser
996 WHERE quiz.id = quiza.quiz
997 AND quizauser.id = quiza.id
999 WHERE $attemptselect";
1002 $DB->execute($updatesql, $params);
1006 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
1008 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1009 * for performance. These can use the table alias iquiza for the quiz attempts table.
1010 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
1012 function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1013 if ($redundantwhereclauses) {
1014 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1016 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1017 // any other group override
1018 $quizausersql = "
1019 SELECT iquiza.id,
1020 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1021 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1023 FROM {quiz_attempts} iquiza
1024 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1025 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1026 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1027 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1028 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1029 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1030 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
1031 $redundantwhereclauses
1032 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1033 return $quizausersql;
1037 * Return the attempt with the best grade for a quiz
1039 * Which attempt is the best depends on $quiz->grademethod. If the grade
1040 * method is GRADEAVERAGE then this function simply returns the last attempt.
1041 * @return object The attempt with the best grade
1042 * @param object $quiz The quiz for which the best grade is to be calculated
1043 * @param array $attempts An array of all the attempts of the user at the quiz
1045 function quiz_calculate_best_attempt($quiz, $attempts) {
1047 switch ($quiz->grademethod) {
1049 case QUIZ_ATTEMPTFIRST:
1050 foreach ($attempts as $attempt) {
1051 return $attempt;
1053 break;
1055 case QUIZ_GRADEAVERAGE: // We need to do something with it.
1056 case QUIZ_ATTEMPTLAST:
1057 foreach ($attempts as $attempt) {
1058 $final = $attempt;
1060 return $final;
1062 default:
1063 case QUIZ_GRADEHIGHEST:
1064 $max = -1;
1065 foreach ($attempts as $attempt) {
1066 if ($attempt->sumgrades > $max) {
1067 $max = $attempt->sumgrades;
1068 $maxattempt = $attempt;
1071 return $maxattempt;
1076 * @return array int => lang string the options for calculating the quiz grade
1077 * from the individual attempt grades.
1079 function quiz_get_grading_options() {
1080 return array(
1081 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1082 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1083 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1084 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1089 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1090 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
1091 * @return the lang string for that option.
1093 function quiz_get_grading_option_name($option) {
1094 $strings = quiz_get_grading_options();
1095 return $strings[$option];
1099 * @return array string => lang string the options for handling overdue quiz
1100 * attempts.
1102 function quiz_get_overdue_handling_options() {
1103 return array(
1104 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1105 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1106 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1111 * Get the choices for what size user picture to show.
1112 * @return array string => lang string the options for whether to display the user's picture.
1114 function quiz_get_user_image_options() {
1115 return array(
1116 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
1117 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
1118 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'),
1123 * Get the human-readable name for a quiz attempt state.
1124 * @param string $state one of the state constants like {@link quiz_attempt::IN_PROGRESS}.
1125 * @return string The lang string to describe that state.
1127 function quiz_attempt_state_name($state) {
1128 switch ($state) {
1129 case quiz_attempt::IN_PROGRESS:
1130 return get_string('stateinprogress', 'quiz');
1131 case quiz_attempt::OVERDUE:
1132 return get_string('stateoverdue', 'quiz');
1133 case quiz_attempt::FINISHED:
1134 return get_string('statefinished', 'quiz');
1135 case quiz_attempt::ABANDONED:
1136 return get_string('stateabandoned', 'quiz');
1137 default:
1138 throw new coding_exception('Unknown quiz attempt state.');
1142 // Other quiz functions ////////////////////////////////////////////////////////
1145 * @param object $quiz the quiz.
1146 * @param int $cmid the course_module object for this quiz.
1147 * @param object $question the question.
1148 * @param string $returnurl url to return to after action is done.
1149 * @return string html for a number of icons linked to action pages for a
1150 * question - preview and edit / view icons depending on user capabilities.
1152 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
1153 $html = quiz_question_preview_button($quiz, $question) . ' ' .
1154 quiz_question_edit_button($cmid, $question, $returnurl);
1155 return $html;
1159 * @param int $cmid the course_module.id for this quiz.
1160 * @param object $question the question.
1161 * @param string $returnurl url to return to after action is done.
1162 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
1163 * @return the HTML for an edit icon, view icon, or nothing for a question
1164 * (depending on permissions).
1166 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
1167 global $CFG, $OUTPUT;
1169 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
1170 static $stredit = null;
1171 static $strview = null;
1172 if ($stredit === null) {
1173 $stredit = get_string('edit');
1174 $strview = get_string('view');
1177 // What sort of icon should we show?
1178 $action = '';
1179 if (!empty($question->id) &&
1180 (question_has_capability_on($question, 'edit', $question->category) ||
1181 question_has_capability_on($question, 'move', $question->category))) {
1182 $action = $stredit;
1183 $icon = '/t/edit';
1184 } else if (!empty($question->id) &&
1185 question_has_capability_on($question, 'view', $question->category)) {
1186 $action = $strview;
1187 $icon = '/i/info';
1190 // Build the icon.
1191 if ($action) {
1192 if ($returnurl instanceof moodle_url) {
1193 $returnurl = $returnurl->out_as_local_url(false);
1195 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
1196 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
1197 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
1198 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
1199 '</a>';
1200 } else if ($contentaftericon) {
1201 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
1202 } else {
1203 return '';
1208 * @param object $quiz the quiz settings
1209 * @param object $question the question
1210 * @return moodle_url to preview this question with the options from this quiz.
1212 function quiz_question_preview_url($quiz, $question) {
1213 // Get the appropriate display options.
1214 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
1215 mod_quiz_display_options::DURING);
1217 $maxmark = null;
1218 if (isset($question->maxmark)) {
1219 $maxmark = $question->maxmark;
1222 // Work out the correcte preview URL.
1223 return question_preview_url($question->id, $quiz->preferredbehaviour,
1224 $maxmark, $displayoptions);
1228 * @param object $quiz the quiz settings
1229 * @param object $question the question
1230 * @param bool $label if true, show the preview question label after the icon
1231 * @return the HTML for a preview question icon.
1233 function quiz_question_preview_button($quiz, $question, $label = false) {
1234 global $CFG, $OUTPUT;
1235 if (!question_has_capability_on($question, 'use', $question->category)) {
1236 return '';
1239 $url = quiz_question_preview_url($quiz, $question);
1241 // Do we want a label?
1242 $strpreviewlabel = '';
1243 if ($label) {
1244 $strpreviewlabel = get_string('preview', 'quiz');
1247 // Build the icon.
1248 $strpreviewquestion = get_string('previewquestion', 'quiz');
1249 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
1251 $action = new popup_action('click', $url, 'questionpreview',
1252 question_preview_popup_params());
1254 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
1258 * @param object $attempt the attempt.
1259 * @param object $context the quiz context.
1260 * @return int whether flags should be shown/editable to the current user for this attempt.
1262 function quiz_get_flag_option($attempt, $context) {
1263 global $USER;
1264 if (!has_capability('moodle/question:flag', $context)) {
1265 return question_display_options::HIDDEN;
1266 } else if ($attempt->userid == $USER->id) {
1267 return question_display_options::EDITABLE;
1268 } else {
1269 return question_display_options::VISIBLE;
1274 * Work out what state this quiz attempt is in - in the sense used by
1275 * quiz_get_review_options, not in the sense of $attempt->state.
1276 * @param object $quiz the quiz settings
1277 * @param object $attempt the quiz_attempt database row.
1278 * @return int one of the mod_quiz_display_options::DURING,
1279 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
1281 function quiz_attempt_state($quiz, $attempt) {
1282 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
1283 return mod_quiz_display_options::DURING;
1284 } else if (time() < $attempt->timefinish + 120) {
1285 return mod_quiz_display_options::IMMEDIATELY_AFTER;
1286 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
1287 return mod_quiz_display_options::LATER_WHILE_OPEN;
1288 } else {
1289 return mod_quiz_display_options::AFTER_CLOSE;
1294 * The the appropraite mod_quiz_display_options object for this attempt at this
1295 * quiz right now.
1297 * @param object $quiz the quiz instance.
1298 * @param object $attempt the attempt in question.
1299 * @param $context the quiz context.
1301 * @return mod_quiz_display_options
1303 function quiz_get_review_options($quiz, $attempt, $context) {
1304 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
1306 $options->readonly = true;
1307 $options->flags = quiz_get_flag_option($attempt, $context);
1308 if (!empty($attempt->id)) {
1309 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1310 array('attempt' => $attempt->id));
1313 // Show a link to the comment box only for closed attempts.
1314 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
1315 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
1316 $options->manualcomment = question_display_options::VISIBLE;
1317 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1318 array('attempt' => $attempt->id));
1321 if (!is_null($context) && !$attempt->preview &&
1322 has_capability('mod/quiz:viewreports', $context) &&
1323 has_capability('moodle/grade:viewhidden', $context)) {
1324 // People who can see reports and hidden grades should be shown everything,
1325 // except during preview when teachers want to see what students see.
1326 $options->attempt = question_display_options::VISIBLE;
1327 $options->correctness = question_display_options::VISIBLE;
1328 $options->marks = question_display_options::MARK_AND_MAX;
1329 $options->feedback = question_display_options::VISIBLE;
1330 $options->numpartscorrect = question_display_options::VISIBLE;
1331 $options->manualcomment = question_display_options::VISIBLE;
1332 $options->generalfeedback = question_display_options::VISIBLE;
1333 $options->rightanswer = question_display_options::VISIBLE;
1334 $options->overallfeedback = question_display_options::VISIBLE;
1335 $options->history = question_display_options::VISIBLE;
1339 return $options;
1343 * Combines the review options from a number of different quiz attempts.
1344 * Returns an array of two ojects, so the suggested way of calling this
1345 * funciton is:
1346 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1348 * @param object $quiz the quiz instance.
1349 * @param array $attempts an array of attempt objects.
1350 * @param $context the roles and permissions context,
1351 * normally the context for the quiz module instance.
1353 * @return array of two options objects, one showing which options are true for
1354 * at least one of the attempts, the other showing which options are true
1355 * for all attempts.
1357 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1358 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1359 $someoptions = new stdClass();
1360 $alloptions = new stdClass();
1361 foreach ($fields as $field) {
1362 $someoptions->$field = false;
1363 $alloptions->$field = true;
1365 $someoptions->marks = question_display_options::HIDDEN;
1366 $alloptions->marks = question_display_options::MARK_AND_MAX;
1368 foreach ($attempts as $attempt) {
1369 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1370 quiz_attempt_state($quiz, $attempt));
1371 foreach ($fields as $field) {
1372 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1373 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1375 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1376 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1378 return array($someoptions, $alloptions);
1381 // Functions for sending notification messages /////////////////////////////////
1384 * Sends a confirmation message to the student confirming that the attempt was processed.
1386 * @param object $a lots of useful information that can be used in the message
1387 * subject and body.
1389 * @return int|false as for {@link message_send()}.
1391 function quiz_send_confirmation($recipient, $a) {
1393 // Add information about the recipient to $a.
1394 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1395 $a->username = fullname($recipient);
1396 $a->userusername = $recipient->username;
1398 // Prepare the message.
1399 $eventdata = new stdClass();
1400 $eventdata->component = 'mod_quiz';
1401 $eventdata->name = 'confirmation';
1402 $eventdata->notification = 1;
1404 $eventdata->userfrom = core_user::get_noreply_user();
1405 $eventdata->userto = $recipient;
1406 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1407 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1408 $eventdata->fullmessageformat = FORMAT_PLAIN;
1409 $eventdata->fullmessagehtml = '';
1411 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1412 $eventdata->contexturl = $a->quizurl;
1413 $eventdata->contexturlname = $a->quizname;
1415 // ... and send it.
1416 return message_send($eventdata);
1420 * Sends notification messages to the interested parties that assign the role capability
1422 * @param object $recipient user object of the intended recipient
1423 * @param object $a associative array of replaceable fields for the templates
1425 * @return int|false as for {@link message_send()}.
1427 function quiz_send_notification($recipient, $submitter, $a) {
1429 // Recipient info for template.
1430 $a->useridnumber = $recipient->idnumber;
1431 $a->username = fullname($recipient);
1432 $a->userusername = $recipient->username;
1434 // Prepare the message.
1435 $eventdata = new stdClass();
1436 $eventdata->component = 'mod_quiz';
1437 $eventdata->name = 'submission';
1438 $eventdata->notification = 1;
1440 $eventdata->userfrom = $submitter;
1441 $eventdata->userto = $recipient;
1442 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1443 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1444 $eventdata->fullmessageformat = FORMAT_PLAIN;
1445 $eventdata->fullmessagehtml = '';
1447 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1448 $eventdata->contexturl = $a->quizreviewurl;
1449 $eventdata->contexturlname = $a->quizname;
1451 // ... and send it.
1452 return message_send($eventdata);
1456 * Send all the requried messages when a quiz attempt is submitted.
1458 * @param object $course the course
1459 * @param object $quiz the quiz
1460 * @param object $attempt this attempt just finished
1461 * @param object $context the quiz context
1462 * @param object $cm the coursemodule for this quiz
1464 * @return bool true if all necessary messages were sent successfully, else false.
1466 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1467 global $CFG, $DB;
1469 // Do nothing if required objects not present.
1470 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1471 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1474 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1476 // Check for confirmation required.
1477 $sendconfirm = false;
1478 $notifyexcludeusers = '';
1479 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1480 $notifyexcludeusers = $submitter->id;
1481 $sendconfirm = true;
1484 // Check for notifications required.
1485 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang, u.timezone, u.mailformat, u.maildisplay, ';
1486 $notifyfields .= get_all_user_name_fields(true, 'u');
1487 $groups = groups_get_all_groups($course->id, $submitter->id);
1488 if (is_array($groups) && count($groups) > 0) {
1489 $groups = array_keys($groups);
1490 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1491 // If the user is not in a group, and the quiz is set to group mode,
1492 // then set $groups to a non-existant id so that only users with
1493 // 'moodle/site:accessallgroups' get notified.
1494 $groups = -1;
1495 } else {
1496 $groups = '';
1498 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1499 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1501 if (empty($userstonotify) && !$sendconfirm) {
1502 return true; // Nothing to do.
1505 $a = new stdClass();
1506 // Course info.
1507 $a->coursename = $course->fullname;
1508 $a->courseshortname = $course->shortname;
1509 // Quiz info.
1510 $a->quizname = $quiz->name;
1511 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1512 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1513 format_string($quiz->name) . ' report</a>';
1514 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1515 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1516 // Attempt info.
1517 $a->submissiontime = userdate($attempt->timefinish);
1518 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1519 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1520 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1521 format_string($quiz->name) . ' review</a>';
1522 // Student who sat the quiz info.
1523 $a->studentidnumber = $submitter->idnumber;
1524 $a->studentname = fullname($submitter);
1525 $a->studentusername = $submitter->username;
1527 $allok = true;
1529 // Send notifications if required.
1530 if (!empty($userstonotify)) {
1531 foreach ($userstonotify as $recipient) {
1532 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1536 // Send confirmation if required. We send the student confirmation last, so
1537 // that if message sending is being intermittently buggy, which means we send
1538 // some but not all messages, and then try again later, then teachers may get
1539 // duplicate messages, but the student will always get exactly one.
1540 if ($sendconfirm) {
1541 $allok = $allok && quiz_send_confirmation($submitter, $a);
1544 return $allok;
1548 * Send the notification message when a quiz attempt becomes overdue.
1550 * @param object $course the course
1551 * @param object $quiz the quiz
1552 * @param object $attempt this attempt just finished
1553 * @param object $context the quiz context
1554 * @param object $cm the coursemodule for this quiz
1556 function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
1557 global $CFG, $DB;
1559 // Do nothing if required objects not present.
1560 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1561 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1564 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1566 if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
1567 return; // Message not required.
1570 // Prepare lots of useful information that admins might want to include in
1571 // the email message.
1572 $quizname = format_string($quiz->name);
1574 $deadlines = array();
1575 if ($quiz->timelimit) {
1576 $deadlines[] = $attempt->timestart + $quiz->timelimit;
1578 if ($quiz->timeclose) {
1579 $deadlines[] = $quiz->timeclose;
1581 $duedate = min($deadlines);
1582 $graceend = $duedate + $quiz->graceperiod;
1584 $a = new stdClass();
1585 // Course info.
1586 $a->coursename = $course->fullname;
1587 $a->courseshortname = $course->shortname;
1588 // Quiz info.
1589 $a->quizname = $quizname;
1590 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1591 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1592 // Attempt info.
1593 $a->attemptduedate = userdate($duedate);
1594 $a->attemptgraceend = userdate($graceend);
1595 $a->attemptsummaryurl = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
1596 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1597 // Student's info.
1598 $a->studentidnumber = $submitter->idnumber;
1599 $a->studentname = fullname($submitter);
1600 $a->studentusername = $submitter->username;
1602 // Prepare the message.
1603 $eventdata = new stdClass();
1604 $eventdata->component = 'mod_quiz';
1605 $eventdata->name = 'attempt_overdue';
1606 $eventdata->notification = 1;
1608 $eventdata->userfrom = core_user::get_noreply_user();
1609 $eventdata->userto = $submitter;
1610 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1611 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1612 $eventdata->fullmessageformat = FORMAT_PLAIN;
1613 $eventdata->fullmessagehtml = '';
1615 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1616 $eventdata->contexturl = $a->quizurl;
1617 $eventdata->contexturlname = $a->quizname;
1619 // Send the message.
1620 return message_send($eventdata);
1624 * Handle the quiz_attempt_submitted event.
1626 * This sends the confirmation and notification messages, if required.
1628 * @param object $event the event object.
1630 function quiz_attempt_submitted_handler($event) {
1631 global $DB;
1633 $course = $DB->get_record('course', array('id' => $event->courseid));
1634 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1635 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1636 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1638 if (!($course && $quiz && $cm && $attempt)) {
1639 // Something has been deleted since the event was raised. Therefore, the
1640 // event is no longer relevant.
1641 return true;
1644 return quiz_send_notification_messages($course, $quiz, $attempt,
1645 context_module::instance($cm->id), $cm);
1649 * Handle the quiz_attempt_overdue event.
1651 * For quizzes with applicable settings, this sends a message to the user, reminding
1652 * them that they forgot to submit, and that they have another chance to do so.
1654 * @param object $event the event object.
1656 function quiz_attempt_overdue_handler($event) {
1657 global $DB;
1659 $course = $DB->get_record('course', array('id' => $event->courseid));
1660 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1661 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1662 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
1664 if (!($course && $quiz && $cm && $attempt)) {
1665 // Something has been deleted since the event was raised. Therefore, the
1666 // event is no longer relevant.
1667 return true;
1670 return quiz_send_overdue_message($course, $quiz, $attempt,
1671 context_module::instance($cm->id), $cm);
1675 * Handle groups_member_added event
1677 * @param object $event the event object.
1678 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_added()}.
1680 function quiz_groups_member_added_handler($event) {
1681 debugging('quiz_groups_member_added_handler() is deprecated, please use ' .
1682 '\mod_quiz\group_observers::group_member_added() instead.', DEBUG_DEVELOPER);
1683 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1687 * Handle groups_member_removed event
1689 * @param object $event the event object.
1690 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1692 function quiz_groups_member_removed_handler($event) {
1693 debugging('quiz_groups_member_removed_handler() is deprecated, please use ' .
1694 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1695 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1699 * Handle groups_group_deleted event
1701 * @param object $event the event object.
1702 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_deleted()}.
1704 function quiz_groups_group_deleted_handler($event) {
1705 global $DB;
1706 debugging('quiz_groups_group_deleted_handler() is deprecated, please use ' .
1707 '\mod_quiz\group_observers::group_deleted() instead.', DEBUG_DEVELOPER);
1708 quiz_process_group_deleted_in_course($event->courseid);
1712 * Logic to happen when a/some group(s) has/have been deleted in a course.
1714 * @param int $courseid The course ID.
1715 * @return void
1717 function quiz_process_group_deleted_in_course($courseid) {
1718 global $DB;
1720 // It would be nice if we got the groupid that was deleted.
1721 // Instead, we just update all quizzes with orphaned group overrides.
1722 $sql = "SELECT o.id, o.quiz
1723 FROM {quiz_overrides} o
1724 JOIN {quiz} quiz ON quiz.id = o.quiz
1725 LEFT JOIN {groups} grp ON grp.id = o.groupid
1726 WHERE quiz.course = :courseid
1727 AND o.groupid IS NOT NULL
1728 AND grp.id IS NULL";
1729 $params = array('courseid' => $courseid);
1730 $records = $DB->get_records_sql_menu($sql, $params);
1731 if (!$records) {
1732 return; // Nothing to do.
1734 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
1735 quiz_update_open_attempts(array('quizid' => array_unique(array_values($records))));
1739 * Handle groups_members_removed event
1741 * @param object $event the event object.
1742 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
1744 function quiz_groups_members_removed_handler($event) {
1745 debugging('quiz_groups_members_removed_handler() is deprecated, please use ' .
1746 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
1747 if ($event->userid == 0) {
1748 quiz_update_open_attempts(array('courseid'=>$event->courseid));
1749 } else {
1750 quiz_update_open_attempts(array('courseid'=>$event->courseid, 'userid'=>$event->userid));
1755 * Get the information about the standard quiz JavaScript module.
1756 * @return array a standard jsmodule structure.
1758 function quiz_get_js_module() {
1759 global $PAGE;
1761 return array(
1762 'name' => 'mod_quiz',
1763 'fullpath' => '/mod/quiz/module.js',
1764 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1765 'core_question_engine', 'moodle-core-formchangechecker'),
1766 'strings' => array(
1767 array('cancel', 'moodle'),
1768 array('flagged', 'question'),
1769 array('functiondisabledbysecuremode', 'quiz'),
1770 array('startattempt', 'quiz'),
1771 array('timesup', 'quiz'),
1772 array('changesmadereallygoaway', 'moodle'),
1779 * An extension of question_display_options that includes the extra options used
1780 * by the quiz.
1782 * @copyright 2010 The Open University
1783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1785 class mod_quiz_display_options extends question_display_options {
1786 /**#@+
1787 * @var integer bits used to indicate various times in relation to a
1788 * quiz attempt.
1790 const DURING = 0x10000;
1791 const IMMEDIATELY_AFTER = 0x01000;
1792 const LATER_WHILE_OPEN = 0x00100;
1793 const AFTER_CLOSE = 0x00010;
1794 /**#@-*/
1797 * @var boolean if this is false, then the student is not allowed to review
1798 * anything about the attempt.
1800 public $attempt = true;
1803 * @var boolean if this is false, then the student is not allowed to review
1804 * anything about the attempt.
1806 public $overallfeedback = self::VISIBLE;
1809 * Set up the various options from the quiz settings, and a time constant.
1810 * @param object $quiz the quiz settings.
1811 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1812 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1813 * @return mod_quiz_display_options set up appropriately.
1815 public static function make_from_quiz($quiz, $when) {
1816 $options = new self();
1818 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1819 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
1820 $options->marks = self::extract($quiz->reviewmarks, $when,
1821 self::MARK_AND_MAX, self::MAX_ONLY);
1822 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1823 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1824 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1825 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1827 $options->numpartscorrect = $options->feedback;
1828 $options->manualcomment = $options->feedback;
1830 if ($quiz->questiondecimalpoints != -1) {
1831 $options->markdp = $quiz->questiondecimalpoints;
1832 } else {
1833 $options->markdp = $quiz->decimalpoints;
1836 return $options;
1839 protected static function extract($bitmask, $bit,
1840 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
1841 if ($bitmask & $bit) {
1842 return $whenset;
1843 } else {
1844 return $whennotset;
1851 * A {@link qubaid_condition} for finding all the question usages belonging to
1852 * a particular quiz.
1854 * @copyright 2010 The Open University
1855 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1857 class qubaids_for_quiz extends qubaid_join {
1858 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1859 $where = 'quiza.quiz = :quizaquiz';
1860 $params = array('quizaquiz' => $quizid);
1862 if (!$includepreviews) {
1863 $where .= ' AND preview = 0';
1866 if ($onlyfinished) {
1867 $where .= ' AND state == :statefinished';
1868 $params['statefinished'] = quiz_attempt::FINISHED;
1871 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);