MDL-32633 quiz editing: recreate grade item when max changed from 0
[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
58
9e83f3d1 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
9e83f3d1 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
9e83f3d1 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
9e83f3d1 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
62a3bfb3
TH
474 $oldgrade = $quiz->grade;
475 $quiz->grade = $newgrade;
476
212b7b8c 477 // Use a transaction, so that on those databases that support it, this is safer.
d5a8d9aa
PS
478 $transaction = $DB->start_delegated_transaction();
479
0f1c59c5
TH
480 // Update the quiz table.
481 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
482
62a3bfb3
TH
483 if ($oldgrade < 1) {
484 // If the old grade was zero, we cannot rescale, we have to recompute.
485 // We also recompute if the old grade was too small to avoid underflow problems.
486 quiz_update_all_final_grades($quiz);
0f1c59c5 487
62a3bfb3
TH
488 } else {
489 // We can rescale the grades efficiently.
0f1c59c5
TH
490 $timemodified = time();
491 $DB->execute("
492 UPDATE {quiz_grades}
493 SET grade = ? * grade, timemodified = ?
494 WHERE quiz = ?
62a3bfb3
TH
495 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
496 }
0f1c59c5 497
62a3bfb3 498 if ($oldgrade > 1e-7) {
0f1c59c5 499 // Update the quiz_feedback table.
62a3bfb3 500 $factor = $newgrade/$oldgrade;
0f1c59c5
TH
501 $DB->execute("
502 UPDATE {quiz_feedback}
503 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
504 WHERE quizid = ?
505 ", array($factor, $factor, $quiz->id));
506 }
77ed3ba5 507
9e83f3d1 508 // Update grade item and send all grades to gradebook.
0f1c59c5
TH
509 quiz_grade_item_update($quiz);
510 quiz_update_grades($quiz);
d6dd2108 511
0f1c59c5
TH
512 $transaction->allow_commit();
513 return true;
212b7b8c 514}
515
516/**
517 * Save the overall grade for a user at a quiz in the quiz_grades table
518 *
519 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
f7970e3c 520 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
98f38217 521 * @param array $attempts The attempts of this user. Useful if you are
522 * looping through many users. Attempts can be fetched in one master query to
523 * avoid repeated querying.
f7970e3c 524 * @return bool Indicates success or failure.
212b7b8c 525 */
98f38217 526function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
cef18275 527 global $DB, $OUTPUT, $USER;
ee1fb969 528
212b7b8c 529 if (empty($userid)) {
ee1fb969 530 $userid = $USER->id;
531 }
76cacec8 532
25a03faa 533 if (!$attempts) {
9e83f3d1 534 // Get all the attempts made by the user.
25302dee 535 $attempts = quiz_get_user_attempts($quiz->id, $userid);
76cacec8 536 }
537
9e83f3d1 538 // Calculate the best grade.
76cacec8 539 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
84e628a0 540 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
77ed3ba5 541
9e83f3d1 542 // Save the best grade in the database.
25302dee
TH
543 if (is_null($bestgrade)) {
544 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
545
25a03faa
TH
546 } else if ($grade = $DB->get_record('quiz_grades',
547 array('quiz' => $quiz->id, 'userid' => $userid))) {
fc44ee0d 548 $grade->grade = $bestgrade;
76cacec8 549 $grade->timemodified = time();
a8c31db2 550 $DB->update_record('quiz_grades', $grade);
25302dee 551
76cacec8 552 } else {
b640e681 553 $grade = new stdClass();
76cacec8 554 $grade->quiz = $quiz->id;
555 $grade->userid = $userid;
fc44ee0d 556 $grade->grade = $bestgrade;
76cacec8 557 $grade->timemodified = time();
a8c31db2 558 $DB->insert_record('quiz_grades', $grade);
76cacec8 559 }
d6dd2108 560
561 quiz_update_grades($quiz, $userid);
76cacec8 562}
563
fc44ee0d 564/**
26d12a0c 565 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
566 *
13bbfebc
TH
567 * @param object $quiz the quiz settings object.
568 * @param array $attempts an array of all the user's attempts at this quiz in order.
569 * @return float the overall grade
26d12a0c 570 */
76cacec8 571function quiz_calculate_best_grade($quiz, $attempts) {
76cacec8 572
573 switch ($quiz->grademethod) {
574
ee1fb969 575 case QUIZ_ATTEMPTFIRST:
13bbfebc
TH
576 $firstattempt = reset($attempts);
577 return $firstattempt->sumgrades;
76cacec8 578
ee1fb969 579 case QUIZ_ATTEMPTLAST:
13bbfebc
TH
580 $lastattempt = end($attempts);
581 return $lastattempt->sumgrades;
76cacec8 582
ee1fb969 583 case QUIZ_GRADEAVERAGE:
76cacec8 584 $sum = 0;
585 $count = 0;
586 foreach ($attempts as $attempt) {
25302dee
TH
587 if (!is_null($attempt->sumgrades)) {
588 $sum += $attempt->sumgrades;
589 $count++;
590 }
76cacec8 591 }
25302dee
TH
592 if ($count == 0) {
593 return null;
594 }
595 return $sum / $count;
76cacec8 596
ee1fb969 597 case QUIZ_GRADEHIGHEST:
13bbfebc 598 default:
25302dee 599 $max = null;
76cacec8 600 foreach ($attempts as $attempt) {
601 if ($attempt->sumgrades > $max) {
602 $max = $attempt->sumgrades;
603 }
604 }
605 return $max;
606 }
607}
608
25302dee
TH
609/**
610 * Update the final grade at this quiz for all students.
611 *
612 * This function is equivalent to calling quiz_save_best_grade for all
613 * users, but much more efficient.
614 *
615 * @param object $quiz the quiz settings.
616 */
617function quiz_update_all_final_grades($quiz) {
618 global $DB;
619
620 if (!$quiz->sumgrades) {
621 return;
622 }
623
be18f589 624 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
25302dee
TH
625 $firstlastattemptjoin = "JOIN (
626 SELECT
627 iquiza.userid,
628 MIN(attempt) AS firstattempt,
629 MAX(attempt) AS lastattempt
630
e50a5813 631 FROM {quiz_attempts} iquiza
25302dee
TH
632
633 WHERE
07051106 634 iquiza.state = :istatefinished AND
25302dee
TH
635 iquiza.preview = 0 AND
636 iquiza.quiz = :iquizid
637
638 GROUP BY iquiza.userid
639 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
640
641 switch ($quiz->grademethod) {
642 case QUIZ_ATTEMPTFIRST:
81522abd 643 // Because of the where clause, there will only be one row, but we
25302dee
TH
644 // must still use an aggregate function.
645 $select = 'MAX(quiza.sumgrades)';
646 $join = $firstlastattemptjoin;
647 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
648 break;
649
650 case QUIZ_ATTEMPTLAST:
81522abd 651 // Because of the where clause, there will only be one row, but we
25302dee
TH
652 // must still use an aggregate function.
653 $select = 'MAX(quiza.sumgrades)';
654 $join = $firstlastattemptjoin;
655 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
656 break;
657
658 case QUIZ_GRADEAVERAGE:
659 $select = 'AVG(quiza.sumgrades)';
660 $join = '';
661 $where = '';
662 break;
663
664 default:
665 case QUIZ_GRADEHIGHEST:
666 $select = 'MAX(quiza.sumgrades)';
667 $join = '';
668 $where = '';
669 break;
670 }
671
672 if ($quiz->sumgrades >= 0.000005) {
673 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
674 } else {
675 $finalgrade = '0';
676 }
677 $param['quizid'] = $quiz->id;
678 $param['quizid2'] = $quiz->id;
679 $param['quizid3'] = $quiz->id;
680 $param['quizid4'] = $quiz->id;
be18f589
TH
681 $param['statefinished'] = quiz_attempt::FINISHED;
682 $param['statefinished2'] = quiz_attempt::FINISHED;
25302dee
TH
683 $finalgradesubquery = "
684 SELECT quiza.userid, $finalgrade AS newgrade
685 FROM {quiz_attempts} quiza
686 $join
687 WHERE
688 $where
a558acf9 689 quiza.state = :statefinished AND
25302dee
TH
690 quiza.preview = 0 AND
691 quiza.quiz = :quizid3
692 GROUP BY quiza.userid";
693
694 $changedgrades = $DB->get_records_sql("
695 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
696
697 FROM (
698 SELECT userid
699 FROM {quiz_grades} qg
700 WHERE quiz = :quizid
701 UNION
702 SELECT DISTINCT userid
703 FROM {quiz_attempts} quiza2
704 WHERE
a558acf9 705 quiza2.state = :statefinished2 AND
25302dee
TH
706 quiza2.preview = 0 AND
707 quiza2.quiz = :quizid2
708 ) users
709
710 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
711
712 LEFT JOIN (
713 $finalgradesubquery
714 ) newgrades ON newgrades.userid = users.userid
715
716 WHERE
717 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
f484a629
TH
718 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
719 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
720 // The mess on the previous line is detecting where the value is
721 // NULL in one column, and NOT NULL in the other, but SQL does
722 // not have an XOR operator, and MS SQL server can't cope with
723 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
a13d4fbd 724 $param);
25302dee
TH
725
726 $timenow = time();
727 $todelete = array();
728 foreach ($changedgrades as $changedgrade) {
729
730 if (is_null($changedgrade->newgrade)) {
731 $todelete[] = $changedgrade->userid;
732
733 } else if (is_null($changedgrade->grade)) {
0ff4bd08 734 $toinsert = new stdClass();
25302dee
TH
735 $toinsert->quiz = $quiz->id;
736 $toinsert->userid = $changedgrade->userid;
737 $toinsert->timemodified = $timenow;
738 $toinsert->grade = $changedgrade->newgrade;
739 $DB->insert_record('quiz_grades', $toinsert);
740
741 } else {
0ff4bd08 742 $toupdate = new stdClass();
25302dee
TH
743 $toupdate->id = $changedgrade->id;
744 $toupdate->grade = $changedgrade->newgrade;
745 $toupdate->timemodified = $timenow;
746 $DB->update_record('quiz_grades', $toupdate);
747 }
748 }
749
750 if (!empty($todelete)) {
e65f89b9 751 list($test, $params) = $DB->get_in_or_equal($todelete);
8d13ea83
TH
752 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
753 array_merge(array($quiz->id), $params));
25302dee
TH
754 }
755}
756
fc44ee0d 757/**
26d12a0c 758 * Return the attempt with the best grade for a quiz
759 *
760 * Which attempt is the best depends on $quiz->grademethod. If the grade
761 * method is GRADEAVERAGE then this function simply returns the last attempt.
762 * @return object The attempt with the best grade
763 * @param object $quiz The quiz for which the best grade is to be calculated
764 * @param array $attempts An array of all the attempts of the user at the quiz
765 */
76cacec8 766function quiz_calculate_best_attempt($quiz, $attempts) {
76cacec8 767
768 switch ($quiz->grademethod) {
769
ee1fb969 770 case QUIZ_ATTEMPTFIRST:
76cacec8 771 foreach ($attempts as $attempt) {
772 return $attempt;
773 }
774 break;
775
9e83f3d1 776 case QUIZ_GRADEAVERAGE: // We need to do something with it.
ee1fb969 777 case QUIZ_ATTEMPTLAST:
76cacec8 778 foreach ($attempts as $attempt) {
779 $final = $attempt;
780 }
781 return $final;
782
783 default:
ee1fb969 784 case QUIZ_GRADEHIGHEST:
76cacec8 785 $max = -1;
786 foreach ($attempts as $attempt) {
787 if ($attempt->sumgrades > $max) {
788 $max = $attempt->sumgrades;
789 $maxattempt = $attempt;
790 }
791 }
792 return $maxattempt;
793 }
794}
795
25302dee 796/**
87427d9c
TH
797 * @return array int => lang string the options for calculating the quiz grade
798 * from the individual attempt grades.
25302dee
TH
799 */
800function quiz_get_grading_options() {
801 return array(
802 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
803 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
804 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
805 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
806 );
807}
808
0675e5eb 809/**
25a03faa
TH
810 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
811 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
0675e5eb 812 * @return the lang string for that option.
813 */
814function quiz_get_grading_option_name($option) {
815 $strings = quiz_get_grading_options();
816 return $strings[$option];
817}
818
87427d9c
TH
819/**
820 * @return array string => lang string the options for handling overdue quiz
821 * attempts.
822 */
823function quiz_get_overdue_handling_options() {
824 return array(
825 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
826 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
827 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
828 );
829}
830
be18f589
TH
831/**
832 * @param string $state one of the state constants like IN_PROGRESS.
833 * @return string the human-readable state name.
834 */
835function quiz_attempt_state_name($state) {
836 switch ($state) {
837 case quiz_attempt::IN_PROGRESS:
838 return get_string('stateinprogress', 'quiz');
839 case quiz_attempt::OVERDUE:
840 return get_string('stateoverdue', 'quiz');
841 case quiz_attempt::FINISHED:
842 return get_string('statefinished', 'quiz');
843 case quiz_attempt::ABANDONED:
844 return get_string('stateabandoned', 'quiz');
845 default:
846 throw new coding_exception('Unknown quiz attempt state.');
847 }
848}
849
9e83f3d1 850// Other quiz functions ////////////////////////////////////////////////////////
ee1fb969 851
26a29b1a 852/**
2a874d65 853 * @param object $quiz the quiz.
f7970e3c 854 * @param int $cmid the course_module object for this quiz.
2a874d65 855 * @param object $question the question.
26a29b1a 856 * @param string $returnurl url to return to after action is done.
857 * @return string html for a number of icons linked to action pages for a
858 * question - preview and edit / view icons depending on user capabilities.
859 */
2a874d65 860function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
861 $html = quiz_question_preview_button($quiz, $question) . ' ' .
862 quiz_question_edit_button($cmid, $question, $returnurl);
863 return $html;
864}
865
866/**
f7970e3c 867 * @param int $cmid the course_module.id for this quiz.
2a874d65 868 * @param object $question the question.
869 * @param string $returnurl url to return to after action is done.
870 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
25a03faa
TH
871 * @return the HTML for an edit icon, view icon, or nothing for a question
872 * (depending on permissions).
2a874d65 873 */
d04f623b 874function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
d436d197 875 global $CFG, $OUTPUT;
2a874d65 876
877 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
26a29b1a 878 static $stredit = null;
879 static $strview = null;
25a03faa 880 if ($stredit === null) {
26a29b1a 881 $stredit = get_string('edit');
882 $strview = get_string('view');
883 }
2a874d65 884
885 // What sort of icon should we show?
886 $action = '';
25a03faa
TH
887 if (!empty($question->id) &&
888 (question_has_capability_on($question, 'edit', $question->category) ||
889 question_has_capability_on($question, 'move', $question->category))) {
2a874d65 890 $action = $stredit;
891 $icon = '/t/edit';
25a03faa
TH
892 } else if (!empty($question->id) &&
893 question_has_capability_on($question, 'view', $question->category)) {
2a874d65 894 $action = $strview;
895 $icon = '/i/info';
896 }
897
898 // Build the icon.
899 if ($action) {
47678d60 900 if ($returnurl instanceof moodle_url) {
a530d4a9 901 $returnurl = $returnurl->out_as_local_url(false);
47678d60 902 }
2a874d65 903 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
904 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
068384ce 905 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
d04f623b
TH
906 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
907 '</a>';
068384ce
TH
908 } else if ($contentaftericon) {
909 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
2a874d65 910 } else {
068384ce 911 return '';
26a29b1a 912 }
26a29b1a 913}
914
7d87171b 915/**
612106b3
TH
916 * @param object $quiz the quiz settings
917 * @param object $question the question
918 * @return moodle_url to preview this question with the options from this quiz.
919 */
920function quiz_question_preview_url($quiz, $question) {
921 // Get the appropriate display options.
922 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
923 mod_quiz_display_options::DURING);
924
925 $maxmark = null;
926 if (isset($question->maxmark)) {
927 $maxmark = $question->maxmark;
928 }
929
930 // Work out the correcte preview URL.
931 return question_preview_url($question->id, $quiz->preferredbehaviour,
932 $maxmark, $displayoptions);
933}
934
935/**
936 * @param object $quiz the quiz settings
7d87171b 937 * @param object $question the question
f7970e3c 938 * @param bool $label if true, show the preview question label after the icon
7d87171b 939 * @return the HTML for a preview question icon.
940 */
2a874d65 941function quiz_question_preview_button($quiz, $question, $label = false) {
56a4ae46 942 global $CFG, $OUTPUT;
2a874d65 943 if (!question_has_capability_on($question, 'use', $question->category)) {
271e6dec 944 return '';
945 }
2a874d65 946
612106b3 947 $url = quiz_question_preview_url($quiz, $question);
2a874d65 948
949 // Do we want a label?
25302dee 950 $strpreviewlabel = '';
2a874d65 951 if ($label) {
25302dee 952 $strpreviewlabel = get_string('preview', 'quiz');
fa583f5f 953 }
2a874d65 954
955 // Build the icon.
f9b0500f 956 $strpreviewquestion = get_string('previewquestion', 'quiz');
000c278c 957 $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
ca4b4f8f 958
612106b3
TH
959 $action = new popup_action('click', $url, 'questionpreview',
960 question_preview_popup_params());
4bcc5118 961
25302dee 962 return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
ad7e7ba8 963}
0d156caa 964
62e76c67 965/**
966 * @param object $attempt the attempt.
967 * @param object $context the quiz context.
f7970e3c 968 * @return int whether flags should be shown/editable to the current user for this attempt.
62e76c67 969 */
970function quiz_get_flag_option($attempt, $context) {
971 global $USER;
25302dee
TH
972 if (!has_capability('moodle/question:flag', $context)) {
973 return question_display_options::HIDDEN;
974 } else if ($attempt->userid == $USER->id) {
975 return question_display_options::EDITABLE;
976 } else {
977 return question_display_options::VISIBLE;
62e76c67 978 }
62e76c67 979}
980
4f48fb42 981/**
be18f589
TH
982 * Work out what state this quiz attempt is in - in the sense used by
983 * quiz_get_review_options, not in the sense of $attempt->state.
25302dee
TH
984 * @param object $quiz the quiz settings
985 * @param object $attempt the quiz_attempt database row.
f7970e3c 986 * @return int one of the mod_quiz_display_options::DURING,
25302dee 987 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
4dca7e51 988 */
25302dee 989function quiz_attempt_state($quiz, $attempt) {
be18f589 990 if ($attempt->state != quiz_attempt::FINISHED) {
25302dee
TH
991 return mod_quiz_display_options::DURING;
992 } else if (time() < $attempt->timefinish + 120) {
993 return mod_quiz_display_options::IMMEDIATELY_AFTER;
994 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
995 return mod_quiz_display_options::LATER_WHILE_OPEN;
996 } else {
997 return mod_quiz_display_options::AFTER_CLOSE;
998 }
4f48fb42 999}
1000
4f48fb42 1001/**
25302dee
TH
1002 * The the appropraite mod_quiz_display_options object for this attempt at this
1003 * quiz right now.
77ed3ba5 1004 *
cd06115f 1005 * @param object $quiz the quiz instance.
1006 * @param object $attempt the attempt in question.
25302dee 1007 * @param $context the quiz context.
77ed3ba5 1008 *
25302dee 1009 * @return mod_quiz_display_options
cd06115f 1010 */
7ee80cab 1011function quiz_get_review_options($quiz, $attempt, $context) {
25302dee 1012 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
62e76c67 1013
4f48fb42 1014 $options->readonly = true;
62e76c67 1015 $options->flags = quiz_get_flag_option($attempt, $context);
2709ee45
TH
1016 if (!empty($attempt->id)) {
1017 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1018 array('attempt' => $attempt->id));
1019 }
b6e907a2 1020
9e83f3d1 1021 // Show a link to the comment box only for closed attempts.
be18f589 1022 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
2709ee45 1023 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
25302dee 1024 $options->manualcomment = question_display_options::VISIBLE;
7ee80cab
TH
1025 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1026 array('attempt' => $attempt->id));
01600b51 1027 }
1028
25a03faa
TH
1029 if (!is_null($context) && !$attempt->preview &&
1030 has_capability('mod/quiz:viewreports', $context) &&
25302dee 1031 has_capability('moodle/grade:viewhidden', $context)) {
e2833e87 1032 // People who can see reports and hidden grades should be shown everything,
1033 // except during preview when teachers want to see what students see.
25302dee
TH
1034 $options->attempt = question_display_options::VISIBLE;
1035 $options->correctness = question_display_options::VISIBLE;
1036 $options->marks = question_display_options::MARK_AND_MAX;
1037 $options->feedback = question_display_options::VISIBLE;
1038 $options->numpartscorrect = question_display_options::VISIBLE;
1039 $options->generalfeedback = question_display_options::VISIBLE;
1040 $options->rightanswer = question_display_options::VISIBLE;
1041 $options->overallfeedback = question_display_options::VISIBLE;
1042 $options->history = question_display_options::VISIBLE;
e2833e87 1043
4f48fb42 1044 }
77ed3ba5 1045
4f48fb42 1046 return $options;
1047}
77ed3ba5 1048
40377b18 1049/**
77ed3ba5 1050 * Combines the review options from a number of different quiz attempts.
25302dee 1051 * Returns an array of two ojects, so the suggested way of calling this
77ed3ba5 1052 * funciton is:
1053 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1054 *
1055 * @param object $quiz the quiz instance.
1056 * @param array $attempts an array of attempt objects.
1057 * @param $context the roles and permissions context,
1058 * normally the context for the quiz module instance.
1059 *
1060 * @return array of two options objects, one showing which options are true for
1061 * at least one of the attempts, the other showing which options are true
1062 * for all attempts.
1063 */
25302dee 1064function quiz_get_combined_reviewoptions($quiz, $attempts) {
6d03fd98 1065 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
0ff4bd08
TH
1066 $someoptions = new stdClass();
1067 $alloptions = new stdClass();
77ed3ba5 1068 foreach ($fields as $field) {
1069 $someoptions->$field = false;
1070 $alloptions->$field = true;
40377b18 1071 }
6d03fd98
TH
1072 $someoptions->marks = question_display_options::HIDDEN;
1073 $alloptions->marks = question_display_options::MARK_AND_MAX;
1074
77ed3ba5 1075 foreach ($attempts as $attempt) {
25302dee
TH
1076 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1077 quiz_attempt_state($quiz, $attempt));
7d014bf5 1078 foreach ($fields as $field) {
1079 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1080 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1081 }
6d03fd98
TH
1082 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1083 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
77ed3ba5 1084 }
1085 return array($someoptions, $alloptions);
40377b18 1086}
ac48e43a 1087
25302dee
TH
1088/**
1089 * Clean the question layout from various possible anomalies:
1090 * - Remove consecutive ","'s
1091 * - Remove duplicate question id's
1092 * - Remove extra "," from beginning and end
1093 * - Finally, add a ",0" in the end if there is none
1094 *
1095 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
f7970e3c 1096 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
25302dee
TH
1097 * @return $string the cleaned-up layout
1098 */
1099function quiz_clean_layout($layout, $removeemptypages = false) {
1100 // Remove repeated ','s. This can happen when a restore fails to find the right
1101 // id to relink to.
1102 $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1103
9e83f3d1 1104 // Remove duplicate question ids.
25302dee
TH
1105 $layout = explode(',', $layout);
1106 $cleanerlayout = array();
1107 $seen = array();
1108 foreach ($layout as $item) {
1109 if ($item == 0) {
1110 $cleanerlayout[] = '0';
1111 } else if (!in_array($item, $seen)) {
1112 $cleanerlayout[] = $item;
1113 $seen[] = $item;
1114 }
1115 }
1116
1117 if ($removeemptypages) {
9e83f3d1 1118 // Avoid duplicate page breaks.
25302dee
TH
1119 $layout = $cleanerlayout;
1120 $cleanerlayout = array();
1121 $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1122 foreach ($layout as $item) {
1123 if ($stripfollowingbreaks && $item == 0) {
1124 continue;
1125 }
1126 $cleanerlayout[] = $item;
1127 $stripfollowingbreaks = $item == 0;
1128 }
1129 }
1130
9e83f3d1 1131 // Add a page break at the end if there is none.
25302dee
TH
1132 if (end($cleanerlayout) !== '0') {
1133 $cleanerlayout[] = '0';
1134 }
1135
1136 return implode(',', $cleanerlayout);
1137}
1138
1139/**
1140 * Get the slot for a question with a particular id.
1141 * @param object $quiz the quiz settings.
f7970e3c
TH
1142 * @param int $questionid the of a question in the quiz.
1143 * @return int the corresponding slot. Null if the question is not in the quiz.
25302dee
TH
1144 */
1145function quiz_get_slot_for_question($quiz, $questionid) {
1146 $questionids = quiz_questions_in_quiz($quiz->questions);
1147 foreach (explode(',', $questionids) as $key => $id) {
1148 if ($id == $questionid) {
1149 return $key + 1;
1150 }
1151 }
1152 return null;
1153}
1154
9e83f3d1 1155// Functions for sending notification messages /////////////////////////////////
ac48e43a 1156
1157/**
cbb8b55c 1158 * Sends a confirmation message to the student confirming that the attempt was processed.
ac48e43a 1159 *
cbb8b55c
TH
1160 * @param object $a lots of useful information that can be used in the message
1161 * subject and body.
ac48e43a 1162 *
cbb8b55c 1163 * @return int|false as for {@link message_send()}.
ac48e43a 1164 */
cbb8b55c 1165function quiz_send_confirmation($recipient, $a) {
ac48e43a 1166
9e83f3d1 1167 // Add information about the recipient to $a.
cbb8b55c
TH
1168 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1169 $a->username = fullname($recipient);
1170 $a->userusername = $recipient->username;
ac48e43a 1171
9e83f3d1 1172 // Prepare the message.
39790bd8 1173 $eventdata = new stdClass();
cbb8b55c
TH
1174 $eventdata->component = 'mod_quiz';
1175 $eventdata->name = 'confirmation';
94263cca
AD
1176 $eventdata->notification = 1;
1177
3b120e46 1178 $eventdata->userfrom = get_admin();
cbb8b55c
TH
1179 $eventdata->userto = $recipient;
1180 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1181 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
3b120e46 1182 $eventdata->fullmessageformat = FORMAT_PLAIN;
1183 $eventdata->fullmessagehtml = '';
94263cca
AD
1184
1185 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1186 $eventdata->contexturl = $a->quizurl;
1187 $eventdata->contexturlname = $a->quizname;
99d19c13 1188
cbb8b55c
TH
1189 // ... and send it.
1190 return message_send($eventdata);
ac48e43a 1191}
1192
1193/**
bc68fc9a 1194 * Sends notification messages to the interested parties that assign the role capability
ac48e43a 1195 *
1196 * @param object $recipient user object of the intended recipient
0ff4bd08 1197 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1198 *
cbb8b55c 1199 * @return int|false as for {@link message_send()}.
ac48e43a 1200 */
cbb8b55c 1201function quiz_send_notification($recipient, $submitter, $a) {
ac48e43a 1202
9e83f3d1 1203 // Recipient info for template.
cbb8b55c
TH
1204 $a->useridnumber = $recipient->idnumber;
1205 $a->username = fullname($recipient);
ac48e43a 1206 $a->userusername = $recipient->username;
ac48e43a 1207
9e83f3d1 1208 // Prepare the message.
39790bd8 1209 $eventdata = new stdClass();
cbb8b55c
TH
1210 $eventdata->component = 'mod_quiz';
1211 $eventdata->name = 'submission';
bc68fc9a
AD
1212 $eventdata->notification = 1;
1213
cbb8b55c 1214 $eventdata->userfrom = $submitter;
3b120e46 1215 $eventdata->userto = $recipient;
cbb8b55c
TH
1216 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1217 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
3b120e46 1218 $eventdata->fullmessageformat = FORMAT_PLAIN;
1219 $eventdata->fullmessagehtml = '';
bc68fc9a
AD
1220
1221 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1222 $eventdata->contexturl = $a->quizreviewurl;
1223 $eventdata->contexturlname = $a->quizname;
1224
cbb8b55c
TH
1225 // ... and send it.
1226 return message_send($eventdata);
ac48e43a 1227}
1228
1229/**
cbb8b55c 1230 * Send all the requried messages when a quiz attempt is submitted.
ac48e43a 1231 *
1232 * @param object $course the course
1233 * @param object $quiz the quiz
1234 * @param object $attempt this attempt just finished
1235 * @param object $context the quiz context
1236 * @param object $cm the coursemodule for this quiz
1237 *
cbb8b55c 1238 * @return bool true if all necessary messages were sent successfully, else false.
ac48e43a 1239 */
cbb8b55c
TH
1240function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1241 global $CFG, $DB;
ac48e43a 1242
9e83f3d1 1243 // Do nothing if required objects not present.
ac48e43a 1244 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
cbb8b55c 1245 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
ac48e43a 1246 }
1247
cbb8b55c
TH
1248 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1249
9e83f3d1 1250 // Check for confirmation required.
ac48e43a 1251 $sendconfirm = false;
1252 $notifyexcludeusers = '';
cbb8b55c
TH
1253 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1254 $notifyexcludeusers = $submitter->id;
ac48e43a 1255 $sendconfirm = true;
1256 }
1257
9e83f3d1 1258 // Check for notifications required.
d8aa5ec7 1259 $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
cbb8b55c
TH
1260 'u.lang, u.timezone, u.mailformat, u.maildisplay';
1261 $groups = groups_get_all_groups($course->id, $submitter->id);
5a128471 1262 if (is_array($groups) && count($groups) > 0) {
1263 $groups = array_keys($groups);
255985f1 1264 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1265 // If the user is not in a group, and the quiz is set to group mode,
cbb8b55c 1266 // then set $groups to a non-existant id so that only users with
255985f1 1267 // 'moodle/site:accessallgroups' get notified.
1268 $groups = -1;
5a128471 1269 } else {
1270 $groups = '';
1271 }
ac48e43a 1272 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
5a128471 1273 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
ac48e43a 1274
cbb8b55c
TH
1275 if (empty($userstonotify) && !$sendconfirm) {
1276 return true; // Nothing to do.
ac48e43a 1277 }
1278
cbb8b55c 1279 $a = new stdClass();
9e83f3d1 1280 // Course info.
cbb8b55c
TH
1281 $a->coursename = $course->fullname;
1282 $a->courseshortname = $course->shortname;
9e83f3d1 1283 // Quiz info.
cbb8b55c
TH
1284 $a->quizname = $quiz->name;
1285 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1286 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1287 format_string($quiz->name) . ' report</a>';
cbb8b55c
TH
1288 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1289 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
9e83f3d1 1290 // Attempt info.
cbb8b55c
TH
1291 $a->submissiontime = userdate($attempt->timefinish);
1292 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
fd0537ce
TH
1293 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1294 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1295 format_string($quiz->name) . ' review</a>';
9e83f3d1 1296 // Student who sat the quiz info.
cbb8b55c
TH
1297 $a->studentidnumber = $submitter->idnumber;
1298 $a->studentname = fullname($submitter);
1299 $a->studentusername = $submitter->username;
1300
1301 $allok = true;
1302
9e83f3d1 1303 // Send notifications if required.
ac48e43a 1304 if (!empty($userstonotify)) {
ac48e43a 1305 foreach ($userstonotify as $recipient) {
cbb8b55c 1306 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
ac48e43a 1307 }
1308 }
1309
cbb8b55c
TH
1310 // Send confirmation if required. We send the student confirmation last, so
1311 // that if message sending is being intermittently buggy, which means we send
1312 // some but not all messages, and then try again later, then teachers may get
1313 // duplicate messages, but the student will always get exactly one.
1314 if ($sendconfirm) {
1315 $allok = $allok && quiz_send_confirmation($submitter, $a);
1316 }
1317
1318 return $allok;
1319}
1320
fd0537ce
TH
1321/**
1322 * Send the notification message when a quiz attempt becomes overdue.
1323 *
1324 * @param object $course the course
1325 * @param object $quiz the quiz
1326 * @param object $attempt this attempt just finished
1327 * @param object $context the quiz context
1328 * @param object $cm the coursemodule for this quiz
1329 */
1330function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
1331 global $CFG, $DB;
1332
9e83f3d1 1333 // Do nothing if required objects not present.
fd0537ce
TH
1334 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1335 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1336 }
1337
1338 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1339
1340 if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
1341 return; // Message not required.
1342 }
1343
1344 // Prepare lots of useful information that admins might want to include in
1345 // the email message.
1346 $quizname = format_string($quiz->name);
1347
1348 $deadlines = array();
1349 if ($quiz->timelimit) {
1350 $deadlines[] = $attempt->timestart + $quiz->timelimit;
1351 }
1352 if ($quiz->timeclose) {
1353 $deadlines[] = $quiz->timeclose;
1354 }
59d14f31
TH
1355 $duedate = min($deadlines);
1356 $graceend = $duedate + $quiz->graceperiod;
fd0537ce
TH
1357
1358 $a = new stdClass();
1359 // Course info.
1360 $a->coursename = $course->fullname;
1361 $a->courseshortname = $course->shortname;
1362 // Quiz info.
1363 $a->quizname = $quizname;
1364 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1365 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1366 // Attempt info.
59d14f31
TH
1367 $a->attemptduedate = userdate($duedate);
1368 $a->attemptgraceend = userdate($graceend);
fd0537ce
TH
1369 $a->attemptsummaryurl = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
1370 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1371 // Student's info.
1372 $a->studentidnumber = $submitter->idnumber;
1373 $a->studentname = fullname($submitter);
1374 $a->studentusername = $submitter->username;
1375
1376 // Prepare the message.
1377 $eventdata = new stdClass();
1378 $eventdata->component = 'mod_quiz';
1379 $eventdata->name = 'attempt_overdue';
1380 $eventdata->notification = 1;
1381
1382 $eventdata->userfrom = get_admin();
1383 $eventdata->userto = $submitter;
1384 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1385 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1386 $eventdata->fullmessageformat = FORMAT_PLAIN;
1387 $eventdata->fullmessagehtml = '';
1388
1389 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1390 $eventdata->contexturl = $a->quizurl;
1391 $eventdata->contexturlname = $a->quizname;
1392
1393 // Send the message.
1394 return message_send($eventdata);
1395}
1396
cbb8b55c
TH
1397/**
1398 * Handle the quiz_attempt_submitted event.
1399 *
1400 * This sends the confirmation and notification messages, if required.
1401 *
1402 * @param object $event the event object.
1403 */
1404function quiz_attempt_submitted_handler($event) {
1405 global $DB;
1406
1407 $course = $DB->get_record('course', array('id' => $event->courseid));
1408 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1409 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1410 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1411
1412 if (!($course && $quiz && $cm && $attempt)) {
1413 // Something has been deleted since the event was raised. Therefore, the
1414 // event is no longer relevant.
1415 return true;
ac48e43a 1416 }
ac48e43a 1417
cbb8b55c
TH
1418 return quiz_send_notification_messages($course, $quiz, $attempt,
1419 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
ac48e43a 1420}
fa583f5f 1421
fd0537ce
TH
1422/**
1423 * Handle the quiz_attempt_overdue event.
1424 *
1425 * For quizzes with applicable settings, this sends a message to the user, reminding
1426 * them that they forgot to submit, and that they have another chance to do so.
1427 *
1428 * @param object $event the event object.
1429 */
1430function quiz_attempt_overdue_handler($event) {
1431 global $DB;
1432
1433 $course = $DB->get_record('course', array('id' => $event->courseid));
1434 $quiz = $DB->get_record('quiz', array('id' => $event->quizid));
1435 $cm = get_coursemodule_from_id('quiz', $event->cmid, $event->courseid);
1436 $attempt = $DB->get_record('quiz_attempts', array('id' => $event->attemptid));
1437
1438 if (!($course && $quiz && $cm && $attempt)) {
1439 // Something has been deleted since the event was raised. Therefore, the
1440 // event is no longer relevant.
1441 return true;
1442 }
1443
1444 return quiz_send_overdue_message($course, $quiz, $attempt,
1445 get_context_instance(CONTEXT_MODULE, $cm->id), $cm);
1446}
1447
1448/**
1449 * Get the information about the standard quiz JavaScript module.
1450 * @return array a standard jsmodule structure.
1451 */
ff065f96 1452function quiz_get_js_module() {
157434a5 1453 global $PAGE;
73a7a0c9 1454
ff065f96
TH
1455 return array(
1456 'name' => 'mod_quiz',
1457 'fullpath' => '/mod/quiz/module.js',
25a03faa
TH
1458 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
1459 'core_question_engine'),
ff065f96 1460 'strings' => array(
73a7a0c9 1461 array('cancel', 'moodle'),
a26246ea 1462 array('flagged', 'question'),
d755b0f5
TH
1463 array('functiondisabledbysecuremode', 'quiz'),
1464 array('startattempt', 'quiz'),
1465 array('timesup', 'quiz'),
ff065f96
TH
1466 ),
1467 );
fe6ce234 1468}
25302dee
TH
1469
1470
1471/**
1472 * An extension of question_display_options that includes the extra options used
1473 * by the quiz.
1474 *
f7970e3c
TH
1475 * @copyright 2010 The Open University
1476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee
TH
1477 */
1478class mod_quiz_display_options extends question_display_options {
1479 /**#@+
1480 * @var integer bits used to indicate various times in relation to a
1481 * quiz attempt.
1482 */
1483 const DURING = 0x10000;
1484 const IMMEDIATELY_AFTER = 0x01000;
1485 const LATER_WHILE_OPEN = 0x00100;
1486 const AFTER_CLOSE = 0x00010;
1487 /**#@-*/
1488
1489 /**
1490 * @var boolean if this is false, then the student is not allowed to review
1491 * anything about the attempt.
1492 */
1493 public $attempt = true;
1494
1495 /**
1496 * @var boolean if this is false, then the student is not allowed to review
1497 * anything about the attempt.
1498 */
1499 public $overallfeedback = self::VISIBLE;
1500
1501 /**
1502 * Set up the various options from the quiz settings, and a time constant.
0ff4bd08 1503 * @param object $quiz the quiz settings.
f7970e3c 1504 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
25302dee
TH
1505 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1506 * @return mod_quiz_display_options set up appropriately.
1507 */
1508 public static function make_from_quiz($quiz, $when) {
1509 $options = new self();
1510
1511 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1512 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
25a03faa
TH
1513 $options->marks = self::extract($quiz->reviewmarks, $when,
1514 self::MARK_AND_MAX, self::MAX_ONLY);
25302dee
TH
1515 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1516 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1517 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1518 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1519
1520 $options->numpartscorrect = $options->feedback;
1521
1522 if ($quiz->questiondecimalpoints != -1) {
1523 $options->markdp = $quiz->questiondecimalpoints;
1524 } else {
1525 $options->markdp = $quiz->decimalpoints;
1526 }
1527
1528 return $options;
1529 }
1530
25a03faa
TH
1531 protected static function extract($bitmask, $bit,
1532 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
25302dee
TH
1533 if ($bitmask & $bit) {
1534 return $whenset;
1535 } else {
1536 return $whennotset;
1537 }
1538 }
1539}
1540
1541
1542/**
1543 * A {@link qubaid_condition} for finding all the question usages belonging to
1544 * a particular quiz.
1545 *
f7970e3c
TH
1546 * @copyright 2010 The Open University
1547 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee 1548 */
6b5f24d3 1549class qubaids_for_quiz extends qubaid_join {
25302dee 1550 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
6b5f24d3 1551 $where = 'quiza.quiz = :quizaquiz';
be18f589
TH
1552 $params = array('quizaquiz' => $quizid);
1553
25302dee
TH
1554 if (!$includepreviews) {
1555 $where .= ' AND preview = 0';
1556 }
be18f589 1557
25302dee 1558 if ($onlyfinished) {
be18f589
TH
1559 $where .= ' AND state == :statefinished';
1560 $params['statefinished'] = quiz_attempt::FINISHED;
25302dee
TH
1561 }
1562
be18f589 1563 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
25302dee
TH
1564 }
1565}