MDL-32572 fix notice when changing internal auth_db passwords
[moodle.git] / mod / quiz / locallib.php
bloba5306ad14c5a9c0eb59de179f03f210ac55e2c21
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
27 * @subpackage quiz
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');
45 /**
46 * 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');
51 /// Functions related to attempts /////////////////////////////////////////
53 /**
54 * Creates an object to represent a new attempt at a quiz
56 * Creates an attempt object to represent an attempt at the quiz by the current
57 * user starting at the current time. The ->id field is not set. The object is
58 * NOT written to the database.
60 * @param object $quiz the quiz to create an attempt for.
61 * @param int $attemptnumber the sequence number for the attempt.
62 * @param object $lastattempt the previous attempt by this user, if any. Only needed
63 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
64 * @param int $timenow the time the attempt was started at.
65 * @param bool $ispreview whether this new attempt is a preview.
67 * @return object the newly created attempt object.
69 function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
70 global $USER;
72 if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
73 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
74 new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
75 array('grade' => quiz_format_grade($quiz, $quiz->grade)));
78 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
79 // We are not building on last attempt so create a new attempt.
80 $attempt = new stdClass();
81 $attempt->quiz = $quiz->id;
82 $attempt->userid = $USER->id;
83 $attempt->preview = 0;
84 $attempt->layout = quiz_clean_layout($quiz->questions, true);
85 if ($quiz->shufflequestions) {
86 $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
88 } else {
89 // Build on last attempt.
90 if (empty($lastattempt)) {
91 print_error('cannotfindprevattempt', 'quiz');
93 $attempt = $lastattempt;
96 $attempt->attempt = $attemptnumber;
97 $attempt->timestart = $timenow;
98 $attempt->timefinish = 0;
99 $attempt->timemodified = $timenow;
101 // If this is a preview, mark it as such.
102 if ($ispreview) {
103 $attempt->preview = 1;
106 return $attempt;
110 * Returns an unfinished attempt (if there is one) for the given
111 * user on the given quiz. This function does not return preview attempts.
113 * @param int $quizid the id of the quiz.
114 * @param int $userid the id of the user.
116 * @return mixed the unfinished attempt if there is one, false if not.
118 function quiz_get_user_attempt_unfinished($quizid, $userid) {
119 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
120 if ($attempts) {
121 return array_shift($attempts);
122 } else {
123 return false;
128 * Delete a quiz attempt.
129 * @param mixed $attempt an integer attempt id or an attempt object
130 * (row of the quiz_attempts table).
131 * @param object $quiz the quiz object.
133 function quiz_delete_attempt($attempt, $quiz) {
134 global $DB;
135 if (is_numeric($attempt)) {
136 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
137 return;
141 if ($attempt->quiz != $quiz->id) {
142 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
143 "but was passed quiz $quiz->id.");
144 return;
147 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
148 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
150 // Search quiz_attempts for other instances by this user.
151 // If none, then delete record for this quiz, this user from quiz_grades
152 // else recalculate best grade
153 $userid = $attempt->userid;
154 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
155 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
156 } else {
157 quiz_save_best_grade($quiz, $userid);
160 quiz_update_grades($quiz, $userid);
164 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
165 * to one user.
166 * @param object $quiz the quiz object.
167 * @param int $userid (optional) if given, only delete the previews belonging to this user.
169 function quiz_delete_previews($quiz, $userid = null) {
170 global $DB;
171 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
172 if (!empty($userid)) {
173 $conditions['userid'] = $userid;
175 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
176 foreach ($previewattempts as $attempt) {
177 quiz_delete_attempt($attempt, $quiz);
182 * @param int $quizid The quiz id.
183 * @return bool whether this quiz has any (non-preview) attempts.
185 function quiz_has_attempts($quizid) {
186 global $DB;
187 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
190 /// Functions to do with quiz layout and pages ////////////////////////////////
193 * Returns a comma separated list of question ids for the quiz
195 * @param string $layout The string representing the quiz layout. Each page is
196 * represented as a comma separated list of question ids and 0 indicating
197 * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
198 * 3 on page 2
199 * @return string comma separated list of question ids, without page breaks.
201 function quiz_questions_in_quiz($layout) {
202 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
203 if ($questions === '0') {
204 return '';
205 } else {
206 return $questions;
211 * Returns the number of pages in a quiz layout
213 * @param string $layout The string representing the quiz layout. Always ends in ,0
214 * @return int The number of pages in the quiz.
216 function quiz_number_of_pages($layout) {
217 return substr_count(',' . $layout, ',0');
221 * Returns the number of questions in the quiz layout
223 * @param string $layout the string representing the quiz layout.
224 * @return int The number of questions in the quiz.
226 function quiz_number_of_questions_in_quiz($layout) {
227 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
228 $count = substr_count($layout, ',');
229 if ($layout !== '') {
230 $count++;
232 return $count;
236 * Re-paginates the quiz layout
238 * @param string $layout The string representing the quiz layout. If there is
239 * if there is any doubt about the quality of the input data, call
240 * quiz_clean_layout before you call this function.
241 * @param int $perpage The number of questions per page
242 * @param bool $shuffle Should the questions be reordered randomly?
243 * @return string the new layout string
245 function quiz_repaginate($layout, $perpage, $shuffle = false) {
246 $questions = quiz_questions_in_quiz($layout);
247 if (!$questions) {
248 return '0';
251 $questions = explode(',', quiz_questions_in_quiz($layout));
252 if ($shuffle) {
253 shuffle($questions);
256 $onthispage = 0;
257 $layout = array();
258 foreach ($questions as $question) {
259 if ($perpage and $onthispage >= $perpage) {
260 $layout[] = 0;
261 $onthispage = 0;
263 $layout[] = $question;
264 $onthispage += 1;
267 $layout[] = 0;
268 return implode(',', $layout);
271 /// Functions to do with quiz grades //////////////////////////////////////////
274 * Creates an array of maximum grades for a quiz
276 * The grades are extracted from the quiz_question_instances table.
277 * @param object $quiz The quiz settings.
278 * @return array of grades indexed by question id. These are the maximum
279 * possible grades that students can achieve for each of the questions.
281 function quiz_get_all_question_grades($quiz) {
282 global $CFG, $DB;
284 $questionlist = quiz_questions_in_quiz($quiz->questions);
285 if (empty($questionlist)) {
286 return array();
289 $params = array($quiz->id);
290 $wheresql = '';
291 if (!is_null($questionlist)) {
292 list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
293 $wheresql = " AND question $usql ";
294 $params = array_merge($params, $question_params);
297 $instances = $DB->get_records_sql("SELECT question, grade, id
298 FROM {quiz_question_instances}
299 WHERE quiz = ? $wheresql", $params);
301 $list = explode(",", $questionlist);
302 $grades = array();
304 foreach ($list as $qid) {
305 if (isset($instances[$qid])) {
306 $grades[$qid] = $instances[$qid]->grade;
307 } else {
308 $grades[$qid] = 1;
311 return $grades;
315 * Convert the raw grade stored in $attempt into a grade out of the maximum
316 * grade for this quiz.
318 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
319 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
320 * @param bool|string $format whether to format the results for display
321 * or 'question' to format a question grade (different number of decimal places.
322 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
323 * if the $grade is null.
325 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
326 if (is_null($rawgrade)) {
327 $grade = null;
328 } else if ($quiz->sumgrades >= 0.000005) {
329 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
330 } else {
331 $grade = 0;
333 if ($format === 'question') {
334 $grade = quiz_format_question_grade($quiz, $grade);
335 } else if ($format) {
336 $grade = quiz_format_grade($quiz, $grade);
338 return $grade;
342 * Get the feedback text that should be show to a student who
343 * got this grade on this quiz. The feedback is processed ready for diplay.
345 * @param float $grade a grade on this quiz.
346 * @param object $quiz the quiz settings.
347 * @param object $context the quiz context.
348 * @return string the comment that corresponds to this grade (empty string if there is not one.
350 function quiz_feedback_for_grade($grade, $quiz, $context) {
351 global $DB;
353 if (is_null($grade)) {
354 return '';
357 // With CBM etc, it is possible to get -ve grades, which would then not match
358 // any feedback. Therefore, we replace -ve grades with 0.
359 $grade = max($grade, 0);
361 $feedback = $DB->get_record_select('quiz_feedback',
362 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
364 if (empty($feedback->feedbacktext)) {
365 return '';
368 // Clean the text, ready for display.
369 $formatoptions = new stdClass();
370 $formatoptions->noclean = true;
371 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
372 $context->id, 'mod_quiz', 'feedback', $feedback->id);
373 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
375 return $feedbacktext;
379 * @param object $quiz the quiz database row.
380 * @return bool Whether this quiz has any non-blank feedback text.
382 function quiz_has_feedback($quiz) {
383 global $DB;
384 static $cache = array();
385 if (!array_key_exists($quiz->id, $cache)) {
386 $cache[$quiz->id] = quiz_has_grades($quiz) &&
387 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
388 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
389 array($quiz->id));
391 return $cache[$quiz->id];
395 * Update the sumgrades field of the quiz. This needs to be called whenever
396 * the grading structure of the quiz is changed. For example if a question is
397 * added or removed, or a question weight is changed.
399 * You should call {@link quiz_delete_previews()} before you call this function.
401 * @param object $quiz a quiz.
403 function quiz_update_sumgrades($quiz) {
404 global $DB;
406 $sql = 'UPDATE {quiz}
407 SET sumgrades = COALESCE((
408 SELECT SUM(grade)
409 FROM {quiz_question_instances}
410 WHERE quiz = {quiz}.id
411 ), 0)
412 WHERE id = ?';
413 $DB->execute($sql, array($quiz->id));
414 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
416 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
417 // If the quiz has been attempted, and the sumgrades has been
418 // set to 0, then we must also set the maximum possible grade to 0, or
419 // we will get a divide by zero error.
420 quiz_set_grade(0, $quiz);
425 * Update the sumgrades field of the attempts at a quiz.
427 * @param object $quiz a quiz.
429 function quiz_update_all_attempt_sumgrades($quiz) {
430 global $DB;
431 $dm = new question_engine_data_mapper();
432 $timenow = time();
434 $sql = "UPDATE {quiz_attempts}
436 timemodified = :timenow,
437 sumgrades = (
438 {$dm->sum_usage_marks_subquery('uniqueid')}
440 WHERE quiz = :quizid AND timefinish <> 0";
441 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id));
445 * The quiz grade is the maximum that student's results are marked out of. When it
446 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
447 * rescaled. After calling this function, you probably need to call
448 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
449 * quiz_update_grades.
451 * @param float $newgrade the new maximum grade for the quiz.
452 * @param object $quiz the quiz we are updating. Passed by reference so its
453 * grade field can be updated too.
454 * @return bool indicating success or failure.
456 function quiz_set_grade($newgrade, $quiz) {
457 global $DB;
458 // This is potentially expensive, so only do it if necessary.
459 if (abs($quiz->grade - $newgrade) < 1e-7) {
460 // Nothing to do.
461 return true;
464 $oldgrade = $quiz->grade;
465 $quiz->grade = $newgrade;
467 // Use a transaction, so that on those databases that support it, this is safer.
468 $transaction = $DB->start_delegated_transaction();
470 // Update the quiz table.
471 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
473 if ($oldgrade < 1) {
474 // If the old grade was zero, we cannot rescale, we have to recompute.
475 // We also recompute if the old grade was too small to avoid underflow problems.
476 quiz_update_all_final_grades($quiz);
478 } else {
479 // We can rescale the grades efficiently.
480 $timemodified = time();
481 $DB->execute("
482 UPDATE {quiz_grades}
483 SET grade = ? * grade, timemodified = ?
484 WHERE quiz = ?
485 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
488 if ($oldgrade > 1e-7) {
489 // Update the quiz_feedback table.
490 $factor = $newgrade/$oldgrade;
491 $DB->execute("
492 UPDATE {quiz_feedback}
493 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
494 WHERE quizid = ?
495 ", array($factor, $factor, $quiz->id));
498 // Update grade item and send all grades to gradebook.
499 quiz_grade_item_update($quiz);
500 quiz_update_grades($quiz);
502 $transaction->allow_commit();
503 return true;
507 * Save the overall grade for a user at a quiz in the quiz_grades table
509 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
510 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
511 * @param array $attempts The attempts of this user. Useful if you are
512 * looping through many users. Attempts can be fetched in one master query to
513 * avoid repeated querying.
514 * @return bool Indicates success or failure.
516 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
517 global $DB, $OUTPUT, $USER;
519 if (empty($userid)) {
520 $userid = $USER->id;
523 if (!$attempts) {
524 // Get all the attempts made by the user
525 $attempts = quiz_get_user_attempts($quiz->id, $userid);
528 // Calculate the best grade
529 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
530 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
532 // Save the best grade in the database
533 if (is_null($bestgrade)) {
534 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
536 } else if ($grade = $DB->get_record('quiz_grades',
537 array('quiz' => $quiz->id, 'userid' => $userid))) {
538 $grade->grade = $bestgrade;
539 $grade->timemodified = time();
540 $DB->update_record('quiz_grades', $grade);
542 } else {
543 $grade->quiz = $quiz->id;
544 $grade->userid = $userid;
545 $grade->grade = $bestgrade;
546 $grade->timemodified = time();
547 $DB->insert_record('quiz_grades', $grade);
550 quiz_update_grades($quiz, $userid);
554 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
556 * @param object $quiz the quiz settings object.
557 * @param array $attempts an array of all the user's attempts at this quiz in order.
558 * @return float the overall grade
560 function quiz_calculate_best_grade($quiz, $attempts) {
562 switch ($quiz->grademethod) {
564 case QUIZ_ATTEMPTFIRST:
565 $firstattempt = reset($attempts);
566 return $firstattempt->sumgrades;
568 case QUIZ_ATTEMPTLAST:
569 $lastattempt = end($attempts);
570 return $lastattempt->sumgrades;
572 case QUIZ_GRADEAVERAGE:
573 $sum = 0;
574 $count = 0;
575 foreach ($attempts as $attempt) {
576 if (!is_null($attempt->sumgrades)) {
577 $sum += $attempt->sumgrades;
578 $count++;
581 if ($count == 0) {
582 return null;
584 return $sum / $count;
586 case QUIZ_GRADEHIGHEST:
587 default:
588 $max = null;
589 foreach ($attempts as $attempt) {
590 if ($attempt->sumgrades > $max) {
591 $max = $attempt->sumgrades;
594 return $max;
599 * Update the final grade at this quiz for all students.
601 * This function is equivalent to calling quiz_save_best_grade for all
602 * users, but much more efficient.
604 * @param object $quiz the quiz settings.
606 function quiz_update_all_final_grades($quiz) {
607 global $DB;
609 if (!$quiz->sumgrades) {
610 return;
613 $param = array('iquizid' => $quiz->id);
614 $firstlastattemptjoin = "JOIN (
615 SELECT
616 iquiza.userid,
617 MIN(attempt) AS firstattempt,
618 MAX(attempt) AS lastattempt
620 FROM {quiz_attempts} iquiza
622 WHERE
623 iquiza.timefinish <> 0 AND
624 iquiza.preview = 0 AND
625 iquiza.quiz = :iquizid
627 GROUP BY iquiza.userid
628 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
630 switch ($quiz->grademethod) {
631 case QUIZ_ATTEMPTFIRST:
632 // Because of the where clause, there will only be one row, but we
633 // must still use an aggregate function.
634 $select = 'MAX(quiza.sumgrades)';
635 $join = $firstlastattemptjoin;
636 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
637 break;
639 case QUIZ_ATTEMPTLAST:
640 // Because of the where clause, there will only be one row, but we
641 // must still use an aggregate function.
642 $select = 'MAX(quiza.sumgrades)';
643 $join = $firstlastattemptjoin;
644 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
645 break;
647 case QUIZ_GRADEAVERAGE:
648 $select = 'AVG(quiza.sumgrades)';
649 $join = '';
650 $where = '';
651 break;
653 default:
654 case QUIZ_GRADEHIGHEST:
655 $select = 'MAX(quiza.sumgrades)';
656 $join = '';
657 $where = '';
658 break;
661 if ($quiz->sumgrades >= 0.000005) {
662 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
663 } else {
664 $finalgrade = '0';
666 $param['quizid'] = $quiz->id;
667 $param['quizid2'] = $quiz->id;
668 $param['quizid3'] = $quiz->id;
669 $param['quizid4'] = $quiz->id;
670 $finalgradesubquery = "
671 SELECT quiza.userid, $finalgrade AS newgrade
672 FROM {quiz_attempts} quiza
673 $join
674 WHERE
675 $where
676 quiza.timefinish <> 0 AND
677 quiza.preview = 0 AND
678 quiza.quiz = :quizid3
679 GROUP BY quiza.userid";
681 $changedgrades = $DB->get_records_sql("
682 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
684 FROM (
685 SELECT userid
686 FROM {quiz_grades} qg
687 WHERE quiz = :quizid
688 UNION
689 SELECT DISTINCT userid
690 FROM {quiz_attempts} quiza2
691 WHERE
692 quiza2.timefinish <> 0 AND
693 quiza2.preview = 0 AND
694 quiza2.quiz = :quizid2
695 ) users
697 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
699 LEFT JOIN (
700 $finalgradesubquery
701 ) newgrades ON newgrades.userid = users.userid
703 WHERE
704 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
705 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
706 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
707 // The mess on the previous line is detecting where the value is
708 // NULL in one column, and NOT NULL in the other, but SQL does
709 // not have an XOR operator, and MS SQL server can't cope with
710 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
711 $param);
713 $timenow = time();
714 $todelete = array();
715 foreach ($changedgrades as $changedgrade) {
717 if (is_null($changedgrade->newgrade)) {
718 $todelete[] = $changedgrade->userid;
720 } else if (is_null($changedgrade->grade)) {
721 $toinsert = new stdClass();
722 $toinsert->quiz = $quiz->id;
723 $toinsert->userid = $changedgrade->userid;
724 $toinsert->timemodified = $timenow;
725 $toinsert->grade = $changedgrade->newgrade;
726 $DB->insert_record('quiz_grades', $toinsert);
728 } else {
729 $toupdate = new stdClass();
730 $toupdate->id = $changedgrade->id;
731 $toupdate->grade = $changedgrade->newgrade;
732 $toupdate->timemodified = $timenow;
733 $DB->update_record('quiz_grades', $toupdate);
737 if (!empty($todelete)) {
738 list($test, $params) = $DB->get_in_or_equal($todelete);
739 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
740 array_merge(array($quiz->id), $params));
745 * Return the attempt with the best grade for a quiz
747 * Which attempt is the best depends on $quiz->grademethod. If the grade
748 * method is GRADEAVERAGE then this function simply returns the last attempt.
749 * @return object The attempt with the best grade
750 * @param object $quiz The quiz for which the best grade is to be calculated
751 * @param array $attempts An array of all the attempts of the user at the quiz
753 function quiz_calculate_best_attempt($quiz, $attempts) {
755 switch ($quiz->grademethod) {
757 case QUIZ_ATTEMPTFIRST:
758 foreach ($attempts as $attempt) {
759 return $attempt;
761 break;
763 case QUIZ_GRADEAVERAGE: // need to do something with it :-)
764 case QUIZ_ATTEMPTLAST:
765 foreach ($attempts as $attempt) {
766 $final = $attempt;
768 return $final;
770 default:
771 case QUIZ_GRADEHIGHEST:
772 $max = -1;
773 foreach ($attempts as $attempt) {
774 if ($attempt->sumgrades > $max) {
775 $max = $attempt->sumgrades;
776 $maxattempt = $attempt;
779 return $maxattempt;
784 * @return the options for calculating the quiz grade from the individual attempt grades.
786 function quiz_get_grading_options() {
787 return array(
788 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
789 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
790 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
791 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
796 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
797 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
798 * @return the lang string for that option.
800 function quiz_get_grading_option_name($option) {
801 $strings = quiz_get_grading_options();
802 return $strings[$option];
805 /// Other quiz functions ////////////////////////////////////////////////////
808 * @param object $quiz the quiz.
809 * @param int $cmid the course_module object for this quiz.
810 * @param object $question the question.
811 * @param string $returnurl url to return to after action is done.
812 * @return string html for a number of icons linked to action pages for a
813 * question - preview and edit / view icons depending on user capabilities.
815 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
816 $html = quiz_question_preview_button($quiz, $question) . ' ' .
817 quiz_question_edit_button($cmid, $question, $returnurl);
818 return $html;
822 * @param int $cmid the course_module.id for this quiz.
823 * @param object $question the question.
824 * @param string $returnurl url to return to after action is done.
825 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
826 * @return the HTML for an edit icon, view icon, or nothing for a question
827 * (depending on permissions).
829 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
830 global $CFG, $OUTPUT;
832 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
833 static $stredit = null;
834 static $strview = null;
835 if ($stredit === null) {
836 $stredit = get_string('edit');
837 $strview = get_string('view');
840 // What sort of icon should we show?
841 $action = '';
842 if (!empty($question->id) &&
843 (question_has_capability_on($question, 'edit', $question->category) ||
844 question_has_capability_on($question, 'move', $question->category))) {
845 $action = $stredit;
846 $icon = '/t/edit';
847 } else if (!empty($question->id) &&
848 question_has_capability_on($question, 'view', $question->category)) {
849 $action = $strview;
850 $icon = '/i/info';
853 // Build the icon.
854 if ($action) {
855 if ($returnurl instanceof moodle_url) {
856 $returnurl = str_replace($CFG->wwwroot, '', $returnurl->out(false));
858 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
859 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
860 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
861 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
862 '</a>';
863 } else if ($contentaftericon) {
864 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
865 } else {
866 return '';
871 * @param object $quiz the quiz settings
872 * @param object $question the question
873 * @return moodle_url to preview this question with the options from this quiz.
875 function quiz_question_preview_url($quiz, $question) {
876 // Get the appropriate display options.
877 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
878 mod_quiz_display_options::DURING);
880 $maxmark = null;
881 if (isset($question->maxmark)) {
882 $maxmark = $question->maxmark;
885 // Work out the correcte preview URL.
886 return question_preview_url($question->id, $quiz->preferredbehaviour,
887 $maxmark, $displayoptions);
891 * @param object $quiz the quiz settings
892 * @param object $question the question
893 * @param bool $label if true, show the preview question label after the icon
894 * @return the HTML for a preview question icon.
896 function quiz_question_preview_button($quiz, $question, $label = false) {
897 global $CFG, $OUTPUT;
898 if (!question_has_capability_on($question, 'use', $question->category)) {
899 return '';
902 $url = quiz_question_preview_url($quiz, $question);
904 // Do we want a label?
905 $strpreviewlabel = '';
906 if ($label) {
907 $strpreviewlabel = get_string('preview', 'quiz');
910 // Build the icon.
911 $strpreviewquestion = get_string('previewquestion', 'quiz');
912 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
914 $action = new popup_action('click', $url, 'questionpreview',
915 question_preview_popup_params());
917 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
921 * @param object $attempt the attempt.
922 * @param object $context the quiz context.
923 * @return int whether flags should be shown/editable to the current user for this attempt.
925 function quiz_get_flag_option($attempt, $context) {
926 global $USER;
927 if (!has_capability('moodle/question:flag', $context)) {
928 return question_display_options::HIDDEN;
929 } else if ($attempt->userid == $USER->id) {
930 return question_display_options::EDITABLE;
931 } else {
932 return question_display_options::VISIBLE;
937 * Work out what state this quiz attempt is in.
938 * @param object $quiz the quiz settings
939 * @param object $attempt the quiz_attempt database row.
940 * @return int one of the mod_quiz_display_options::DURING,
941 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
943 function quiz_attempt_state($quiz, $attempt) {
944 if ($attempt->timefinish == 0) {
945 return mod_quiz_display_options::DURING;
946 } else if (time() < $attempt->timefinish + 120) {
947 return mod_quiz_display_options::IMMEDIATELY_AFTER;
948 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
949 return mod_quiz_display_options::LATER_WHILE_OPEN;
950 } else {
951 return mod_quiz_display_options::AFTER_CLOSE;
956 * The the appropraite mod_quiz_display_options object for this attempt at this
957 * quiz right now.
959 * @param object $quiz the quiz instance.
960 * @param object $attempt the attempt in question.
961 * @param $context the quiz context.
963 * @return mod_quiz_display_options
965 function quiz_get_review_options($quiz, $attempt, $context) {
966 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
968 $options->readonly = true;
969 $options->flags = quiz_get_flag_option($attempt, $context);
970 if (!empty($attempt->id)) {
971 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
972 array('attempt' => $attempt->id));
975 // Show a link to the comment box only for closed attempts
976 if (!empty($attempt->id) && $attempt->timefinish && !$attempt->preview &&
977 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
978 $options->manualcomment = question_display_options::VISIBLE;
979 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
980 array('attempt' => $attempt->id));
983 if (!is_null($context) && !$attempt->preview &&
984 has_capability('mod/quiz:viewreports', $context) &&
985 has_capability('moodle/grade:viewhidden', $context)) {
986 // People who can see reports and hidden grades should be shown everything,
987 // except during preview when teachers want to see what students see.
988 $options->attempt = question_display_options::VISIBLE;
989 $options->correctness = question_display_options::VISIBLE;
990 $options->marks = question_display_options::MARK_AND_MAX;
991 $options->feedback = question_display_options::VISIBLE;
992 $options->numpartscorrect = question_display_options::VISIBLE;
993 $options->generalfeedback = question_display_options::VISIBLE;
994 $options->rightanswer = question_display_options::VISIBLE;
995 $options->overallfeedback = question_display_options::VISIBLE;
996 $options->history = question_display_options::VISIBLE;
1000 return $options;
1004 * Combines the review options from a number of different quiz attempts.
1005 * Returns an array of two ojects, so the suggested way of calling this
1006 * funciton is:
1007 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1009 * @param object $quiz the quiz instance.
1010 * @param array $attempts an array of attempt objects.
1011 * @param $context the roles and permissions context,
1012 * normally the context for the quiz module instance.
1014 * @return array of two options objects, one showing which options are true for
1015 * at least one of the attempts, the other showing which options are true
1016 * for all attempts.
1018 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1019 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1020 $someoptions = new stdClass();
1021 $alloptions = new stdClass();
1022 foreach ($fields as $field) {
1023 $someoptions->$field = false;
1024 $alloptions->$field = true;
1026 $someoptions->marks = question_display_options::HIDDEN;
1027 $alloptions->marks = question_display_options::MARK_AND_MAX;
1029 foreach ($attempts as $attempt) {
1030 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1031 quiz_attempt_state($quiz, $attempt));
1032 foreach ($fields as $field) {
1033 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1034 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1036 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1037 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1039 return array($someoptions, $alloptions);
1043 * Clean the question layout from various possible anomalies:
1044 * - Remove consecutive ","'s
1045 * - Remove duplicate question id's
1046 * - Remove extra "," from beginning and end
1047 * - Finally, add a ",0" in the end if there is none
1049 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
1050 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
1051 * @return $string the cleaned-up layout
1053 function quiz_clean_layout($layout, $removeemptypages = false) {
1054 // Remove repeated ','s. This can happen when a restore fails to find the right
1055 // id to relink to.
1056 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1058 // Remove duplicate question ids
1059 $layout = explode(',', $layout);
1060 $cleanerlayout = array();
1061 $seen = array();
1062 foreach ($layout as $item) {
1063 if ($item == 0) {
1064 $cleanerlayout[] = '0';
1065 } else if (!in_array($item, $seen)) {
1066 $cleanerlayout[] = $item;
1067 $seen[] = $item;
1071 if ($removeemptypages) {
1072 // Avoid duplicate page breaks
1073 $layout = $cleanerlayout;
1074 $cleanerlayout = array();
1075 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1076 foreach ($layout as $item) {
1077 if ($stripfollowingbreaks && $item == 0) {
1078 continue;
1080 $cleanerlayout[] = $item;
1081 $stripfollowingbreaks = $item == 0;
1085 // Add a page break at the end if there is none
1086 if (end($cleanerlayout) !== '0') {
1087 $cleanerlayout[] = '0';
1090 return implode(',', $cleanerlayout);
1094 * Get the slot for a question with a particular id.
1095 * @param object $quiz the quiz settings.
1096 * @param int $questionid the of a question in the quiz.
1097 * @return int the corresponding slot. Null if the question is not in the quiz.
1099 function quiz_get_slot_for_question($quiz, $questionid) {
1100 $questionids = quiz_questions_in_quiz($quiz->questions);
1101 foreach (explode(',', $questionids) as $key => $id) {
1102 if ($id == $questionid) {
1103 return $key + 1;
1106 return null;
1109 /// FUNCTIONS FOR SENDING NOTIFICATION MESSAGES ///////////////////////////////
1112 * Sends a confirmation message to the student confirming that the attempt was processed.
1114 * @param object $a lots of useful information that can be used in the message
1115 * subject and body.
1117 * @return int|false as for {@link message_send()}.
1119 function quiz_send_confirmation($recipient, $a) {
1121 // Add information about the recipient to $a
1122 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1123 $a->username = fullname($recipient);
1124 $a->userusername = $recipient->username;
1126 // Prepare message
1127 $eventdata = new stdClass();
1128 $eventdata->component = 'mod_quiz';
1129 $eventdata->name = 'confirmation';
1130 $eventdata->notification = 1;
1132 $eventdata->userfrom = get_admin();
1133 $eventdata->userto = $recipient;
1134 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1135 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1136 $eventdata->fullmessageformat = FORMAT_PLAIN;
1137 $eventdata->fullmessagehtml = '';
1139 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1140 $eventdata->contexturl = $a->quizurl;
1141 $eventdata->contexturlname = $a->quizname;
1143 // ... and send it.
1144 return message_send($eventdata);
1148 * Sends notification messages to the interested parties that assign the role capability
1150 * @param object $recipient user object of the intended recipient
1151 * @param object $a associative array of replaceable fields for the templates
1153 * @return int|false as for {@link message_send()}.
1155 function quiz_send_notification($recipient, $submitter, $a) {
1157 // Recipient info for template
1158 $a->useridnumber = $recipient->idnumber;
1159 $a->username = fullname($recipient);
1160 $a->userusername = $recipient->username;
1162 // Prepare message
1163 $eventdata = new stdClass();
1164 $eventdata->component = 'mod_quiz';
1165 $eventdata->name = 'submission';
1166 $eventdata->notification = 1;
1168 $eventdata->userfrom = $submitter;
1169 $eventdata->userto = $recipient;
1170 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1171 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1172 $eventdata->fullmessageformat = FORMAT_PLAIN;
1173 $eventdata->fullmessagehtml = '';
1175 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1176 $eventdata->contexturl = $a->quizreviewurl;
1177 $eventdata->contexturlname = $a->quizname;
1179 // ... and send it.
1180 return message_send($eventdata);
1184 * Send all the requried messages when a quiz attempt is submitted.
1186 * @param object $course the course
1187 * @param object $quiz the quiz
1188 * @param object $attempt this attempt just finished
1189 * @param object $context the quiz context
1190 * @param object $cm the coursemodule for this quiz
1192 * @return bool true if all necessary messages were sent successfully, else false.
1194 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1195 global $CFG, $DB;
1197 // Do nothing if required objects not present
1198 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1199 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1202 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1204 // Check for confirmation required
1205 $sendconfirm = false;
1206 $notifyexcludeusers = '';
1207 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1208 $notifyexcludeusers = $submitter->id;
1209 $sendconfirm = true;
1212 // check for notifications required
1213 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
1214 'u.lang, u.timezone, u.mailformat, u.maildisplay';
1215 $groups = groups_get_all_groups($course->id, $submitter->id);
1216 if (is_array($groups) && count($groups) > 0) {
1217 $groups = array_keys($groups);
1218 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1219 // If the user is not in a group, and the quiz is set to group mode,
1220 // then set $groups to a non-existant id so that only users with
1221 // 'moodle/site:accessallgroups' get notified.
1222 $groups = -1;
1223 } else {
1224 $groups = '';
1226 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1227 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1229 if (empty($userstonotify) && !$sendconfirm) {
1230 return true; // Nothing to do.
1233 $a = new stdClass();
1234 // Course info
1235 $a->coursename = $course->fullname;
1236 $a->courseshortname = $course->shortname;
1237 // Quiz info
1238 $a->quizname = $quiz->name;
1239 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1240 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1241 format_string($quiz->name) . ' report</a>';
1242 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1243 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1244 format_string($quiz->name) . ' review</a>';
1245 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1246 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1247 // Attempt info
1248 $a->submissiontime = userdate($attempt->timefinish);
1249 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1250 // Student who sat the quiz info
1251 $a->studentidnumber = $submitter->idnumber;
1252 $a->studentname = fullname($submitter);
1253 $a->studentusername = $submitter->username;
1255 $allok = true;
1257 // Send notifications if required
1258 if (!empty($userstonotify)) {
1259 foreach ($userstonotify as $recipient) {
1260 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1264 // Send confirmation if required. We send the student confirmation last, so
1265 // that if message sending is being intermittently buggy, which means we send
1266 // some but not all messages, and then try again later, then teachers may get
1267 // duplicate messages, but the student will always get exactly one.
1268 if ($sendconfirm) {
1269 $allok = $allok && quiz_send_confirmation($submitter, $a);
1272 return $allok;
1276 * Handle the quiz_attempt_submitted event.
1278 * This sends the confirmation and notification messages, if required.
1280 * @param object $event the event object.
1282 function quiz_attempt_submitted_handler($event) {
1283 global $DB;
1285 $course = $DB->get_record('course', array('id' => $event->courseid));
1286 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1287 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1288 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1290 if (!($course && $quiz && $cm && $attempt)) {
1291 // Something has been deleted since the event was raised. Therefore, the
1292 // event is no longer relevant.
1293 return true;
1296 return quiz_send_notification_messages($course, $quiz, $attempt,
1297 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
1300 function quiz_get_js_module() {
1301 global $PAGE;
1303 return array(
1304 'name' => 'mod_quiz',
1305 'fullpath' => '/mod/quiz/module.js',
1306 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1307 'core_question_engine'),
1308 'strings' => array(
1309 array('cancel', 'moodle'),
1310 array('flagged', 'question'),
1311 array('functiondisabledbysecuremode', 'quiz'),
1312 array('startattempt', 'quiz'),
1313 array('timesup', 'quiz'),
1320 * An extension of question_display_options that includes the extra options used
1321 * by the quiz.
1323 * @copyright 2010 The Open University
1324 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1326 class mod_quiz_display_options extends question_display_options {
1327 /**#@+
1328 * @var integer bits used to indicate various times in relation to a
1329 * quiz attempt.
1331 const DURING = 0x10000;
1332 const IMMEDIATELY_AFTER = 0x01000;
1333 const LATER_WHILE_OPEN = 0x00100;
1334 const AFTER_CLOSE = 0x00010;
1335 /**#@-*/
1338 * @var boolean if this is false, then the student is not allowed to review
1339 * anything about the attempt.
1341 public $attempt = true;
1344 * @var boolean if this is false, then the student is not allowed to review
1345 * anything about the attempt.
1347 public $overallfeedback = self::VISIBLE;
1350 * Set up the various options from the quiz settings, and a time constant.
1351 * @param object $quiz the quiz settings.
1352 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1353 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1354 * @return mod_quiz_display_options set up appropriately.
1356 public static function make_from_quiz($quiz, $when) {
1357 $options = new self();
1359 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1360 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
1361 $options->marks = self::extract($quiz->reviewmarks, $when,
1362 self::MARK_AND_MAX, self::MAX_ONLY);
1363 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1364 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1365 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1366 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1368 $options->numpartscorrect = $options->feedback;
1370 if ($quiz->questiondecimalpoints != -1) {
1371 $options->markdp = $quiz->questiondecimalpoints;
1372 } else {
1373 $options->markdp = $quiz->decimalpoints;
1376 return $options;
1379 protected static function extract($bitmask, $bit,
1380 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
1381 if ($bitmask & $bit) {
1382 return $whenset;
1383 } else {
1384 return $whennotset;
1391 * A {@link qubaid_condition} for finding all the question usages belonging to
1392 * a particular quiz.
1394 * @copyright 2010 The Open University
1395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1397 class qubaids_for_quiz extends qubaid_join {
1398 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1399 $where = 'quiza.quiz = :quizaquiz';
1400 if (!$includepreviews) {
1401 $where .= ' AND preview = 0';
1403 if ($onlyfinished) {
1404 $where .= ' AND timefinish <> 0';
1407 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where,
1408 array('quizaquiz' => $quizid));