MDL-52455 quiz: doesn't include all user fields required by messaging
[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 *
01773a6d 26 * @package mod_quiz
ba643847
TH
27 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26d12a0c 29 */
76cacec8 30
66d07f81 31
a17b297d
TH
32defined('MOODLE_INTERNAL') || die();
33
26d12a0c 34require_once($CFG->dirroot . '/mod/quiz/lib.php');
ea38245c 35require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
987c2d49 36require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
39759ac4 37require_once($CFG->dirroot . '/mod/quiz/renderer.php');
78e7a3dd 38require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
3b120e46 39require_once($CFG->libdir . '/eventslib.php');
99d19c13 40require_once($CFG->libdir . '/filelib.php');
16fa272e 41require_once($CFG->libdir . '/questionlib.php');
76cacec8 42
76cacec8 43
c52c62d1 44/**
9e83f3d1 45 * @var int We show the countdown timer if there is less than this amount of time left before the
c52c62d1 46 * the quiz close date. (1 hour)
47 */
48define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
49
34b7d838
TH
50/**
51 * @var int If there are fewer than this many seconds left when the student submits
52 * a page of the quiz, then do not take them to the next page of the quiz. Instead
53 * close the quiz immediately.
54 */
55define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
56
1ecd3c30
JA
57/**
58 * @var int We show no image when user selects No image from dropdown menu in quiz settings.
59 */
60define('QUIZ_SHOWIMAGE_NONE', 0);
61
62/**
63 * @var int We show small image when user selects small image from dropdown menu in quiz settings.
64 */
65define('QUIZ_SHOWIMAGE_SMALL', 1);
66
67/**
68 * @var int We show Large image when user selects Large image from dropdown menu in quiz settings.
69 */
70define('QUIZ_SHOWIMAGE_LARGE', 2);
71
34b7d838 72
9e83f3d1 73// Functions related to attempts ///////////////////////////////////////////////
ee1fb969 74
75/**
26d12a0c 76 * Creates an object to represent a new attempt at a quiz
77 *
78 * Creates an attempt object to represent an attempt at the quiz by the current
79 * user starting at the current time. The ->id field is not set. The object is
80 * NOT written to the database.
c52c62d1 81 *
8e771aed 82 * @param object $quizobj the quiz object to create an attempt for.
f7970e3c 83 * @param int $attemptnumber the sequence number for the attempt.
c52c62d1 84 * @param object $lastattempt the previous attempt by this user, if any. Only needed
85 * if $attemptnumber > 1 and $quiz->attemptonlast is true.
f7970e3c
TH
86 * @param int $timenow the time the attempt was started at.
87 * @param bool $ispreview whether this new attempt is a preview.
70782526 88 * @param int $userid the id of the user attempting this quiz.
c52c62d1 89 *
90 * @return object the newly created attempt object.
26d12a0c 91 */
70782526 92function quiz_create_attempt(quiz $quizobj, $attemptnumber, $lastattempt, $timenow, $ispreview = false, $userid = null) {
c52c62d1 93 global $USER;
ee1fb969 94
70782526
JP
95 if ($userid === null) {
96 $userid = $USER->id;
97 }
98
8e771aed 99 $quiz = $quizobj->get_quiz();
18dff757
TH
100 if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
101 throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
ba3fedfb
TH
102 new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
103 array('grade' => quiz_format_grade($quiz, $quiz->grade)));
18dff757
TH
104 }
105
e89e09d2 106 if ($attemptnumber == 1 || !$quiz->attemptonlast) {
25a03faa 107 // We are not building on last attempt so create a new attempt.
0ff4bd08 108 $attempt = new stdClass();
75e1df6f 109 $attempt->quiz = $quiz->id;
70782526 110 $attempt->userid = $userid;
75e1df6f 111 $attempt->preview = 0;
ccba5b88 112 $attempt->layout = '';
c52c62d1 113 } else {
25a03faa 114 // Build on last attempt.
c52c62d1 115 if (empty($lastattempt)) {
5a2a5331 116 print_error('cannotfindprevattempt', 'quiz');
c52c62d1 117 }
118 $attempt = $lastattempt;
75e1df6f 119 }
120
ee1fb969 121 $attempt->attempt = $attemptnumber;
ee1fb969 122 $attempt->timestart = $timenow;
123 $attempt->timefinish = 0;
124 $attempt->timemodified = $timenow;
be18f589 125 $attempt->state = quiz_attempt::IN_PROGRESS;
cd5be9a5
MG
126 $attempt->currentpage = 0;
127 $attempt->sumgrades = null;
75e1df6f 128
25a03faa 129 // If this is a preview, mark it as such.
c52c62d1 130 if ($ispreview) {
131 $attempt->preview = 1;
132 }
133
8e771aed
MP
134 $timeclose = $quizobj->get_access_manager($timenow)->get_end_time($attempt);
135 if ($timeclose === false || $ispreview) {
136 $attempt->timecheckstate = null;
137 } else {
138 $attempt->timecheckstate = $timeclose;
139 }
140
ee1fb969 141 return $attempt;
142}
1cd7c92e
JP
143/**
144 * Start a normal, new, quiz attempt.
145 *
c2b051c7
JP
146 * @param quiz $quizobj the quiz object to start an attempt for.
147 * @param question_usage_by_activity $quba
148 * @param object $attempt
149 * @param integer $attemptnumber starting from 1
150 * @param integer $timenow the attempt start time
151 * @param array $questionids slot number => question id. Used for random questions, to force the choice
152 * of a particular actual question. Intended for testing purposes only.
153 * @param array $forcedvariantsbyslot slot number => variant. Used for questions with variants,
154 * to force the choice of a particular variant. Intended for testing
155 * purposes only.
c2f2e7f0 156 * @throws moodle_exception
c2b051c7 157 * @return object modified attempt object
1cd7c92e 158 */
c2b051c7
JP
159function quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,
160 $questionids = array(), $forcedvariantsbyslot = array()) {
bb93fc24
TH
161
162 // Usages for this user's previous quiz attempts.
163 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
164 $quizobj->get_quizid(), $attempt->userid);
165
1cd7c92e
JP
166 // Fully load all the questions in this quiz.
167 $quizobj->preload_questions();
168 $quizobj->load_questions();
169
bb93fc24
TH
170 // First load all the non-random questions.
171 $randomfound = false;
172 $slot = 0;
173 $questions = array();
174 $maxmark = array();
5d949702 175 $page = array();
ccba5b88 176 foreach ($quizobj->get_questions() as $questiondata) {
bb93fc24
TH
177 $slot += 1;
178 $maxmark[$slot] = $questiondata->maxmark;
5d949702 179 $page[$slot] = $questiondata->page;
bb93fc24
TH
180 if ($questiondata->qtype == 'random') {
181 $randomfound = true;
182 continue;
183 }
184 if (!$quizobj->get_quiz()->shuffleanswers) {
185 $questiondata->options->shuffleanswers = false;
186 }
187 $questions[$slot] = question_bank::make_question($questiondata);
188 }
1cd7c92e 189
bb93fc24
TH
190 // Then find a question to go in place of each random question.
191 if ($randomfound) {
192 $slot = 0;
193 $usedquestionids = array();
194 foreach ($questions as $question) {
195 if (isset($usedquestions[$question->id])) {
196 $usedquestionids[$question->id] += 1;
c2f2e7f0 197 } else {
bb93fc24
TH
198 $usedquestionids[$question->id] = 1;
199 }
200 }
201 $randomloader = new \core_question\bank\random_question_loader($qubaids, $usedquestionids);
202
203 foreach ($quizobj->get_questions() as $questiondata) {
204 $slot += 1;
205 if ($questiondata->qtype != 'random') {
206 continue;
207 }
208
209 // Deal with fixed random choices for testing.
210 if (isset($questionids[$quba->next_slot_number()])) {
211 if ($randomloader->is_question_available($questiondata->category,
212 (bool) $questiondata->questiontext, $questionids[$quba->next_slot_number()])) {
213 $questions[$slot] = question_bank::load_question(
214 $questionids[$quba->next_slot_number()], $quizobj->get_quiz()->shuffleanswers);
215 continue;
216 } else {
217 throw new coding_exception('Forced question id not available.');
218 }
c2f2e7f0
JP
219 }
220
bb93fc24
TH
221 // Normal case, pick one at random.
222 $questionid = $randomloader->get_next_question_id($questiondata->category,
223 (bool) $questiondata->questiontext);
224 if ($questionid === null) {
1cd7c92e
JP
225 throw new moodle_exception('notenoughrandomquestions', 'quiz',
226 $quizobj->view_url(), $questiondata);
227 }
bb93fc24
TH
228
229 $questions[$slot] = question_bank::load_question($questionid,
230 $quizobj->get_quiz()->shuffleanswers);
1cd7c92e 231 }
bb93fc24 232 }
1cd7c92e 233
bb93fc24
TH
234 // Finally add them all to the usage.
235 ksort($questions);
236 foreach ($questions as $slot => $question) {
237 $newslot = $quba->add_question($question, $maxmark[$slot]);
238 if ($newslot != $slot) {
239 throw new coding_exception('Slot numbers have got confused.');
240 }
1cd7c92e
JP
241 }
242
243 // Start all the questions.
bb93fc24 244 $variantstrategy = new core_question\engine\variants\least_used_strategy($quba, $qubaids);
c2b051c7
JP
245
246 if (!empty($forcedvariantsbyslot)) {
247 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
248 $forcedvariantsbyslot, $quba);
249 $variantstrategy = new question_variant_forced_choices_selection_strategy(
250 $forcedvariantsbyseed, $variantstrategy);
251 }
252
253 $quba->start_all_questions($variantstrategy, $timenow);
1cd7c92e 254
ccba5b88 255 // Work out the attempt layout.
5d949702
K
256 $sections = $quizobj->get_sections();
257 foreach ($sections as $i => $section) {
258 if (isset($sections[$i + 1])) {
259 $sections[$i]->lastslot = $sections[$i + 1]->firstslot - 1;
260 } else {
261 $sections[$i]->lastslot = count($questions);
262 }
263 }
264
ccba5b88 265 $layout = array();
5d949702
K
266 foreach ($sections as $section) {
267 if ($section->shufflequestions) {
268 $questionsinthissection = array();
269 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
270 $questionsinthissection[] = $slot;
271 }
272 shuffle($questionsinthissection);
273 $questionsonthispage = 0;
274 foreach ($questionsinthissection as $slot) {
275 if ($questionsonthispage && $questionsonthispage == $quizobj->get_quiz()->questionsperpage) {
276 $layout[] = 0;
277 $questionsonthispage = 0;
278 }
279 $layout[] = $slot;
280 $questionsonthispage += 1;
ccba5b88 281 }
ccba5b88 282
5d949702
K
283 } else {
284 $currentpage = $page[$section->firstslot];
285 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
286 if ($currentpage !== null && $page[$slot] != $currentpage) {
287 $layout[] = 0;
288 }
289 $layout[] = $slot;
290 $currentpage = $page[$slot];
ccba5b88 291 }
1cd7c92e 292 }
ccba5b88 293
5d949702
K
294 // Each section ends with a page break.
295 $layout[] = 0;
296 }
ccba5b88
TH
297 $attempt->layout = implode(',', $layout);
298
1cd7c92e
JP
299 return $attempt;
300}
301
302/**
303 * Start a subsequent new attempt, in each attempt builds on last mode.
304 *
305 * @param question_usage_by_activity $quba this question usage
306 * @param object $attempt this attempt
307 * @param object $lastattempt last attempt
308 * @return object modified attempt object
309 *
310 */
311function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
312 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
313
314 $oldnumberstonew = array();
315 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
316 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
317
318 $quba->start_question_based_on($newslot, $oldqa);
319
320 $oldnumberstonew[$oldslot] = $newslot;
321 }
322
323 // Update attempt layout.
324 $newlayout = array();
325 foreach (explode(',', $lastattempt->layout) as $oldslot) {
326 if ($oldslot != 0) {
327 $newlayout[] = $oldnumberstonew[$oldslot];
328 } else {
329 $newlayout[] = 0;
330 }
331 }
332 $attempt->layout = implode(',', $newlayout);
333 return $attempt;
334}
335
336/**
337 * The save started question usage and quiz attempt in db and log the started attempt.
338 *
339 * @param quiz $quizobj
340 * @param question_usage_by_activity $quba
341 * @param object $attempt
342 * @return object attempt object with uniqueid and id set.
343 */
344function quiz_attempt_save_started($quizobj, $quba, $attempt) {
345 global $DB;
346 // Save the attempt in the database.
347 question_engine::save_questions_usage_by_activity($quba);
348 $attempt->uniqueid = $quba->get_id();
349 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
a2caf56d
MN
350
351 // Params used by the events below.
352 $params = array(
353 'objectid' => $attempt->id,
354 'relateduserid' => $attempt->userid,
355 'courseid' => $quizobj->get_courseid(),
356 'context' => $quizobj->get_context()
357 );
358 // Decide which event we are using.
1cd7c92e 359 if ($attempt->preview) {
a2caf56d
MN
360 $params['other'] = array(
361 'quizid' => $quizobj->get_quizid()
45e1e3bd
MN
362 );
363 $event = \mod_quiz\event\attempt_preview_started::create($params);
1cd7c92e 364 } else {
a2caf56d
MN
365 $event = \mod_quiz\event\attempt_started::create($params);
366
1cd7c92e 367 }
a2caf56d
MN
368
369 // Trigger the event.
370 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
546a2c95 371 $event->add_record_snapshot('quiz_attempts', $attempt);
a2caf56d
MN
372 $event->trigger();
373
1cd7c92e
JP
374 return $attempt;
375}
376
cd06115f 377/**
25302dee
TH
378 * Returns an unfinished attempt (if there is one) for the given
379 * user on the given quiz. This function does not return preview attempts.
77ed3ba5 380 *
f7970e3c
TH
381 * @param int $quizid the id of the quiz.
382 * @param int $userid the id of the user.
77ed3ba5 383 *
384 * @return mixed the unfinished attempt if there is one, false if not.
cd06115f 385 */
0d156caa 386function quiz_get_user_attempt_unfinished($quizid, $userid) {
ed8bebce 387 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
77ed3ba5 388 if ($attempts) {
389 return array_shift($attempts);
390 } else {
391 return false;
392 }
920fb237 393}
394
ff51d646 395/**
396 * Delete a quiz attempt.
25a03faa
TH
397 * @param mixed $attempt an integer attempt id or an attempt object
398 * (row of the quiz_attempts table).
97344ae3 399 * @param object $quiz the quiz object.
ff51d646 400 */
401function quiz_delete_attempt($attempt, $quiz) {
9cf4a18b 402 global $DB;
ff51d646 403 if (is_numeric($attempt)) {
9cf4a18b 404 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
ff51d646 405 return;
406 }
407 }
271e6dec 408
ff51d646 409 if ($attempt->quiz != $quiz->id) {
410 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
411 "but was passed quiz $quiz->id.");
412 return;
413 }
271e6dec 414
a97a7585
MN
415 if (!isset($quiz->cmid)) {
416 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
417 $quiz->cmid = $cm->id;
418 }
419
25302dee 420 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
6b5f24d3 421 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
ff51d646 422
52940528
DP
423 // Log the deletion of the attempt if not a preview.
424 if (!$attempt->preview) {
425 $params = array(
426 'objectid' => $attempt->id,
427 'relateduserid' => $attempt->userid,
428 'context' => context_module::instance($quiz->cmid),
429 'other' => array(
430 'quizid' => $quiz->id
431 )
432 );
433 $event = \mod_quiz\event\attempt_deleted::create($params);
434 $event->add_record_snapshot('quiz_attempts', $attempt);
435 $event->trigger();
436 }
7dad3d95 437
ff51d646 438 // Search quiz_attempts for other instances by this user.
439 // If none, then delete record for this quiz, this user from quiz_grades
9e83f3d1 440 // else recalculate best grade.
ff51d646 441 $userid = $attempt->userid;
9cf4a18b 442 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
25a03faa 443 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
ff51d646 444 } else {
445 quiz_save_best_grade($quiz, $userid);
446 }
07a7d859 447
448 quiz_update_grades($quiz, $userid);
ff51d646 449}
450
4299df1d 451/**
452 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
453 * to one user.
454 * @param object $quiz the quiz object.
f7970e3c 455 * @param int $userid (optional) if given, only delete the previews belonging to this user.
4299df1d 456 */
457function quiz_delete_previews($quiz, $userid = null) {
458 global $DB;
459 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
460 if (!empty($userid)) {
461 $conditions['userid'] = $userid;
462 }
463 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
464 foreach ($previewattempts as $attempt) {
465 quiz_delete_attempt($attempt, $quiz);
466 }
467}
468
84e628a0 469/**
f7970e3c
TH
470 * @param int $quizid The quiz id.
471 * @return bool whether this quiz has any (non-preview) attempts.
84e628a0 472 */
473function quiz_has_attempts($quizid) {
474 global $DB;
475 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
476}
477
9e83f3d1 478// Functions to do with quiz layout and pages //////////////////////////////////
0d156caa 479
ee1fb969 480/**
ccba5b88
TH
481 * Repaginate the questions in a quiz
482 * @param int $quizid the id of the quiz to repaginate.
483 * @param int $slotsperpage number of items to put on each page. 0 means unlimited.
26d12a0c 484 */
ccba5b88
TH
485function quiz_repaginate_questions($quizid, $slotsperpage) {
486 global $DB;
487 $trans = $DB->start_delegated_transaction();
0c5abe6c 488
5d949702
K
489 $sections = $DB->get_records('quiz_sections', array('quizid' => $quizid), 'firstslot ASC');
490 $firstslots = array();
491 foreach ($sections as $section) {
492 if ((int)$section->firstslot === 1) {
493 continue;
494 }
495 $firstslots[] = $section->firstslot;
496 }
497
ccba5b88
TH
498 $slots = $DB->get_records('quiz_slots', array('quizid' => $quizid),
499 'slot');
ccba5b88
TH
500 $currentpage = 1;
501 $slotsonthispage = 0;
502 foreach ($slots as $slot) {
5d949702
K
503 if (($firstslots && in_array($slot->slot, $firstslots)) ||
504 ($slotsonthispage && $slotsonthispage == $slotsperpage)) {
ccba5b88
TH
505 $currentpage += 1;
506 $slotsonthispage = 0;
76cacec8 507 }
ccba5b88
TH
508 if ($slot->page != $currentpage) {
509 $DB->set_field('quiz_slots', 'page', $currentpage, array('id' => $slot->id));
510 }
511 $slotsonthispage += 1;
76cacec8 512 }
0c5abe6c 513
ccba5b88 514 $trans->allow_commit();
ee1fb969 515}
76cacec8 516
9e83f3d1 517// Functions to do with quiz grades ////////////////////////////////////////////
76cacec8 518
212b7b8c 519/**
520 * Convert the raw grade stored in $attempt into a grade out of the maximum
521 * grade for this quiz.
77ed3ba5 522 *
212b7b8c 523 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
25302dee 524 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
f7970e3c 525 * @param bool|string $format whether to format the results for display
25302dee 526 * or 'question' to format a question grade (different number of decimal places.
25a03faa
TH
527 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
528 * if the $grade is null.
212b7b8c 529 */
25302dee
TH
530function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
531 if (is_null($rawgrade)) {
532 $grade = null;
533 } else if ($quiz->sumgrades >= 0.000005) {
b7b4f8bd 534 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
212b7b8c 535 } else {
b7b4f8bd 536 $grade = 0;
212b7b8c 537 }
25302dee
TH
538 if ($format === 'question') {
539 $grade = quiz_format_question_grade($quiz, $grade);
540 } else if ($format) {
541 $grade = quiz_format_grade($quiz, $grade);
542 }
b7b4f8bd 543 return $grade;
76cacec8 544}
545
ee1fb969 546/**
212b7b8c 547 * Get the feedback text that should be show to a student who
de266537 548 * got this grade on this quiz. The feedback is processed ready for diplay.
77ed3ba5 549 *
212b7b8c 550 * @param float $grade a grade on this quiz.
2709ee45
TH
551 * @param object $quiz the quiz settings.
552 * @param object $context the quiz context.
212b7b8c 553 * @return string the comment that corresponds to this grade (empty string if there is not one.
554 */
2709ee45 555function quiz_feedback_for_grade($grade, $quiz, $context) {
9cf4a18b 556 global $DB;
212b7b8c 557
25302dee
TH
558 if (is_null($grade)) {
559 return '';
560 }
561
b7ab57f3
TH
562 // With CBM etc, it is possible to get -ve grades, which would then not match
563 // any feedback. Therefore, we replace -ve grades with 0.
564 $grade = max($grade, 0);
565
2709ee45
TH
566 $feedback = $DB->get_record_select('quiz_feedback',
567 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
fe6ce234
DC
568
569 if (empty($feedback->feedbacktext)) {
2709ee45 570 return '';
212b7b8c 571 }
77ed3ba5 572
de266537 573 // Clean the text, ready for display.
0ff4bd08 574 $formatoptions = new stdClass();
de266537 575 $formatoptions->noclean = true;
25a03faa
TH
576 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
577 $context->id, 'mod_quiz', 'feedback', $feedback->id);
fe6ce234 578 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
de266537 579
fe6ce234 580 return $feedbacktext;
212b7b8c 581}
582
583/**
8ce3e17f 584 * @param object $quiz the quiz database row.
f7970e3c 585 * @return bool Whether this quiz has any non-blank feedback text.
212b7b8c 586 */
739b0711 587function quiz_has_feedback($quiz) {
9cf4a18b 588 global $DB;
212b7b8c 589 static $cache = array();
739b0711 590 if (!array_key_exists($quiz->id, $cache)) {
591 $cache[$quiz->id] = quiz_has_grades($quiz) &&
592 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
593 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
594 array($quiz->id));
212b7b8c 595 }
739b0711 596 return $cache[$quiz->id];
212b7b8c 597}
598
25302dee
TH
599/**
600 * Update the sumgrades field of the quiz. This needs to be called whenever
601 * the grading structure of the quiz is changed. For example if a question is
602 * added or removed, or a question weight is changed.
603 *
18dff757
TH
604 * You should call {@link quiz_delete_previews()} before you call this function.
605 *
25302dee
TH
606 * @param object $quiz a quiz.
607 */
608function quiz_update_sumgrades($quiz) {
609 global $DB;
18dff757 610
25302dee
TH
611 $sql = 'UPDATE {quiz}
612 SET sumgrades = COALESCE((
dc4a3ea1 613 SELECT SUM(maxmark)
ccba5b88 614 FROM {quiz_slots}
dc4a3ea1 615 WHERE quizid = {quiz}.id
25302dee
TH
616 ), 0)
617 WHERE id = ?';
a13d4fbd
TH
618 $DB->execute($sql, array($quiz->id));
619 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
18dff757
TH
620
621 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
622 // If the quiz has been attempted, and the sumgrades has been
623 // set to 0, then we must also set the maximum possible grade to 0, or
624 // we will get a divide by zero error.
25302dee
TH
625 quiz_set_grade(0, $quiz);
626 }
627}
628
18dff757
TH
629/**
630 * Update the sumgrades field of the attempts at a quiz.
631 *
632 * @param object $quiz a quiz.
633 */
25302dee
TH
634function quiz_update_all_attempt_sumgrades($quiz) {
635 global $DB;
636 $dm = new question_engine_data_mapper();
637 $timenow = time();
638
639 $sql = "UPDATE {quiz_attempts}
640 SET
641 timemodified = :timenow,
642 sumgrades = (
643 {$dm->sum_usage_marks_subquery('uniqueid')}
644 )
be18f589
TH
645 WHERE quiz = :quizid AND state = :finishedstate";
646 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
647 'finishedstate' => quiz_attempt::FINISHED));
25302dee
TH
648}
649
212b7b8c 650/**
b2607ccc 651 * The quiz grade is the maximum that student's results are marked out of. When it
212b7b8c 652 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
25302dee
TH
653 * rescaled. After calling this function, you probably need to call
654 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
655 * quiz_update_grades.
77ed3ba5 656 *
212b7b8c 657 * @param float $newgrade the new maximum grade for the quiz.
25a03faa
TH
658 * @param object $quiz the quiz we are updating. Passed by reference so its
659 * grade field can be updated too.
f7970e3c 660 * @return bool indicating success or failure.
212b7b8c 661 */
25302dee 662function quiz_set_grade($newgrade, $quiz) {
9cf4a18b 663 global $DB;
212b7b8c 664 // This is potentially expensive, so only do it if necessary.
665 if (abs($quiz->grade - $newgrade) < 1e-7) {
666 // Nothing to do.
667 return true;
668 }
b22fc901 669
62a3bfb3
TH
670 $oldgrade = $quiz->grade;
671 $quiz->grade = $newgrade;
672
212b7b8c 673 // Use a transaction, so that on those databases that support it, this is safer.
d5a8d9aa
PS
674 $transaction = $DB->start_delegated_transaction();
675
0f1c59c5
TH
676 // Update the quiz table.
677 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
678
62a3bfb3
TH
679 if ($oldgrade < 1) {
680 // If the old grade was zero, we cannot rescale, we have to recompute.
681 // We also recompute if the old grade was too small to avoid underflow problems.
682 quiz_update_all_final_grades($quiz);
0f1c59c5 683
62a3bfb3
TH
684 } else {
685 // We can rescale the grades efficiently.
0f1c59c5
TH
686 $timemodified = time();
687 $DB->execute("
688 UPDATE {quiz_grades}
689 SET grade = ? * grade, timemodified = ?
690 WHERE quiz = ?
62a3bfb3
TH
691 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
692 }
0f1c59c5 693
62a3bfb3 694 if ($oldgrade > 1e-7) {
0f1c59c5 695 // Update the quiz_feedback table.
62a3bfb3 696 $factor = $newgrade/$oldgrade;
0f1c59c5
TH
697 $DB->execute("
698 UPDATE {quiz_feedback}
699 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
700 WHERE quizid = ?
701 ", array($factor, $factor, $quiz->id));
702 }
77ed3ba5 703
9e83f3d1 704 // Update grade item and send all grades to gradebook.
0f1c59c5
TH
705 quiz_grade_item_update($quiz);
706 quiz_update_grades($quiz);
d6dd2108 707
0f1c59c5
TH
708 $transaction->allow_commit();
709 return true;
212b7b8c 710}
711
712/**
713 * Save the overall grade for a user at a quiz in the quiz_grades table
714 *
715 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
f7970e3c 716 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
98f38217 717 * @param array $attempts The attempts of this user. Useful if you are
718 * looping through many users. Attempts can be fetched in one master query to
719 * avoid repeated querying.
f7970e3c 720 * @return bool Indicates success or failure.
212b7b8c 721 */
98f38217 722function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
cef18275 723 global $DB, $OUTPUT, $USER;
ee1fb969 724
212b7b8c 725 if (empty($userid)) {
ee1fb969 726 $userid = $USER->id;
727 }
76cacec8 728
25a03faa 729 if (!$attempts) {
9e83f3d1 730 // Get all the attempts made by the user.
25302dee 731 $attempts = quiz_get_user_attempts($quiz->id, $userid);
76cacec8 732 }
733
9e83f3d1 734 // Calculate the best grade.
76cacec8 735 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
84e628a0 736 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
77ed3ba5 737
9e83f3d1 738 // Save the best grade in the database.
25302dee
TH
739 if (is_null($bestgrade)) {
740 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
741
25a03faa
TH
742 } else if ($grade = $DB->get_record('quiz_grades',
743 array('quiz' => $quiz->id, 'userid' => $userid))) {
fc44ee0d 744 $grade->grade = $bestgrade;
76cacec8 745 $grade->timemodified = time();
a8c31db2 746 $DB->update_record('quiz_grades', $grade);
25302dee 747
76cacec8 748 } else {
b640e681 749 $grade = new stdClass();
76cacec8 750 $grade->quiz = $quiz->id;
751 $grade->userid = $userid;
fc44ee0d 752 $grade->grade = $bestgrade;
76cacec8 753 $grade->timemodified = time();
a8c31db2 754 $DB->insert_record('quiz_grades', $grade);
76cacec8 755 }
d6dd2108 756
757 quiz_update_grades($quiz, $userid);
76cacec8 758}
759
fc44ee0d 760/**
26d12a0c 761 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
762 *
13bbfebc
TH
763 * @param object $quiz the quiz settings object.
764 * @param array $attempts an array of all the user's attempts at this quiz in order.
765 * @return float the overall grade
26d12a0c 766 */
76cacec8 767function quiz_calculate_best_grade($quiz, $attempts) {
76cacec8 768
769 switch ($quiz->grademethod) {
770
ee1fb969 771 case QUIZ_ATTEMPTFIRST:
13bbfebc
TH
772 $firstattempt = reset($attempts);
773 return $firstattempt->sumgrades;
76cacec8 774
ee1fb969 775 case QUIZ_ATTEMPTLAST:
13bbfebc
TH
776 $lastattempt = end($attempts);
777 return $lastattempt->sumgrades;
76cacec8 778
ee1fb969 779 case QUIZ_GRADEAVERAGE:
76cacec8 780 $sum = 0;
781 $count = 0;
782 foreach ($attempts as $attempt) {
25302dee
TH
783 if (!is_null($attempt->sumgrades)) {
784 $sum += $attempt->sumgrades;
785 $count++;
786 }
76cacec8 787 }
25302dee
TH
788 if ($count == 0) {
789 return null;
790 }
791 return $sum / $count;
76cacec8 792
ee1fb969 793 case QUIZ_GRADEHIGHEST:
13bbfebc 794 default:
25302dee 795 $max = null;
76cacec8 796 foreach ($attempts as $attempt) {
797 if ($attempt->sumgrades > $max) {
798 $max = $attempt->sumgrades;
799 }
800 }
801 return $max;
802 }
803}
804
25302dee
TH
805/**
806 * Update the final grade at this quiz for all students.
807 *
808 * This function is equivalent to calling quiz_save_best_grade for all
809 * users, but much more efficient.
810 *
811 * @param object $quiz the quiz settings.
812 */
813function quiz_update_all_final_grades($quiz) {
814 global $DB;
815
816 if (!$quiz->sumgrades) {
817 return;
818 }
819
be18f589 820 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
25302dee
TH
821 $firstlastattemptjoin = "JOIN (
822 SELECT
823 iquiza.userid,
824 MIN(attempt) AS firstattempt,
825 MAX(attempt) AS lastattempt
826
e50a5813 827 FROM {quiz_attempts} iquiza
25302dee
TH
828
829 WHERE
07051106 830 iquiza.state = :istatefinished AND
25302dee
TH
831 iquiza.preview = 0 AND
832 iquiza.quiz = :iquizid
833
834 GROUP BY iquiza.userid
835 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
836
837 switch ($quiz->grademethod) {
838 case QUIZ_ATTEMPTFIRST:
81522abd 839 // Because of the where clause, there will only be one row, but we
25302dee
TH
840 // must still use an aggregate function.
841 $select = 'MAX(quiza.sumgrades)';
842 $join = $firstlastattemptjoin;
843 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
844 break;
845
846 case QUIZ_ATTEMPTLAST:
81522abd 847 // Because of the where clause, there will only be one row, but we
25302dee
TH
848 // must still use an aggregate function.
849 $select = 'MAX(quiza.sumgrades)';
850 $join = $firstlastattemptjoin;
851 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
852 break;
853
854 case QUIZ_GRADEAVERAGE:
855 $select = 'AVG(quiza.sumgrades)';
856 $join = '';
857 $where = '';
858 break;
859
860 default:
861 case QUIZ_GRADEHIGHEST:
862 $select = 'MAX(quiza.sumgrades)';
863 $join = '';
864 $where = '';
865 break;
866 }
867
868 if ($quiz->sumgrades >= 0.000005) {
869 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
870 } else {
871 $finalgrade = '0';
872 }
873 $param['quizid'] = $quiz->id;
874 $param['quizid2'] = $quiz->id;
875 $param['quizid3'] = $quiz->id;
876 $param['quizid4'] = $quiz->id;
be18f589
TH
877 $param['statefinished'] = quiz_attempt::FINISHED;
878 $param['statefinished2'] = quiz_attempt::FINISHED;
25302dee
TH
879 $finalgradesubquery = "
880 SELECT quiza.userid, $finalgrade AS newgrade
881 FROM {quiz_attempts} quiza
882 $join
883 WHERE
884 $where
a558acf9 885 quiza.state = :statefinished AND
25302dee
TH
886 quiza.preview = 0 AND
887 quiza.quiz = :quizid3
888 GROUP BY quiza.userid";
889
890 $changedgrades = $DB->get_records_sql("
891 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
892
893 FROM (
894 SELECT userid
895 FROM {quiz_grades} qg
896 WHERE quiz = :quizid
897 UNION
898 SELECT DISTINCT userid
899 FROM {quiz_attempts} quiza2
900 WHERE
a558acf9 901 quiza2.state = :statefinished2 AND
25302dee
TH
902 quiza2.preview = 0 AND
903 quiza2.quiz = :quizid2
904 ) users
905
906 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
907
908 LEFT JOIN (
909 $finalgradesubquery
910 ) newgrades ON newgrades.userid = users.userid
911
912 WHERE
913 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
f484a629
TH
914 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
915 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
916 // The mess on the previous line is detecting where the value is
917 // NULL in one column, and NOT NULL in the other, but SQL does
918 // not have an XOR operator, and MS SQL server can't cope with
919 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
a13d4fbd 920 $param);
25302dee
TH
921
922 $timenow = time();
923 $todelete = array();
924 foreach ($changedgrades as $changedgrade) {
925
926 if (is_null($changedgrade->newgrade)) {
927 $todelete[] = $changedgrade->userid;
928
929 } else if (is_null($changedgrade->grade)) {
0ff4bd08 930 $toinsert = new stdClass();
25302dee
TH
931 $toinsert->quiz = $quiz->id;
932 $toinsert->userid = $changedgrade->userid;
933 $toinsert->timemodified = $timenow;
934 $toinsert->grade = $changedgrade->newgrade;
935 $DB->insert_record('quiz_grades', $toinsert);
936
937 } else {
0ff4bd08 938 $toupdate = new stdClass();
25302dee
TH
939 $toupdate->id = $changedgrade->id;
940 $toupdate->grade = $changedgrade->newgrade;
941 $toupdate->timemodified = $timenow;
942 $DB->update_record('quiz_grades', $toupdate);
943 }
944 }
945
946 if (!empty($todelete)) {
e65f89b9 947 list($test, $params) = $DB->get_in_or_equal($todelete);
8d13ea83
TH
948 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
949 array_merge(array($quiz->id), $params));
25302dee
TH
950 }
951}
952
8e771aed
MP
953/**
954 * Efficiently update check state time on all open attempts
955 *
956 * @param array $conditions optional restrictions on which attempts to update
957 * Allowed conditions:
958 * courseid => (array|int) attempts in given course(s)
959 * userid => (array|int) attempts for given user(s)
960 * quizid => (array|int) attempts in given quiz(s)
961 * groupid => (array|int) quizzes with some override for given group(s)
962 *
963 */
964function quiz_update_open_attempts(array $conditions) {
965 global $DB;
966
967 foreach ($conditions as &$value) {
968 if (!is_array($value)) {
969 $value = array($value);
970 }
971 }
972
973 $params = array();
805e32f7
TH
974 $wheres = array("quiza.state IN ('inprogress', 'overdue')");
975 $iwheres = array("iquiza.state IN ('inprogress', 'overdue')");
8e771aed
MP
976
977 if (isset($conditions['courseid'])) {
978 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
979 $params = array_merge($params, $inparams);
805e32f7
TH
980 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
981 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
982 $params = array_merge($params, $inparams);
983 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
8e771aed 984 }
805e32f7 985
8e771aed
MP
986 if (isset($conditions['userid'])) {
987 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
988 $params = array_merge($params, $inparams);
805e32f7
TH
989 $wheres[] = "quiza.userid $incond";
990 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
991 $params = array_merge($params, $inparams);
992 $iwheres[] = "iquiza.userid $incond";
8e771aed 993 }
805e32f7 994
8e771aed
MP
995 if (isset($conditions['quizid'])) {
996 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
997 $params = array_merge($params, $inparams);
805e32f7
TH
998 $wheres[] = "quiza.quiz $incond";
999 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
1000 $params = array_merge($params, $inparams);
1001 $iwheres[] = "iquiza.quiz $incond";
8e771aed 1002 }
805e32f7 1003
8e771aed
MP
1004 if (isset($conditions['groupid'])) {
1005 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
1006 $params = array_merge($params, $inparams);
805e32f7
TH
1007 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1008 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
1009 $params = array_merge($params, $inparams);
1010 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
8e771aed
MP
1011 }
1012
1013 // SQL to compute timeclose and timelimit for each attempt:
805e32f7
TH
1014 $quizausersql = quiz_get_attempt_usertime_sql(
1015 implode("\n AND ", $iwheres));
8e771aed
MP
1016
1017 // SQL to compute the new timecheckstate
1018 $timecheckstatesql = "
1019 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
1020 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
1021 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
1022 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
1023 ELSE quizauser.usertimeclose END +
1024 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
1025
1026 // SQL to select which attempts to process
805e32f7 1027 $attemptselect = implode("\n AND ", $wheres);
8e771aed
MP
1028
1029 /*
1030 * Each database handles updates with inner joins differently:
1031 * - mysql does not allow a FROM clause
1032 * - postgres and mssql allow FROM but handle table aliases differently
1033 * - oracle requires a subquery
1034 *
1035 * Different code for each database.
1036 */
1037
1038 $dbfamily = $DB->get_dbfamily();
1039 if ($dbfamily == 'mysql') {
1040 $updatesql = "UPDATE {quiz_attempts} quiza
1041 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1042 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1043 SET quiza.timecheckstate = $timecheckstatesql
1044 WHERE $attemptselect";
1045 } else if ($dbfamily == 'postgres') {
1046 $updatesql = "UPDATE {quiz_attempts} quiza
1047 SET timecheckstate = $timecheckstatesql
1048 FROM {quiz} quiz, ( $quizausersql ) quizauser
1049 WHERE quiz.id = quiza.quiz
1050 AND quizauser.id = quiza.id
1051 AND $attemptselect";
1052 } else if ($dbfamily == 'mssql') {
1053 $updatesql = "UPDATE quiza
1054 SET timecheckstate = $timecheckstatesql
1055 FROM {quiz_attempts} quiza
1056 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1057 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1058 WHERE $attemptselect";
1059 } else {
1060 // oracle, sqlite and others
1061 $updatesql = "UPDATE {quiz_attempts} quiza
1062 SET timecheckstate = (
1063 SELECT $timecheckstatesql
1064 FROM {quiz} quiz, ( $quizausersql ) quizauser
1065 WHERE quiz.id = quiza.quiz
1066 AND quizauser.id = quiza.id
1067 )
1068 WHERE $attemptselect";
1069 }
1070
1071 $DB->execute($updatesql, $params);
1072}
1073
1074/**
1075 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
1076 *
805e32f7
TH
1077 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1078 * for performance. These can use the table alias iquiza for the quiz attempts table.
1079 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
8e771aed 1080 */
805e32f7
TH
1081function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1082 if ($redundantwhereclauses) {
1083 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1084 }
8e771aed
MP
1085 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1086 // any other group override
1087 $quizausersql = "
1088 SELECT iquiza.id,
1089 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1090 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1091
1092 FROM {quiz_attempts} iquiza
1093 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1094 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1095 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1096 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1097 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1098 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1099 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
805e32f7 1100 $redundantwhereclauses
8e771aed
MP
1101 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1102 return $quizausersql;
1103}
1104
fc44ee0d 1105/**
26d12a0c 1106 * Return the attempt with the best grade for a quiz
1107 *
1108 * Which attempt is the best depends on $quiz->grademethod. If the grade
1109 * method is GRADEAVERAGE then this function simply returns the last attempt.
1110 * @return object The attempt with the best grade
1111 * @param object $quiz The quiz for which the best grade is to be calculated
1112 * @param array $attempts An array of all the attempts of the user at the quiz
1113 */
76cacec8 1114function quiz_calculate_best_attempt($quiz, $attempts) {
76cacec8 1115
1116 switch ($quiz->grademethod) {
1117
ee1fb969 1118 case QUIZ_ATTEMPTFIRST:
76cacec8 1119 foreach ($attempts as $attempt) {
1120 return $attempt;
1121 }
1122 break;
1123
9e83f3d1 1124 case QUIZ_GRADEAVERAGE: // We need to do something with it.
ee1fb969 1125 case QUIZ_ATTEMPTLAST:
76cacec8 1126 foreach ($attempts as $attempt) {
1127 $final = $attempt;
1128 }
1129 return $final;
1130
1131 default:
ee1fb969 1132 case QUIZ_GRADEHIGHEST:
76cacec8 1133 $max = -1;
1134 foreach ($attempts as $attempt) {
1135 if ($attempt->sumgrades > $max) {
1136 $max = $attempt->sumgrades;
1137 $maxattempt = $attempt;
1138 }
1139 }
1140 return $maxattempt;
1141 }
1142}
1143
25302dee 1144/**
87427d9c
TH
1145 * @return array int => lang string the options for calculating the quiz grade
1146 * from the individual attempt grades.
25302dee
TH
1147 */
1148function quiz_get_grading_options() {
1149 return array(
1150 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1151 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1152 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1153 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1154 );
1155}
1156
0675e5eb 1157/**
25a03faa
TH
1158 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1159 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
0675e5eb 1160 * @return the lang string for that option.
1161 */
1162function quiz_get_grading_option_name($option) {
1163 $strings = quiz_get_grading_options();
1164 return $strings[$option];
1165}
1166
87427d9c
TH
1167/**
1168 * @return array string => lang string the options for handling overdue quiz
1169 * attempts.
1170 */
1171function quiz_get_overdue_handling_options() {
1172 return array(
1173 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1174 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1175 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1176 );
1177}
1178
9ec7a716 1179/**
31805089 1180 * Get the choices for what size user picture to show.
9ec7a716
TH
1181 * @return array string => lang string the options for whether to display the user's picture.
1182 */
1183function quiz_get_user_image_options() {
1184 return array(
1185 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
1186 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
1187 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'),
1188 );
1189}
1190
e1a2d0d9
CC
1191/**
1192 * Get the choices to offer for the 'Questions per page' option.
1193 * @return array int => string.
1194 */
1195function quiz_questions_per_page_options() {
1196 $pageoptions = array();
1197 $pageoptions[0] = get_string('neverallononepage', 'quiz');
1198 $pageoptions[1] = get_string('everyquestion', 'quiz');
1199 for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
1200 $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
1201 }
1202 return $pageoptions;
1203}
1204
be18f589 1205/**
31805089
TH
1206 * Get the human-readable name for a quiz attempt state.
1207 * @param string $state one of the state constants like {@link quiz_attempt::IN_PROGRESS}.
1208 * @return string The lang string to describe that state.
be18f589
TH
1209 */
1210function quiz_attempt_state_name($state) {
1211 switch ($state) {
1212 case quiz_attempt::IN_PROGRESS:
1213 return get_string('stateinprogress', 'quiz');
1214 case quiz_attempt::OVERDUE:
1215 return get_string('stateoverdue', 'quiz');
1216 case quiz_attempt::FINISHED:
1217 return get_string('statefinished', 'quiz');
1218 case quiz_attempt::ABANDONED:
1219 return get_string('stateabandoned', 'quiz');
1220 default:
1221 throw new coding_exception('Unknown quiz attempt state.');
1222 }
1223}
1224
9e83f3d1 1225// Other quiz functions ////////////////////////////////////////////////////////
ee1fb969 1226
26a29b1a 1227/**
2a874d65 1228 * @param object $quiz the quiz.
f7970e3c 1229 * @param int $cmid the course_module object for this quiz.
2a874d65 1230 * @param object $question the question.
26a29b1a 1231 * @param string $returnurl url to return to after action is done.
1232 * @return string html for a number of icons linked to action pages for a
1233 * question - preview and edit / view icons depending on user capabilities.
1234 */
2a874d65 1235function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
1236 $html = quiz_question_preview_button($quiz, $question) . ' ' .
1237 quiz_question_edit_button($cmid, $question, $returnurl);
1238 return $html;
1239}
1240
1241/**
f7970e3c 1242 * @param int $cmid the course_module.id for this quiz.
2a874d65 1243 * @param object $question the question.
1244 * @param string $returnurl url to return to after action is done.
1245 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
25a03faa
TH
1246 * @return the HTML for an edit icon, view icon, or nothing for a question
1247 * (depending on permissions).
2a874d65 1248 */
d04f623b 1249function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
d436d197 1250 global $CFG, $OUTPUT;
2a874d65 1251
1252 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
26a29b1a 1253 static $stredit = null;
1254 static $strview = null;
25a03faa 1255 if ($stredit === null) {
26a29b1a 1256 $stredit = get_string('edit');
1257 $strview = get_string('view');
1258 }
2a874d65 1259
1260 // What sort of icon should we show?
1261 $action = '';
25a03faa
TH
1262 if (!empty($question->id) &&
1263 (question_has_capability_on($question, 'edit', $question->category) ||
1264 question_has_capability_on($question, 'move', $question->category))) {
2a874d65 1265 $action = $stredit;
1266 $icon = '/t/edit';
25a03faa
TH
1267 } else if (!empty($question->id) &&
1268 question_has_capability_on($question, 'view', $question->category)) {
2a874d65 1269 $action = $strview;
1270 $icon = '/i/info';
1271 }
1272
1273 // Build the icon.
1274 if ($action) {
47678d60 1275 if ($returnurl instanceof moodle_url) {
a530d4a9 1276 $returnurl = $returnurl->out_as_local_url(false);
47678d60 1277 }
2a874d65 1278 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
1279 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
068384ce 1280 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
d04f623b
TH
1281 $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
1282 '</a>';
068384ce
TH
1283 } else if ($contentaftericon) {
1284 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
2a874d65 1285 } else {
068384ce 1286 return '';
26a29b1a 1287 }
26a29b1a 1288}
1289
7d87171b 1290/**
612106b3
TH
1291 * @param object $quiz the quiz settings
1292 * @param object $question the question
1293 * @return moodle_url to preview this question with the options from this quiz.
1294 */
1295function quiz_question_preview_url($quiz, $question) {
1296 // Get the appropriate display options.
1297 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
1298 mod_quiz_display_options::DURING);
1299
1300 $maxmark = null;
1301 if (isset($question->maxmark)) {
1302 $maxmark = $question->maxmark;
1303 }
1304
1305 // Work out the correcte preview URL.
1306 return question_preview_url($question->id, $quiz->preferredbehaviour,
1307 $maxmark, $displayoptions);
1308}
1309
1310/**
1311 * @param object $quiz the quiz settings
7d87171b 1312 * @param object $question the question
f7970e3c 1313 * @param bool $label if true, show the preview question label after the icon
7d87171b 1314 * @return the HTML for a preview question icon.
1315 */
2a874d65 1316function quiz_question_preview_button($quiz, $question, $label = false) {
e1a2d0d9 1317 global $PAGE;
2a874d65 1318 if (!question_has_capability_on($question, 'use', $question->category)) {
271e6dec 1319 return '';
1320 }
2a874d65 1321
e1a2d0d9 1322 return $PAGE->get_renderer('mod_quiz', 'edit')->question_preview_icon($quiz, $question, $label);
ad7e7ba8 1323}
0d156caa 1324
62e76c67 1325/**
1326 * @param object $attempt the attempt.
1327 * @param object $context the quiz context.
f7970e3c 1328 * @return int whether flags should be shown/editable to the current user for this attempt.
62e76c67 1329 */
1330function quiz_get_flag_option($attempt, $context) {
1331 global $USER;
25302dee
TH
1332 if (!has_capability('moodle/question:flag', $context)) {
1333 return question_display_options::HIDDEN;
1334 } else if ($attempt->userid == $USER->id) {
1335 return question_display_options::EDITABLE;
1336 } else {
1337 return question_display_options::VISIBLE;
62e76c67 1338 }
62e76c67 1339}
1340
4f48fb42 1341/**
be18f589
TH
1342 * Work out what state this quiz attempt is in - in the sense used by
1343 * quiz_get_review_options, not in the sense of $attempt->state.
25302dee
TH
1344 * @param object $quiz the quiz settings
1345 * @param object $attempt the quiz_attempt database row.
f7970e3c 1346 * @return int one of the mod_quiz_display_options::DURING,
25302dee 1347 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
4dca7e51 1348 */
25302dee 1349function quiz_attempt_state($quiz, $attempt) {
b3c18b86 1350 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
25302dee
TH
1351 return mod_quiz_display_options::DURING;
1352 } else if (time() < $attempt->timefinish + 120) {
1353 return mod_quiz_display_options::IMMEDIATELY_AFTER;
1354 } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
1355 return mod_quiz_display_options::LATER_WHILE_OPEN;
1356 } else {
1357 return mod_quiz_display_options::AFTER_CLOSE;
1358 }
4f48fb42 1359}
1360
4f48fb42 1361/**
25302dee
TH
1362 * The the appropraite mod_quiz_display_options object for this attempt at this
1363 * quiz right now.
77ed3ba5 1364 *
cd06115f 1365 * @param object $quiz the quiz instance.
1366 * @param object $attempt the attempt in question.
25302dee 1367 * @param $context the quiz context.
77ed3ba5 1368 *
25302dee 1369 * @return mod_quiz_display_options
cd06115f 1370 */
7ee80cab 1371function quiz_get_review_options($quiz, $attempt, $context) {
25302dee 1372 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
62e76c67 1373
4f48fb42 1374 $options->readonly = true;
62e76c67 1375 $options->flags = quiz_get_flag_option($attempt, $context);
2709ee45
TH
1376 if (!empty($attempt->id)) {
1377 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1378 array('attempt' => $attempt->id));
1379 }
b6e907a2 1380
9e83f3d1 1381 // Show a link to the comment box only for closed attempts.
be18f589 1382 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
2709ee45 1383 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
25302dee 1384 $options->manualcomment = question_display_options::VISIBLE;
7ee80cab
TH
1385 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1386 array('attempt' => $attempt->id));
01600b51 1387 }
1388
25a03faa
TH
1389 if (!is_null($context) && !$attempt->preview &&
1390 has_capability('mod/quiz:viewreports', $context) &&
25302dee 1391 has_capability('moodle/grade:viewhidden', $context)) {
e2833e87 1392 // People who can see reports and hidden grades should be shown everything,
1393 // except during preview when teachers want to see what students see.
25302dee
TH
1394 $options->attempt = question_display_options::VISIBLE;
1395 $options->correctness = question_display_options::VISIBLE;
1396 $options->marks = question_display_options::MARK_AND_MAX;
1397 $options->feedback = question_display_options::VISIBLE;
1398 $options->numpartscorrect = question_display_options::VISIBLE;
e101ec9f 1399 $options->manualcomment = question_display_options::VISIBLE;
25302dee
TH
1400 $options->generalfeedback = question_display_options::VISIBLE;
1401 $options->rightanswer = question_display_options::VISIBLE;
1402 $options->overallfeedback = question_display_options::VISIBLE;
1403 $options->history = question_display_options::VISIBLE;
e2833e87 1404
4f48fb42 1405 }
77ed3ba5 1406
4f48fb42 1407 return $options;
1408}
77ed3ba5 1409
40377b18 1410/**
77ed3ba5 1411 * Combines the review options from a number of different quiz attempts.
25302dee 1412 * Returns an array of two ojects, so the suggested way of calling this
77ed3ba5 1413 * funciton is:
1414 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1415 *
1416 * @param object $quiz the quiz instance.
1417 * @param array $attempts an array of attempt objects.
1418 * @param $context the roles and permissions context,
1419 * normally the context for the quiz module instance.
1420 *
1421 * @return array of two options objects, one showing which options are true for
1422 * at least one of the attempts, the other showing which options are true
1423 * for all attempts.
1424 */
25302dee 1425function quiz_get_combined_reviewoptions($quiz, $attempts) {
6d03fd98 1426 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
0ff4bd08
TH
1427 $someoptions = new stdClass();
1428 $alloptions = new stdClass();
77ed3ba5 1429 foreach ($fields as $field) {
1430 $someoptions->$field = false;
1431 $alloptions->$field = true;
40377b18 1432 }
6d03fd98
TH
1433 $someoptions->marks = question_display_options::HIDDEN;
1434 $alloptions->marks = question_display_options::MARK_AND_MAX;
1435
77ed3ba5 1436 foreach ($attempts as $attempt) {
25302dee
TH
1437 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1438 quiz_attempt_state($quiz, $attempt));
7d014bf5 1439 foreach ($fields as $field) {
1440 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1441 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1442 }
6d03fd98
TH
1443 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1444 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
77ed3ba5 1445 }
1446 return array($someoptions, $alloptions);
40377b18 1447}
ac48e43a 1448
9e83f3d1 1449// Functions for sending notification messages /////////////////////////////////
ac48e43a 1450
1451/**
cbb8b55c 1452 * Sends a confirmation message to the student confirming that the attempt was processed.
ac48e43a 1453 *
cbb8b55c
TH
1454 * @param object $a lots of useful information that can be used in the message
1455 * subject and body.
ac48e43a 1456 *
cbb8b55c 1457 * @return int|false as for {@link message_send()}.
ac48e43a 1458 */
cbb8b55c 1459function quiz_send_confirmation($recipient, $a) {
ac48e43a 1460
9e83f3d1 1461 // Add information about the recipient to $a.
cbb8b55c
TH
1462 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1463 $a->username = fullname($recipient);
1464 $a->userusername = $recipient->username;
ac48e43a 1465
9e83f3d1 1466 // Prepare the message.
39790bd8 1467 $eventdata = new stdClass();
cbb8b55c
TH
1468 $eventdata->component = 'mod_quiz';
1469 $eventdata->name = 'confirmation';
94263cca
AD
1470 $eventdata->notification = 1;
1471
5540b2ca 1472 $eventdata->userfrom = core_user::get_noreply_user();
cbb8b55c
TH
1473 $eventdata->userto = $recipient;
1474 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1475 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
3b120e46 1476 $eventdata->fullmessageformat = FORMAT_PLAIN;
1477 $eventdata->fullmessagehtml = '';
94263cca
AD
1478
1479 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1480 $eventdata->contexturl = $a->quizurl;
1481 $eventdata->contexturlname = $a->quizname;
99d19c13 1482
cbb8b55c
TH
1483 // ... and send it.
1484 return message_send($eventdata);
ac48e43a 1485}
1486
1487/**
bc68fc9a 1488 * Sends notification messages to the interested parties that assign the role capability
ac48e43a 1489 *
1490 * @param object $recipient user object of the intended recipient
0ff4bd08 1491 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1492 *
cbb8b55c 1493 * @return int|false as for {@link message_send()}.
ac48e43a 1494 */
cbb8b55c 1495function quiz_send_notification($recipient, $submitter, $a) {
ac48e43a 1496
9e83f3d1 1497 // Recipient info for template.
cbb8b55c
TH
1498 $a->useridnumber = $recipient->idnumber;
1499 $a->username = fullname($recipient);
ac48e43a 1500 $a->userusername = $recipient->username;
ac48e43a 1501
9e83f3d1 1502 // Prepare the message.
39790bd8 1503 $eventdata = new stdClass();
cbb8b55c
TH
1504 $eventdata->component = 'mod_quiz';
1505 $eventdata->name = 'submission';
bc68fc9a
AD
1506 $eventdata->notification = 1;
1507
cbb8b55c 1508 $eventdata->userfrom = $submitter;
3b120e46 1509 $eventdata->userto = $recipient;
cbb8b55c
TH
1510 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1511 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
3b120e46 1512 $eventdata->fullmessageformat = FORMAT_PLAIN;
1513 $eventdata->fullmessagehtml = '';
bc68fc9a
AD
1514
1515 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1516 $eventdata->contexturl = $a->quizreviewurl;
1517 $eventdata->contexturlname = $a->quizname;
1518
cbb8b55c
TH
1519 // ... and send it.
1520 return message_send($eventdata);
ac48e43a 1521}
1522
1523/**
cbb8b55c 1524 * Send all the requried messages when a quiz attempt is submitted.
ac48e43a 1525 *
1526 * @param object $course the course
1527 * @param object $quiz the quiz
1528 * @param object $attempt this attempt just finished
1529 * @param object $context the quiz context
1530 * @param object $cm the coursemodule for this quiz
1531 *
cbb8b55c 1532 * @return bool true if all necessary messages were sent successfully, else false.
ac48e43a 1533 */
cbb8b55c
TH
1534function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1535 global $CFG, $DB;
ac48e43a 1536
9e83f3d1 1537 // Do nothing if required objects not present.
ac48e43a 1538 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
cbb8b55c 1539 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
ac48e43a 1540 }
1541
cbb8b55c
TH
1542 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1543
9e83f3d1 1544 // Check for confirmation required.
ac48e43a 1545 $sendconfirm = false;
1546 $notifyexcludeusers = '';
cbb8b55c
TH
1547 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1548 $notifyexcludeusers = $submitter->id;
ac48e43a 1549 $sendconfirm = true;
1550 }
1551
9e83f3d1 1552 // Check for notifications required.
692ef101
AD
1553 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang,
1554 u.timezone, u.mailformat, u.maildisplay, u.auth, u.suspended, u.deleted, ';
b2b50d92 1555 $notifyfields .= get_all_user_name_fields(true, 'u');
efc76e9e 1556 $groups = groups_get_all_groups($course->id, $submitter->id, $cm->groupingid);
5a128471 1557 if (is_array($groups) && count($groups) > 0) {
1558 $groups = array_keys($groups);
255985f1 1559 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1560 // If the user is not in a group, and the quiz is set to group mode,
cbb8b55c 1561 // then set $groups to a non-existant id so that only users with
255985f1 1562 // 'moodle/site:accessallgroups' get notified.
1563 $groups = -1;
5a128471 1564 } else {
1565 $groups = '';
1566 }
ac48e43a 1567 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
5a128471 1568 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
ac48e43a 1569
cbb8b55c
TH
1570 if (empty($userstonotify) && !$sendconfirm) {
1571 return true; // Nothing to do.
ac48e43a 1572 }
1573
cbb8b55c 1574 $a = new stdClass();
9e83f3d1 1575 // Course info.
cbb8b55c
TH
1576 $a->coursename = $course->fullname;
1577 $a->courseshortname = $course->shortname;
9e83f3d1 1578 // Quiz info.
cbb8b55c
TH
1579 $a->quizname = $quiz->name;
1580 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1581 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1582 format_string($quiz->name) . ' report</a>';
cbb8b55c
TH
1583 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1584 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
9e83f3d1 1585 // Attempt info.
cbb8b55c
TH
1586 $a->submissiontime = userdate($attempt->timefinish);
1587 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
fd0537ce
TH
1588 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1589 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1590 format_string($quiz->name) . ' review</a>';
9e83f3d1 1591 // Student who sat the quiz info.
cbb8b55c
TH
1592 $a->studentidnumber = $submitter->idnumber;
1593 $a->studentname = fullname($submitter);
1594 $a->studentusername = $submitter->username;
1595
1596 $allok = true;
1597
9e83f3d1 1598 // Send notifications if required.
ac48e43a 1599 if (!empty($userstonotify)) {
ac48e43a 1600 foreach ($userstonotify as $recipient) {
cbb8b55c 1601 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
ac48e43a 1602 }
1603 }
1604
cbb8b55c
TH
1605 // Send confirmation if required. We send the student confirmation last, so
1606 // that if message sending is being intermittently buggy, which means we send
1607 // some but not all messages, and then try again later, then teachers may get
1608 // duplicate messages, but the student will always get exactly one.
1609 if ($sendconfirm) {
1610 $allok = $allok && quiz_send_confirmation($submitter, $a);
1611 }
1612
1613 return $allok;
1614}
1615
fd0537ce
TH
1616/**
1617 * Send the notification message when a quiz attempt becomes overdue.
1618 *
1c2e05c0 1619 * @param quiz_attempt $attemptobj all the data about the quiz attempt.
fd0537ce 1620 */
1c2e05c0 1621function quiz_send_overdue_message($attemptobj) {
fd0537ce
TH
1622 global $CFG, $DB;
1623
1c2e05c0 1624 $submitter = $DB->get_record('user', array('id' => $attemptobj->get_userid()), '*', MUST_EXIST);
fd0537ce 1625
1c2e05c0
TH
1626 if (!$attemptobj->has_capability('mod/quiz:emailwarnoverdue', $submitter->id, false)) {
1627 return; // Message not required.
1628 }
fd0537ce 1629
1c2e05c0 1630 if (!$attemptobj->has_response_to_at_least_one_graded_question()) {
fd0537ce
TH
1631 return; // Message not required.
1632 }
1633
1634 // Prepare lots of useful information that admins might want to include in
1635 // the email message.
1c2e05c0 1636 $quizname = format_string($attemptobj->get_quiz_name());
fd0537ce
TH
1637
1638 $deadlines = array();
1c2e05c0
TH
1639 if ($attemptobj->get_quiz()->timelimit) {
1640 $deadlines[] = $attemptobj->get_attempt()->timestart + $attemptobj->get_quiz()->timelimit;
fd0537ce 1641 }
1c2e05c0
TH
1642 if ($attemptobj->get_quiz()->timeclose) {
1643 $deadlines[] = $attemptobj->get_quiz()->timeclose;
fd0537ce 1644 }
59d14f31 1645 $duedate = min($deadlines);
1c2e05c0 1646 $graceend = $duedate + $attemptobj->get_quiz()->graceperiod;
fd0537ce
TH
1647
1648 $a = new stdClass();
1649 // Course info.
1c2e05c0
TH
1650 $a->coursename = format_string($attemptobj->get_course()->fullname);
1651 $a->courseshortname = format_string($attemptobj->get_course()->shortname);
fd0537ce
TH
1652 // Quiz info.
1653 $a->quizname = $quizname;
1c2e05c0 1654 $a->quizurl = $attemptobj->view_url();
fd0537ce
TH
1655 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1656 // Attempt info.
1c2e05c0 1657 $a->attemptduedate = userdate($duedate);
59d14f31 1658 $a->attemptgraceend = userdate($graceend);
1c2e05c0 1659 $a->attemptsummaryurl = $attemptobj->summary_url()->out(false);
fd0537ce
TH
1660 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1661 // Student's info.
1662 $a->studentidnumber = $submitter->idnumber;
1663 $a->studentname = fullname($submitter);
1664 $a->studentusername = $submitter->username;
1665
1666 // Prepare the message.
1667 $eventdata = new stdClass();
1668 $eventdata->component = 'mod_quiz';
1669 $eventdata->name = 'attempt_overdue';
1670 $eventdata->notification = 1;
1671
5540b2ca 1672 $eventdata->userfrom = core_user::get_noreply_user();
fd0537ce
TH
1673 $eventdata->userto = $submitter;
1674 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1675 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1676 $eventdata->fullmessageformat = FORMAT_PLAIN;
1677 $eventdata->fullmessagehtml = '';
1678
1679 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1680 $eventdata->contexturl = $a->quizurl;
1681 $eventdata->contexturlname = $a->quizname;
1682
1683 // Send the message.
1684 return message_send($eventdata);
1685}
1686
cbb8b55c
TH
1687/**
1688 * Handle the quiz_attempt_submitted event.
1689 *
1690 * This sends the confirmation and notification messages, if required.
1691 *
1692 * @param object $event the event object.
1693 */
1694function quiz_attempt_submitted_handler($event) {
1695 global $DB;
1696
1697 $course = $DB->get_record('course', array('id' => $event->courseid));
d900f1dc
FM
1698 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1699 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1700 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
cbb8b55c
TH
1701
1702 if (!($course && $quiz && $cm && $attempt)) {
1703 // Something has been deleted since the event was raised. Therefore, the
1704 // event is no longer relevant.
1705 return true;
ac48e43a 1706 }
ac48e43a 1707
db3686d5
RM
1708 // Update completion state.
1709 $completion = new completion_info($course);
1710 if ($completion->is_enabled($cm) && ($quiz->completionattemptsexhausted || $quiz->completionpass)) {
1711 $completion->update_state($cm, COMPLETION_COMPLETE, $event->userid);
1712 }
cbb8b55c 1713 return quiz_send_notification_messages($course, $quiz, $attempt,
c492a78e 1714 context_module::instance($cm->id), $cm);
ac48e43a 1715}
fa583f5f 1716
8e771aed
MP
1717/**
1718 * Handle groups_member_added event
1719 *
1720 * @param object $event the event object.
11b0c8e0 1721 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_added()}.
8e771aed
MP
1722 */
1723function quiz_groups_member_added_handler($event) {
11b0c8e0
FM
1724 debugging('quiz_groups_member_added_handler() is deprecated, please use ' .
1725 '\mod_quiz\group_observers::group_member_added() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1726 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1727}
1728
1729/**
1730 * Handle groups_member_removed event
1731 *
1732 * @param object $event the event object.
11b0c8e0 1733 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
8e771aed
MP
1734 */
1735function quiz_groups_member_removed_handler($event) {
11b0c8e0
FM
1736 debugging('quiz_groups_member_removed_handler() is deprecated, please use ' .
1737 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1738 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1739}
1740
1741/**
1742 * Handle groups_group_deleted event
1743 *
1744 * @param object $event the event object.
11b0c8e0 1745 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_deleted()}.
8e771aed
MP
1746 */
1747function quiz_groups_group_deleted_handler($event) {
1748 global $DB;
11b0c8e0
FM
1749 debugging('quiz_groups_group_deleted_handler() is deprecated, please use ' .
1750 '\mod_quiz\group_observers::group_deleted() instead.', DEBUG_DEVELOPER);
1751 quiz_process_group_deleted_in_course($event->courseid);
1752}
1753
1754/**
1755 * Logic to happen when a/some group(s) has/have been deleted in a course.
1756 *
1757 * @param int $courseid The course ID.
1758 * @return void
1759 */
1760function quiz_process_group_deleted_in_course($courseid) {
1761 global $DB;
8e771aed
MP
1762
1763 // It would be nice if we got the groupid that was deleted.
11b0c8e0 1764 // Instead, we just update all quizzes with orphaned group overrides.
8e771aed
MP
1765 $sql = "SELECT o.id, o.quiz
1766 FROM {quiz_overrides} o
1767 JOIN {quiz} quiz ON quiz.id = o.quiz
1768 LEFT JOIN {groups} grp ON grp.id = o.groupid
74b3c4e5
MP
1769 WHERE quiz.course = :courseid
1770 AND o.groupid IS NOT NULL
1771 AND grp.id IS NULL";
11b0c8e0 1772 $params = array('courseid' => $courseid);
8e771aed 1773 $records = $DB->get_records_sql_menu($sql, $params);
1744033c
TH
1774 if (!$records) {
1775 return; // Nothing to do.
1776 }
8e771aed 1777 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
11b0c8e0 1778 quiz_update_open_attempts(array('quizid' => array_unique(array_values($records))));
8e771aed
MP
1779}
1780
1781/**
1782 * Handle groups_members_removed event
1783 *
1784 * @param object $event the event object.
11b0c8e0 1785 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
8e771aed
MP
1786 */
1787function quiz_groups_members_removed_handler($event) {
11b0c8e0
FM
1788 debugging('quiz_groups_members_removed_handler() is deprecated, please use ' .
1789 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1790 if ($event->userid == 0) {
1791 quiz_update_open_attempts(array('courseid'=>$event->courseid));
1792 } else {
1793 quiz_update_open_attempts(array('courseid'=>$event->courseid, 'userid'=>$event->userid));
1794 }
1795}
1796
fd0537ce
TH
1797/**
1798 * Get the information about the standard quiz JavaScript module.
1799 * @return array a standard jsmodule structure.
1800 */
ff065f96 1801function quiz_get_js_module() {
157434a5 1802 global $PAGE;
73a7a0c9 1803
ff065f96
TH
1804 return array(
1805 'name' => 'mod_quiz',
1806 'fullpath' => '/mod/quiz/module.js',
25a03faa 1807 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
aebbfb7b 1808 'core_question_engine', 'moodle-core-formchangechecker'),
ff065f96 1809 'strings' => array(
73a7a0c9 1810 array('cancel', 'moodle'),
a26246ea 1811 array('flagged', 'question'),
d755b0f5
TH
1812 array('functiondisabledbysecuremode', 'quiz'),
1813 array('startattempt', 'quiz'),
1814 array('timesup', 'quiz'),
aebbfb7b 1815 array('changesmadereallygoaway', 'moodle'),
ff065f96
TH
1816 ),
1817 );
fe6ce234 1818}
25302dee
TH
1819
1820
1821/**
1822 * An extension of question_display_options that includes the extra options used
1823 * by the quiz.
1824 *
f7970e3c
TH
1825 * @copyright 2010 The Open University
1826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee
TH
1827 */
1828class mod_quiz_display_options extends question_display_options {
1829 /**#@+
1830 * @var integer bits used to indicate various times in relation to a
1831 * quiz attempt.
1832 */
1833 const DURING = 0x10000;
1834 const IMMEDIATELY_AFTER = 0x01000;
1835 const LATER_WHILE_OPEN = 0x00100;
1836 const AFTER_CLOSE = 0x00010;
1837 /**#@-*/
1838
1839 /**
1840 * @var boolean if this is false, then the student is not allowed to review
1841 * anything about the attempt.
1842 */
1843 public $attempt = true;
1844
1845 /**
1846 * @var boolean if this is false, then the student is not allowed to review
1847 * anything about the attempt.
1848 */
1849 public $overallfeedback = self::VISIBLE;
1850
1851 /**
1852 * Set up the various options from the quiz settings, and a time constant.
0ff4bd08 1853 * @param object $quiz the quiz settings.
f7970e3c 1854 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
25302dee
TH
1855 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1856 * @return mod_quiz_display_options set up appropriately.
1857 */
1858 public static function make_from_quiz($quiz, $when) {
1859 $options = new self();
1860
1861 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1862 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
25a03faa
TH
1863 $options->marks = self::extract($quiz->reviewmarks, $when,
1864 self::MARK_AND_MAX, self::MAX_ONLY);
25302dee
TH
1865 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1866 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1867 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1868 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1869
1870 $options->numpartscorrect = $options->feedback;
e101ec9f 1871 $options->manualcomment = $options->feedback;
25302dee
TH
1872
1873 if ($quiz->questiondecimalpoints != -1) {
1874 $options->markdp = $quiz->questiondecimalpoints;
1875 } else {
1876 $options->markdp = $quiz->decimalpoints;
1877 }
1878
1879 return $options;
1880 }
1881
25a03faa
TH
1882 protected static function extract($bitmask, $bit,
1883 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
25302dee
TH
1884 if ($bitmask & $bit) {
1885 return $whenset;
1886 } else {
1887 return $whennotset;
1888 }
1889 }
1890}
1891
1892
1893/**
1894 * A {@link qubaid_condition} for finding all the question usages belonging to
1895 * a particular quiz.
1896 *
f7970e3c
TH
1897 * @copyright 2010 The Open University
1898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee 1899 */
6b5f24d3 1900class qubaids_for_quiz extends qubaid_join {
25302dee 1901 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
6b5f24d3 1902 $where = 'quiza.quiz = :quizaquiz';
be18f589
TH
1903 $params = array('quizaquiz' => $quizid);
1904
25302dee
TH
1905 if (!$includepreviews) {
1906 $where .= ' AND preview = 0';
1907 }
be18f589 1908
25302dee 1909 if ($onlyfinished) {
be18f589
TH
1910 $where .= ' AND state == :statefinished';
1911 $params['statefinished'] = quiz_attempt::FINISHED;
25302dee
TH
1912 }
1913
be18f589 1914 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
25302dee
TH
1915 }
1916}
e1a2d0d9
CC
1917
1918/**
1919 * Creates a textual representation of a question for display.
1920 *
1921 * @param object $question A question object from the database questions table
1922 * @param bool $showicon If true, show the question's icon with the question. False by default.
1923 * @param bool $showquestiontext If true (default), show question text after question name.
1924 * If false, show only question name.
1925 * @return string
1926 */
1927function quiz_question_tostring($question, $showicon = false, $showquestiontext = true) {
1928 $result = '';
1929
1930 $name = shorten_text(format_string($question->name), 200);
1931 if ($showicon) {
1932 $name .= print_question_icon($question) . ' ' . $name;
1933 }
1934 $result .= html_writer::span($name, 'questionname');
1935
1936 if ($showquestiontext) {
1937 $questiontext = question_utils::to_plain_text($question->questiontext,
1938 $question->questiontextformat, array('noclean' => true, 'para' => false));
1939 $questiontext = shorten_text($questiontext, 200);
1940 if ($questiontext) {
1941 $result .= ' ' . html_writer::span(s($questiontext), 'questiontext');
1942 }
1943 }
1944
1945 return $result;
1946}
16fa272e
TH
1947
1948/**
1949 * Verify that the question exists, and the user has permission to use it.
1950 * Does not return. Throws an exception if the question cannot be used.
1951 * @param int $questionid The id of the question.
1952 */
1953function quiz_require_question_use($questionid) {
1954 global $DB;
1955 $question = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
1956 question_require_capability_on($question, 'use');
1957}
1958
1959/**
1960 * Verify that the question exists, and the user has permission to use it.
1961 * @param object $quiz the quiz settings.
1962 * @param int $slot which question in the quiz to test.
1963 * @return bool whether the user can use this question.
1964 */
1965function quiz_has_question_use($quiz, $slot) {
1966 global $DB;
1967 $question = $DB->get_record_sql("
1968 SELECT q.*
1969 FROM {quiz_slots} slot
1970 JOIN {question} q ON q.id = slot.questionid
1971 WHERE slot.quizid = ? AND slot.slot = ?", array($quiz->id, $slot));
1972 if (!$question) {
1973 return false;
1974 }
1975 return question_has_capability_on($question, 'use');
1976}
1977
1978/**
1979 * Add a question to a quiz
1980 *
1981 * Adds a question to a quiz by updating $quiz as well as the
1982 * quiz and quiz_slots tables. It also adds a page break if required.
1983 * @param int $questionid The id of the question to be added
1984 * @param object $quiz The extended quiz object as used by edit.php
1985 * This is updated by this function
1986 * @param int $page Which page in quiz to add the question on. If 0 (default),
1987 * add at the end
1988 * @param float $maxmark The maximum mark to set for this question. (Optional,
1989 * defaults to question.defaultmark.
1990 * @return bool false if the question was already in the quiz
1991 */
1992function quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null) {
1993 global $DB;
1994 $slots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id),
1995 'slot', 'questionid, slot, page, id');
1996 if (array_key_exists($questionid, $slots)) {
1997 return false;
1998 }
1999
2000 $trans = $DB->start_delegated_transaction();
2001
2002 $maxpage = 1;
2003 $numonlastpage = 0;
2004 foreach ($slots as $slot) {
2005 if ($slot->page > $maxpage) {
2006 $maxpage = $slot->page;
2007 $numonlastpage = 1;
2008 } else {
2009 $numonlastpage += 1;
2010 }
2011 }
2012
2013 // Add the new question instance.
2014 $slot = new stdClass();
2015 $slot->quizid = $quiz->id;
2016 $slot->questionid = $questionid;
2017
2018 if ($maxmark !== null) {
2019 $slot->maxmark = $maxmark;
2020 } else {
2021 $slot->maxmark = $DB->get_field('question', 'defaultmark', array('id' => $questionid));
2022 }
2023
2024 if (is_int($page) && $page >= 1) {
2025 // Adding on a given page.
2026 $lastslotbefore = 0;
2027 foreach (array_reverse($slots) as $otherslot) {
2028 if ($otherslot->page > $page) {
2029 $DB->set_field('quiz_slots', 'slot', $otherslot->slot + 1, array('id' => $otherslot->id));
2030 } else {
2031 $lastslotbefore = $otherslot->slot;
2032 break;
2033 }
2034 }
2035 $slot->slot = $lastslotbefore + 1;
2036 $slot->page = min($page, $maxpage + 1);
2037
5d949702
K
2038 $DB->execute("
2039 UPDATE {quiz_sections}
2040 SET firstslot = firstslot + 1
2041 WHERE quizid = ?
2042 AND firstslot > ?
2043 ", array($quiz->id, max($lastslotbefore, 1)));
2044
16fa272e
TH
2045 } else {
2046 $lastslot = end($slots);
2047 if ($lastslot) {
2048 $slot->slot = $lastslot->slot + 1;
2049 } else {
2050 $slot->slot = 1;
2051 }
2052 if ($quiz->questionsperpage && $numonlastpage >= $quiz->questionsperpage) {
2053 $slot->page = $maxpage + 1;
2054 } else {
2055 $slot->page = $maxpage;
2056 }
2057 }
2058
2059 $DB->insert_record('quiz_slots', $slot);
2060 $trans->allow_commit();
2061}
2062
2063/**
2064 * Add a random question to the quiz at a given point.
2065 * @param object $quiz the quiz settings.
2066 * @param int $addonpage the page on which to add the question.
2067 * @param int $categoryid the question category to add the question from.
2068 * @param int $number the number of random questions to add.
2069 * @param bool $includesubcategories whether to include questoins from subcategories.
2070 */
2071function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,
2072 $includesubcategories) {
2073 global $DB;
2074
2075 $category = $DB->get_record('question_categories', array('id' => $categoryid));
2076 if (!$category) {
2077 print_error('invalidcategoryid', 'error');
2078 }
2079
2080 $catcontext = context::instance_by_id($category->contextid);
2081 require_capability('moodle/question:useall', $catcontext);
2082
2083 // Find existing random questions in this category that are
2084 // not used by any quiz.
2085 if ($existingquestions = $DB->get_records_sql(
2086 "SELECT q.id, q.qtype FROM {question} q
2087 WHERE qtype = 'random'
2088 AND category = ?
2089 AND " . $DB->sql_compare_text('questiontext') . " = ?
2090 AND NOT EXISTS (
2091 SELECT *
2092 FROM {quiz_slots}
2093 WHERE questionid = q.id)
2094 ORDER BY id", array($category->id, ($includesubcategories ? '1' : '0')))) {
2095 // Take as many of these as needed.
2096 while (($existingquestion = array_shift($existingquestions)) && $number > 0) {
2097 quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage);
2098 $number -= 1;
2099 }
2100 }
2101
2102 if ($number <= 0) {
2103 return;
2104 }
2105
2106 // More random questions are needed, create them.
2107 for ($i = 0; $i < $number; $i += 1) {
2108 $form = new stdClass();
2109 $form->questiontext = array('text' => ($includesubcategories ? '1' : '0'), 'format' => 0);
2110 $form->category = $category->id . ',' . $category->contextid;
2111 $form->defaultmark = 1;
2112 $form->hidden = 1;
2113 $form->stamp = make_unique_id_code(); // Set the unique code (not to be changed).
2114 $question = new stdClass();
2115 $question->qtype = 'random';
2116 $question = question_bank::get_qtype('random')->save_question($question, $form);
2117 if (!isset($question->id)) {
2118 print_error('cannotinsertrandomquestion', 'quiz');
2119 }
2120 quiz_add_quiz_question($question->id, $quiz, $addonpage);
2121 }
2122}