2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions used by the quiz module.
20 * This contains functions that are called from within the quiz module only
21 * Functions that are also called by core Moodle are in {@link lib.php}
22 * This script also loads the code in {@link questionlib.php} which holds
23 * the module-indpendent code for handling questions and which in turn
24 * initialises all the questiontype classes.
28 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 defined('MOODLE_INTERNAL') ||
die();
35 require_once($CFG->dirroot
. '/mod/quiz/lib.php');
36 require_once($CFG->dirroot
. '/mod/quiz/accessrules.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');
45 * Options determining how the grades from individual attempts are combined to give
46 * the overall grade for a user
48 define('QUIZ_GRADEHIGHEST', '1');
49 define('QUIZ_GRADEAVERAGE', '2');
50 define('QUIZ_ATTEMPTFIRST', '3');
51 define('QUIZ_ATTEMPTLAST', '4');
55 * We show the countdown timer if there is less than this amount of time left before the
56 * the quiz close date. (1 hour)
58 define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
60 /// Functions related to attempts /////////////////////////////////////////
63 * Creates an object to represent a new attempt at a quiz
65 * Creates an attempt object to represent an attempt at the quiz by the current
66 * user starting at the current time. The ->id field is not set. The object is
67 * NOT written to the database.
69 * @param object $quiz the quiz to create an attempt for.
70 * @param int $attemptnumber the sequence number for the attempt.
71 * @param object $lastattempt the previous attempt by this user, if any. Only needed
72 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
73 * @param int $timenow the time the attempt was started at.
74 * @param bool $ispreview whether this new attempt is a preview.
76 * @return object the newly created attempt object.
78 function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
81 if ($quiz->sumgrades
< 0.000005 && $quiz->grade
> 0.000005) {
82 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
83 new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id
)),
84 array('grade' => quiz_format_grade($quiz, $quiz->grade
)));
87 if ($attemptnumber == 1 ||
!$quiz->attemptonlast
) {
88 // We are not building on last attempt so create a new attempt.
89 $attempt = new stdClass();
90 $attempt->quiz
= $quiz->id
;
91 $attempt->userid
= $USER->id
;
92 $attempt->preview
= 0;
93 $attempt->layout
= quiz_clean_layout($quiz->questions
, true);
94 if ($quiz->shufflequestions
) {
95 $attempt->layout
= quiz_repaginate($attempt->layout
, $quiz->questionsperpage
, true);
98 // Build on last attempt.
99 if (empty($lastattempt)) {
100 print_error('cannotfindprevattempt', 'quiz');
102 $attempt = $lastattempt;
105 $attempt->attempt
= $attemptnumber;
106 $attempt->timestart
= $timenow;
107 $attempt->timefinish
= 0;
108 $attempt->timemodified
= $timenow;
110 // If this is a preview, mark it as such.
112 $attempt->preview
= 1;
119 * Returns an unfinished attempt (if there is one) for the given
120 * user on the given quiz. This function does not return preview attempts.
122 * @param int $quizid the id of the quiz.
123 * @param int $userid the id of the user.
125 * @return mixed the unfinished attempt if there is one, false if not.
127 function quiz_get_user_attempt_unfinished($quizid, $userid) {
128 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
130 return array_shift($attempts);
137 * Delete a quiz attempt.
138 * @param mixed $attempt an integer attempt id or an attempt object
139 * (row of the quiz_attempts table).
140 * @param object $quiz the quiz object.
142 function quiz_delete_attempt($attempt, $quiz) {
144 if (is_numeric($attempt)) {
145 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
150 if ($attempt->quiz
!= $quiz->id
) {
151 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
152 "but was passed quiz $quiz->id.");
156 question_engine
::delete_questions_usage_by_activity($attempt->uniqueid
);
157 $DB->delete_records('quiz_attempts', array('id' => $attempt->id
));
159 // Search quiz_attempts for other instances by this user.
160 // If none, then delete record for this quiz, this user from quiz_grades
161 // else recalculate best grade
162 $userid = $attempt->userid
;
163 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id
))) {
164 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id
));
166 quiz_save_best_grade($quiz, $userid);
169 quiz_update_grades($quiz, $userid);
173 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
175 * @param object $quiz the quiz object.
176 * @param int $userid (optional) if given, only delete the previews belonging to this user.
178 function quiz_delete_previews($quiz, $userid = null) {
180 $conditions = array('quiz' => $quiz->id
, 'preview' => 1);
181 if (!empty($userid)) {
182 $conditions['userid'] = $userid;
184 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
185 foreach ($previewattempts as $attempt) {
186 quiz_delete_attempt($attempt, $quiz);
191 * @param int $quizid The quiz id.
192 * @return bool whether this quiz has any (non-preview) attempts.
194 function quiz_has_attempts($quizid) {
196 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
199 /// Functions to do with quiz layout and pages ////////////////////////////////
202 * Returns a comma separated list of question ids for the quiz
204 * @param string $layout The string representing the quiz layout. Each page is
205 * represented as a comma separated list of question ids and 0 indicating
206 * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
208 * @return string comma separated list of question ids, without page breaks.
210 function quiz_questions_in_quiz($layout) {
211 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
212 if ($questions === '0') {
220 * Returns the number of pages in a quiz layout
222 * @param string $layout The string representing the quiz layout. Always ends in ,0
223 * @return int The number of pages in the quiz.
225 function quiz_number_of_pages($layout) {
226 return substr_count(',' . $layout, ',0');
230 * Returns the number of questions in the quiz layout
232 * @param string $layout the string representing the quiz layout.
233 * @return int The number of questions in the quiz.
235 function quiz_number_of_questions_in_quiz($layout) {
236 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
237 $count = substr_count($layout, ',');
238 if ($layout !== '') {
245 * Re-paginates the quiz layout
247 * @param string $layout The string representing the quiz layout. If there is
248 * if there is any doubt about the quality of the input data, call
249 * quiz_clean_layout before you call this function.
250 * @param int $perpage The number of questions per page
251 * @param bool $shuffle Should the questions be reordered randomly?
252 * @return string the new layout string
254 function quiz_repaginate($layout, $perpage, $shuffle = false) {
255 $questions = quiz_questions_in_quiz($layout);
260 $questions = explode(',', quiz_questions_in_quiz($layout));
267 foreach ($questions as $question) {
268 if ($perpage and $onthispage >= $perpage) {
272 $layout[] = $question;
277 return implode(',', $layout);
280 /// Functions to do with quiz grades //////////////////////////////////////////
283 * Creates an array of maximum grades for a quiz
285 * The grades are extracted from the quiz_question_instances table.
286 * @param object $quiz The quiz settings.
287 * @return array of grades indexed by question id. These are the maximum
288 * possible grades that students can achieve for each of the questions.
290 function quiz_get_all_question_grades($quiz) {
293 $questionlist = quiz_questions_in_quiz($quiz->questions
);
294 if (empty($questionlist)) {
298 $params = array($quiz->id
);
300 if (!is_null($questionlist)) {
301 list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
302 $wheresql = " AND question $usql ";
303 $params = array_merge($params, $question_params);
306 $instances = $DB->get_records_sql("SELECT question, grade, id
307 FROM {quiz_question_instances}
308 WHERE quiz = ? $wheresql", $params);
310 $list = explode(",", $questionlist);
313 foreach ($list as $qid) {
314 if (isset($instances[$qid])) {
315 $grades[$qid] = $instances[$qid]->grade
;
324 * Convert the raw grade stored in $attempt into a grade out of the maximum
325 * grade for this quiz.
327 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
328 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
329 * @param bool|string $format whether to format the results for display
330 * or 'question' to format a question grade (different number of decimal places.
331 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
332 * if the $grade is null.
334 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
335 if (is_null($rawgrade)) {
337 } else if ($quiz->sumgrades
>= 0.000005) {
338 $grade = $rawgrade * $quiz->grade
/ $quiz->sumgrades
;
342 if ($format === 'question') {
343 $grade = quiz_format_question_grade($quiz, $grade);
344 } else if ($format) {
345 $grade = quiz_format_grade($quiz, $grade);
351 * Get the feedback text that should be show to a student who
352 * got this grade on this quiz. The feedback is processed ready for diplay.
354 * @param float $grade a grade on this quiz.
355 * @param object $quiz the quiz settings.
356 * @param object $context the quiz context.
357 * @return string the comment that corresponds to this grade (empty string if there is not one.
359 function quiz_feedback_for_grade($grade, $quiz, $context) {
362 if (is_null($grade)) {
366 // With CBM etc, it is possible to get -ve grades, which would then not match
367 // any feedback. Therefore, we replace -ve grades with 0.
368 $grade = max($grade, 0);
370 $feedback = $DB->get_record_select('quiz_feedback',
371 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id
, $grade, $grade));
373 if (empty($feedback->feedbacktext
)) {
377 // Clean the text, ready for display.
378 $formatoptions = new stdClass();
379 $formatoptions->noclean
= true;
380 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext
, 'pluginfile.php',
381 $context->id
, 'mod_quiz', 'feedback', $feedback->id
);
382 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat
, $formatoptions);
384 return $feedbacktext;
388 * @param object $quiz the quiz database row.
389 * @return bool Whether this quiz has any non-blank feedback text.
391 function quiz_has_feedback($quiz) {
393 static $cache = array();
394 if (!array_key_exists($quiz->id
, $cache)) {
395 $cache[$quiz->id
] = quiz_has_grades($quiz) &&
396 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
397 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
400 return $cache[$quiz->id
];
403 function quiz_no_questions_message($quiz, $cm, $context) {
407 $output .= $OUTPUT->notification(get_string('noquestions', 'quiz'));
408 if (has_capability('mod/quiz:manage', $context)) {
409 $output .= $OUTPUT->single_button(new moodle_url('/mod/quiz/edit.php',
410 array('cmid' => $cm->id
)), get_string('editquiz', 'quiz'), 'get');
417 * Update the sumgrades field of the quiz. This needs to be called whenever
418 * the grading structure of the quiz is changed. For example if a question is
419 * added or removed, or a question weight is changed.
421 * You should call {@link quiz_delete_previews()} before you call this function.
423 * @param object $quiz a quiz.
425 function quiz_update_sumgrades($quiz) {
428 $sql = 'UPDATE {quiz}
429 SET sumgrades = COALESCE((
431 FROM {quiz_question_instances}
432 WHERE quiz = {quiz}.id
435 $DB->execute($sql, array($quiz->id
));
436 $quiz->sumgrades
= $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id
));
438 if ($quiz->sumgrades
< 0.000005 && quiz_has_attempts($quiz->id
)) {
439 // If the quiz has been attempted, and the sumgrades has been
440 // set to 0, then we must also set the maximum possible grade to 0, or
441 // we will get a divide by zero error.
442 quiz_set_grade(0, $quiz);
447 * Update the sumgrades field of the attempts at a quiz.
449 * @param object $quiz a quiz.
451 function quiz_update_all_attempt_sumgrades($quiz) {
453 $dm = new question_engine_data_mapper();
456 $sql = "UPDATE {quiz_attempts}
458 timemodified = :timenow,
460 {$dm->sum_usage_marks_subquery('uniqueid')}
462 WHERE quiz = :quizid AND timefinish <> 0";
463 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id
));
467 * The quiz grade is the maximum that student's results are marked out of. When it
468 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
469 * rescaled. After calling this function, you probably need to call
470 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
471 * quiz_update_grades.
473 * @param float $newgrade the new maximum grade for the quiz.
474 * @param object $quiz the quiz we are updating. Passed by reference so its
475 * grade field can be updated too.
476 * @return bool indicating success or failure.
478 function quiz_set_grade($newgrade, $quiz) {
480 // This is potentially expensive, so only do it if necessary.
481 if (abs($quiz->grade
- $newgrade) < 1e-7) {
486 // Use a transaction, so that on those databases that support it, this is safer.
487 $transaction = $DB->start_delegated_transaction();
489 // Update the quiz table.
490 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance
));
492 // Rescaling the other data is only possible if the old grade was non-zero.
493 if ($quiz->grade
> 1e-7) {
496 $factor = $newgrade/$quiz->grade
;
497 $quiz->grade
= $newgrade;
499 // Update the quiz_grades table.
500 $timemodified = time();
503 SET grade = ? * grade, timemodified = ?
505 ", array($factor, $timemodified, $quiz->id
));
507 // Update the quiz_feedback table.
509 UPDATE {quiz_feedback}
510 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
512 ", array($factor, $factor, $quiz->id
));
515 // update grade item and send all grades to gradebook
516 quiz_grade_item_update($quiz);
517 quiz_update_grades($quiz);
519 $transaction->allow_commit();
524 * Save the overall grade for a user at a quiz in the quiz_grades table
526 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
527 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
528 * @param array $attempts The attempts of this user. Useful if you are
529 * looping through many users. Attempts can be fetched in one master query to
530 * avoid repeated querying.
531 * @return bool Indicates success or failure.
533 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
534 global $DB, $OUTPUT, $USER;
536 if (empty($userid)) {
541 // Get all the attempts made by the user
542 $attempts = quiz_get_user_attempts($quiz->id
, $userid);
545 // Calculate the best grade
546 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
547 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
549 // Save the best grade in the database
550 if (is_null($bestgrade)) {
551 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id
, 'userid' => $userid));
553 } else if ($grade = $DB->get_record('quiz_grades',
554 array('quiz' => $quiz->id
, 'userid' => $userid))) {
555 $grade->grade
= $bestgrade;
556 $grade->timemodified
= time();
557 $DB->update_record('quiz_grades', $grade);
560 $grade->quiz
= $quiz->id
;
561 $grade->userid
= $userid;
562 $grade->grade
= $bestgrade;
563 $grade->timemodified
= time();
564 $DB->insert_record('quiz_grades', $grade);
567 quiz_update_grades($quiz, $userid);
571 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
573 * @param object $quiz the quiz settings object.
574 * @param array $attempts an array of all the user's attempts at this quiz in order.
575 * @return float the overall grade
577 function quiz_calculate_best_grade($quiz, $attempts) {
579 switch ($quiz->grademethod
) {
581 case QUIZ_ATTEMPTFIRST
:
582 $firstattempt = reset($attempts);
583 return $firstattempt->sumgrades
;
585 case QUIZ_ATTEMPTLAST
:
586 $lastattempt = end($attempts);
587 return $lastattempt->sumgrades
;
589 case QUIZ_GRADEAVERAGE
:
592 foreach ($attempts as $attempt) {
593 if (!is_null($attempt->sumgrades
)) {
594 $sum +
= $attempt->sumgrades
;
601 return $sum / $count;
603 case QUIZ_GRADEHIGHEST
:
606 foreach ($attempts as $attempt) {
607 if ($attempt->sumgrades
> $max) {
608 $max = $attempt->sumgrades
;
616 * Update the final grade at this quiz for all students.
618 * This function is equivalent to calling quiz_save_best_grade for all
619 * users, but much more efficient.
621 * @param object $quiz the quiz settings.
623 function quiz_update_all_final_grades($quiz) {
626 if (!$quiz->sumgrades
) {
630 $param = array('iquizid' => $quiz->id
);
631 $firstlastattemptjoin = "JOIN (
634 MIN(attempt) AS firstattempt,
635 MAX(attempt) AS lastattempt
637 FROM {quiz_attempts} iquiza
640 iquiza.timefinish <> 0 AND
641 iquiza.preview = 0 AND
642 iquiza.quiz = :iquizid
644 GROUP BY iquiza.userid
645 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
647 switch ($quiz->grademethod
) {
648 case QUIZ_ATTEMPTFIRST
:
649 // Because of the where clause, there will only be one row, but we
650 // must still use an aggregate function.
651 $select = 'MAX(quiza.sumgrades)';
652 $join = $firstlastattemptjoin;
653 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
656 case QUIZ_ATTEMPTLAST
:
657 // Because of the where clause, there will only be one row, but we
658 // must still use an aggregate function.
659 $select = 'MAX(quiza.sumgrades)';
660 $join = $firstlastattemptjoin;
661 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
664 case QUIZ_GRADEAVERAGE
:
665 $select = 'AVG(quiza.sumgrades)';
671 case QUIZ_GRADEHIGHEST
:
672 $select = 'MAX(quiza.sumgrades)';
678 if ($quiz->sumgrades
>= 0.000005) {
679 $finalgrade = $select . ' * ' . ($quiz->grade
/ $quiz->sumgrades
);
683 $param['quizid'] = $quiz->id
;
684 $param['quizid2'] = $quiz->id
;
685 $param['quizid3'] = $quiz->id
;
686 $param['quizid4'] = $quiz->id
;
687 $finalgradesubquery = "
688 SELECT quiza.userid, $finalgrade AS newgrade
689 FROM {quiz_attempts} quiza
693 quiza.timefinish <> 0 AND
694 quiza.preview = 0 AND
695 quiza.quiz = :quizid3
696 GROUP BY quiza.userid";
698 $changedgrades = $DB->get_records_sql("
699 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
703 FROM {quiz_grades} qg
706 SELECT DISTINCT userid
707 FROM {quiz_attempts} quiza2
709 quiza2.timefinish <> 0 AND
710 quiza2.preview = 0 AND
711 quiza2.quiz = :quizid2
714 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
718 ) newgrades ON newgrades.userid = users.userid
721 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
722 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
723 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
724 // The mess on the previous line is detecting where the value is
725 // NULL in one column, and NOT NULL in the other, but SQL does
726 // not have an XOR operator, and MS SQL server can't cope with
727 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
732 foreach ($changedgrades as $changedgrade) {
734 if (is_null($changedgrade->newgrade
)) {
735 $todelete[] = $changedgrade->userid
;
737 } else if (is_null($changedgrade->grade
)) {
738 $toinsert = new stdClass();
739 $toinsert->quiz
= $quiz->id
;
740 $toinsert->userid
= $changedgrade->userid
;
741 $toinsert->timemodified
= $timenow;
742 $toinsert->grade
= $changedgrade->newgrade
;
743 $DB->insert_record('quiz_grades', $toinsert);
746 $toupdate = new stdClass();
747 $toupdate->id
= $changedgrade->id
;
748 $toupdate->grade
= $changedgrade->newgrade
;
749 $toupdate->timemodified
= $timenow;
750 $DB->update_record('quiz_grades', $toupdate);
754 if (!empty($todelete)) {
755 list($test, $params) = $DB->get_in_or_equal($todelete);
756 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
757 array_merge(array($quiz->id
), $params));
762 * Return the attempt with the best grade for a quiz
764 * Which attempt is the best depends on $quiz->grademethod. If the grade
765 * method is GRADEAVERAGE then this function simply returns the last attempt.
766 * @return object The attempt with the best grade
767 * @param object $quiz The quiz for which the best grade is to be calculated
768 * @param array $attempts An array of all the attempts of the user at the quiz
770 function quiz_calculate_best_attempt($quiz, $attempts) {
772 switch ($quiz->grademethod
) {
774 case QUIZ_ATTEMPTFIRST
:
775 foreach ($attempts as $attempt) {
780 case QUIZ_GRADEAVERAGE
: // need to do something with it :-)
781 case QUIZ_ATTEMPTLAST
:
782 foreach ($attempts as $attempt) {
788 case QUIZ_GRADEHIGHEST
:
790 foreach ($attempts as $attempt) {
791 if ($attempt->sumgrades
> $max) {
792 $max = $attempt->sumgrades
;
793 $maxattempt = $attempt;
801 * @return the options for calculating the quiz grade from the individual attempt grades.
803 function quiz_get_grading_options() {
805 QUIZ_GRADEHIGHEST
=> get_string('gradehighest', 'quiz'),
806 QUIZ_GRADEAVERAGE
=> get_string('gradeaverage', 'quiz'),
807 QUIZ_ATTEMPTFIRST
=> get_string('attemptfirst', 'quiz'),
808 QUIZ_ATTEMPTLAST
=> get_string('attemptlast', 'quiz')
813 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
814 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
815 * @return the lang string for that option.
817 function quiz_get_grading_option_name($option) {
818 $strings = quiz_get_grading_options();
819 return $strings[$option];
822 /// Other quiz functions ////////////////////////////////////////////////////
825 * @param object $quiz the quiz.
826 * @param int $cmid the course_module object for this quiz.
827 * @param object $question the question.
828 * @param string $returnurl url to return to after action is done.
829 * @return string html for a number of icons linked to action pages for a
830 * question - preview and edit / view icons depending on user capabilities.
832 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
833 $html = quiz_question_preview_button($quiz, $question) . ' ' .
834 quiz_question_edit_button($cmid, $question, $returnurl);
839 * @param int $cmid the course_module.id for this quiz.
840 * @param object $question the question.
841 * @param string $returnurl url to return to after action is done.
842 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
843 * @return the HTML for an edit icon, view icon, or nothing for a question
844 * (depending on permissions).
846 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
847 global $CFG, $OUTPUT;
849 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
850 static $stredit = null;
851 static $strview = null;
852 if ($stredit === null) {
853 $stredit = get_string('edit');
854 $strview = get_string('view');
857 // What sort of icon should we show?
859 if (!empty($question->id
) &&
860 (question_has_capability_on($question, 'edit', $question->category
) ||
861 question_has_capability_on($question, 'move', $question->category
))) {
864 } else if (!empty($question->id
) &&
865 question_has_capability_on($question, 'view', $question->category
)) {
872 if ($returnurl instanceof moodle_url
) {
873 $returnurl = str_replace($CFG->wwwroot
, '', $returnurl->out(false));
875 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id
);
876 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
877 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
878 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
880 } else if ($contentaftericon) {
881 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
888 * @param object $quiz the quiz settings
889 * @param object $question the question
890 * @return moodle_url to preview this question with the options from this quiz.
892 function quiz_question_preview_url($quiz, $question) {
893 // Get the appropriate display options.
894 $displayoptions = mod_quiz_display_options
::make_from_quiz($quiz,
895 mod_quiz_display_options
::DURING
);
898 if (isset($question->maxmark
)) {
899 $maxmark = $question->maxmark
;
902 // Work out the correcte preview URL.
903 return question_preview_url($question->id
, $quiz->preferredbehaviour
,
904 $maxmark, $displayoptions);
908 * @param object $quiz the quiz settings
909 * @param object $question the question
910 * @param bool $label if true, show the preview question label after the icon
911 * @return the HTML for a preview question icon.
913 function quiz_question_preview_button($quiz, $question, $label = false) {
914 global $CFG, $OUTPUT;
915 if (!question_has_capability_on($question, 'use', $question->category
)) {
919 $url = quiz_question_preview_url($quiz, $question);
921 // Do we want a label?
922 $strpreviewlabel = '';
924 $strpreviewlabel = get_string('preview', 'quiz');
928 $strpreviewquestion = get_string('previewquestion', 'quiz');
929 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
931 $action = new popup_action('click', $url, 'questionpreview',
932 question_preview_popup_params());
934 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
938 * @param object $attempt the attempt.
939 * @param object $context the quiz context.
940 * @return int whether flags should be shown/editable to the current user for this attempt.
942 function quiz_get_flag_option($attempt, $context) {
944 if (!has_capability('moodle/question:flag', $context)) {
945 return question_display_options
::HIDDEN
;
946 } else if ($attempt->userid
== $USER->id
) {
947 return question_display_options
::EDITABLE
;
949 return question_display_options
::VISIBLE
;
954 * Work out what state this quiz attempt is in.
955 * @param object $quiz the quiz settings
956 * @param object $attempt the quiz_attempt database row.
957 * @return int one of the mod_quiz_display_options::DURING,
958 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
960 function quiz_attempt_state($quiz, $attempt) {
961 if ($attempt->timefinish
== 0) {
962 return mod_quiz_display_options
::DURING
;
963 } else if (time() < $attempt->timefinish +
120) {
964 return mod_quiz_display_options
::IMMEDIATELY_AFTER
;
965 } else if (!$quiz->timeclose ||
time() < $quiz->timeclose
) {
966 return mod_quiz_display_options
::LATER_WHILE_OPEN
;
968 return mod_quiz_display_options
::AFTER_CLOSE
;
973 * The the appropraite mod_quiz_display_options object for this attempt at this
976 * @param object $quiz the quiz instance.
977 * @param object $attempt the attempt in question.
978 * @param $context the quiz context.
980 * @return mod_quiz_display_options
982 function quiz_get_review_options($quiz, $attempt, $context) {
983 $options = mod_quiz_display_options
::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
985 $options->readonly
= true;
986 $options->flags
= quiz_get_flag_option($attempt, $context);
987 if (!empty($attempt->id
)) {
988 $options->questionreviewlink
= new moodle_url('/mod/quiz/reviewquestion.php',
989 array('attempt' => $attempt->id
));
992 // Show a link to the comment box only for closed attempts
993 if (!empty($attempt->id
) && $attempt->timefinish
&& !$attempt->preview
&&
994 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
995 $options->manualcomment
= question_display_options
::VISIBLE
;
996 $options->manualcommentlink
= new moodle_url('/mod/quiz/comment.php',
997 array('attempt' => $attempt->id
));
1000 if (!is_null($context) && !$attempt->preview
&&
1001 has_capability('mod/quiz:viewreports', $context) &&
1002 has_capability('moodle/grade:viewhidden', $context)) {
1003 // People who can see reports and hidden grades should be shown everything,
1004 // except during preview when teachers want to see what students see.
1005 $options->attempt
= question_display_options
::VISIBLE
;
1006 $options->correctness
= question_display_options
::VISIBLE
;
1007 $options->marks
= question_display_options
::MARK_AND_MAX
;
1008 $options->feedback
= question_display_options
::VISIBLE
;
1009 $options->numpartscorrect
= question_display_options
::VISIBLE
;
1010 $options->generalfeedback
= question_display_options
::VISIBLE
;
1011 $options->rightanswer
= question_display_options
::VISIBLE
;
1012 $options->overallfeedback
= question_display_options
::VISIBLE
;
1013 $options->history
= question_display_options
::VISIBLE
;
1021 * Combines the review options from a number of different quiz attempts.
1022 * Returns an array of two ojects, so the suggested way of calling this
1024 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1026 * @param object $quiz the quiz instance.
1027 * @param array $attempts an array of attempt objects.
1028 * @param $context the roles and permissions context,
1029 * normally the context for the quiz module instance.
1031 * @return array of two options objects, one showing which options are true for
1032 * at least one of the attempts, the other showing which options are true
1035 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1036 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1037 $someoptions = new stdClass();
1038 $alloptions = new stdClass();
1039 foreach ($fields as $field) {
1040 $someoptions->$field = false;
1041 $alloptions->$field = true;
1043 $someoptions->marks
= question_display_options
::HIDDEN
;
1044 $alloptions->marks
= question_display_options
::MARK_AND_MAX
;
1046 foreach ($attempts as $attempt) {
1047 $attemptoptions = mod_quiz_display_options
::make_from_quiz($quiz,
1048 quiz_attempt_state($quiz, $attempt));
1049 foreach ($fields as $field) {
1050 $someoptions->$field = $someoptions->$field ||
$attemptoptions->$field;
1051 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1053 $someoptions->marks
= max($someoptions->marks
, $attemptoptions->marks
);
1054 $alloptions->marks
= min($alloptions->marks
, $attemptoptions->marks
);
1056 return array($someoptions, $alloptions);
1060 * Clean the question layout from various possible anomalies:
1061 * - Remove consecutive ","'s
1062 * - Remove duplicate question id's
1063 * - Remove extra "," from beginning and end
1064 * - Finally, add a ",0" in the end if there is none
1066 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
1067 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
1068 * @return $string the cleaned-up layout
1070 function quiz_clean_layout($layout, $removeemptypages = false) {
1071 // Remove repeated ','s. This can happen when a restore fails to find the right
1073 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1075 // Remove duplicate question ids
1076 $layout = explode(',', $layout);
1077 $cleanerlayout = array();
1079 foreach ($layout as $item) {
1081 $cleanerlayout[] = '0';
1082 } else if (!in_array($item, $seen)) {
1083 $cleanerlayout[] = $item;
1088 if ($removeemptypages) {
1089 // Avoid duplicate page breaks
1090 $layout = $cleanerlayout;
1091 $cleanerlayout = array();
1092 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1093 foreach ($layout as $item) {
1094 if ($stripfollowingbreaks && $item == 0) {
1097 $cleanerlayout[] = $item;
1098 $stripfollowingbreaks = $item == 0;
1102 // Add a page break at the end if there is none
1103 if (end($cleanerlayout) !== '0') {
1104 $cleanerlayout[] = '0';
1107 return implode(',', $cleanerlayout);
1111 * Get the slot for a question with a particular id.
1112 * @param object $quiz the quiz settings.
1113 * @param int $questionid the of a question in the quiz.
1114 * @return int the corresponding slot. Null if the question is not in the quiz.
1116 function quiz_get_slot_for_question($quiz, $questionid) {
1117 $questionids = quiz_questions_in_quiz($quiz->questions
);
1118 foreach (explode(',', $questionids) as $key => $id) {
1119 if ($id == $questionid) {
1126 /// FUNCTIONS FOR SENDING NOTIFICATION MESSAGES ///////////////////////////////
1129 * Sends a confirmation message to the student confirming that the attempt was processed.
1131 * @param object $a lots of useful information that can be used in the message
1134 * @return int|false as for {@link message_send()}.
1136 function quiz_send_confirmation($recipient, $a) {
1138 // Add information about the recipient to $a
1139 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1140 $a->username
= fullname($recipient);
1141 $a->userusername
= $recipient->username
;
1144 $eventdata = new stdClass();
1145 $eventdata->component
= 'mod_quiz';
1146 $eventdata->name
= 'confirmation';
1147 $eventdata->notification
= 1;
1149 $eventdata->userfrom
= get_admin();
1150 $eventdata->userto
= $recipient;
1151 $eventdata->subject
= get_string('emailconfirmsubject', 'quiz', $a);
1152 $eventdata->fullmessage
= get_string('emailconfirmbody', 'quiz', $a);
1153 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1154 $eventdata->fullmessagehtml
= '';
1156 $eventdata->smallmessage
= get_string('emailconfirmsmall', 'quiz', $a);
1157 $eventdata->contexturl
= $a->quizurl
;
1158 $eventdata->contexturlname
= $a->quizname
;
1161 return message_send($eventdata);
1165 * Sends notification messages to the interested parties that assign the role capability
1167 * @param object $recipient user object of the intended recipient
1168 * @param object $a associative array of replaceable fields for the templates
1170 * @return int|false as for {@link message_send()}.
1172 function quiz_send_notification($recipient, $submitter, $a) {
1174 // Recipient info for template
1175 $a->useridnumber
= $recipient->idnumber
;
1176 $a->username
= fullname($recipient);
1177 $a->userusername
= $recipient->username
;
1180 $eventdata = new stdClass();
1181 $eventdata->component
= 'mod_quiz';
1182 $eventdata->name
= 'submission';
1183 $eventdata->notification
= 1;
1185 $eventdata->userfrom
= $submitter;
1186 $eventdata->userto
= $recipient;
1187 $eventdata->subject
= get_string('emailnotifysubject', 'quiz', $a);
1188 $eventdata->fullmessage
= get_string('emailnotifybody', 'quiz', $a);
1189 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1190 $eventdata->fullmessagehtml
= '';
1192 $eventdata->smallmessage
= get_string('emailnotifysmall', 'quiz', $a);
1193 $eventdata->contexturl
= $a->quizreviewurl
;
1194 $eventdata->contexturlname
= $a->quizname
;
1197 return message_send($eventdata);
1201 * Send all the requried messages when a quiz attempt is submitted.
1203 * @param object $course the course
1204 * @param object $quiz the quiz
1205 * @param object $attempt this attempt just finished
1206 * @param object $context the quiz context
1207 * @param object $cm the coursemodule for this quiz
1209 * @return bool true if all necessary messages were sent successfully, else false.
1211 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1214 // Do nothing if required objects not present
1215 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1216 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1219 $submitter = $DB->get_record('user', array('id' => $attempt->userid
), '*', MUST_EXIST
);
1221 // Check for confirmation required
1222 $sendconfirm = false;
1223 $notifyexcludeusers = '';
1224 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1225 $notifyexcludeusers = $submitter->id
;
1226 $sendconfirm = true;
1229 // check for notifications required
1230 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
1231 'u.lang, u.timezone, u.mailformat, u.maildisplay';
1232 $groups = groups_get_all_groups($course->id
, $submitter->id
);
1233 if (is_array($groups) && count($groups) > 0) {
1234 $groups = array_keys($groups);
1235 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS
) {
1236 // If the user is not in a group, and the quiz is set to group mode,
1237 // then set $groups to a non-existant id so that only users with
1238 // 'moodle/site:accessallgroups' get notified.
1243 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1244 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1246 if (empty($userstonotify) && !$sendconfirm) {
1247 return true; // Nothing to do.
1250 $a = new stdClass();
1252 $a->coursename
= $course->fullname
;
1253 $a->courseshortname
= $course->shortname
;
1255 $a->quizname
= $quiz->name
;
1256 $a->quizreporturl
= $CFG->wwwroot
. '/mod/quiz/report.php?id=' . $cm->id
;
1257 $a->quizreportlink
= '<a href="' . $a->quizreporturl
. '">' .
1258 format_string($quiz->name
) . ' report</a>';
1259 $a->quizreviewurl
= $CFG->wwwroot
. '/mod/quiz/review.php?attempt=' . $attempt->id
;
1260 $a->quizreviewlink
= '<a href="' . $a->quizreviewurl
. '">' .
1261 format_string($quiz->name
) . ' review</a>';
1262 $a->quizurl
= $CFG->wwwroot
. '/mod/quiz/view.php?id=' . $cm->id
;
1263 $a->quizlink
= '<a href="' . $a->quizurl
. '">' . format_string($quiz->name
) . '</a>';
1265 $a->submissiontime
= userdate($attempt->timefinish
);
1266 $a->timetaken
= format_time($attempt->timefinish
- $attempt->timestart
);
1267 // Student who sat the quiz info
1268 $a->studentidnumber
= $submitter->idnumber
;
1269 $a->studentname
= fullname($submitter);
1270 $a->studentusername
= $submitter->username
;
1274 // Send notifications if required
1275 if (!empty($userstonotify)) {
1276 foreach ($userstonotify as $recipient) {
1277 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1281 // Send confirmation if required. We send the student confirmation last, so
1282 // that if message sending is being intermittently buggy, which means we send
1283 // some but not all messages, and then try again later, then teachers may get
1284 // duplicate messages, but the student will always get exactly one.
1286 $allok = $allok && quiz_send_confirmation($submitter, $a);
1293 * Handle the quiz_attempt_submitted event.
1295 * This sends the confirmation and notification messages, if required.
1297 * @param object $event the event object.
1299 function quiz_attempt_submitted_handler($event) {
1302 $course = $DB->get_record('course', array('id' => $event->courseid
));
1303 $quiz = $DB->get_record('quiz', array('id' => $event->quizid
));
1304 $cm = get_coursemodule_from_id('quiz', $event->cmid
, $event->courseid
);
1305 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid
));
1307 if (!($course && $quiz && $cm && $attempt)) {
1308 // Something has been deleted since the event was raised. Therefore, the
1309 // event is no longer relevant.
1313 return quiz_send_notification_messages($course, $quiz, $attempt,
1314 get_context_instance(CONTEXT_MODULE
, $cm->id
), $cm);
1318 * Checks if browser is safe browser
1320 * @return true, if browser is safe browser else false
1322 function quiz_check_safe_browser() {
1323 return strpos($_SERVER['HTTP_USER_AGENT'], "SEB") !== false;
1326 function quiz_get_js_module() {
1330 'name' => 'mod_quiz',
1331 'fullpath' => '/mod/quiz/module.js',
1332 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1333 'core_question_engine'),
1335 array('cancel', 'moodle'),
1336 array('timesup', 'quiz'),
1337 array('functiondisabledbysecuremode', 'quiz'),
1338 array('flagged', 'question'),
1345 * An extension of question_display_options that includes the extra options used
1348 * @copyright 2010 The Open University
1349 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1351 class mod_quiz_display_options
extends question_display_options
{
1353 * @var integer bits used to indicate various times in relation to a
1356 const DURING
= 0x10000;
1357 const IMMEDIATELY_AFTER
= 0x01000;
1358 const LATER_WHILE_OPEN
= 0x00100;
1359 const AFTER_CLOSE
= 0x00010;
1363 * @var boolean if this is false, then the student is not allowed to review
1364 * anything about the attempt.
1366 public $attempt = true;
1369 * @var boolean if this is false, then the student is not allowed to review
1370 * anything about the attempt.
1372 public $overallfeedback = self
::VISIBLE
;
1375 * Set up the various options from the quiz settings, and a time constant.
1376 * @param object $quiz the quiz settings.
1377 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1378 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1379 * @return mod_quiz_display_options set up appropriately.
1381 public static function make_from_quiz($quiz, $when) {
1382 $options = new self();
1384 $options->attempt
= self
::extract($quiz->reviewattempt
, $when, true, false);
1385 $options->correctness
= self
::extract($quiz->reviewcorrectness
, $when);
1386 $options->marks
= self
::extract($quiz->reviewmarks
, $when,
1387 self
::MARK_AND_MAX
, self
::MAX_ONLY
);
1388 $options->feedback
= self
::extract($quiz->reviewspecificfeedback
, $when);
1389 $options->generalfeedback
= self
::extract($quiz->reviewgeneralfeedback
, $when);
1390 $options->rightanswer
= self
::extract($quiz->reviewrightanswer
, $when);
1391 $options->overallfeedback
= self
::extract($quiz->reviewoverallfeedback
, $when);
1393 $options->numpartscorrect
= $options->feedback
;
1395 if ($quiz->questiondecimalpoints
!= -1) {
1396 $options->markdp
= $quiz->questiondecimalpoints
;
1398 $options->markdp
= $quiz->decimalpoints
;
1404 protected static function extract($bitmask, $bit,
1405 $whenset = self
::VISIBLE
, $whennotset = self
::HIDDEN
) {
1406 if ($bitmask & $bit) {
1416 * A {@link qubaid_condition} for finding all the question usages belonging to
1417 * a particular quiz.
1419 * @copyright 2010 The Open University
1420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1422 class qubaids_for_quiz
extends qubaid_join
{
1423 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1424 $where = 'quiza.quiz = :quizaquiz';
1425 if (!$includepreviews) {
1426 $where .= ' AND preview = 0';
1428 if ($onlyfinished) {
1429 $where .= ' AND timefinish <> 0';
1432 parent
::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where,
1433 array('quizaquiz' => $quizid));