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