Improve the wording of overdue messages. Thanks Phil.
[moodle.git] / mod / quiz / locallib.php
CommitLineData
83192608 1<?php
25302dee
TH
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.
13//
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/>.
84e628a0 16
ee1fb969 17/**
26d12a0c 18 * Library of functions used by the quiz module.
19 *
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.
f63a4ff2 25 *
ba643847 26 * @package mod
25302dee 27 * @subpackage quiz
ba643847
TH
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
26d12a0c 30 */
76cacec8 31
66d07f81 32
a17b297d
TH
33defined('MOODLE_INTERNAL') || die();
34
26d12a0c 35require_once($CFG->dirroot . '/mod/quiz/lib.php');
ea38245c 36require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
987c2d49 37require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
39759ac4 38require_once($CFG->dirroot . '/mod/quiz/renderer.php');
78e7a3dd 39require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
84e628a0 40require_once($CFG->dirroot . '/question/editlib.php');
3b120e46 41require_once($CFG->libdir . '/eventslib.php');
99d19c13 42require_once($CFG->libdir . '/filelib.php');
76cacec8 43
76cacec8 44
c52c62d1 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)
48 */
49define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
50
34b7d838
TH
51/**
52 * @var int If there are fewer than this many seconds left when the student submits
53 * a page of the quiz, then do not take them to the next page of the quiz. Instead
54 * close the quiz immediately.
55 */
56define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
57
58
26d12a0c 59/// Functions related to attempts /////////////////////////////////////////
ee1fb969 60
61/**
26d12a0c 62 * Creates an object to represent a new attempt at a quiz
63 *
64 * Creates an attempt object to represent an attempt at the quiz by the current
65 * user starting at the current time. The ->id field is not set. The object is
66 * NOT written to the database.
c52c62d1 67 *
68 * @param object $quiz the quiz to create an attempt for.
f7970e3c 69 * @param int $attemptnumber the sequence number for the attempt.
c52c62d1 70 * @param object $lastattempt the previous attempt by this user, if any. Only needed
71 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
f7970e3c
TH
72 * @param int $timenow the time the attempt was started at.
73 * @param bool $ispreview whether this new attempt is a preview.
c52c62d1 74 *
75 * @return object the newly created attempt object.
26d12a0c 76 */
c52c62d1 77function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
78 global $USER;
ee1fb969 79
18dff757
TH
80 if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
81 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
ba3fedfb
TH
82 new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
83 array('grade' => quiz_format_grade($quiz, $quiz->grade)));
18dff757
TH
84 }
85
e89e09d2 86 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
25a03faa 87 // We are not building on last attempt so create a new attempt.
0ff4bd08 88 $attempt = new stdClass();
75e1df6f 89 $attempt->quiz = $quiz->id;
90 $attempt->userid = $USER->id;
91 $attempt->preview = 0;
7bf53cf2 92 $attempt->layout = quiz_clean_layout($quiz->questions, true);
75e1df6f 93 if ($quiz->shufflequestions) {
7bf53cf2 94 $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
75e1df6f 95 }
c52c62d1 96 } else {
25a03faa 97 // Build on last attempt.
c52c62d1 98 if (empty($lastattempt)) {
5a2a5331 99 print_error('cannotfindprevattempt', 'quiz');
c52c62d1 100 }
101 $attempt = $lastattempt;
75e1df6f 102 }
103
ee1fb969 104 $attempt->attempt = $attemptnumber;
ee1fb969 105 $attempt->timestart = $timenow;
106 $attempt->timefinish = 0;
107 $attempt->timemodified = $timenow;
be18f589 108 $attempt->state = quiz_attempt::IN_PROGRESS;
75e1df6f 109
25a03faa 110 // If this is a preview, mark it as such.
c52c62d1 111 if ($ispreview) {
112 $attempt->preview = 1;
113 }
114
ee1fb969 115 return $attempt;
116}
117
cd06115f 118/**
25302dee
TH
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.
77ed3ba5 121 *
f7970e3c
TH
122 * @param int $quizid the id of the quiz.
123 * @param int $userid the id of the user.
77ed3ba5 124 *
125 * @return mixed the unfinished attempt if there is one, false if not.
cd06115f 126 */
0d156caa 127function quiz_get_user_attempt_unfinished($quizid, $userid) {
ed8bebce 128 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
77ed3ba5 129 if ($attempts) {
130 return array_shift($attempts);
131 } else {
132 return false;
133 }
920fb237 134}
135
ff51d646 136/**
137 * Delete a quiz attempt.
25a03faa
TH
138 * @param mixed $attempt an integer attempt id or an attempt object
139 * (row of the quiz_attempts table).
97344ae3 140 * @param object $quiz the quiz object.
ff51d646 141 */
142function quiz_delete_attempt($attempt, $quiz) {
9cf4a18b 143 global $DB;
ff51d646 144 if (is_numeric($attempt)) {
9cf4a18b 145 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
ff51d646 146 return;
147 }
148 }
271e6dec 149
ff51d646 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.");
153 return;
154 }
271e6dec 155
25302dee 156 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
6b5f24d3 157 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
ff51d646 158
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
ff51d646 162 $userid = $attempt->userid;
9cf4a18b 163 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
25a03faa 164 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
ff51d646 165 } else {
166 quiz_save_best_grade($quiz, $userid);
167 }
07a7d859 168
169 quiz_update_grades($quiz, $userid);
ff51d646 170}
171
4299df1d 172/**
173 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
174 * to one user.
175 * @param object $quiz the quiz object.
f7970e3c 176 * @param int $userid (optional) if given, only delete the previews belonging to this user.
4299df1d 177 */
178function quiz_delete_previews($quiz, $userid = null) {
179 global $DB;
180 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
181 if (!empty($userid)) {
182 $conditions['userid'] = $userid;
183 }
184 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
185 foreach ($previewattempts as $attempt) {
186 quiz_delete_attempt($attempt, $quiz);
187 }
188}
189
84e628a0 190/**
f7970e3c
TH
191 * @param int $quizid The quiz id.
192 * @return bool whether this quiz has any (non-preview) attempts.
84e628a0 193 */
194function quiz_has_attempts($quizid) {
195 global $DB;
196 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
197}
198
26d12a0c 199/// Functions to do with quiz layout and pages ////////////////////////////////
0d156caa 200
ee1fb969 201/**
26d12a0c 202 * Returns a comma separated list of question ids for the quiz
203 *
1332ce53 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
207 * 3 on page 2
208 * @return string comma separated list of question ids, without page breaks.
26d12a0c 209 */
ee1fb969 210function quiz_questions_in_quiz($layout) {
167f1562
TH
211 $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
212 if ($questions === '0') {
213 return '';
214 } else {
215 return $questions;
216 }
ee1fb969 217}
76cacec8 218
ee1fb969 219/**
1332ce53 220 * Returns the number of pages in a quiz layout
26d12a0c 221 *
1332ce53 222 * @param string $layout The string representing the quiz layout. Always ends in ,0
f7970e3c 223 * @return int The number of pages in the quiz.
26d12a0c 224 */
ee1fb969 225function quiz_number_of_pages($layout) {
167f1562 226 return substr_count(',' . $layout, ',0');
fa583f5f 227}
25302dee 228
fa583f5f 229/**
230 * Returns the number of questions in the quiz layout
231 *
1332ce53 232 * @param string $layout the string representing the quiz layout.
f7970e3c 233 * @return int The number of questions in the quiz.
fa583f5f 234 */
235function quiz_number_of_questions_in_quiz($layout) {
78634f1e 236 $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
1332ce53 237 $count = substr_count($layout, ',');
238 if ($layout !== '') {
fa583f5f 239 $count++;
240 }
241 return $count;
ee1fb969 242}
76cacec8 243
ee1fb969 244/**
26d12a0c 245 * Re-paginates the quiz layout
246 *
7bf53cf2
TH
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.
f7970e3c
TH
250 * @param int $perpage The number of questions per page
251 * @param bool $shuffle Should the questions be reordered randomly?
1332ce53 252 * @return string the new layout string
26d12a0c 253 */
4299df1d 254function quiz_repaginate($layout, $perpage, $shuffle = false) {
0c5abe6c
TH
255 $questions = quiz_questions_in_quiz($layout);
256 if (!$questions) {
257 return '0';
258 }
259
260 $questions = explode(',', quiz_questions_in_quiz($layout));
ee1fb969 261 if ($shuffle) {
ee1fb969 262 shuffle($questions);
263 }
0c5abe6c
TH
264
265 $onthispage = 0;
266 $layout = array();
ee1fb969 267 foreach ($questions as $question) {
0c5abe6c
TH
268 if ($perpage and $onthispage >= $perpage) {
269 $layout[] = 0;
270 $onthispage = 0;
76cacec8 271 }
0c5abe6c
TH
272 $layout[] = $question;
273 $onthispage += 1;
76cacec8 274 }
0c5abe6c
TH
275
276 $layout[] = 0;
277 return implode(',', $layout);
ee1fb969 278}
76cacec8 279
26d12a0c 280/// Functions to do with quiz grades //////////////////////////////////////////
76cacec8 281
ee1fb969 282/**
26d12a0c 283 * Creates an array of maximum grades for a quiz
83192608 284 *
25302dee
TH
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
4e6f553d 288 * possible grades that students can achieve for each of the questions.
26d12a0c 289 */
ee1fb969 290function quiz_get_all_question_grades($quiz) {
9cf4a18b 291 global $CFG, $DB;
76cacec8 292
ee1fb969 293 $questionlist = quiz_questions_in_quiz($quiz->questions);
76cacec8 294 if (empty($questionlist)) {
295 return array();
296 }
297
9cf4a18b 298 $params = array($quiz->id);
299 $wheresql = '';
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);
304 }
305
25a03faa 306 $instances = $DB->get_records_sql("SELECT question, grade, id
9cf4a18b 307 FROM {quiz_question_instances}
308 WHERE quiz = ? $wheresql", $params);
76cacec8 309
310 $list = explode(",", $questionlist);
311 $grades = array();
312
313 foreach ($list as $qid) {
ee1fb969 314 if (isset($instances[$qid])) {
315 $grades[$qid] = $instances[$qid]->grade;
76cacec8 316 } else {
317 $grades[$qid] = 1;
318 }
319 }
320 return $grades;
321}
322
212b7b8c 323/**
324 * Convert the raw grade stored in $attempt into a grade out of the maximum
325 * grade for this quiz.
77ed3ba5 326 *
212b7b8c 327 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
25302dee 328 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
f7970e3c 329 * @param bool|string $format whether to format the results for display
25302dee 330 * or 'question' to format a question grade (different number of decimal places.
25a03faa
TH
331 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
332 * if the $grade is null.
212b7b8c 333 */
25302dee
TH
334function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
335 if (is_null($rawgrade)) {
336 $grade = null;
337 } else if ($quiz->sumgrades >= 0.000005) {
b7b4f8bd 338 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
212b7b8c 339 } else {
b7b4f8bd 340 $grade = 0;
212b7b8c 341 }
25302dee
TH
342 if ($format === 'question') {
343 $grade = quiz_format_question_grade($quiz, $grade);
344 } else if ($format) {
345 $grade = quiz_format_grade($quiz, $grade);
346 }
b7b4f8bd 347 return $grade;
76cacec8 348}
349
ee1fb969 350/**
212b7b8c 351 * Get the feedback text that should be show to a student who
de266537 352 * got this grade on this quiz. The feedback is processed ready for diplay.
77ed3ba5 353 *
212b7b8c 354 * @param float $grade a grade on this quiz.
2709ee45
TH
355 * @param object $quiz the quiz settings.
356 * @param object $context the quiz context.
212b7b8c 357 * @return string the comment that corresponds to this grade (empty string if there is not one.
358 */
2709ee45 359function quiz_feedback_for_grade($grade, $quiz, $context) {
9cf4a18b 360 global $DB;
212b7b8c 361
25302dee
TH
362 if (is_null($grade)) {
363 return '';
364 }
365
b7ab57f3
TH
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);
369
2709ee45
TH
370 $feedback = $DB->get_record_select('quiz_feedback',
371 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
fe6ce234
DC
372
373 if (empty($feedback->feedbacktext)) {
2709ee45 374 return '';
212b7b8c 375 }
77ed3ba5 376
de266537 377 // Clean the text, ready for display.
0ff4bd08 378 $formatoptions = new stdClass();
de266537 379 $formatoptions->noclean = true;
25a03faa
TH
380 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
381 $context->id, 'mod_quiz', 'feedback', $feedback->id);
fe6ce234 382 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
de266537 383
fe6ce234 384 return $feedbacktext;
212b7b8c 385}
386
387/**
8ce3e17f 388 * @param object $quiz the quiz database row.
f7970e3c 389 * @return bool Whether this quiz has any non-blank feedback text.
212b7b8c 390 */
739b0711 391function quiz_has_feedback($quiz) {
9cf4a18b 392 global $DB;
212b7b8c 393 static $cache = array();
739b0711 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),
398 array($quiz->id));
212b7b8c 399 }
739b0711 400 return $cache[$quiz->id];
212b7b8c 401}
402
25302dee
TH
403/**
404 * Update the sumgrades field of the quiz. This needs to be called whenever
405 * the grading structure of the quiz is changed. For example if a question is
406 * added or removed, or a question weight is changed.
407 *
18dff757
TH
408 * You should call {@link quiz_delete_previews()} before you call this function.
409 *
25302dee
TH
410 * @param object $quiz a quiz.
411 */
412function quiz_update_sumgrades($quiz) {
413 global $DB;
18dff757 414
25302dee
TH
415 $sql = 'UPDATE {quiz}
416 SET sumgrades = COALESCE((
417 SELECT SUM(grade)
418 FROM {quiz_question_instances}
419 WHERE quiz = {quiz}.id
420 ), 0)
421 WHERE id = ?';
a13d4fbd
TH
422 $DB->execute($sql, array($quiz->id));
423 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
18dff757
TH
424
425 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
426 // If the quiz has been attempted, and the sumgrades has been
427 // set to 0, then we must also set the maximum possible grade to 0, or
428 // we will get a divide by zero error.
25302dee
TH
429 quiz_set_grade(0, $quiz);
430 }
431}
432
18dff757
TH
433/**
434 * Update the sumgrades field of the attempts at a quiz.
435 *
436 * @param object $quiz a quiz.
437 */
25302dee
TH
438function quiz_update_all_attempt_sumgrades($quiz) {
439 global $DB;
440 $dm = new question_engine_data_mapper();
441 $timenow = time();
442
443 $sql = "UPDATE {quiz_attempts}
444 SET
445 timemodified = :timenow,
446 sumgrades = (
447 {$dm->sum_usage_marks_subquery('uniqueid')}
448 )
be18f589
TH
449 WHERE quiz = :quizid AND state = :finishedstate";
450 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
451 'finishedstate' => quiz_attempt::FINISHED));
25302dee
TH
452}
453
212b7b8c 454/**
b2607ccc 455 * The quiz grade is the maximum that student's results are marked out of. When it
212b7b8c 456 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
25302dee
TH
457 * rescaled. After calling this function, you probably need to call
458 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
459 * quiz_update_grades.
77ed3ba5 460 *
212b7b8c 461 * @param float $newgrade the new maximum grade for the quiz.
25a03faa
TH
462 * @param object $quiz the quiz we are updating. Passed by reference so its
463 * grade field can be updated too.
f7970e3c 464 * @return bool indicating success or failure.
212b7b8c 465 */
25302dee 466function quiz_set_grade($newgrade, $quiz) {
9cf4a18b 467 global $DB;
212b7b8c 468 // This is potentially expensive, so only do it if necessary.
469 if (abs($quiz->grade - $newgrade) < 1e-7) {
470 // Nothing to do.
471 return true;
472 }
b22fc901 473
212b7b8c 474 // Use a transaction, so that on those databases that support it, this is safer.
d5a8d9aa
PS
475 $transaction = $DB->start_delegated_transaction();
476
0f1c59c5
TH
477 // Update the quiz table.
478 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
479
480 // Rescaling the other data is only possible if the old grade was non-zero.
481 if ($quiz->grade > 1e-7) {
482 global $CFG;
483
484 $factor = $newgrade/$quiz->grade;
485 $quiz->grade = $newgrade;
486
487 // Update the quiz_grades table.
488 $timemodified = time();
489 $DB->execute("
490 UPDATE {quiz_grades}
491 SET grade = ? * grade, timemodified = ?
492 WHERE quiz = ?
493 ", array($factor, $timemodified, $quiz->id));
494
495 // Update the quiz_feedback table.
496 $DB->execute("
497 UPDATE {quiz_feedback}
498 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
499 WHERE quizid = ?
500 ", array($factor, $factor, $quiz->id));
501 }
77ed3ba5 502
0f1c59c5
TH
503 // update grade item and send all grades to gradebook
504 quiz_grade_item_update($quiz);
505 quiz_update_grades($quiz);
d6dd2108 506
0f1c59c5
TH
507 $transaction->allow_commit();
508 return true;
212b7b8c 509}
510
511/**
512 * Save the overall grade for a user at a quiz in the quiz_grades table
513 *
514 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
f7970e3c 515 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
98f38217 516 * @param array $attempts The attempts of this user. Useful if you are
517 * looping through many users. Attempts can be fetched in one master query to
518 * avoid repeated querying.
f7970e3c 519 * @return bool Indicates success or failure.
212b7b8c 520 */
98f38217 521function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
cef18275 522 global $DB, $OUTPUT, $USER;
ee1fb969 523
212b7b8c 524 if (empty($userid)) {
ee1fb969 525 $userid = $USER->id;
526 }
76cacec8 527
25a03faa 528 if (!$attempts) {
98f38217 529 // Get all the attempts made by the user
25302dee 530 $attempts = quiz_get_user_attempts($quiz->id, $userid);
76cacec8 531 }
532
ee1fb969 533 // Calculate the best grade
76cacec8 534 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
84e628a0 535 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
77ed3ba5 536
ee1fb969 537 // Save the best grade in the database
25302dee
TH
538 if (is_null($bestgrade)) {
539 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
540
25a03faa
TH
541 } else if ($grade = $DB->get_record('quiz_grades',
542 array('quiz' => $quiz->id, 'userid' => $userid))) {
fc44ee0d 543 $grade->grade = $bestgrade;
76cacec8 544 $grade->timemodified = time();
a8c31db2 545 $DB->update_record('quiz_grades', $grade);
25302dee 546
76cacec8 547 } else {
b640e681 548 $grade = new stdClass();
76cacec8 549 $grade->quiz = $quiz->id;
550 $grade->userid = $userid;
fc44ee0d 551 $grade->grade = $bestgrade;
76cacec8 552 $grade->timemodified = time();
a8c31db2 553 $DB->insert_record('quiz_grades', $grade);
76cacec8 554 }
d6dd2108 555
556 quiz_update_grades($quiz, $userid);
76cacec8 557}
558
fc44ee0d 559/**
26d12a0c 560 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
561 *
13bbfebc
TH
562 * @param object $quiz the quiz settings object.
563 * @param array $attempts an array of all the user's attempts at this quiz in order.
564 * @return float the overall grade
26d12a0c 565 */
76cacec8 566function quiz_calculate_best_grade($quiz, $attempts) {
76cacec8 567
568 switch ($quiz->grademethod) {
569
ee1fb969 570 case QUIZ_ATTEMPTFIRST:
13bbfebc
TH
571 $firstattempt = reset($attempts);
572 return $firstattempt->sumgrades;
76cacec8 573
ee1fb969 574 case QUIZ_ATTEMPTLAST:
13bbfebc
TH
575 $lastattempt = end($attempts);
576 return $lastattempt->sumgrades;
76cacec8 577
ee1fb969 578 case QUIZ_GRADEAVERAGE:
76cacec8 579 $sum = 0;
580 $count = 0;
581 foreach ($attempts as $attempt) {
25302dee
TH
582 if (!is_null($attempt->sumgrades)) {
583 $sum += $attempt->sumgrades;
584 $count++;
585 }
76cacec8 586 }
25302dee
TH
587 if ($count == 0) {
588 return null;
589 }
590 return $sum / $count;
76cacec8 591
ee1fb969 592 case QUIZ_GRADEHIGHEST:
13bbfebc 593 default:
25302dee 594 $max = null;
76cacec8 595 foreach ($attempts as $attempt) {
596 if ($attempt->sumgrades > $max) {
597 $max = $attempt->sumgrades;
598 }
599 }
600 return $max;
601 }
602}
603
25302dee
TH
604/**
605 * Update the final grade at this quiz for all students.
606 *
607 * This function is equivalent to calling quiz_save_best_grade for all
608 * users, but much more efficient.
609 *
610 * @param object $quiz the quiz settings.
611 */
612function quiz_update_all_final_grades($quiz) {
613 global $DB;
614
615 if (!$quiz->sumgrades) {
616 return;
617 }
618
be18f589 619 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
25302dee
TH
620 $firstlastattemptjoin = "JOIN (
621 SELECT
622 iquiza.userid,
623 MIN(attempt) AS firstattempt,
624 MAX(attempt) AS lastattempt
625
e50a5813 626 FROM {quiz_attempts} iquiza
25302dee
TH
627
628 WHERE
be18f589 629 iquiza.state = :istatefinished
25302dee
TH
630 iquiza.preview = 0 AND
631 iquiza.quiz = :iquizid
632
633 GROUP BY iquiza.userid
634 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
635
636 switch ($quiz->grademethod) {
637 case QUIZ_ATTEMPTFIRST:
81522abd 638 // Because of the where clause, there will only be one row, but we
25302dee
TH
639 // must still use an aggregate function.
640 $select = 'MAX(quiza.sumgrades)';
641 $join = $firstlastattemptjoin;
642 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
643 break;
644
645 case QUIZ_ATTEMPTLAST:
81522abd 646 // Because of the where clause, there will only be one row, but we
25302dee
TH
647 // must still use an aggregate function.
648 $select = 'MAX(quiza.sumgrades)';
649 $join = $firstlastattemptjoin;
650 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
651 break;
652
653 case QUIZ_GRADEAVERAGE:
654 $select = 'AVG(quiza.sumgrades)';
655 $join = '';
656 $where = '';
657 break;
658
659 default:
660 case QUIZ_GRADEHIGHEST:
661 $select = 'MAX(quiza.sumgrades)';
662 $join = '';
663 $where = '';
664 break;
665 }
666
667 if ($quiz->sumgrades >= 0.000005) {
668 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
669 } else {
670 $finalgrade = '0';
671 }
672 $param['quizid'] = $quiz->id;
673 $param['quizid2'] = $quiz->id;
674 $param['quizid3'] = $quiz->id;
675 $param['quizid4'] = $quiz->id;
be18f589
TH
676 $param['statefinished'] = quiz_attempt::FINISHED;
677 $param['statefinished2'] = quiz_attempt::FINISHED;
25302dee
TH
678 $finalgradesubquery = "
679 SELECT quiza.userid, $finalgrade AS newgrade
680 FROM {quiz_attempts} quiza
681 $join
682 WHERE
683 $where
be18f589 684 quiza.quiza.state = :statefinished AND
25302dee
TH
685 quiza.preview = 0 AND
686 quiza.quiz = :quizid3
687 GROUP BY quiza.userid";
688
689 $changedgrades = $DB->get_records_sql("
690 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
691
692 FROM (
693 SELECT userid
694 FROM {quiz_grades} qg
695 WHERE quiz = :quizid
696 UNION
697 SELECT DISTINCT userid
698 FROM {quiz_attempts} quiza2
699 WHERE
be18f589 700 quiza2.quiza.state = :statefinished2 AND
25302dee
TH
701 quiza2.preview = 0 AND
702 quiza2.quiz = :quizid2
703 ) users
704
705 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
706
707 LEFT JOIN (
708 $finalgradesubquery
709 ) newgrades ON newgrades.userid = users.userid
710
711 WHERE
712 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
f484a629
TH
713 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
714 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
715 // The mess on the previous line is detecting where the value is
716 // NULL in one column, and NOT NULL in the other, but SQL does
717 // not have an XOR operator, and MS SQL server can't cope with
718 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
a13d4fbd 719 $param);
25302dee
TH
720
721 $timenow = time();
722 $todelete = array();
723 foreach ($changedgrades as $changedgrade) {
724
725 if (is_null($changedgrade->newgrade)) {
726 $todelete[] = $changedgrade->userid;
727
728 } else if (is_null($changedgrade->grade)) {
0ff4bd08 729 $toinsert = new stdClass();
25302dee
TH
730 $toinsert->quiz = $quiz->id;
731 $toinsert->userid = $changedgrade->userid;
732 $toinsert->timemodified = $timenow;
733 $toinsert->grade = $changedgrade->newgrade;
734 $DB->insert_record('quiz_grades', $toinsert);
735
736 } else {
0ff4bd08 737 $toupdate = new stdClass();
25302dee
TH
738 $toupdate->id = $changedgrade->id;
739 $toupdate->grade = $changedgrade->newgrade;
740 $toupdate->timemodified = $timenow;
741 $DB->update_record('quiz_grades', $toupdate);
742 }
743 }
744
745 if (!empty($todelete)) {
e65f89b9 746 list($test, $params) = $DB->get_in_or_equal($todelete);
8d13ea83
TH
747 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
748 array_merge(array($quiz->id), $params));
25302dee
TH
749 }
750}
751
fc44ee0d 752/**
26d12a0c 753 * Return the attempt with the best grade for a quiz
754 *
755 * Which attempt is the best depends on $quiz->grademethod. If the grade
756 * method is GRADEAVERAGE then this function simply returns the last attempt.
757 * @return object The attempt with the best grade
758 * @param object $quiz The quiz for which the best grade is to be calculated
759 * @param array $attempts An array of all the attempts of the user at the quiz
760 */
76cacec8 761function quiz_calculate_best_attempt($quiz, $attempts) {
76cacec8 762
763 switch ($quiz->grademethod) {
764
ee1fb969 765 case QUIZ_ATTEMPTFIRST:
76cacec8 766 foreach ($attempts as $attempt) {
767 return $attempt;
768 }
769 break;
770
ee1fb969 771 case QUIZ_GRADEAVERAGE: // need to do something with it :-)
772 case QUIZ_ATTEMPTLAST:
76cacec8 773 foreach ($attempts as $attempt) {
774 $final = $attempt;
775 }
776 return $final;
777
778 default:
ee1fb969 779 case QUIZ_GRADEHIGHEST:
76cacec8 780 $max = -1;
781 foreach ($attempts as $attempt) {
782 if ($attempt->sumgrades > $max) {
783 $max = $attempt->sumgrades;
784 $maxattempt = $attempt;
785 }
786 }
787 return $maxattempt;
788 }
789}
790
25302dee 791/**
87427d9c
TH
792 * @return array int => lang string the options for calculating the quiz grade
793 * from the individual attempt grades.
25302dee
TH
794 */
795function quiz_get_grading_options() {
796 return array(
797 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
798 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
799 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
800 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
801 );
802}
803
0675e5eb 804/**
25a03faa
TH
805 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
806 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
0675e5eb 807 * @return the lang string for that option.
808 */
809function quiz_get_grading_option_name($option) {
810 $strings = quiz_get_grading_options();
811 return $strings[$option];
812}
813
87427d9c
TH
814/**
815 * @return array string => lang string the options for handling overdue quiz
816 * attempts.
817 */
818function quiz_get_overdue_handling_options() {
819 return array(
820 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
821 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
822 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
823 );
824}
825
be18f589
TH
826/**
827 * @param string $state one of the state constants like IN_PROGRESS.
828 * @return string the human-readable state name.
829 */
830function quiz_attempt_state_name($state) {
831 switch ($state) {
832 case quiz_attempt::IN_PROGRESS:
833 return get_string('stateinprogress', 'quiz');
834 case quiz_attempt::OVERDUE:
835 return get_string('stateoverdue', 'quiz');
836 case quiz_attempt::FINISHED:
837 return get_string('statefinished', 'quiz');
838 case quiz_attempt::ABANDONED:
839 return get_string('stateabandoned', 'quiz');
840 default:
841 throw new coding_exception('Unknown quiz attempt state.');
842 }
843}
844
26d12a0c 845/// Other quiz functions ////////////////////////////////////////////////////
ee1fb969 846
26a29b1a 847/**
2a874d65 848 * @param object $quiz the quiz.
f7970e3c 849 * @param int $cmid the course_module object for this quiz.
2a874d65 850 * @param object $question the question.
26a29b1a 851 * @param string $returnurl url to return to after action is done.
852 * @return string html for a number of icons linked to action pages for a
853 * question - preview and edit / view icons depending on user capabilities.
854 */
2a874d65 855function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
856 $html = quiz_question_preview_button($quiz, $question) . ' ' .
857 quiz_question_edit_button($cmid, $question, $returnurl);
858 return $html;
859}
860
861/**
f7970e3c 862 * @param int $cmid the course_module.id for this quiz.
2a874d65 863 * @param object $question the question.
864 * @param string $returnurl url to return to after action is done.
865 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
25a03faa
TH
866 * @return the HTML for an edit icon, view icon, or nothing for a question
867 * (depending on permissions).
2a874d65 868 */
d04f623b 869function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
d436d197 870 global $CFG, $OUTPUT;
2a874d65 871
872 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
26a29b1a 873 static $stredit = null;
874 static $strview = null;
25a03faa 875 if ($stredit === null) {
26a29b1a 876 $stredit = get_string('edit');
877 $strview = get_string('view');
878 }
2a874d65 879
880 // What sort of icon should we show?
881 $action = '';
25a03faa
TH
882 if (!empty($question->id) &&
883 (question_has_capability_on($question, 'edit', $question->category) ||
884 question_has_capability_on($question, 'move', $question->category))) {
2a874d65 885 $action = $stredit;
886 $icon = '/t/edit';
25a03faa
TH
887 } else if (!empty($question->id) &&
888 question_has_capability_on($question, 'view', $question->category)) {
2a874d65 889 $action = $strview;
890 $icon = '/i/info';
891 }
892
893 // Build the icon.
894 if ($action) {
47678d60 895 if ($returnurl instanceof moodle_url) {
a530d4a9 896 $returnurl = $returnurl->out_as_local_url(false);
47678d60 897 }
2a874d65 898 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
899 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
068384ce 900 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
d04f623b
TH
901 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
902 '</a>';
068384ce
TH
903 } else if ($contentaftericon) {
904 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
2a874d65 905 } else {
068384ce 906 return '';
26a29b1a 907 }
26a29b1a 908}
909
7d87171b 910/**
612106b3
TH
911 * @param object $quiz the quiz settings
912 * @param object $question the question
913 * @return moodle_url to preview this question with the options from this quiz.
914 */
915function quiz_question_preview_url($quiz, $question) {
916 // Get the appropriate display options.
917 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
918 mod_quiz_display_options::DURING);
919
920 $maxmark = null;
921 if (isset($question->maxmark)) {
922 $maxmark = $question->maxmark;
923 }
924
925 // Work out the correcte preview URL.
926 return question_preview_url($question->id, $quiz->preferredbehaviour,
927 $maxmark, $displayoptions);
928}
929
930/**
931 * @param object $quiz the quiz settings
7d87171b 932 * @param object $question the question
f7970e3c 933 * @param bool $label if true, show the preview question label after the icon
7d87171b 934 * @return the HTML for a preview question icon.
935 */
2a874d65 936function quiz_question_preview_button($quiz, $question, $label = false) {
56a4ae46 937 global $CFG, $OUTPUT;
2a874d65 938 if (!question_has_capability_on($question, 'use', $question->category)) {
271e6dec 939 return '';
940 }
2a874d65 941
612106b3 942 $url = quiz_question_preview_url($quiz, $question);
2a874d65 943
944 // Do we want a label?
25302dee 945 $strpreviewlabel = '';
2a874d65 946 if ($label) {
25302dee 947 $strpreviewlabel = get_string('preview', 'quiz');
fa583f5f 948 }
2a874d65 949
950 // Build the icon.
f9b0500f 951 $strpreviewquestion = get_string('previewquestion', 'quiz');
000c278c 952 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
ca4b4f8f 953
612106b3
TH
954 $action = new popup_action('click', $url, 'questionpreview',
955 question_preview_popup_params());
4bcc5118 956
25302dee 957 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
ad7e7ba8 958}
0d156caa 959
62e76c67 960/**
961 * @param object $attempt the attempt.
962 * @param object $context the quiz context.
f7970e3c 963 * @return int whether flags should be shown/editable to the current user for this attempt.
62e76c67 964 */
965function quiz_get_flag_option($attempt, $context) {
966 global $USER;
25302dee
TH
967 if (!has_capability('moodle/question:flag', $context)) {
968 return question_display_options::HIDDEN;
969 } else if ($attempt->userid == $USER->id) {
970 return question_display_options::EDITABLE;
971 } else {
972 return question_display_options::VISIBLE;
62e76c67 973 }
62e76c67 974}
975
4f48fb42 976/**
be18f589
TH
977 * Work out what state this quiz attempt is in - in the sense used by
978 * quiz_get_review_options, not in the sense of $attempt->state.
25302dee
TH
979 * @param object $quiz the quiz settings
980 * @param object $attempt the quiz_attempt database row.
f7970e3c 981 * @return int one of the mod_quiz_display_options::DURING,
25302dee 982 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
4dca7e51 983 */
25302dee 984function quiz_attempt_state($quiz, $attempt) {
be18f589 985 if ($attempt->state != quiz_attempt::FINISHED) {
25302dee
TH
986 return mod_quiz_display_options::DURING;
987 } else if (time() < $attempt->timefinish + 120) {
988 return mod_quiz_display_options::IMMEDIATELY_AFTER;
989 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
990 return mod_quiz_display_options::LATER_WHILE_OPEN;
991 } else {
992 return mod_quiz_display_options::AFTER_CLOSE;
993 }
4f48fb42 994}
995
4f48fb42 996/**
25302dee
TH
997 * The the appropraite mod_quiz_display_options object for this attempt at this
998 * quiz right now.
77ed3ba5 999 *
cd06115f 1000 * @param object $quiz the quiz instance.
1001 * @param object $attempt the attempt in question.
25302dee 1002 * @param $context the quiz context.
77ed3ba5 1003 *
25302dee 1004 * @return mod_quiz_display_options
cd06115f 1005 */
7ee80cab 1006function quiz_get_review_options($quiz, $attempt, $context) {
25302dee 1007 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
62e76c67 1008
4f48fb42 1009 $options->readonly = true;
62e76c67 1010 $options->flags = quiz_get_flag_option($attempt, $context);
2709ee45
TH
1011 if (!empty($attempt->id)) {
1012 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1013 array('attempt' => $attempt->id));
1014 }
b6e907a2 1015
e2833e87 1016 // Show a link to the comment box only for closed attempts
be18f589 1017 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
2709ee45 1018 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
25302dee 1019 $options->manualcomment = question_display_options::VISIBLE;
7ee80cab
TH
1020 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1021 array('attempt' => $attempt->id));
01600b51 1022 }
1023
25a03faa
TH
1024 if (!is_null($context) && !$attempt->preview &&
1025 has_capability('mod/quiz:viewreports', $context) &&
25302dee 1026 has_capability('moodle/grade:viewhidden', $context)) {
e2833e87 1027 // People who can see reports and hidden grades should be shown everything,
1028 // except during preview when teachers want to see what students see.
25302dee
TH
1029 $options->attempt = question_display_options::VISIBLE;
1030 $options->correctness = question_display_options::VISIBLE;
1031 $options->marks = question_display_options::MARK_AND_MAX;
1032 $options->feedback = question_display_options::VISIBLE;
1033 $options->numpartscorrect = question_display_options::VISIBLE;
1034 $options->generalfeedback = question_display_options::VISIBLE;
1035 $options->rightanswer = question_display_options::VISIBLE;
1036 $options->overallfeedback = question_display_options::VISIBLE;
1037 $options->history = question_display_options::VISIBLE;
e2833e87 1038
4f48fb42 1039 }
77ed3ba5 1040
4f48fb42 1041 return $options;
1042}
77ed3ba5 1043
40377b18 1044/**
77ed3ba5 1045 * Combines the review options from a number of different quiz attempts.
25302dee 1046 * Returns an array of two ojects, so the suggested way of calling this
77ed3ba5 1047 * funciton is:
1048 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1049 *
1050 * @param object $quiz the quiz instance.
1051 * @param array $attempts an array of attempt objects.
1052 * @param $context the roles and permissions context,
1053 * normally the context for the quiz module instance.
1054 *
1055 * @return array of two options objects, one showing which options are true for
1056 * at least one of the attempts, the other showing which options are true
1057 * for all attempts.
1058 */
25302dee 1059function quiz_get_combined_reviewoptions($quiz, $attempts) {
6d03fd98 1060 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
0ff4bd08
TH
1061 $someoptions = new stdClass();
1062 $alloptions = new stdClass();
77ed3ba5 1063 foreach ($fields as $field) {
1064 $someoptions->$field = false;
1065 $alloptions->$field = true;
40377b18 1066 }
6d03fd98
TH
1067 $someoptions->marks = question_display_options::HIDDEN;
1068 $alloptions->marks = question_display_options::MARK_AND_MAX;
1069
77ed3ba5 1070 foreach ($attempts as $attempt) {
25302dee
TH
1071 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1072 quiz_attempt_state($quiz, $attempt));
7d014bf5 1073 foreach ($fields as $field) {
1074 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1075 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1076 }
6d03fd98
TH
1077 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1078 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
77ed3ba5 1079 }
1080 return array($someoptions, $alloptions);
40377b18 1081}
ac48e43a 1082
25302dee
TH
1083/**
1084 * Clean the question layout from various possible anomalies:
1085 * - Remove consecutive ","'s
1086 * - Remove duplicate question id's
1087 * - Remove extra "," from beginning and end
1088 * - Finally, add a ",0" in the end if there is none
1089 *
1090 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
f7970e3c 1091 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
25302dee
TH
1092 * @return $string the cleaned-up layout
1093 */
1094function quiz_clean_layout($layout, $removeemptypages = false) {
1095 // Remove repeated ','s. This can happen when a restore fails to find the right
1096 // id to relink to.
1097 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1098
1099 // Remove duplicate question ids
1100 $layout = explode(',', $layout);
1101 $cleanerlayout = array();
1102 $seen = array();
1103 foreach ($layout as $item) {
1104 if ($item == 0) {
1105 $cleanerlayout[] = '0';
1106 } else if (!in_array($item, $seen)) {
1107 $cleanerlayout[] = $item;
1108 $seen[] = $item;
1109 }
1110 }
1111
1112 if ($removeemptypages) {
1113 // Avoid duplicate page breaks
1114 $layout = $cleanerlayout;
1115 $cleanerlayout = array();
1116 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1117 foreach ($layout as $item) {
1118 if ($stripfollowingbreaks && $item == 0) {
1119 continue;
1120 }
1121 $cleanerlayout[] = $item;
1122 $stripfollowingbreaks = $item == 0;
1123 }
1124 }
1125
1126 // Add a page break at the end if there is none
1127 if (end($cleanerlayout) !== '0') {
1128 $cleanerlayout[] = '0';
1129 }
1130
1131 return implode(',', $cleanerlayout);
1132}
1133
1134/**
1135 * Get the slot for a question with a particular id.
1136 * @param object $quiz the quiz settings.
f7970e3c
TH
1137 * @param int $questionid the of a question in the quiz.
1138 * @return int the corresponding slot. Null if the question is not in the quiz.
25302dee
TH
1139 */
1140function quiz_get_slot_for_question($quiz, $questionid) {
1141 $questionids = quiz_questions_in_quiz($quiz->questions);
1142 foreach (explode(',', $questionids) as $key => $id) {
1143 if ($id == $questionid) {
1144 return $key + 1;
1145 }
1146 }
1147 return null;
1148}
1149
cbb8b55c 1150/// FUNCTIONS FOR SENDING NOTIFICATION MESSAGES ///////////////////////////////
ac48e43a 1151
1152/**
cbb8b55c 1153 * Sends a confirmation message to the student confirming that the attempt was processed.
ac48e43a 1154 *
cbb8b55c
TH
1155 * @param object $a lots of useful information that can be used in the message
1156 * subject and body.
ac48e43a 1157 *
cbb8b55c 1158 * @return int|false as for {@link message_send()}.
ac48e43a 1159 */
cbb8b55c 1160function quiz_send_confirmation($recipient, $a) {
ac48e43a 1161
cbb8b55c
TH
1162 // Add information about the recipient to $a
1163 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1164 $a->username = fullname($recipient);
1165 $a->userusername = $recipient->username;
ac48e43a 1166
cbb8b55c 1167 // Prepare message
39790bd8 1168 $eventdata = new stdClass();
cbb8b55c
TH
1169 $eventdata->component = 'mod_quiz';
1170 $eventdata->name = 'confirmation';
94263cca
AD
1171 $eventdata->notification = 1;
1172
3b120e46 1173 $eventdata->userfrom = get_admin();
cbb8b55c
TH
1174 $eventdata->userto = $recipient;
1175 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1176 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
3b120e46 1177 $eventdata->fullmessageformat = FORMAT_PLAIN;
1178 $eventdata->fullmessagehtml = '';
94263cca
AD
1179
1180 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1181 $eventdata->contexturl = $a->quizurl;
1182 $eventdata->contexturlname = $a->quizname;
99d19c13 1183
cbb8b55c
TH
1184 // ... and send it.
1185 return message_send($eventdata);
ac48e43a 1186}
1187
1188/**
bc68fc9a 1189 * Sends notification messages to the interested parties that assign the role capability
ac48e43a 1190 *
1191 * @param object $recipient user object of the intended recipient
0ff4bd08 1192 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1193 *
cbb8b55c 1194 * @return int|false as for {@link message_send()}.
ac48e43a 1195 */
cbb8b55c 1196function quiz_send_notification($recipient, $submitter, $a) {
ac48e43a 1197
cbb8b55c
TH
1198 // Recipient info for template
1199 $a->useridnumber = $recipient->idnumber;
1200 $a->username = fullname($recipient);
ac48e43a 1201 $a->userusername = $recipient->username;
ac48e43a 1202
cbb8b55c 1203 // Prepare message
39790bd8 1204 $eventdata = new stdClass();
cbb8b55c
TH
1205 $eventdata->component = 'mod_quiz';
1206 $eventdata->name = 'submission';
bc68fc9a
AD
1207 $eventdata->notification = 1;
1208
cbb8b55c 1209 $eventdata->userfrom = $submitter;
3b120e46 1210 $eventdata->userto = $recipient;
cbb8b55c
TH
1211 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1212 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
3b120e46 1213 $eventdata->fullmessageformat = FORMAT_PLAIN;
1214 $eventdata->fullmessagehtml = '';
bc68fc9a
AD
1215
1216 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1217 $eventdata->contexturl = $a->quizreviewurl;
1218 $eventdata->contexturlname = $a->quizname;
1219
cbb8b55c
TH
1220 // ... and send it.
1221 return message_send($eventdata);
ac48e43a 1222}
1223
1224/**
cbb8b55c 1225 * Send all the requried messages when a quiz attempt is submitted.
ac48e43a 1226 *
1227 * @param object $course the course
1228 * @param object $quiz the quiz
1229 * @param object $attempt this attempt just finished
1230 * @param object $context the quiz context
1231 * @param object $cm the coursemodule for this quiz
1232 *
cbb8b55c 1233 * @return bool true if all necessary messages were sent successfully, else false.
ac48e43a 1234 */
cbb8b55c
TH
1235function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1236 global $CFG, $DB;
ac48e43a 1237
cbb8b55c 1238 // Do nothing if required objects not present
ac48e43a 1239 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
cbb8b55c 1240 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
ac48e43a 1241 }
1242
cbb8b55c
TH
1243 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1244
1245 // Check for confirmation required
ac48e43a 1246 $sendconfirm = false;
1247 $notifyexcludeusers = '';
cbb8b55c
TH
1248 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1249 $notifyexcludeusers = $submitter->id;
ac48e43a 1250 $sendconfirm = true;
1251 }
1252
1253 // check for notifications required
d8aa5ec7 1254 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
cbb8b55c
TH
1255 'u.lang, u.timezone, u.mailformat, u.maildisplay';
1256 $groups = groups_get_all_groups($course->id, $submitter->id);
5a128471 1257 if (is_array($groups) && count($groups) > 0) {
1258 $groups = array_keys($groups);
255985f1 1259 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1260 // If the user is not in a group, and the quiz is set to group mode,
cbb8b55c 1261 // then set $groups to a non-existant id so that only users with
255985f1 1262 // 'moodle/site:accessallgroups' get notified.
1263 $groups = -1;
5a128471 1264 } else {
1265 $groups = '';
1266 }
ac48e43a 1267 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
5a128471 1268 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
ac48e43a 1269
cbb8b55c
TH
1270 if (empty($userstonotify) && !$sendconfirm) {
1271 return true; // Nothing to do.
ac48e43a 1272 }
1273
cbb8b55c
TH
1274 $a = new stdClass();
1275 // Course info
1276 $a->coursename = $course->fullname;
1277 $a->courseshortname = $course->shortname;
1278 // Quiz info
1279 $a->quizname = $quiz->name;
1280 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1281 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1282 format_string($quiz->name) . ' report</a>';
cbb8b55c
TH
1283 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1284 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1285 // Attempt info
1286 $a->submissiontime = userdate($attempt->timefinish);
1287 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
fd0537ce
TH
1288 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1289 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1290 format_string($quiz->name) . ' review</a>';
cbb8b55c
TH
1291 // Student who sat the quiz info
1292 $a->studentidnumber = $submitter->idnumber;
1293 $a->studentname = fullname($submitter);
1294 $a->studentusername = $submitter->username;
1295
1296 $allok = true;
1297
1298 // Send notifications if required
ac48e43a 1299 if (!empty($userstonotify)) {
ac48e43a 1300 foreach ($userstonotify as $recipient) {
cbb8b55c 1301 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
ac48e43a 1302 }
1303 }
1304
cbb8b55c
TH
1305 // Send confirmation if required. We send the student confirmation last, so
1306 // that if message sending is being intermittently buggy, which means we send
1307 // some but not all messages, and then try again later, then teachers may get
1308 // duplicate messages, but the student will always get exactly one.
1309 if ($sendconfirm) {
1310 $allok = $allok && quiz_send_confirmation($submitter, $a);
1311 }
1312
1313 return $allok;
1314}
1315
fd0537ce
TH
1316/**
1317 * Send the notification message when a quiz attempt becomes overdue.
1318 *
1319 * @param object $course the course
1320 * @param object $quiz the quiz
1321 * @param object $attempt this attempt just finished
1322 * @param object $context the quiz context
1323 * @param object $cm the coursemodule for this quiz
1324 */
1325function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
1326 global $CFG, $DB;
1327
1328 // Do nothing if required objects not present
1329 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1330 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1331 }
1332
1333 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1334
1335 if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
1336 return; // Message not required.
1337 }
1338
1339 // Prepare lots of useful information that admins might want to include in
1340 // the email message.
1341 $quizname = format_string($quiz->name);
1342
1343 $deadlines = array();
1344 if ($quiz->timelimit) {
1345 $deadlines[] = $attempt->timestart + $quiz->timelimit;
1346 }
1347 if ($quiz->timeclose) {
1348 $deadlines[] = $quiz->timeclose;
1349 }
59d14f31
TH
1350 $duedate = min($deadlines);
1351 $graceend = $duedate + $quiz->graceperiod;
fd0537ce
TH
1352
1353 $a = new stdClass();
1354 // Course info.
1355 $a->coursename = $course->fullname;
1356 $a->courseshortname = $course->shortname;
1357 // Quiz info.
1358 $a->quizname = $quizname;
1359 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1360 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1361 // Attempt info.
59d14f31
TH
1362 $a->attemptduedate = userdate($duedate);
1363 $a->attemptgraceend = userdate($graceend);
fd0537ce
TH
1364 $a->attemptsummaryurl = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
1365 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1366 // Student's info.
1367 $a->studentidnumber = $submitter->idnumber;
1368 $a->studentname = fullname($submitter);
1369 $a->studentusername = $submitter->username;
1370
1371 // Prepare the message.
1372 $eventdata = new stdClass();
1373 $eventdata->component = 'mod_quiz';
1374 $eventdata->name = 'attempt_overdue';
1375 $eventdata->notification = 1;
1376
1377 $eventdata->userfrom = get_admin();
1378 $eventdata->userto = $submitter;
1379 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1380 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1381 $eventdata->fullmessageformat = FORMAT_PLAIN;
1382 $eventdata->fullmessagehtml = '';
1383
1384 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1385 $eventdata->contexturl = $a->quizurl;
1386 $eventdata->contexturlname = $a->quizname;
1387
1388 // Send the message.
1389 return message_send($eventdata);
1390}
1391
cbb8b55c
TH
1392/**
1393 * Handle the quiz_attempt_submitted event.
1394 *
1395 * This sends the confirmation and notification messages, if required.
1396 *
1397 * @param object $event the event object.
1398 */
1399function quiz_attempt_submitted_handler($event) {
1400 global $DB;
1401
1402 $course = $DB->get_record('course', array('id' => $event->courseid));
1403 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1404 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1405 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1406
1407 if (!($course && $quiz && $cm && $attempt)) {
1408 // Something has been deleted since the event was raised. Therefore, the
1409 // event is no longer relevant.
1410 return true;
ac48e43a 1411 }
ac48e43a 1412
cbb8b55c
TH
1413 return quiz_send_notification_messages($course, $quiz, $attempt,
1414 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
ac48e43a 1415}
fa583f5f 1416
fd0537ce
TH
1417/**
1418 * Handle the quiz_attempt_overdue event.
1419 *
1420 * For quizzes with applicable settings, this sends a message to the user, reminding
1421 * them that they forgot to submit, and that they have another chance to do so.
1422 *
1423 * @param object $event the event object.
1424 */
1425function quiz_attempt_overdue_handler($event) {
1426 global $DB;
1427
1428 $course = $DB->get_record('course', array('id' => $event->courseid));
1429 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1430 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1431 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1432
1433 if (!($course && $quiz && $cm && $attempt)) {
1434 // Something has been deleted since the event was raised. Therefore, the
1435 // event is no longer relevant.
1436 return true;
1437 }
1438
1439 return quiz_send_overdue_message($course, $quiz, $attempt,
1440 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
1441}
1442
1443/**
1444 * Get the information about the standard quiz JavaScript module.
1445 * @return array a standard jsmodule structure.
1446 */
ff065f96 1447function quiz_get_js_module() {
157434a5 1448 global $PAGE;
73a7a0c9 1449
ff065f96
TH
1450 return array(
1451 'name' => 'mod_quiz',
1452 'fullpath' => '/mod/quiz/module.js',
25a03faa
TH
1453 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1454 'core_question_engine'),
ff065f96 1455 'strings' => array(
73a7a0c9 1456 array('cancel', 'moodle'),
a26246ea 1457 array('flagged', 'question'),
d755b0f5
TH
1458 array('functiondisabledbysecuremode', 'quiz'),
1459 array('startattempt', 'quiz'),
1460 array('timesup', 'quiz'),
ff065f96
TH
1461 ),
1462 );
fe6ce234 1463}
25302dee
TH
1464
1465
1466/**
1467 * An extension of question_display_options that includes the extra options used
1468 * by the quiz.
1469 *
f7970e3c
TH
1470 * @copyright 2010 The Open University
1471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee
TH
1472 */
1473class mod_quiz_display_options extends question_display_options {
1474 /**#@+
1475 * @var integer bits used to indicate various times in relation to a
1476 * quiz attempt.
1477 */
1478 const DURING = 0x10000;
1479 const IMMEDIATELY_AFTER = 0x01000;
1480 const LATER_WHILE_OPEN = 0x00100;
1481 const AFTER_CLOSE = 0x00010;
1482 /**#@-*/
1483
1484 /**
1485 * @var boolean if this is false, then the student is not allowed to review
1486 * anything about the attempt.
1487 */
1488 public $attempt = true;
1489
1490 /**
1491 * @var boolean if this is false, then the student is not allowed to review
1492 * anything about the attempt.
1493 */
1494 public $overallfeedback = self::VISIBLE;
1495
1496 /**
1497 * Set up the various options from the quiz settings, and a time constant.
0ff4bd08 1498 * @param object $quiz the quiz settings.
f7970e3c 1499 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
25302dee
TH
1500 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1501 * @return mod_quiz_display_options set up appropriately.
1502 */
1503 public static function make_from_quiz($quiz, $when) {
1504 $options = new self();
1505
1506 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1507 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
25a03faa
TH
1508 $options->marks = self::extract($quiz->reviewmarks, $when,
1509 self::MARK_AND_MAX, self::MAX_ONLY);
25302dee
TH
1510 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1511 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1512 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1513 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1514
1515 $options->numpartscorrect = $options->feedback;
1516
1517 if ($quiz->questiondecimalpoints != -1) {
1518 $options->markdp = $quiz->questiondecimalpoints;
1519 } else {
1520 $options->markdp = $quiz->decimalpoints;
1521 }
1522
1523 return $options;
1524 }
1525
25a03faa
TH
1526 protected static function extract($bitmask, $bit,
1527 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
25302dee
TH
1528 if ($bitmask & $bit) {
1529 return $whenset;
1530 } else {
1531 return $whennotset;
1532 }
1533 }
1534}
1535
1536
1537/**
1538 * A {@link qubaid_condition} for finding all the question usages belonging to
1539 * a particular quiz.
1540 *
f7970e3c
TH
1541 * @copyright 2010 The Open University
1542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee 1543 */
6b5f24d3 1544class qubaids_for_quiz extends qubaid_join {
25302dee 1545 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
6b5f24d3 1546 $where = 'quiza.quiz = :quizaquiz';
be18f589
TH
1547 $params = array('quizaquiz' => $quizid);
1548
25302dee
TH
1549 if (!$includepreviews) {
1550 $where .= ' AND preview = 0';
1551 }
be18f589 1552
25302dee 1553 if ($onlyfinished) {
be18f589
TH
1554 $where .= ' AND state == :statefinished';
1555 $params['statefinished'] = quiz_attempt::FINISHED;
25302dee
TH
1556 }
1557
be18f589 1558 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
25302dee
TH
1559 }
1560}