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