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