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 ($attemptnumber == 1 || !$quiz->attemptonlast) {
82 // We are not building on last attempt so create a new attempt.
83 $attempt = new stdClass();
84 $attempt->quiz = $quiz->id;
85 $attempt->userid = $USER->id;
86 $attempt->preview = 0;
87 $attempt->layout = quiz_clean_layout($quiz->questions, true);
88 if ($quiz->shufflequestions) {
89 $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
92 // Build on last attempt.
93 if (empty($lastattempt)) {
94 print_error('cannotfindprevattempt', 'quiz');
96 $attempt = $lastattempt;
99 $attempt->attempt = $attemptnumber;
100 $attempt->timestart = $timenow;
101 $attempt->timefinish = 0;
102 $attempt->timemodified = $timenow;
104 // If this is a preview, mark it as such.
106 $attempt->preview = 1;
113 * Returns an unfinished attempt (if there is one) for the given
114 * user on the given quiz. This function does not return preview attempts.
116 * @param int $quizid the id of the quiz.
117 * @param int $userid the id of the user.
119 * @return mixed the unfinished attempt if there is one, false if not.
121 function quiz_get_user_attempt_unfinished($quizid, $userid) {
122 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
124 return array_shift($attempts);
131 * Delete a quiz attempt.
132 * @param mixed $attempt an integer attempt id or an attempt object
133 * (row of the quiz_attempts table).
134 * @param object $quiz the quiz object.
136 function quiz_delete_attempt($attempt, $quiz) {
138 if (is_numeric($attempt)) {
139 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
144 if ($attempt->quiz != $quiz->id) {
145 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
146 "but was passed quiz $quiz->id.");
150 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
151 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
153 // Search quiz_attempts for other instances by this user.
154 // If none, then delete record for this quiz, this user from quiz_grades
155 // else recalculate best grade
156 $userid = $attempt->userid;
157 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
158 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
160 quiz_save_best_grade($quiz, $userid);
163 quiz_update_grades($quiz, $userid);
167 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
169 * @param object $quiz the quiz object.
170 * @param int $userid (optional) if given, only delete the previews belonging to this user.
172 function quiz_delete_previews($quiz, $userid = null) {
174 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
175 if (!empty($userid)) {
176 $conditions['userid'] = $userid;
178 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
179 foreach ($previewattempts as $attempt) {
180 quiz_delete_attempt($attempt, $quiz);
185 * @param int $quizid The quiz id.
186 * @return bool whether this quiz has any (non-preview) attempts.
188 function quiz_has_attempts($quizid) {
190 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
193 /// Functions to do with quiz layout and pages ////////////////////////////////
196 * Returns a comma separated list of question ids for the quiz
198 * @param string $layout The string representing the quiz layout. Each page is
199 * represented as a comma separated list of question ids and 0 indicating
200 * page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
202 * @return string comma separated list of question ids, without page breaks.
204 function quiz_questions_in_quiz($layout) {
205 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
206 if ($questions === '0') {
214 * Returns the number of pages in a quiz layout
216 * @param string $layout The string representing the quiz layout. Always ends in ,0
217 * @return int The number of pages in the quiz.
219 function quiz_number_of_pages($layout) {
220 return substr_count(',' . $layout, ',0');
224 * Returns the number of questions in the quiz layout
226 * @param string $layout the string representing the quiz layout.
227 * @return int The number of questions in the quiz.
229 function quiz_number_of_questions_in_quiz($layout) {
230 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
231 $count = substr_count($layout, ',');
232 if ($layout !== '') {
239 * Re-paginates the quiz layout
241 * @param string $layout The string representing the quiz layout. If there is
242 * if there is any doubt about the quality of the input data, call
243 * quiz_clean_layout before you call this function.
244 * @param int $perpage The number of questions per page
245 * @param bool $shuffle Should the questions be reordered randomly?
246 * @return string the new layout string
248 function quiz_repaginate($layout, $perpage, $shuffle = false) {
249 $layout = str_replace(',0', '', $layout); // remove existing page breaks
250 $questions = explode(',', $layout);
256 foreach ($questions as $question) {
257 if ($perpage and $i > $perpage) {
261 $layout .= $question.',';
267 /// Functions to do with quiz grades //////////////////////////////////////////
270 * Creates an array of maximum grades for a quiz
272 * The grades are extracted from the quiz_question_instances table.
273 * @param object $quiz The quiz settings.
274 * @return array of grades indexed by question id. These are the maximum
275 * possible grades that students can achieve for each of the questions.
277 function quiz_get_all_question_grades($quiz) {
280 $questionlist = quiz_questions_in_quiz($quiz->questions);
281 if (empty($questionlist)) {
285 $params = array($quiz->id);
287 if (!is_null($questionlist)) {
288 list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
289 $wheresql = " AND question $usql ";
290 $params = array_merge($params, $question_params);
293 $instances = $DB->get_records_sql("SELECT question, grade, id
294 FROM {quiz_question_instances}
295 WHERE quiz = ? $wheresql", $params);
297 $list = explode(",", $questionlist);
300 foreach ($list as $qid) {
301 if (isset($instances[$qid])) {
302 $grades[$qid] = $instances[$qid]->grade;
311 * Convert the raw grade stored in $attempt into a grade out of the maximum
312 * grade for this quiz.
314 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
315 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
316 * @param bool|string $format whether to format the results for display
317 * or 'question' to format a question grade (different number of decimal places.
318 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
319 * if the $grade is null.
321 function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
322 if (is_null($rawgrade)) {
324 } else if ($quiz->sumgrades >= 0.000005) {
325 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
329 if ($format === 'question') {
330 $grade = quiz_format_question_grade($quiz, $grade);
331 } else if ($format) {
332 $grade = quiz_format_grade($quiz, $grade);
338 * Get the feedback text that should be show to a student who
339 * got this grade on this quiz. The feedback is processed ready for diplay.
341 * @param float $grade a grade on this quiz.
342 * @param object $quiz the quiz settings.
343 * @param object $context the quiz context.
344 * @return string the comment that corresponds to this grade (empty string if there is not one.
346 function quiz_feedback_for_grade($grade, $quiz, $context) {
349 if (is_null($grade)) {
353 $feedback = $DB->get_record_select('quiz_feedback',
354 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
356 if (empty($feedback->feedbacktext)) {
360 // Clean the text, ready for display.
361 $formatoptions = new stdClass();
362 $formatoptions->noclean = true;
363 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
364 $context->id, 'mod_quiz', 'feedback', $feedback->id);
365 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
367 return $feedbacktext;
371 * @param object $quiz the quiz database row.
372 * @return bool Whether this quiz has any non-blank feedback text.
374 function quiz_has_feedback($quiz) {
376 static $cache = array();
377 if (!array_key_exists($quiz->id, $cache)) {
378 $cache[$quiz->id] = quiz_has_grades($quiz) &&
379 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
380 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
383 return $cache[$quiz->id];
386 function quiz_no_questions_message($quiz, $cm, $context) {
390 $output .= $OUTPUT->notification(get_string('noquestions', 'quiz'));
391 if (has_capability('mod/quiz:manage', $context)) {
392 $output .= $OUTPUT->single_button(new moodle_url('/mod/quiz/edit.php',
393 array('cmid' => $cm->id)), get_string('editquiz', 'quiz'), 'get');
400 * Update the sumgrades field of the quiz. This needs to be called whenever
401 * the grading structure of the quiz is changed. For example if a question is
402 * added or removed, or a question weight is changed.
404 * @param object $quiz a quiz.
406 function quiz_update_sumgrades($quiz) {
408 $sql = 'UPDATE {quiz}
409 SET sumgrades = COALESCE((
411 FROM {quiz_question_instances}
412 WHERE quiz = {quiz}.id
415 $DB->execute($sql, array($quiz->id));
416 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
417 if ($quiz->sumgrades < 0.000005) {
418 quiz_set_grade(0, $quiz);
422 function quiz_update_all_attempt_sumgrades($quiz) {
424 $dm = new question_engine_data_mapper();
427 $sql = "UPDATE {quiz_attempts}
429 timemodified = :timenow,
431 {$dm->sum_usage_marks_subquery('uniqueid')}
433 WHERE quiz = :quizid AND timefinish <> 0";
434 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id));
438 * The quiz grade is the maximum that student's results are marked out of. When it
439 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
440 * rescaled. After calling this function, you probably need to call
441 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
442 * quiz_update_grades.
444 * @param float $newgrade the new maximum grade for the quiz.
445 * @param object $quiz the quiz we are updating. Passed by reference so its
446 * grade field can be updated too.
447 * @return bool indicating success or failure.
449 function quiz_set_grade($newgrade, $quiz) {
451 // This is potentially expensive, so only do it if necessary.
452 if (abs($quiz->grade - $newgrade) < 1e-7) {
457 // Use a transaction, so that on those databases that support it, this is safer.
458 $transaction = $DB->start_delegated_transaction();
460 // Update the quiz table.
461 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
463 // Rescaling the other data is only possible if the old grade was non-zero.
464 if ($quiz->grade > 1e-7) {
467 $factor = $newgrade/$quiz->grade;
468 $quiz->grade = $newgrade;
470 // Update the quiz_grades table.
471 $timemodified = time();
474 SET grade = ? * grade, timemodified = ?
476 ", array($factor, $timemodified, $quiz->id));
478 // Update the quiz_feedback table.
480 UPDATE {quiz_feedback}
481 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
483 ", array($factor, $factor, $quiz->id));
486 // update grade item and send all grades to gradebook
487 quiz_grade_item_update($quiz);
488 quiz_update_grades($quiz);
490 $transaction->allow_commit();
495 * Save the overall grade for a user at a quiz in the quiz_grades table
497 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
498 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
499 * @param array $attempts The attempts of this user. Useful if you are
500 * looping through many users. Attempts can be fetched in one master query to
501 * avoid repeated querying.
502 * @return bool Indicates success or failure.
504 function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
506 global $USER, $OUTPUT;
508 if (empty($userid)) {
513 // Get all the attempts made by the user
514 $attempts = quiz_get_user_attempts($quiz->id, $userid);
517 // Calculate the best grade
518 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
519 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
521 // Save the best grade in the database
522 if (is_null($bestgrade)) {
523 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
525 } else if ($grade = $DB->get_record('quiz_grades',
526 array('quiz' => $quiz->id, 'userid' => $userid))) {
527 $grade->grade = $bestgrade;
528 $grade->timemodified = time();
529 $DB->update_record('quiz_grades', $grade);
532 $grade->quiz = $quiz->id;
533 $grade->userid = $userid;
534 $grade->grade = $bestgrade;
535 $grade->timemodified = time();
536 $DB->insert_record('quiz_grades', $grade);
539 quiz_update_grades($quiz, $userid);
543 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
545 * @return float The overall grade
546 * @param object $quiz The quiz for which the best grade is to be calculated
547 * @param array $attempts An array of all the attempts of the user at the quiz
549 function quiz_calculate_best_grade($quiz, $attempts) {
551 switch ($quiz->grademethod) {
553 case QUIZ_ATTEMPTFIRST:
554 foreach ($attempts as $attempt) {
555 return $attempt->sumgrades;
559 case QUIZ_ATTEMPTLAST:
560 foreach ($attempts as $attempt) {
561 $final = $attempt->sumgrades;
565 case QUIZ_GRADEAVERAGE:
568 foreach ($attempts as $attempt) {
569 if (!is_null($attempt->sumgrades)) {
570 $sum += $attempt->sumgrades;
577 return $sum / $count;
580 case QUIZ_GRADEHIGHEST:
582 foreach ($attempts as $attempt) {
583 if ($attempt->sumgrades > $max) {
584 $max = $attempt->sumgrades;
592 * Update the final grade at this quiz for all students.
594 * This function is equivalent to calling quiz_save_best_grade for all
595 * users, but much more efficient.
597 * @param object $quiz the quiz settings.
599 function quiz_update_all_final_grades($quiz) {
602 if (!$quiz->sumgrades) {
606 $param = array('iquizid' => $quiz->id);
607 $firstlastattemptjoin = "JOIN (
610 MIN(attempt) AS firstattempt,
611 MAX(attempt) AS lastattempt
613 FROM {quiz_attempts} iquiza
616 iquiza.timefinish <> 0 AND
617 iquiza.preview = 0 AND
618 iquiza.quiz = :iquizid
620 GROUP BY iquiza.userid
621 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
623 switch ($quiz->grademethod) {
624 case QUIZ_ATTEMPTFIRST:
625 // Because of the where clause, there will only be one row, but we
626 // must still use an aggregate function.
627 $select = 'MAX(quiza.sumgrades)';
628 $join = $firstlastattemptjoin;
629 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
632 case QUIZ_ATTEMPTLAST:
633 // Because of the where clause, there will only be one row, but we
634 // must still use an aggregate function.
635 $select = 'MAX(quiza.sumgrades)';
636 $join = $firstlastattemptjoin;
637 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
640 case QUIZ_GRADEAVERAGE:
641 $select = 'AVG(quiza.sumgrades)';
647 case QUIZ_GRADEHIGHEST:
648 $select = 'MAX(quiza.sumgrades)';
654 if ($quiz->sumgrades >= 0.000005) {
655 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
659 $param['quizid'] = $quiz->id;
660 $param['quizid2'] = $quiz->id;
661 $param['quizid3'] = $quiz->id;
662 $param['quizid4'] = $quiz->id;
663 $finalgradesubquery = "
664 SELECT quiza.userid, $finalgrade AS newgrade
665 FROM {quiz_attempts} quiza
669 quiza.timefinish <> 0 AND
670 quiza.preview = 0 AND
671 quiza.quiz = :quizid3
672 GROUP BY quiza.userid";
674 $changedgrades = $DB->get_records_sql("
675 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
679 FROM {quiz_grades} qg
682 SELECT DISTINCT userid
683 FROM {quiz_attempts} quiza2
685 quiza2.timefinish <> 0 AND
686 quiza2.preview = 0 AND
687 quiza2.quiz = :quizid2
690 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
694 ) newgrades ON newgrades.userid = users.userid
697 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
698 (newgrades.newgrade IS NULL) <> (qg.grade IS NULL)",
703 foreach ($changedgrades as $changedgrade) {
705 if (is_null($changedgrade->newgrade)) {
706 $todelete[] = $changedgrade->userid;
708 } else if (is_null($changedgrade->grade)) {
709 $toinsert = new stdClass();
710 $toinsert->quiz = $quiz->id;
711 $toinsert->userid = $changedgrade->userid;
712 $toinsert->timemodified = $timenow;
713 $toinsert->grade = $changedgrade->newgrade;
714 $DB->insert_record('quiz_grades', $toinsert);
717 $toupdate = new stdClass();
718 $toupdate->id = $changedgrade->id;
719 $toupdate->grade = $changedgrade->newgrade;
720 $toupdate->timemodified = $timenow;
721 $DB->update_record('quiz_grades', $toupdate);
725 if (!empty($todelete)) {
726 list($test, $params) = $DB->get_in_or_equal($todelete);
727 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
728 array_merge(array($quiz->id), $params));
733 * Return the attempt with the best grade for a quiz
735 * Which attempt is the best depends on $quiz->grademethod. If the grade
736 * method is GRADEAVERAGE then this function simply returns the last attempt.
737 * @return object The attempt with the best grade
738 * @param object $quiz The quiz for which the best grade is to be calculated
739 * @param array $attempts An array of all the attempts of the user at the quiz
741 function quiz_calculate_best_attempt($quiz, $attempts) {
743 switch ($quiz->grademethod) {
745 case QUIZ_ATTEMPTFIRST:
746 foreach ($attempts as $attempt) {
751 case QUIZ_GRADEAVERAGE: // need to do something with it :-)
752 case QUIZ_ATTEMPTLAST:
753 foreach ($attempts as $attempt) {
759 case QUIZ_GRADEHIGHEST:
761 foreach ($attempts as $attempt) {
762 if ($attempt->sumgrades > $max) {
763 $max = $attempt->sumgrades;
764 $maxattempt = $attempt;
772 * @return the options for calculating the quiz grade from the individual attempt grades.
774 function quiz_get_grading_options() {
776 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
777 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
778 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
779 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
784 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
785 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
786 * @return the lang string for that option.
788 function quiz_get_grading_option_name($option) {
789 $strings = quiz_get_grading_options();
790 return $strings[$option];
793 /// Other quiz functions ////////////////////////////////////////////////////
796 * @param object $quiz the quiz.
797 * @param int $cmid the course_module object for this quiz.
798 * @param object $question the question.
799 * @param string $returnurl url to return to after action is done.
800 * @return string html for a number of icons linked to action pages for a
801 * question - preview and edit / view icons depending on user capabilities.
803 function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
804 $html = quiz_question_preview_button($quiz, $question) . ' ' .
805 quiz_question_edit_button($cmid, $question, $returnurl);
810 * @param int $cmid the course_module.id for this quiz.
811 * @param object $question the question.
812 * @param string $returnurl url to return to after action is done.
813 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
814 * @return the HTML for an edit icon, view icon, or nothing for a question
815 * (depending on permissions).
817 function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
818 global $CFG, $OUTPUT;
820 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
821 static $stredit = null;
822 static $strview = null;
823 if ($stredit === null) {
824 $stredit = get_string('edit');
825 $strview = get_string('view');
828 // What sort of icon should we show?
830 if (!empty($question->id) &&
831 (question_has_capability_on($question, 'edit', $question->category) ||
832 question_has_capability_on($question, 'move', $question->category))) {
835 } else if (!empty($question->id) &&
836 question_has_capability_on($question, 'view', $question->category)) {
843 if ($returnurl instanceof moodle_url) {
844 $returnurl = str_replace($CFG->wwwroot, '', $returnurl->out(false));
846 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
847 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
848 return '<a title="' . $action . '" href="' . $questionurl->out() . '"><img src="' .
849 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
852 return $contentaftericon;
857 * @param object $quiz the quiz settings
858 * @param object $question the question
859 * @return moodle_url to preview this question with the options from this quiz.
861 function quiz_question_preview_url($quiz, $question) {
862 // Get the appropriate display options.
863 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
864 mod_quiz_display_options::DURING);
867 if (isset($question->maxmark)) {
868 $maxmark = $question->maxmark;
871 // Work out the correcte preview URL.
872 return question_preview_url($question->id, $quiz->preferredbehaviour,
873 $maxmark, $displayoptions);
877 * @param object $quiz the quiz settings
878 * @param object $question the question
879 * @param bool $label if true, show the preview question label after the icon
880 * @return the HTML for a preview question icon.
882 function quiz_question_preview_button($quiz, $question, $label = false) {
883 global $CFG, $OUTPUT;
884 if (!question_has_capability_on($question, 'use', $question->category)) {
888 $url = quiz_question_preview_url($quiz, $question);
890 // Do we want a label?
891 $strpreviewlabel = '';
893 $strpreviewlabel = get_string('preview', 'quiz');
897 $strpreviewquestion = get_string('previewquestion', 'quiz');
898 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
900 $action = new popup_action('click', $url, 'questionpreview',
901 question_preview_popup_params());
903 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
907 * @param object $attempt the attempt.
908 * @param object $context the quiz context.
909 * @return int whether flags should be shown/editable to the current user for this attempt.
911 function quiz_get_flag_option($attempt, $context) {
913 if (!has_capability('moodle/question:flag', $context)) {
914 return question_display_options::HIDDEN;
915 } else if ($attempt->userid == $USER->id) {
916 return question_display_options::EDITABLE;
918 return question_display_options::VISIBLE;
923 * Work out what state this quiz attempt is in.
924 * @param object $quiz the quiz settings
925 * @param object $attempt the quiz_attempt database row.
926 * @return int one of the mod_quiz_display_options::DURING,
927 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
929 function quiz_attempt_state($quiz, $attempt) {
930 if ($attempt->timefinish == 0) {
931 return mod_quiz_display_options::DURING;
932 } else if (time() < $attempt->timefinish + 120) {
933 return mod_quiz_display_options::IMMEDIATELY_AFTER;
934 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
935 return mod_quiz_display_options::LATER_WHILE_OPEN;
937 return mod_quiz_display_options::AFTER_CLOSE;
942 * The the appropraite mod_quiz_display_options object for this attempt at this
945 * @param object $quiz the quiz instance.
946 * @param object $attempt the attempt in question.
947 * @param $context the quiz context.
949 * @return mod_quiz_display_options
951 function quiz_get_review_options($quiz, $attempt, $context) {
952 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
954 $options->readonly = true;
955 $options->flags = quiz_get_flag_option($attempt, $context);
956 if (!empty($attempt->id)) {
957 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
958 array('attempt' => $attempt->id));
961 // Show a link to the comment box only for closed attempts
962 if (!empty($attempt->id) && $attempt->timefinish && !$attempt->preview &&
963 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
964 $options->manualcomment = question_display_options::VISIBLE;
965 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
966 array('attempt' => $attempt->id));
969 if (!is_null($context) && !$attempt->preview &&
970 has_capability('mod/quiz:viewreports', $context) &&
971 has_capability('moodle/grade:viewhidden', $context)) {
972 // People who can see reports and hidden grades should be shown everything,
973 // except during preview when teachers want to see what students see.
974 $options->attempt = question_display_options::VISIBLE;
975 $options->correctness = question_display_options::VISIBLE;
976 $options->marks = question_display_options::MARK_AND_MAX;
977 $options->feedback = question_display_options::VISIBLE;
978 $options->numpartscorrect = question_display_options::VISIBLE;
979 $options->generalfeedback = question_display_options::VISIBLE;
980 $options->rightanswer = question_display_options::VISIBLE;
981 $options->overallfeedback = question_display_options::VISIBLE;
982 $options->history = question_display_options::VISIBLE;
990 * Combines the review options from a number of different quiz attempts.
991 * Returns an array of two ojects, so the suggested way of calling this
993 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
995 * @param object $quiz the quiz instance.
996 * @param array $attempts an array of attempt objects.
997 * @param $context the roles and permissions context,
998 * normally the context for the quiz module instance.
1000 * @return array of two options objects, one showing which options are true for
1001 * at least one of the attempts, the other showing which options are true
1004 function quiz_get_combined_reviewoptions($quiz, $attempts) {
1005 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1006 $someoptions = new stdClass();
1007 $alloptions = new stdClass();
1008 foreach ($fields as $field) {
1009 $someoptions->$field = false;
1010 $alloptions->$field = true;
1012 $someoptions->marks = question_display_options::HIDDEN;
1013 $alloptions->marks = question_display_options::MARK_AND_MAX;
1015 foreach ($attempts as $attempt) {
1016 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1017 quiz_attempt_state($quiz, $attempt));
1018 foreach ($fields as $field) {
1019 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1020 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1022 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1023 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1025 return array($someoptions, $alloptions);
1029 * Clean the question layout from various possible anomalies:
1030 * - Remove consecutive ","'s
1031 * - Remove duplicate question id's
1032 * - Remove extra "," from beginning and end
1033 * - Finally, add a ",0" in the end if there is none
1035 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
1036 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
1037 * @return $string the cleaned-up layout
1039 function quiz_clean_layout($layout, $removeemptypages = false) {
1040 // Remove repeated ','s. This can happen when a restore fails to find the right
1042 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1044 // Remove duplicate question ids
1045 $layout = explode(',', $layout);
1046 $cleanerlayout = array();
1048 foreach ($layout as $item) {
1050 $cleanerlayout[] = '0';
1051 } else if (!in_array($item, $seen)) {
1052 $cleanerlayout[] = $item;
1057 if ($removeemptypages) {
1058 // Avoid duplicate page breaks
1059 $layout = $cleanerlayout;
1060 $cleanerlayout = array();
1061 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1062 foreach ($layout as $item) {
1063 if ($stripfollowingbreaks && $item == 0) {
1066 $cleanerlayout[] = $item;
1067 $stripfollowingbreaks = $item == 0;
1071 // Add a page break at the end if there is none
1072 if (end($cleanerlayout) !== '0') {
1073 $cleanerlayout[] = '0';
1076 return implode(',', $cleanerlayout);
1080 * Get the slot for a question with a particular id.
1081 * @param object $quiz the quiz settings.
1082 * @param int $questionid the of a question in the quiz.
1083 * @return int the corresponding slot. Null if the question is not in the quiz.
1085 function quiz_get_slot_for_question($quiz, $questionid) {
1086 $questionids = quiz_questions_in_quiz($quiz->questions);
1087 foreach (explode(',', $questionids) as $key => $id) {
1088 if ($id == $questionid) {
1095 /// FUNCTIONS FOR SENDING NOTIFICATION MESSAGES ///////////////////////////////
1098 * Sends a confirmation message to the student confirming that the attempt was processed.
1100 * @param object $a lots of useful information that can be used in the message
1103 * @return int|false as for {@link message_send()}.
1105 function quiz_send_confirmation($recipient, $a) {
1107 // Add information about the recipient to $a
1108 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1109 $a->username = fullname($recipient);
1110 $a->userusername = $recipient->username;
1113 $eventdata = new stdClass();
1114 $eventdata->component = 'mod_quiz';
1115 $eventdata->name = 'confirmation';
1116 $eventdata->notification = 1;
1118 $eventdata->userfrom = get_admin();
1119 $eventdata->userto = $recipient;
1120 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1121 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
1122 $eventdata->fullmessageformat = FORMAT_PLAIN;
1123 $eventdata->fullmessagehtml = '';
1125 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1126 $eventdata->contexturl = $a->quizurl;
1127 $eventdata->contexturlname = $a->quizname;
1130 return message_send($eventdata);
1134 * Sends notification messages to the interested parties that assign the role capability
1136 * @param object $recipient user object of the intended recipient
1137 * @param object $a associative array of replaceable fields for the templates
1139 * @return int|false as for {@link message_send()}.
1141 function quiz_send_notification($recipient, $submitter, $a) {
1145 // Recipient info for template
1146 $a->useridnumber = $recipient->idnumber;
1147 $a->username = fullname($recipient);
1148 $a->userusername = $recipient->username;
1151 $eventdata = new stdClass();
1152 $eventdata->component = 'mod_quiz';
1153 $eventdata->name = 'submission';
1154 $eventdata->notification = 1;
1156 $eventdata->userfrom = $submitter;
1157 $eventdata->userto = $recipient;
1158 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1159 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
1160 $eventdata->fullmessageformat = FORMAT_PLAIN;
1161 $eventdata->fullmessagehtml = '';
1163 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1164 $eventdata->contexturl = $a->quizreviewurl;
1165 $eventdata->contexturlname = $a->quizname;
1168 return message_send($eventdata);
1172 * Send all the requried messages when a quiz attempt is submitted.
1174 * @param object $course the course
1175 * @param object $quiz the quiz
1176 * @param object $attempt this attempt just finished
1177 * @param object $context the quiz context
1178 * @param object $cm the coursemodule for this quiz
1180 * @return bool true if all necessary messages were sent successfully, else false.
1182 function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1185 // Do nothing if required objects not present
1186 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1187 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1190 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1192 // Check for confirmation required
1193 $sendconfirm = false;
1194 $notifyexcludeusers = '';
1195 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1196 $notifyexcludeusers = $submitter->id;
1197 $sendconfirm = true;
1200 // check for notifications required
1201 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, ' .
1202 'u.lang, u.timezone, u.mailformat, u.maildisplay';
1203 $groups = groups_get_all_groups($course->id, $submitter->id);
1204 if (is_array($groups) && count($groups) > 0) {
1205 $groups = array_keys($groups);
1206 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1207 // If the user is not in a group, and the quiz is set to group mode,
1208 // then set $groups to a non-existant id so that only users with
1209 // 'moodle/site:accessallgroups' get notified.
1214 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1215 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1217 if (empty($userstonotify) && !$sendconfirm) {
1218 return true; // Nothing to do.
1221 $a = new stdClass();
1223 $a->coursename = $course->fullname;
1224 $a->courseshortname = $course->shortname;
1226 $a->quizname = $quiz->name;
1227 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1228 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1229 format_string($quiz->name) . ' report</a>';
1230 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1231 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1232 format_string($quiz->name) . ' review</a>';
1233 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1234 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1236 $a->submissiontime = userdate($attempt->timefinish);
1237 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
1238 // Student who sat the quiz info
1239 $a->studentidnumber = $submitter->idnumber;
1240 $a->studentname = fullname($submitter);
1241 $a->studentusername = $submitter->username;
1245 // Send notifications if required
1246 if (!empty($userstonotify)) {
1247 foreach ($userstonotify as $recipient) {
1248 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1252 // Send confirmation if required. We send the student confirmation last, so
1253 // that if message sending is being intermittently buggy, which means we send
1254 // some but not all messages, and then try again later, then teachers may get
1255 // duplicate messages, but the student will always get exactly one.
1257 $allok = $allok && quiz_send_confirmation($submitter, $a);
1264 * Handle the quiz_attempt_submitted event.
1266 * This sends the confirmation and notification messages, if required.
1268 * @param object $event the event object.
1270 function quiz_attempt_submitted_handler($event) {
1273 $course = $DB->get_record('course', array('id' => $event->courseid));
1274 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1275 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1276 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1278 if (!($course && $quiz && $cm && $attempt)) {
1279 // Something has been deleted since the event was raised. Therefore, the
1280 // event is no longer relevant.
1284 return quiz_send_notification_messages($course, $quiz, $attempt,
1285 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
1289 * Checks if browser is safe browser
1291 * @return true, if browser is safe browser else false
1293 function quiz_check_safe_browser() {
1294 return strpos($_SERVER['HTTP_USER_AGENT'], "SEB") !== false;
1297 function quiz_get_js_module() {
1300 'name' => 'mod_quiz',
1301 'fullpath' => '/mod/quiz/module.js',
1302 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1303 'core_question_engine'),
1305 array('timesup', 'quiz'),
1306 array('functiondisabledbysecuremode', 'quiz'),
1307 array('flagged', 'question'),
1314 * An extension of question_display_options that includes the extra options used
1317 * @copyright 2010 The Open University
1318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1320 class mod_quiz_display_options extends question_display_options {
1322 * @var integer bits used to indicate various times in relation to a
1325 const DURING = 0x10000;
1326 const IMMEDIATELY_AFTER = 0x01000;
1327 const LATER_WHILE_OPEN = 0x00100;
1328 const AFTER_CLOSE = 0x00010;
1332 * @var boolean if this is false, then the student is not allowed to review
1333 * anything about the attempt.
1335 public $attempt = true;
1338 * @var boolean if this is false, then the student is not allowed to review
1339 * anything about the attempt.
1341 public $overallfeedback = self::VISIBLE;
1344 * Set up the various options from the quiz settings, and a time constant.
1345 * @param object $quiz the quiz settings.
1346 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
1347 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1348 * @return mod_quiz_display_options set up appropriately.
1350 public static function make_from_quiz($quiz, $when) {
1351 $options = new self();
1353 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1354 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
1355 $options->marks = self::extract($quiz->reviewmarks, $when,
1356 self::MARK_AND_MAX, self::MAX_ONLY);
1357 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1358 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1359 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1360 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1362 $options->numpartscorrect = $options->feedback;
1364 if ($quiz->questiondecimalpoints != -1) {
1365 $options->markdp = $quiz->questiondecimalpoints;
1367 $options->markdp = $quiz->decimalpoints;
1373 protected static function extract($bitmask, $bit,
1374 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
1375 if ($bitmask & $bit) {
1385 * A {@link qubaid_condition} for finding all the question usages belonging to
1386 * a particular quiz.
1388 * @copyright 2010 The Open University
1389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1391 class qubaids_for_quiz extends qubaid_join {
1392 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
1393 $where = 'quiza.quiz = :quizaquiz';
1394 if (!$includepreviews) {
1395 $where .= ' AND preview = 0';
1397 if ($onlyfinished) {
1398 $where .= ' AND timefinish <> 0';
1401 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where,
1402 array('quizaquiz' => $quizid));