MDL-55188 events: First deprecation of eventslib.php
[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 39require_once($CFG->libdir . '/completionlib.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;
8a972ab3 125 $attempt->timemodifiedoffline = 0;
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
66aa172c 210 $tagids = quiz_retrieve_slot_tag_ids($questiondata->slotid);
2a1c9dac 211
bb93fc24
TH
212 // Deal with fixed random choices for testing.
213 if (isset($questionids[$quba->next_slot_number()])) {
214 if ($randomloader->is_question_available($questiondata->category,
2a1c9dac 215 (bool) $questiondata->questiontext, $questionids[$quba->next_slot_number()], $tagids)) {
bb93fc24
TH
216 $questions[$slot] = question_bank::load_question(
217 $questionids[$quba->next_slot_number()], $quizobj->get_quiz()->shuffleanswers);
218 continue;
219 } else {
220 throw new coding_exception('Forced question id not available.');
221 }
c2f2e7f0
JP
222 }
223
bb93fc24 224 // Normal case, pick one at random.
2a1c9dac
SR
225 $questionid = $randomloader->get_next_question_id($questiondata->randomfromcategory,
226 $questiondata->randomincludingsubcategories, $tagids);
bb93fc24 227 if ($questionid === null) {
1cd7c92e
JP
228 throw new moodle_exception('notenoughrandomquestions', 'quiz',
229 $quizobj->view_url(), $questiondata);
230 }
bb93fc24
TH
231
232 $questions[$slot] = question_bank::load_question($questionid,
233 $quizobj->get_quiz()->shuffleanswers);
1cd7c92e 234 }
bb93fc24 235 }
1cd7c92e 236
bb93fc24
TH
237 // Finally add them all to the usage.
238 ksort($questions);
239 foreach ($questions as $slot => $question) {
240 $newslot = $quba->add_question($question, $maxmark[$slot]);
241 if ($newslot != $slot) {
242 throw new coding_exception('Slot numbers have got confused.');
243 }
1cd7c92e
JP
244 }
245
246 // Start all the questions.
bb93fc24 247 $variantstrategy = new core_question\engine\variants\least_used_strategy($quba, $qubaids);
c2b051c7
JP
248
249 if (!empty($forcedvariantsbyslot)) {
250 $forcedvariantsbyseed = question_variant_forced_choices_selection_strategy::prepare_forced_choices_array(
251 $forcedvariantsbyslot, $quba);
252 $variantstrategy = new question_variant_forced_choices_selection_strategy(
253 $forcedvariantsbyseed, $variantstrategy);
254 }
255
256 $quba->start_all_questions($variantstrategy, $timenow);
1cd7c92e 257
ccba5b88 258 // Work out the attempt layout.
5d949702
K
259 $sections = $quizobj->get_sections();
260 foreach ($sections as $i => $section) {
261 if (isset($sections[$i + 1])) {
262 $sections[$i]->lastslot = $sections[$i + 1]->firstslot - 1;
263 } else {
264 $sections[$i]->lastslot = count($questions);
265 }
266 }
267
ccba5b88 268 $layout = array();
5d949702
K
269 foreach ($sections as $section) {
270 if ($section->shufflequestions) {
271 $questionsinthissection = array();
272 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
273 $questionsinthissection[] = $slot;
274 }
275 shuffle($questionsinthissection);
276 $questionsonthispage = 0;
277 foreach ($questionsinthissection as $slot) {
278 if ($questionsonthispage && $questionsonthispage == $quizobj->get_quiz()->questionsperpage) {
279 $layout[] = 0;
280 $questionsonthispage = 0;
281 }
282 $layout[] = $slot;
283 $questionsonthispage += 1;
ccba5b88 284 }
ccba5b88 285
5d949702
K
286 } else {
287 $currentpage = $page[$section->firstslot];
288 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
289 if ($currentpage !== null && $page[$slot] != $currentpage) {
290 $layout[] = 0;
291 }
292 $layout[] = $slot;
293 $currentpage = $page[$slot];
ccba5b88 294 }
1cd7c92e 295 }
ccba5b88 296
5d949702
K
297 // Each section ends with a page break.
298 $layout[] = 0;
299 }
ccba5b88
TH
300 $attempt->layout = implode(',', $layout);
301
1cd7c92e
JP
302 return $attempt;
303}
304
305/**
306 * Start a subsequent new attempt, in each attempt builds on last mode.
307 *
308 * @param question_usage_by_activity $quba this question usage
309 * @param object $attempt this attempt
310 * @param object $lastattempt last attempt
311 * @return object modified attempt object
312 *
313 */
314function quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt) {
315 $oldquba = question_engine::load_questions_usage_by_activity($lastattempt->uniqueid);
316
317 $oldnumberstonew = array();
318 foreach ($oldquba->get_attempt_iterator() as $oldslot => $oldqa) {
319 $newslot = $quba->add_question($oldqa->get_question(), $oldqa->get_max_mark());
320
321 $quba->start_question_based_on($newslot, $oldqa);
322
323 $oldnumberstonew[$oldslot] = $newslot;
324 }
325
326 // Update attempt layout.
327 $newlayout = array();
328 foreach (explode(',', $lastattempt->layout) as $oldslot) {
329 if ($oldslot != 0) {
330 $newlayout[] = $oldnumberstonew[$oldslot];
331 } else {
332 $newlayout[] = 0;
333 }
334 }
335 $attempt->layout = implode(',', $newlayout);
336 return $attempt;
337}
338
339/**
340 * The save started question usage and quiz attempt in db and log the started attempt.
341 *
342 * @param quiz $quizobj
343 * @param question_usage_by_activity $quba
344 * @param object $attempt
345 * @return object attempt object with uniqueid and id set.
346 */
347function quiz_attempt_save_started($quizobj, $quba, $attempt) {
348 global $DB;
349 // Save the attempt in the database.
350 question_engine::save_questions_usage_by_activity($quba);
351 $attempt->uniqueid = $quba->get_id();
352 $attempt->id = $DB->insert_record('quiz_attempts', $attempt);
a2caf56d
MN
353
354 // Params used by the events below.
355 $params = array(
356 'objectid' => $attempt->id,
357 'relateduserid' => $attempt->userid,
358 'courseid' => $quizobj->get_courseid(),
359 'context' => $quizobj->get_context()
360 );
361 // Decide which event we are using.
1cd7c92e 362 if ($attempt->preview) {
a2caf56d
MN
363 $params['other'] = array(
364 'quizid' => $quizobj->get_quizid()
45e1e3bd
MN
365 );
366 $event = \mod_quiz\event\attempt_preview_started::create($params);
1cd7c92e 367 } else {
a2caf56d
MN
368 $event = \mod_quiz\event\attempt_started::create($params);
369
1cd7c92e 370 }
a2caf56d
MN
371
372 // Trigger the event.
373 $event->add_record_snapshot('quiz', $quizobj->get_quiz());
546a2c95 374 $event->add_record_snapshot('quiz_attempts', $attempt);
a2caf56d
MN
375 $event->trigger();
376
1cd7c92e
JP
377 return $attempt;
378}
379
cd06115f 380/**
25302dee
TH
381 * Returns an unfinished attempt (if there is one) for the given
382 * user on the given quiz. This function does not return preview attempts.
77ed3ba5 383 *
f7970e3c
TH
384 * @param int $quizid the id of the quiz.
385 * @param int $userid the id of the user.
77ed3ba5 386 *
387 * @return mixed the unfinished attempt if there is one, false if not.
cd06115f 388 */
0d156caa 389function quiz_get_user_attempt_unfinished($quizid, $userid) {
ed8bebce 390 $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
77ed3ba5 391 if ($attempts) {
392 return array_shift($attempts);
393 } else {
394 return false;
395 }
920fb237 396}
397
ff51d646 398/**
399 * Delete a quiz attempt.
25a03faa
TH
400 * @param mixed $attempt an integer attempt id or an attempt object
401 * (row of the quiz_attempts table).
97344ae3 402 * @param object $quiz the quiz object.
ff51d646 403 */
404function quiz_delete_attempt($attempt, $quiz) {
9cf4a18b 405 global $DB;
ff51d646 406 if (is_numeric($attempt)) {
9cf4a18b 407 if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
ff51d646 408 return;
409 }
410 }
271e6dec 411
ff51d646 412 if ($attempt->quiz != $quiz->id) {
413 debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
414 "but was passed quiz $quiz->id.");
415 return;
416 }
271e6dec 417
a97a7585
MN
418 if (!isset($quiz->cmid)) {
419 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
420 $quiz->cmid = $cm->id;
421 }
422
25302dee 423 question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
6b5f24d3 424 $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
ff51d646 425
52940528
DP
426 // Log the deletion of the attempt if not a preview.
427 if (!$attempt->preview) {
428 $params = array(
429 'objectid' => $attempt->id,
430 'relateduserid' => $attempt->userid,
431 'context' => context_module::instance($quiz->cmid),
432 'other' => array(
433 'quizid' => $quiz->id
434 )
435 );
436 $event = \mod_quiz\event\attempt_deleted::create($params);
437 $event->add_record_snapshot('quiz_attempts', $attempt);
438 $event->trigger();
439 }
7dad3d95 440
ff51d646 441 // Search quiz_attempts for other instances by this user.
442 // If none, then delete record for this quiz, this user from quiz_grades
9e83f3d1 443 // else recalculate best grade.
ff51d646 444 $userid = $attempt->userid;
9cf4a18b 445 if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
25a03faa 446 $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
ff51d646 447 } else {
448 quiz_save_best_grade($quiz, $userid);
449 }
07a7d859 450
451 quiz_update_grades($quiz, $userid);
ff51d646 452}
453
4299df1d 454/**
455 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
456 * to one user.
457 * @param object $quiz the quiz object.
f7970e3c 458 * @param int $userid (optional) if given, only delete the previews belonging to this user.
4299df1d 459 */
460function quiz_delete_previews($quiz, $userid = null) {
461 global $DB;
462 $conditions = array('quiz' => $quiz->id, 'preview' => 1);
463 if (!empty($userid)) {
464 $conditions['userid'] = $userid;
465 }
466 $previewattempts = $DB->get_records('quiz_attempts', $conditions);
467 foreach ($previewattempts as $attempt) {
468 quiz_delete_attempt($attempt, $quiz);
469 }
470}
471
84e628a0 472/**
f7970e3c
TH
473 * @param int $quizid The quiz id.
474 * @return bool whether this quiz has any (non-preview) attempts.
84e628a0 475 */
476function quiz_has_attempts($quizid) {
477 global $DB;
478 return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
479}
480
9e83f3d1 481// Functions to do with quiz layout and pages //////////////////////////////////
0d156caa 482
ee1fb969 483/**
ccba5b88
TH
484 * Repaginate the questions in a quiz
485 * @param int $quizid the id of the quiz to repaginate.
486 * @param int $slotsperpage number of items to put on each page. 0 means unlimited.
26d12a0c 487 */
ccba5b88
TH
488function quiz_repaginate_questions($quizid, $slotsperpage) {
489 global $DB;
490 $trans = $DB->start_delegated_transaction();
0c5abe6c 491
5d949702
K
492 $sections = $DB->get_records('quiz_sections', array('quizid' => $quizid), 'firstslot ASC');
493 $firstslots = array();
494 foreach ($sections as $section) {
495 if ((int)$section->firstslot === 1) {
496 continue;
497 }
498 $firstslots[] = $section->firstslot;
499 }
500
ccba5b88
TH
501 $slots = $DB->get_records('quiz_slots', array('quizid' => $quizid),
502 'slot');
ccba5b88
TH
503 $currentpage = 1;
504 $slotsonthispage = 0;
505 foreach ($slots as $slot) {
5d949702
K
506 if (($firstslots && in_array($slot->slot, $firstslots)) ||
507 ($slotsonthispage && $slotsonthispage == $slotsperpage)) {
ccba5b88
TH
508 $currentpage += 1;
509 $slotsonthispage = 0;
76cacec8 510 }
ccba5b88
TH
511 if ($slot->page != $currentpage) {
512 $DB->set_field('quiz_slots', 'page', $currentpage, array('id' => $slot->id));
513 }
514 $slotsonthispage += 1;
76cacec8 515 }
0c5abe6c 516
ccba5b88 517 $trans->allow_commit();
ee1fb969 518}
76cacec8 519
9e83f3d1 520// Functions to do with quiz grades ////////////////////////////////////////////
76cacec8 521
212b7b8c 522/**
523 * Convert the raw grade stored in $attempt into a grade out of the maximum
524 * grade for this quiz.
77ed3ba5 525 *
212b7b8c 526 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
25302dee 527 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
f7970e3c 528 * @param bool|string $format whether to format the results for display
25302dee 529 * or 'question' to format a question grade (different number of decimal places.
25a03faa
TH
530 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
531 * if the $grade is null.
212b7b8c 532 */
25302dee
TH
533function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
534 if (is_null($rawgrade)) {
535 $grade = null;
536 } else if ($quiz->sumgrades >= 0.000005) {
b7b4f8bd 537 $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
212b7b8c 538 } else {
b7b4f8bd 539 $grade = 0;
212b7b8c 540 }
25302dee
TH
541 if ($format === 'question') {
542 $grade = quiz_format_question_grade($quiz, $grade);
543 } else if ($format) {
544 $grade = quiz_format_grade($quiz, $grade);
545 }
b7b4f8bd 546 return $grade;
76cacec8 547}
548
48abca79
JL
549/**
550 * Get the feedback object for this grade on this quiz.
551 *
552 * @param float $grade a grade on this quiz.
553 * @param object $quiz the quiz settings.
554 * @return false|stdClass the record object or false if there is not feedback for the given grade
555 * @since Moodle 3.1
556 */
557function quiz_feedback_record_for_grade($grade, $quiz) {
558 global $DB;
559
560 // With CBM etc, it is possible to get -ve grades, which would then not match
561 // any feedback. Therefore, we replace -ve grades with 0.
562 $grade = max($grade, 0);
563
564 $feedback = $DB->get_record_select('quiz_feedback',
565 'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
566
567 return $feedback;
568}
569
ee1fb969 570/**
212b7b8c 571 * Get the feedback text that should be show to a student who
de266537 572 * got this grade on this quiz. The feedback is processed ready for diplay.
77ed3ba5 573 *
212b7b8c 574 * @param float $grade a grade on this quiz.
2709ee45
TH
575 * @param object $quiz the quiz settings.
576 * @param object $context the quiz context.
212b7b8c 577 * @return string the comment that corresponds to this grade (empty string if there is not one.
578 */
2709ee45 579function quiz_feedback_for_grade($grade, $quiz, $context) {
212b7b8c 580
25302dee
TH
581 if (is_null($grade)) {
582 return '';
583 }
584
48abca79 585 $feedback = quiz_feedback_record_for_grade($grade, $quiz);
fe6ce234
DC
586
587 if (empty($feedback->feedbacktext)) {
2709ee45 588 return '';
212b7b8c 589 }
77ed3ba5 590
de266537 591 // Clean the text, ready for display.
0ff4bd08 592 $formatoptions = new stdClass();
de266537 593 $formatoptions->noclean = true;
25a03faa
TH
594 $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
595 $context->id, 'mod_quiz', 'feedback', $feedback->id);
fe6ce234 596 $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
de266537 597
fe6ce234 598 return $feedbacktext;
212b7b8c 599}
600
601/**
8ce3e17f 602 * @param object $quiz the quiz database row.
f7970e3c 603 * @return bool Whether this quiz has any non-blank feedback text.
212b7b8c 604 */
739b0711 605function quiz_has_feedback($quiz) {
9cf4a18b 606 global $DB;
212b7b8c 607 static $cache = array();
739b0711 608 if (!array_key_exists($quiz->id, $cache)) {
609 $cache[$quiz->id] = quiz_has_grades($quiz) &&
610 $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
611 $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
612 array($quiz->id));
212b7b8c 613 }
739b0711 614 return $cache[$quiz->id];
212b7b8c 615}
616
25302dee
TH
617/**
618 * Update the sumgrades field of the quiz. This needs to be called whenever
619 * the grading structure of the quiz is changed. For example if a question is
620 * added or removed, or a question weight is changed.
621 *
18dff757
TH
622 * You should call {@link quiz_delete_previews()} before you call this function.
623 *
25302dee
TH
624 * @param object $quiz a quiz.
625 */
626function quiz_update_sumgrades($quiz) {
627 global $DB;
18dff757 628
25302dee
TH
629 $sql = 'UPDATE {quiz}
630 SET sumgrades = COALESCE((
dc4a3ea1 631 SELECT SUM(maxmark)
ccba5b88 632 FROM {quiz_slots}
dc4a3ea1 633 WHERE quizid = {quiz}.id
25302dee
TH
634 ), 0)
635 WHERE id = ?';
a13d4fbd
TH
636 $DB->execute($sql, array($quiz->id));
637 $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
18dff757
TH
638
639 if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
640 // If the quiz has been attempted, and the sumgrades has been
641 // set to 0, then we must also set the maximum possible grade to 0, or
642 // we will get a divide by zero error.
25302dee
TH
643 quiz_set_grade(0, $quiz);
644 }
645}
646
18dff757
TH
647/**
648 * Update the sumgrades field of the attempts at a quiz.
649 *
650 * @param object $quiz a quiz.
651 */
25302dee
TH
652function quiz_update_all_attempt_sumgrades($quiz) {
653 global $DB;
654 $dm = new question_engine_data_mapper();
655 $timenow = time();
656
657 $sql = "UPDATE {quiz_attempts}
658 SET
659 timemodified = :timenow,
660 sumgrades = (
661 {$dm->sum_usage_marks_subquery('uniqueid')}
662 )
be18f589
TH
663 WHERE quiz = :quizid AND state = :finishedstate";
664 $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
665 'finishedstate' => quiz_attempt::FINISHED));
25302dee
TH
666}
667
212b7b8c 668/**
b2607ccc 669 * The quiz grade is the maximum that student's results are marked out of. When it
212b7b8c 670 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
25302dee
TH
671 * rescaled. After calling this function, you probably need to call
672 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
673 * quiz_update_grades.
77ed3ba5 674 *
212b7b8c 675 * @param float $newgrade the new maximum grade for the quiz.
25a03faa
TH
676 * @param object $quiz the quiz we are updating. Passed by reference so its
677 * grade field can be updated too.
f7970e3c 678 * @return bool indicating success or failure.
212b7b8c 679 */
25302dee 680function quiz_set_grade($newgrade, $quiz) {
9cf4a18b 681 global $DB;
212b7b8c 682 // This is potentially expensive, so only do it if necessary.
683 if (abs($quiz->grade - $newgrade) < 1e-7) {
684 // Nothing to do.
685 return true;
686 }
b22fc901 687
62a3bfb3
TH
688 $oldgrade = $quiz->grade;
689 $quiz->grade = $newgrade;
690
212b7b8c 691 // Use a transaction, so that on those databases that support it, this is safer.
d5a8d9aa
PS
692 $transaction = $DB->start_delegated_transaction();
693
0f1c59c5
TH
694 // Update the quiz table.
695 $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
696
62a3bfb3
TH
697 if ($oldgrade < 1) {
698 // If the old grade was zero, we cannot rescale, we have to recompute.
699 // We also recompute if the old grade was too small to avoid underflow problems.
700 quiz_update_all_final_grades($quiz);
0f1c59c5 701
62a3bfb3
TH
702 } else {
703 // We can rescale the grades efficiently.
0f1c59c5
TH
704 $timemodified = time();
705 $DB->execute("
706 UPDATE {quiz_grades}
707 SET grade = ? * grade, timemodified = ?
708 WHERE quiz = ?
62a3bfb3
TH
709 ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
710 }
0f1c59c5 711
62a3bfb3 712 if ($oldgrade > 1e-7) {
0f1c59c5 713 // Update the quiz_feedback table.
62a3bfb3 714 $factor = $newgrade/$oldgrade;
0f1c59c5
TH
715 $DB->execute("
716 UPDATE {quiz_feedback}
717 SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
718 WHERE quizid = ?
719 ", array($factor, $factor, $quiz->id));
720 }
77ed3ba5 721
9e83f3d1 722 // Update grade item and send all grades to gradebook.
0f1c59c5
TH
723 quiz_grade_item_update($quiz);
724 quiz_update_grades($quiz);
d6dd2108 725
0f1c59c5
TH
726 $transaction->allow_commit();
727 return true;
212b7b8c 728}
729
730/**
731 * Save the overall grade for a user at a quiz in the quiz_grades table
732 *
733 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
f7970e3c 734 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
98f38217 735 * @param array $attempts The attempts of this user. Useful if you are
736 * looping through many users. Attempts can be fetched in one master query to
737 * avoid repeated querying.
f7970e3c 738 * @return bool Indicates success or failure.
212b7b8c 739 */
98f38217 740function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
cef18275 741 global $DB, $OUTPUT, $USER;
ee1fb969 742
212b7b8c 743 if (empty($userid)) {
ee1fb969 744 $userid = $USER->id;
745 }
76cacec8 746
25a03faa 747 if (!$attempts) {
9e83f3d1 748 // Get all the attempts made by the user.
25302dee 749 $attempts = quiz_get_user_attempts($quiz->id, $userid);
76cacec8 750 }
751
9e83f3d1 752 // Calculate the best grade.
76cacec8 753 $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
84e628a0 754 $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
77ed3ba5 755
9e83f3d1 756 // Save the best grade in the database.
25302dee
TH
757 if (is_null($bestgrade)) {
758 $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
759
25a03faa
TH
760 } else if ($grade = $DB->get_record('quiz_grades',
761 array('quiz' => $quiz->id, 'userid' => $userid))) {
fc44ee0d 762 $grade->grade = $bestgrade;
76cacec8 763 $grade->timemodified = time();
a8c31db2 764 $DB->update_record('quiz_grades', $grade);
25302dee 765
76cacec8 766 } else {
b640e681 767 $grade = new stdClass();
76cacec8 768 $grade->quiz = $quiz->id;
769 $grade->userid = $userid;
fc44ee0d 770 $grade->grade = $bestgrade;
76cacec8 771 $grade->timemodified = time();
a8c31db2 772 $DB->insert_record('quiz_grades', $grade);
76cacec8 773 }
d6dd2108 774
775 quiz_update_grades($quiz, $userid);
76cacec8 776}
777
fc44ee0d 778/**
26d12a0c 779 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
780 *
13bbfebc
TH
781 * @param object $quiz the quiz settings object.
782 * @param array $attempts an array of all the user's attempts at this quiz in order.
783 * @return float the overall grade
26d12a0c 784 */
76cacec8 785function quiz_calculate_best_grade($quiz, $attempts) {
76cacec8 786
787 switch ($quiz->grademethod) {
788
ee1fb969 789 case QUIZ_ATTEMPTFIRST:
13bbfebc
TH
790 $firstattempt = reset($attempts);
791 return $firstattempt->sumgrades;
76cacec8 792
ee1fb969 793 case QUIZ_ATTEMPTLAST:
13bbfebc
TH
794 $lastattempt = end($attempts);
795 return $lastattempt->sumgrades;
76cacec8 796
ee1fb969 797 case QUIZ_GRADEAVERAGE:
76cacec8 798 $sum = 0;
799 $count = 0;
800 foreach ($attempts as $attempt) {
25302dee
TH
801 if (!is_null($attempt->sumgrades)) {
802 $sum += $attempt->sumgrades;
803 $count++;
804 }
76cacec8 805 }
25302dee
TH
806 if ($count == 0) {
807 return null;
808 }
809 return $sum / $count;
76cacec8 810
ee1fb969 811 case QUIZ_GRADEHIGHEST:
13bbfebc 812 default:
25302dee 813 $max = null;
76cacec8 814 foreach ($attempts as $attempt) {
815 if ($attempt->sumgrades > $max) {
816 $max = $attempt->sumgrades;
817 }
818 }
819 return $max;
820 }
821}
822
25302dee
TH
823/**
824 * Update the final grade at this quiz for all students.
825 *
826 * This function is equivalent to calling quiz_save_best_grade for all
827 * users, but much more efficient.
828 *
829 * @param object $quiz the quiz settings.
830 */
831function quiz_update_all_final_grades($quiz) {
832 global $DB;
833
834 if (!$quiz->sumgrades) {
835 return;
836 }
837
be18f589 838 $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
25302dee
TH
839 $firstlastattemptjoin = "JOIN (
840 SELECT
841 iquiza.userid,
842 MIN(attempt) AS firstattempt,
843 MAX(attempt) AS lastattempt
844
e50a5813 845 FROM {quiz_attempts} iquiza
25302dee
TH
846
847 WHERE
07051106 848 iquiza.state = :istatefinished AND
25302dee
TH
849 iquiza.preview = 0 AND
850 iquiza.quiz = :iquizid
851
852 GROUP BY iquiza.userid
853 ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
854
855 switch ($quiz->grademethod) {
856 case QUIZ_ATTEMPTFIRST:
81522abd 857 // Because of the where clause, there will only be one row, but we
25302dee
TH
858 // must still use an aggregate function.
859 $select = 'MAX(quiza.sumgrades)';
860 $join = $firstlastattemptjoin;
861 $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
862 break;
863
864 case QUIZ_ATTEMPTLAST:
81522abd 865 // Because of the where clause, there will only be one row, but we
25302dee
TH
866 // must still use an aggregate function.
867 $select = 'MAX(quiza.sumgrades)';
868 $join = $firstlastattemptjoin;
869 $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
870 break;
871
872 case QUIZ_GRADEAVERAGE:
873 $select = 'AVG(quiza.sumgrades)';
874 $join = '';
875 $where = '';
876 break;
877
878 default:
879 case QUIZ_GRADEHIGHEST:
880 $select = 'MAX(quiza.sumgrades)';
881 $join = '';
882 $where = '';
883 break;
884 }
885
886 if ($quiz->sumgrades >= 0.000005) {
887 $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
888 } else {
889 $finalgrade = '0';
890 }
891 $param['quizid'] = $quiz->id;
892 $param['quizid2'] = $quiz->id;
893 $param['quizid3'] = $quiz->id;
894 $param['quizid4'] = $quiz->id;
be18f589
TH
895 $param['statefinished'] = quiz_attempt::FINISHED;
896 $param['statefinished2'] = quiz_attempt::FINISHED;
25302dee
TH
897 $finalgradesubquery = "
898 SELECT quiza.userid, $finalgrade AS newgrade
899 FROM {quiz_attempts} quiza
900 $join
901 WHERE
902 $where
a558acf9 903 quiza.state = :statefinished AND
25302dee
TH
904 quiza.preview = 0 AND
905 quiza.quiz = :quizid3
906 GROUP BY quiza.userid";
907
908 $changedgrades = $DB->get_records_sql("
909 SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
910
911 FROM (
912 SELECT userid
913 FROM {quiz_grades} qg
914 WHERE quiz = :quizid
915 UNION
916 SELECT DISTINCT userid
917 FROM {quiz_attempts} quiza2
918 WHERE
a558acf9 919 quiza2.state = :statefinished2 AND
25302dee
TH
920 quiza2.preview = 0 AND
921 quiza2.quiz = :quizid2
922 ) users
923
924 LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
925
926 LEFT JOIN (
927 $finalgradesubquery
928 ) newgrades ON newgrades.userid = users.userid
929
930 WHERE
931 ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
f484a629
TH
932 ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
933 (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
934 // The mess on the previous line is detecting where the value is
935 // NULL in one column, and NOT NULL in the other, but SQL does
936 // not have an XOR operator, and MS SQL server can't cope with
937 // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
a13d4fbd 938 $param);
25302dee
TH
939
940 $timenow = time();
941 $todelete = array();
942 foreach ($changedgrades as $changedgrade) {
943
944 if (is_null($changedgrade->newgrade)) {
945 $todelete[] = $changedgrade->userid;
946
947 } else if (is_null($changedgrade->grade)) {
0ff4bd08 948 $toinsert = new stdClass();
25302dee
TH
949 $toinsert->quiz = $quiz->id;
950 $toinsert->userid = $changedgrade->userid;
951 $toinsert->timemodified = $timenow;
952 $toinsert->grade = $changedgrade->newgrade;
953 $DB->insert_record('quiz_grades', $toinsert);
954
955 } else {
0ff4bd08 956 $toupdate = new stdClass();
25302dee
TH
957 $toupdate->id = $changedgrade->id;
958 $toupdate->grade = $changedgrade->newgrade;
959 $toupdate->timemodified = $timenow;
960 $DB->update_record('quiz_grades', $toupdate);
961 }
962 }
963
964 if (!empty($todelete)) {
e65f89b9 965 list($test, $params) = $DB->get_in_or_equal($todelete);
8d13ea83
TH
966 $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
967 array_merge(array($quiz->id), $params));
25302dee
TH
968 }
969}
970
8e771aed
MP
971/**
972 * Efficiently update check state time on all open attempts
973 *
974 * @param array $conditions optional restrictions on which attempts to update
975 * Allowed conditions:
976 * courseid => (array|int) attempts in given course(s)
977 * userid => (array|int) attempts for given user(s)
978 * quizid => (array|int) attempts in given quiz(s)
979 * groupid => (array|int) quizzes with some override for given group(s)
980 *
981 */
982function quiz_update_open_attempts(array $conditions) {
983 global $DB;
984
985 foreach ($conditions as &$value) {
986 if (!is_array($value)) {
987 $value = array($value);
988 }
989 }
990
991 $params = array();
805e32f7
TH
992 $wheres = array("quiza.state IN ('inprogress', 'overdue')");
993 $iwheres = array("iquiza.state IN ('inprogress', 'overdue')");
8e771aed
MP
994
995 if (isset($conditions['courseid'])) {
996 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'cid');
997 $params = array_merge($params, $inparams);
805e32f7
TH
998 $wheres[] = "quiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
999 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['courseid'], SQL_PARAMS_NAMED, 'icid');
1000 $params = array_merge($params, $inparams);
1001 $iwheres[] = "iquiza.quiz IN (SELECT q.id FROM {quiz} q WHERE q.course $incond)";
8e771aed 1002 }
805e32f7 1003
8e771aed
MP
1004 if (isset($conditions['userid'])) {
1005 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'uid');
1006 $params = array_merge($params, $inparams);
805e32f7
TH
1007 $wheres[] = "quiza.userid $incond";
1008 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['userid'], SQL_PARAMS_NAMED, 'iuid');
1009 $params = array_merge($params, $inparams);
1010 $iwheres[] = "iquiza.userid $incond";
8e771aed 1011 }
805e32f7 1012
8e771aed
MP
1013 if (isset($conditions['quizid'])) {
1014 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'qid');
1015 $params = array_merge($params, $inparams);
805e32f7
TH
1016 $wheres[] = "quiza.quiz $incond";
1017 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['quizid'], SQL_PARAMS_NAMED, 'iqid');
1018 $params = array_merge($params, $inparams);
1019 $iwheres[] = "iquiza.quiz $incond";
8e771aed 1020 }
805e32f7 1021
8e771aed
MP
1022 if (isset($conditions['groupid'])) {
1023 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'gid');
1024 $params = array_merge($params, $inparams);
805e32f7
TH
1025 $wheres[] = "quiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
1026 list ($incond, $inparams) = $DB->get_in_or_equal($conditions['groupid'], SQL_PARAMS_NAMED, 'igid');
1027 $params = array_merge($params, $inparams);
1028 $iwheres[] = "iquiza.quiz IN (SELECT qo.quiz FROM {quiz_overrides} qo WHERE qo.groupid $incond)";
8e771aed
MP
1029 }
1030
1031 // SQL to compute timeclose and timelimit for each attempt:
805e32f7
TH
1032 $quizausersql = quiz_get_attempt_usertime_sql(
1033 implode("\n AND ", $iwheres));
8e771aed
MP
1034
1035 // SQL to compute the new timecheckstate
1036 $timecheckstatesql = "
1037 CASE WHEN quizauser.usertimelimit = 0 AND quizauser.usertimeclose = 0 THEN NULL
1038 WHEN quizauser.usertimelimit = 0 THEN quizauser.usertimeclose
1039 WHEN quizauser.usertimeclose = 0 THEN quiza.timestart + quizauser.usertimelimit
1040 WHEN quiza.timestart + quizauser.usertimelimit < quizauser.usertimeclose THEN quiza.timestart + quizauser.usertimelimit
1041 ELSE quizauser.usertimeclose END +
1042 CASE WHEN quiza.state = 'overdue' THEN quiz.graceperiod ELSE 0 END";
1043
1044 // SQL to select which attempts to process
805e32f7 1045 $attemptselect = implode("\n AND ", $wheres);
8e771aed
MP
1046
1047 /*
1048 * Each database handles updates with inner joins differently:
1049 * - mysql does not allow a FROM clause
1050 * - postgres and mssql allow FROM but handle table aliases differently
1051 * - oracle requires a subquery
1052 *
1053 * Different code for each database.
1054 */
1055
1056 $dbfamily = $DB->get_dbfamily();
1057 if ($dbfamily == 'mysql') {
1058 $updatesql = "UPDATE {quiz_attempts} quiza
1059 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1060 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1061 SET quiza.timecheckstate = $timecheckstatesql
1062 WHERE $attemptselect";
1063 } else if ($dbfamily == 'postgres') {
1064 $updatesql = "UPDATE {quiz_attempts} quiza
1065 SET timecheckstate = $timecheckstatesql
1066 FROM {quiz} quiz, ( $quizausersql ) quizauser
1067 WHERE quiz.id = quiza.quiz
1068 AND quizauser.id = quiza.id
1069 AND $attemptselect";
1070 } else if ($dbfamily == 'mssql') {
1071 $updatesql = "UPDATE quiza
1072 SET timecheckstate = $timecheckstatesql
1073 FROM {quiz_attempts} quiza
1074 JOIN {quiz} quiz ON quiz.id = quiza.quiz
1075 JOIN ( $quizausersql ) quizauser ON quizauser.id = quiza.id
1076 WHERE $attemptselect";
1077 } else {
1078 // oracle, sqlite and others
1079 $updatesql = "UPDATE {quiz_attempts} quiza
1080 SET timecheckstate = (
1081 SELECT $timecheckstatesql
1082 FROM {quiz} quiz, ( $quizausersql ) quizauser
1083 WHERE quiz.id = quiza.quiz
1084 AND quizauser.id = quiza.id
1085 )
1086 WHERE $attemptselect";
1087 }
1088
1089 $DB->execute($updatesql, $params);
1090}
1091
1092/**
1093 * Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
bcf4a7f0
LB
1094 * The query used herein is very similar to the one in function quiz_get_user_timeclose, so, in case you
1095 * would change either one of them, make sure to apply your changes to both.
8e771aed 1096 *
805e32f7
TH
1097 * @param string $redundantwhereclauses extra where clauses to add to the subquery
1098 * for performance. These can use the table alias iquiza for the quiz attempts table.
1099 * @return string SQL select with columns attempt.id, usertimeclose, usertimelimit.
8e771aed 1100 */
805e32f7
TH
1101function quiz_get_attempt_usertime_sql($redundantwhereclauses = '') {
1102 if ($redundantwhereclauses) {
1103 $redundantwhereclauses = 'WHERE ' . $redundantwhereclauses;
1104 }
8e771aed
MP
1105 // The multiple qgo JOINS are necessary because we want timeclose/timelimit = 0 (unlimited) to supercede
1106 // any other group override
1107 $quizausersql = "
1108 SELECT iquiza.id,
1109 COALESCE(MAX(quo.timeclose), MAX(qgo1.timeclose), MAX(qgo2.timeclose), iquiz.timeclose) AS usertimeclose,
1110 COALESCE(MAX(quo.timelimit), MAX(qgo3.timelimit), MAX(qgo4.timelimit), iquiz.timelimit) AS usertimelimit
1111
1112 FROM {quiz_attempts} iquiza
1113 JOIN {quiz} iquiz ON iquiz.id = iquiza.quiz
1114 LEFT JOIN {quiz_overrides} quo ON quo.quiz = iquiza.quiz AND quo.userid = iquiza.userid
1115 LEFT JOIN {groups_members} gm ON gm.userid = iquiza.userid
1116 LEFT JOIN {quiz_overrides} qgo1 ON qgo1.quiz = iquiza.quiz AND qgo1.groupid = gm.groupid AND qgo1.timeclose = 0
1117 LEFT JOIN {quiz_overrides} qgo2 ON qgo2.quiz = iquiza.quiz AND qgo2.groupid = gm.groupid AND qgo2.timeclose > 0
1118 LEFT JOIN {quiz_overrides} qgo3 ON qgo3.quiz = iquiza.quiz AND qgo3.groupid = gm.groupid AND qgo3.timelimit = 0
1119 LEFT JOIN {quiz_overrides} qgo4 ON qgo4.quiz = iquiza.quiz AND qgo4.groupid = gm.groupid AND qgo4.timelimit > 0
805e32f7 1120 $redundantwhereclauses
8e771aed
MP
1121 GROUP BY iquiza.id, iquiz.id, iquiz.timeclose, iquiz.timelimit";
1122 return $quizausersql;
1123}
1124
fc44ee0d 1125/**
26d12a0c 1126 * Return the attempt with the best grade for a quiz
1127 *
1128 * Which attempt is the best depends on $quiz->grademethod. If the grade
1129 * method is GRADEAVERAGE then this function simply returns the last attempt.
1130 * @return object The attempt with the best grade
1131 * @param object $quiz The quiz for which the best grade is to be calculated
1132 * @param array $attempts An array of all the attempts of the user at the quiz
1133 */
76cacec8 1134function quiz_calculate_best_attempt($quiz, $attempts) {
76cacec8 1135
1136 switch ($quiz->grademethod) {
1137
ee1fb969 1138 case QUIZ_ATTEMPTFIRST:
76cacec8 1139 foreach ($attempts as $attempt) {
1140 return $attempt;
1141 }
1142 break;
1143
9e83f3d1 1144 case QUIZ_GRADEAVERAGE: // We need to do something with it.
ee1fb969 1145 case QUIZ_ATTEMPTLAST:
76cacec8 1146 foreach ($attempts as $attempt) {
1147 $final = $attempt;
1148 }
1149 return $final;
1150
1151 default:
ee1fb969 1152 case QUIZ_GRADEHIGHEST:
76cacec8 1153 $max = -1;
1154 foreach ($attempts as $attempt) {
1155 if ($attempt->sumgrades > $max) {
1156 $max = $attempt->sumgrades;
1157 $maxattempt = $attempt;
1158 }
1159 }
1160 return $maxattempt;
1161 }
1162}
1163
25302dee 1164/**
87427d9c
TH
1165 * @return array int => lang string the options for calculating the quiz grade
1166 * from the individual attempt grades.
25302dee
TH
1167 */
1168function quiz_get_grading_options() {
1169 return array(
1170 QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
1171 QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
1172 QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
1173 QUIZ_ATTEMPTLAST => get_string('attemptlast', 'quiz')
1174 );
1175}
1176
0675e5eb 1177/**
25a03faa
TH
1178 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
1179 * QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
0675e5eb 1180 * @return the lang string for that option.
1181 */
1182function quiz_get_grading_option_name($option) {
1183 $strings = quiz_get_grading_options();
1184 return $strings[$option];
1185}
1186
87427d9c
TH
1187/**
1188 * @return array string => lang string the options for handling overdue quiz
1189 * attempts.
1190 */
1191function quiz_get_overdue_handling_options() {
1192 return array(
1193 'autosubmit' => get_string('overduehandlingautosubmit', 'quiz'),
1194 'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
1195 'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
1196 );
1197}
1198
9ec7a716 1199/**
31805089 1200 * Get the choices for what size user picture to show.
9ec7a716
TH
1201 * @return array string => lang string the options for whether to display the user's picture.
1202 */
1203function quiz_get_user_image_options() {
1204 return array(
1205 QUIZ_SHOWIMAGE_NONE => get_string('shownoimage', 'quiz'),
1206 QUIZ_SHOWIMAGE_SMALL => get_string('showsmallimage', 'quiz'),
1207 QUIZ_SHOWIMAGE_LARGE => get_string('showlargeimage', 'quiz'),
1208 );
1209}
1210
bcf4a7f0
LB
1211/**
1212 * Return an user's timeclose for all quizzes in a course, hereby taking into account group and user overrides.
bcf4a7f0
LB
1213 *
1214 * @param int $courseid the course id.
4a73ecc6
LB
1215 * @return object An object with of all quizids and close unixdates in this course, taking into account the most lenient
1216 * overrides, if existing and 0 if no close date is set.
bcf4a7f0
LB
1217 */
1218function quiz_get_user_timeclose($courseid) {
1219 global $DB, $USER;
1220
1221 // For teacher and manager/admins return timeclose.
1222 if (has_capability('moodle/course:update', context_course::instance($courseid))) {
4a73ecc6 1223 $sql = "SELECT quiz.id, quiz.timeclose AS usertimeclose
bcf4a7f0 1224 FROM {quiz} quiz
496e80e1 1225 WHERE quiz.course = :courseid";
bcf4a7f0
LB
1226
1227 $results = $DB->get_records_sql($sql, array('courseid' => $courseid));
1228 return $results;
1229 }
1230
496e80e1 1231 $sql = "SELECT q.id,
4a73ecc6 1232 COALESCE(v.userclose, v.groupclose, q.timeclose, 0) AS usertimeclose
496e80e1 1233 FROM (
4a73ecc6
LB
1234 SELECT quiz.id as quizid,
1235 MAX(quo.timeclose) AS userclose, MAX(qgo.timeclose) AS groupclose
bcf4a7f0 1236 FROM {quiz} quiz
4a73ecc6
LB
1237 LEFT JOIN {quiz_overrides} quo on quiz.id = quo.quiz AND quo.userid = :userid
1238 LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
1239 LEFT JOIN {quiz_overrides} qgo on quiz.id = qgo.quiz AND qgo.groupid = gm.groupid
bcf4a7f0 1240 WHERE quiz.course = :courseid
496e80e1 1241 GROUP BY quiz.id) v
4a73ecc6 1242 JOIN {quiz} q ON q.id = v.quizid";
bcf4a7f0 1243
4a73ecc6 1244 $results = $DB->get_records_sql($sql, array('userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid));
bcf4a7f0 1245 return $results;
4a73ecc6 1246
bcf4a7f0
LB
1247}
1248
e1a2d0d9
CC
1249/**
1250 * Get the choices to offer for the 'Questions per page' option.
1251 * @return array int => string.
1252 */
1253function quiz_questions_per_page_options() {
1254 $pageoptions = array();
1255 $pageoptions[0] = get_string('neverallononepage', 'quiz');
1256 $pageoptions[1] = get_string('everyquestion', 'quiz');
1257 for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) {
1258 $pageoptions[$i] = get_string('everynquestions', 'quiz', $i);
1259 }
1260 return $pageoptions;
1261}
1262
be18f589 1263/**
31805089
TH
1264 * Get the human-readable name for a quiz attempt state.
1265 * @param string $state one of the state constants like {@link quiz_attempt::IN_PROGRESS}.
1266 * @return string The lang string to describe that state.
be18f589
TH
1267 */
1268function quiz_attempt_state_name($state) {
1269 switch ($state) {
1270 case quiz_attempt::IN_PROGRESS:
1271 return get_string('stateinprogress', 'quiz');
1272 case quiz_attempt::OVERDUE:
1273 return get_string('stateoverdue', 'quiz');
1274 case quiz_attempt::FINISHED:
1275 return get_string('statefinished', 'quiz');
1276 case quiz_attempt::ABANDONED:
1277 return get_string('stateabandoned', 'quiz');
1278 default:
1279 throw new coding_exception('Unknown quiz attempt state.');
1280 }
1281}
1282
9e83f3d1 1283// Other quiz functions ////////////////////////////////////////////////////////
ee1fb969 1284
26a29b1a 1285/**
2a874d65 1286 * @param object $quiz the quiz.
f7970e3c 1287 * @param int $cmid the course_module object for this quiz.
2a874d65 1288 * @param object $question the question.
26a29b1a 1289 * @param string $returnurl url to return to after action is done.
de3b803d 1290 * @param int $variant which question variant to preview (optional).
26a29b1a 1291 * @return string html for a number of icons linked to action pages for a
1292 * question - preview and edit / view icons depending on user capabilities.
1293 */
de3b803d
TH
1294function quiz_question_action_icons($quiz, $cmid, $question, $returnurl, $variant = null) {
1295 $html = quiz_question_preview_button($quiz, $question, false, $variant) . ' ' .
2a874d65 1296 quiz_question_edit_button($cmid, $question, $returnurl);
1297 return $html;
1298}
1299
1300/**
f7970e3c 1301 * @param int $cmid the course_module.id for this quiz.
2a874d65 1302 * @param object $question the question.
1303 * @param string $returnurl url to return to after action is done.
1304 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
25a03faa
TH
1305 * @return the HTML for an edit icon, view icon, or nothing for a question
1306 * (depending on permissions).
2a874d65 1307 */
d04f623b 1308function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
d436d197 1309 global $CFG, $OUTPUT;
2a874d65 1310
1311 // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
26a29b1a 1312 static $stredit = null;
1313 static $strview = null;
25a03faa 1314 if ($stredit === null) {
26a29b1a 1315 $stredit = get_string('edit');
1316 $strview = get_string('view');
1317 }
2a874d65 1318
1319 // What sort of icon should we show?
1320 $action = '';
25a03faa 1321 if (!empty($question->id) &&
13e2b198
SL
1322 (question_has_capability_on($question, 'edit') ||
1323 question_has_capability_on($question, 'move'))) {
2a874d65 1324 $action = $stredit;
663640f5 1325 $icon = 't/edit';
25a03faa 1326 } else if (!empty($question->id) &&
13e2b198 1327 question_has_capability_on($question, 'view')) {
2a874d65 1328 $action = $strview;
663640f5 1329 $icon = 'i/info';
2a874d65 1330 }
1331
1332 // Build the icon.
1333 if ($action) {
47678d60 1334 if ($returnurl instanceof moodle_url) {
a530d4a9 1335 $returnurl = $returnurl->out_as_local_url(false);
47678d60 1336 }
2a874d65 1337 $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
1338 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
663640f5
DW
1339 return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton">' .
1340 $OUTPUT->pix_icon($icon, $action) . $contentaftericon .
d04f623b 1341 '</a>';
068384ce
TH
1342 } else if ($contentaftericon) {
1343 return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
2a874d65 1344 } else {
068384ce 1345 return '';
26a29b1a 1346 }
26a29b1a 1347}
1348
7d87171b 1349/**
612106b3
TH
1350 * @param object $quiz the quiz settings
1351 * @param object $question the question
de3b803d 1352 * @param int $variant which question variant to preview (optional).
612106b3
TH
1353 * @return moodle_url to preview this question with the options from this quiz.
1354 */
de3b803d 1355function quiz_question_preview_url($quiz, $question, $variant = null) {
612106b3
TH
1356 // Get the appropriate display options.
1357 $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
1358 mod_quiz_display_options::DURING);
1359
1360 $maxmark = null;
1361 if (isset($question->maxmark)) {
1362 $maxmark = $question->maxmark;
1363 }
1364
1365 // Work out the correcte preview URL.
1366 return question_preview_url($question->id, $quiz->preferredbehaviour,
de3b803d 1367 $maxmark, $displayoptions, $variant);
612106b3
TH
1368}
1369
1370/**
1371 * @param object $quiz the quiz settings
7d87171b 1372 * @param object $question the question
f7970e3c 1373 * @param bool $label if true, show the preview question label after the icon
de3b803d 1374 * @param int $variant which question variant to preview (optional).
7d87171b 1375 * @return the HTML for a preview question icon.
1376 */
de3b803d 1377function quiz_question_preview_button($quiz, $question, $label = false, $variant = null) {
e1a2d0d9 1378 global $PAGE;
13e2b198 1379 if (!question_has_capability_on($question, 'use')) {
271e6dec 1380 return '';
1381 }
2a874d65 1382
de3b803d 1383 return $PAGE->get_renderer('mod_quiz', 'edit')->question_preview_icon($quiz, $question, $label, $variant);
ad7e7ba8 1384}
0d156caa 1385
62e76c67 1386/**
1387 * @param object $attempt the attempt.
1388 * @param object $context the quiz context.
f7970e3c 1389 * @return int whether flags should be shown/editable to the current user for this attempt.
62e76c67 1390 */
1391function quiz_get_flag_option($attempt, $context) {
1392 global $USER;
25302dee
TH
1393 if (!has_capability('moodle/question:flag', $context)) {
1394 return question_display_options::HIDDEN;
1395 } else if ($attempt->userid == $USER->id) {
1396 return question_display_options::EDITABLE;
1397 } else {
1398 return question_display_options::VISIBLE;
62e76c67 1399 }
62e76c67 1400}
1401
4f48fb42 1402/**
be18f589
TH
1403 * Work out what state this quiz attempt is in - in the sense used by
1404 * quiz_get_review_options, not in the sense of $attempt->state.
25302dee
TH
1405 * @param object $quiz the quiz settings
1406 * @param object $attempt the quiz_attempt database row.
f7970e3c 1407 * @return int one of the mod_quiz_display_options::DURING,
25302dee 1408 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
4dca7e51 1409 */
25302dee 1410function quiz_attempt_state($quiz, $attempt) {
b3c18b86 1411 if ($attempt->state == quiz_attempt::IN_PROGRESS) {
25302dee 1412 return mod_quiz_display_options::DURING;
d0f8daef
TH
1413 } else if ($quiz->timeclose && time() >= $quiz->timeclose) {
1414 return mod_quiz_display_options::AFTER_CLOSE;
25302dee
TH
1415 } else if (time() < $attempt->timefinish + 120) {
1416 return mod_quiz_display_options::IMMEDIATELY_AFTER;
25302dee 1417 } else {
d0f8daef 1418 return mod_quiz_display_options::LATER_WHILE_OPEN;
25302dee 1419 }
4f48fb42 1420}
1421
4f48fb42 1422/**
25302dee
TH
1423 * The the appropraite mod_quiz_display_options object for this attempt at this
1424 * quiz right now.
77ed3ba5 1425 *
cd06115f 1426 * @param object $quiz the quiz instance.
1427 * @param object $attempt the attempt in question.
25302dee 1428 * @param $context the quiz context.
77ed3ba5 1429 *
25302dee 1430 * @return mod_quiz_display_options
cd06115f 1431 */
7ee80cab 1432function quiz_get_review_options($quiz, $attempt, $context) {
25302dee 1433 $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
62e76c67 1434
4f48fb42 1435 $options->readonly = true;
62e76c67 1436 $options->flags = quiz_get_flag_option($attempt, $context);
2709ee45
TH
1437 if (!empty($attempt->id)) {
1438 $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1439 array('attempt' => $attempt->id));
1440 }
b6e907a2 1441
9e83f3d1 1442 // Show a link to the comment box only for closed attempts.
be18f589 1443 if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
2709ee45 1444 !is_null($context) && has_capability('mod/quiz:grade', $context)) {
25302dee 1445 $options->manualcomment = question_display_options::VISIBLE;
7ee80cab
TH
1446 $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1447 array('attempt' => $attempt->id));
01600b51 1448 }
1449
25a03faa
TH
1450 if (!is_null($context) && !$attempt->preview &&
1451 has_capability('mod/quiz:viewreports', $context) &&
25302dee 1452 has_capability('moodle/grade:viewhidden', $context)) {
e2833e87 1453 // People who can see reports and hidden grades should be shown everything,
1454 // except during preview when teachers want to see what students see.
25302dee
TH
1455 $options->attempt = question_display_options::VISIBLE;
1456 $options->correctness = question_display_options::VISIBLE;
1457 $options->marks = question_display_options::MARK_AND_MAX;
1458 $options->feedback = question_display_options::VISIBLE;
1459 $options->numpartscorrect = question_display_options::VISIBLE;
e101ec9f 1460 $options->manualcomment = question_display_options::VISIBLE;
25302dee
TH
1461 $options->generalfeedback = question_display_options::VISIBLE;
1462 $options->rightanswer = question_display_options::VISIBLE;
1463 $options->overallfeedback = question_display_options::VISIBLE;
1464 $options->history = question_display_options::VISIBLE;
e2833e87 1465
4f48fb42 1466 }
77ed3ba5 1467
4f48fb42 1468 return $options;
1469}
77ed3ba5 1470
40377b18 1471/**
77ed3ba5 1472 * Combines the review options from a number of different quiz attempts.
25302dee 1473 * Returns an array of two ojects, so the suggested way of calling this
77ed3ba5 1474 * funciton is:
1475 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1476 *
1477 * @param object $quiz the quiz instance.
1478 * @param array $attempts an array of attempt objects.
77ed3ba5 1479 *
1480 * @return array of two options objects, one showing which options are true for
1481 * at least one of the attempts, the other showing which options are true
1482 * for all attempts.
1483 */
25302dee 1484function quiz_get_combined_reviewoptions($quiz, $attempts) {
6d03fd98 1485 $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
0ff4bd08
TH
1486 $someoptions = new stdClass();
1487 $alloptions = new stdClass();
77ed3ba5 1488 foreach ($fields as $field) {
1489 $someoptions->$field = false;
1490 $alloptions->$field = true;
40377b18 1491 }
6d03fd98
TH
1492 $someoptions->marks = question_display_options::HIDDEN;
1493 $alloptions->marks = question_display_options::MARK_AND_MAX;
1494
c76425e8
JL
1495 // This shouldn't happen, but we need to prevent reveal information.
1496 if (empty($attempts)) {
1497 return array($someoptions, $someoptions);
1498 }
1499
77ed3ba5 1500 foreach ($attempts as $attempt) {
25302dee
TH
1501 $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1502 quiz_attempt_state($quiz, $attempt));
7d014bf5 1503 foreach ($fields as $field) {
1504 $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1505 $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1506 }
6d03fd98
TH
1507 $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1508 $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
77ed3ba5 1509 }
1510 return array($someoptions, $alloptions);
40377b18 1511}
ac48e43a 1512
9e83f3d1 1513// Functions for sending notification messages /////////////////////////////////
ac48e43a 1514
1515/**
cbb8b55c 1516 * Sends a confirmation message to the student confirming that the attempt was processed.
ac48e43a 1517 *
cbb8b55c
TH
1518 * @param object $a lots of useful information that can be used in the message
1519 * subject and body.
ac48e43a 1520 *
cbb8b55c 1521 * @return int|false as for {@link message_send()}.
ac48e43a 1522 */
cbb8b55c 1523function quiz_send_confirmation($recipient, $a) {
ac48e43a 1524
9e83f3d1 1525 // Add information about the recipient to $a.
cbb8b55c
TH
1526 // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1527 $a->username = fullname($recipient);
1528 $a->userusername = $recipient->username;
ac48e43a 1529
9e83f3d1 1530 // Prepare the message.
cc350fd9
AD
1531 $eventdata = new \core\message\message();
1532 $eventdata->courseid = $a->courseid;
cbb8b55c
TH
1533 $eventdata->component = 'mod_quiz';
1534 $eventdata->name = 'confirmation';
94263cca
AD
1535 $eventdata->notification = 1;
1536
5540b2ca 1537 $eventdata->userfrom = core_user::get_noreply_user();
cbb8b55c
TH
1538 $eventdata->userto = $recipient;
1539 $eventdata->subject = get_string('emailconfirmsubject', 'quiz', $a);
1540 $eventdata->fullmessage = get_string('emailconfirmbody', 'quiz', $a);
3b120e46 1541 $eventdata->fullmessageformat = FORMAT_PLAIN;
1542 $eventdata->fullmessagehtml = '';
94263cca
AD
1543
1544 $eventdata->smallmessage = get_string('emailconfirmsmall', 'quiz', $a);
1545 $eventdata->contexturl = $a->quizurl;
1546 $eventdata->contexturlname = $a->quizname;
99d19c13 1547
cbb8b55c
TH
1548 // ... and send it.
1549 return message_send($eventdata);
ac48e43a 1550}
1551
1552/**
bc68fc9a 1553 * Sends notification messages to the interested parties that assign the role capability
ac48e43a 1554 *
1555 * @param object $recipient user object of the intended recipient
0ff4bd08 1556 * @param object $a associative array of replaceable fields for the templates
ac48e43a 1557 *
cbb8b55c 1558 * @return int|false as for {@link message_send()}.
ac48e43a 1559 */
cbb8b55c 1560function quiz_send_notification($recipient, $submitter, $a) {
ac48e43a 1561
9e83f3d1 1562 // Recipient info for template.
cbb8b55c
TH
1563 $a->useridnumber = $recipient->idnumber;
1564 $a->username = fullname($recipient);
ac48e43a 1565 $a->userusername = $recipient->username;
ac48e43a 1566
9e83f3d1 1567 // Prepare the message.
cc350fd9
AD
1568 $eventdata = new \core\message\message();
1569 $eventdata->courseid = $a->courseid;
cbb8b55c
TH
1570 $eventdata->component = 'mod_quiz';
1571 $eventdata->name = 'submission';
bc68fc9a
AD
1572 $eventdata->notification = 1;
1573
cbb8b55c 1574 $eventdata->userfrom = $submitter;
3b120e46 1575 $eventdata->userto = $recipient;
cbb8b55c
TH
1576 $eventdata->subject = get_string('emailnotifysubject', 'quiz', $a);
1577 $eventdata->fullmessage = get_string('emailnotifybody', 'quiz', $a);
3b120e46 1578 $eventdata->fullmessageformat = FORMAT_PLAIN;
1579 $eventdata->fullmessagehtml = '';
bc68fc9a
AD
1580
1581 $eventdata->smallmessage = get_string('emailnotifysmall', 'quiz', $a);
1582 $eventdata->contexturl = $a->quizreviewurl;
1583 $eventdata->contexturlname = $a->quizname;
1584
cbb8b55c
TH
1585 // ... and send it.
1586 return message_send($eventdata);
ac48e43a 1587}
1588
1589/**
cbb8b55c 1590 * Send all the requried messages when a quiz attempt is submitted.
ac48e43a 1591 *
1592 * @param object $course the course
1593 * @param object $quiz the quiz
1594 * @param object $attempt this attempt just finished
1595 * @param object $context the quiz context
1596 * @param object $cm the coursemodule for this quiz
1597 *
cbb8b55c 1598 * @return bool true if all necessary messages were sent successfully, else false.
ac48e43a 1599 */
cbb8b55c
TH
1600function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1601 global $CFG, $DB;
ac48e43a 1602
9e83f3d1 1603 // Do nothing if required objects not present.
ac48e43a 1604 if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
cbb8b55c 1605 throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
ac48e43a 1606 }
1607
cbb8b55c
TH
1608 $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1609
9e83f3d1 1610 // Check for confirmation required.
ac48e43a 1611 $sendconfirm = false;
1612 $notifyexcludeusers = '';
cbb8b55c
TH
1613 if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1614 $notifyexcludeusers = $submitter->id;
ac48e43a 1615 $sendconfirm = true;
1616 }
1617
9e83f3d1 1618 // Check for notifications required.
692ef101
AD
1619 $notifyfields = 'u.id, u.username, u.idnumber, u.email, u.emailstop, u.lang,
1620 u.timezone, u.mailformat, u.maildisplay, u.auth, u.suspended, u.deleted, ';
b2b50d92 1621 $notifyfields .= get_all_user_name_fields(true, 'u');
efc76e9e 1622 $groups = groups_get_all_groups($course->id, $submitter->id, $cm->groupingid);
5a128471 1623 if (is_array($groups) && count($groups) > 0) {
1624 $groups = array_keys($groups);
255985f1 1625 } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1626 // If the user is not in a group, and the quiz is set to group mode,
cbb8b55c 1627 // then set $groups to a non-existant id so that only users with
255985f1 1628 // 'moodle/site:accessallgroups' get notified.
1629 $groups = -1;
5a128471 1630 } else {
1631 $groups = '';
1632 }
ac48e43a 1633 $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
5a128471 1634 $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
ac48e43a 1635
cbb8b55c
TH
1636 if (empty($userstonotify) && !$sendconfirm) {
1637 return true; // Nothing to do.
ac48e43a 1638 }
1639
cbb8b55c 1640 $a = new stdClass();
9e83f3d1 1641 // Course info.
cc350fd9 1642 $a->courseid = $course->id;
cbb8b55c
TH
1643 $a->coursename = $course->fullname;
1644 $a->courseshortname = $course->shortname;
9e83f3d1 1645 // Quiz info.
cbb8b55c
TH
1646 $a->quizname = $quiz->name;
1647 $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1648 $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' .
1649 format_string($quiz->name) . ' report</a>';
cbb8b55c
TH
1650 $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1651 $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
9e83f3d1 1652 // Attempt info.
cbb8b55c
TH
1653 $a->submissiontime = userdate($attempt->timefinish);
1654 $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
fd0537ce
TH
1655 $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1656 $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' .
1657 format_string($quiz->name) . ' review</a>';
9e83f3d1 1658 // Student who sat the quiz info.
cbb8b55c
TH
1659 $a->studentidnumber = $submitter->idnumber;
1660 $a->studentname = fullname($submitter);
1661 $a->studentusername = $submitter->username;
1662
1663 $allok = true;
1664
9e83f3d1 1665 // Send notifications if required.
ac48e43a 1666 if (!empty($userstonotify)) {
ac48e43a 1667 foreach ($userstonotify as $recipient) {
cbb8b55c 1668 $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
ac48e43a 1669 }
1670 }
1671
cbb8b55c
TH
1672 // Send confirmation if required. We send the student confirmation last, so
1673 // that if message sending is being intermittently buggy, which means we send
1674 // some but not all messages, and then try again later, then teachers may get
1675 // duplicate messages, but the student will always get exactly one.
1676 if ($sendconfirm) {
1677 $allok = $allok && quiz_send_confirmation($submitter, $a);
1678 }
1679
1680 return $allok;
1681}
1682
fd0537ce
TH
1683/**
1684 * Send the notification message when a quiz attempt becomes overdue.
1685 *
1c2e05c0 1686 * @param quiz_attempt $attemptobj all the data about the quiz attempt.
fd0537ce 1687 */
1c2e05c0 1688function quiz_send_overdue_message($attemptobj) {
fd0537ce
TH
1689 global $CFG, $DB;
1690
1c2e05c0 1691 $submitter = $DB->get_record('user', array('id' => $attemptobj->get_userid()), '*', MUST_EXIST);
fd0537ce 1692
1c2e05c0
TH
1693 if (!$attemptobj->has_capability('mod/quiz:emailwarnoverdue', $submitter->id, false)) {
1694 return; // Message not required.
1695 }
fd0537ce 1696
1c2e05c0 1697 if (!$attemptobj->has_response_to_at_least_one_graded_question()) {
fd0537ce
TH
1698 return; // Message not required.
1699 }
1700
1701 // Prepare lots of useful information that admins might want to include in
1702 // the email message.
1c2e05c0 1703 $quizname = format_string($attemptobj->get_quiz_name());
fd0537ce
TH
1704
1705 $deadlines = array();
1c2e05c0
TH
1706 if ($attemptobj->get_quiz()->timelimit) {
1707 $deadlines[] = $attemptobj->get_attempt()->timestart + $attemptobj->get_quiz()->timelimit;
fd0537ce 1708 }
1c2e05c0
TH
1709 if ($attemptobj->get_quiz()->timeclose) {
1710 $deadlines[] = $attemptobj->get_quiz()->timeclose;
fd0537ce 1711 }
59d14f31 1712 $duedate = min($deadlines);
1c2e05c0 1713 $graceend = $duedate + $attemptobj->get_quiz()->graceperiod;
fd0537ce
TH
1714
1715 $a = new stdClass();
1716 // Course info.
cc350fd9 1717 $a->courseid = $attemptobj->get_course()->id;
1c2e05c0
TH
1718 $a->coursename = format_string($attemptobj->get_course()->fullname);
1719 $a->courseshortname = format_string($attemptobj->get_course()->shortname);
fd0537ce
TH
1720 // Quiz info.
1721 $a->quizname = $quizname;
1c2e05c0 1722 $a->quizurl = $attemptobj->view_url();
fd0537ce
TH
1723 $a->quizlink = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1724 // Attempt info.
1c2e05c0 1725 $a->attemptduedate = userdate($duedate);
59d14f31 1726 $a->attemptgraceend = userdate($graceend);
1c2e05c0 1727 $a->attemptsummaryurl = $attemptobj->summary_url()->out(false);
fd0537ce
TH
1728 $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1729 // Student's info.
1730 $a->studentidnumber = $submitter->idnumber;
1731 $a->studentname = fullname($submitter);
1732 $a->studentusername = $submitter->username;
1733
1734 // Prepare the message.
cc350fd9
AD
1735 $eventdata = new \core\message\message();
1736 $eventdata->courseid = $a->courseid;
fd0537ce
TH
1737 $eventdata->component = 'mod_quiz';
1738 $eventdata->name = 'attempt_overdue';
1739 $eventdata->notification = 1;
1740
5540b2ca 1741 $eventdata->userfrom = core_user::get_noreply_user();
fd0537ce
TH
1742 $eventdata->userto = $submitter;
1743 $eventdata->subject = get_string('emailoverduesubject', 'quiz', $a);
1744 $eventdata->fullmessage = get_string('emailoverduebody', 'quiz', $a);
1745 $eventdata->fullmessageformat = FORMAT_PLAIN;
1746 $eventdata->fullmessagehtml = '';
1747
1748 $eventdata->smallmessage = get_string('emailoverduesmall', 'quiz', $a);
1749 $eventdata->contexturl = $a->quizurl;
1750 $eventdata->contexturlname = $a->quizname;
1751
1752 // Send the message.
1753 return message_send($eventdata);
1754}
1755
cbb8b55c
TH
1756/**
1757 * Handle the quiz_attempt_submitted event.
1758 *
1759 * This sends the confirmation and notification messages, if required.
1760 *
1761 * @param object $event the event object.
1762 */
1763function quiz_attempt_submitted_handler($event) {
1764 global $DB;
1765
1766 $course = $DB->get_record('course', array('id' => $event->courseid));
d900f1dc
FM
1767 $attempt = $event->get_record_snapshot('quiz_attempts', $event->objectid);
1768 $quiz = $event->get_record_snapshot('quiz', $attempt->quiz);
1769 $cm = get_coursemodule_from_id('quiz', $event->get_context()->instanceid, $event->courseid);
cbb8b55c
TH
1770
1771 if (!($course && $quiz && $cm && $attempt)) {
1772 // Something has been deleted since the event was raised. Therefore, the
1773 // event is no longer relevant.
1774 return true;
ac48e43a 1775 }
ac48e43a 1776
db3686d5
RM
1777 // Update completion state.
1778 $completion = new completion_info($course);
1779 if ($completion->is_enabled($cm) && ($quiz->completionattemptsexhausted || $quiz->completionpass)) {
1780 $completion->update_state($cm, COMPLETION_COMPLETE, $event->userid);
1781 }
cbb8b55c 1782 return quiz_send_notification_messages($course, $quiz, $attempt,
c492a78e 1783 context_module::instance($cm->id), $cm);
ac48e43a 1784}
fa583f5f 1785
8e771aed
MP
1786/**
1787 * Handle groups_member_added event
1788 *
1789 * @param object $event the event object.
11b0c8e0 1790 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_added()}.
8e771aed
MP
1791 */
1792function quiz_groups_member_added_handler($event) {
11b0c8e0
FM
1793 debugging('quiz_groups_member_added_handler() is deprecated, please use ' .
1794 '\mod_quiz\group_observers::group_member_added() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1795 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1796}
1797
1798/**
1799 * Handle groups_member_removed event
1800 *
1801 * @param object $event the event object.
11b0c8e0 1802 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
8e771aed
MP
1803 */
1804function quiz_groups_member_removed_handler($event) {
11b0c8e0
FM
1805 debugging('quiz_groups_member_removed_handler() is deprecated, please use ' .
1806 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1807 quiz_update_open_attempts(array('userid'=>$event->userid, 'groupid'=>$event->groupid));
1808}
1809
1810/**
1811 * Handle groups_group_deleted event
1812 *
1813 * @param object $event the event object.
11b0c8e0 1814 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_deleted()}.
8e771aed
MP
1815 */
1816function quiz_groups_group_deleted_handler($event) {
1817 global $DB;
11b0c8e0
FM
1818 debugging('quiz_groups_group_deleted_handler() is deprecated, please use ' .
1819 '\mod_quiz\group_observers::group_deleted() instead.', DEBUG_DEVELOPER);
1820 quiz_process_group_deleted_in_course($event->courseid);
1821}
1822
1823/**
1824 * Logic to happen when a/some group(s) has/have been deleted in a course.
1825 *
1826 * @param int $courseid The course ID.
1827 * @return void
1828 */
1829function quiz_process_group_deleted_in_course($courseid) {
1830 global $DB;
8e771aed
MP
1831
1832 // It would be nice if we got the groupid that was deleted.
11b0c8e0 1833 // Instead, we just update all quizzes with orphaned group overrides.
8e771aed
MP
1834 $sql = "SELECT o.id, o.quiz
1835 FROM {quiz_overrides} o
1836 JOIN {quiz} quiz ON quiz.id = o.quiz
1837 LEFT JOIN {groups} grp ON grp.id = o.groupid
74b3c4e5
MP
1838 WHERE quiz.course = :courseid
1839 AND o.groupid IS NOT NULL
1840 AND grp.id IS NULL";
11b0c8e0 1841 $params = array('courseid' => $courseid);
8e771aed 1842 $records = $DB->get_records_sql_menu($sql, $params);
1744033c
TH
1843 if (!$records) {
1844 return; // Nothing to do.
1845 }
8e771aed 1846 $DB->delete_records_list('quiz_overrides', 'id', array_keys($records));
11b0c8e0 1847 quiz_update_open_attempts(array('quizid' => array_unique(array_values($records))));
8e771aed
MP
1848}
1849
1850/**
1851 * Handle groups_members_removed event
1852 *
1853 * @param object $event the event object.
11b0c8e0 1854 * @deprecated since 2.6, see {@link \mod_quiz\group_observers::group_member_removed()}.
8e771aed
MP
1855 */
1856function quiz_groups_members_removed_handler($event) {
11b0c8e0
FM
1857 debugging('quiz_groups_members_removed_handler() is deprecated, please use ' .
1858 '\mod_quiz\group_observers::group_member_removed() instead.', DEBUG_DEVELOPER);
8e771aed
MP
1859 if ($event->userid == 0) {
1860 quiz_update_open_attempts(array('courseid'=>$event->courseid));
1861 } else {
1862 quiz_update_open_attempts(array('courseid'=>$event->courseid, 'userid'=>$event->userid));
1863 }
1864}
1865
fd0537ce
TH
1866/**
1867 * Get the information about the standard quiz JavaScript module.
1868 * @return array a standard jsmodule structure.
1869 */
ff065f96 1870function quiz_get_js_module() {
157434a5 1871 global $PAGE;
73a7a0c9 1872
ff065f96
TH
1873 return array(
1874 'name' => 'mod_quiz',
1875 'fullpath' => '/mod/quiz/module.js',
25a03faa 1876 'requires' => array('base', 'dom', 'event-delegate', 'event-key',
aebbfb7b 1877 'core_question_engine', 'moodle-core-formchangechecker'),
ff065f96 1878 'strings' => array(
73a7a0c9 1879 array('cancel', 'moodle'),
a26246ea 1880 array('flagged', 'question'),
d755b0f5
TH
1881 array('functiondisabledbysecuremode', 'quiz'),
1882 array('startattempt', 'quiz'),
1883 array('timesup', 'quiz'),
aebbfb7b 1884 array('changesmadereallygoaway', 'moodle'),
ff065f96
TH
1885 ),
1886 );
fe6ce234 1887}
25302dee
TH
1888
1889
1890/**
1891 * An extension of question_display_options that includes the extra options used
1892 * by the quiz.
1893 *
f7970e3c
TH
1894 * @copyright 2010 The Open University
1895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee
TH
1896 */
1897class mod_quiz_display_options extends question_display_options {
1898 /**#@+
1899 * @var integer bits used to indicate various times in relation to a
1900 * quiz attempt.
1901 */
1902 const DURING = 0x10000;
1903 const IMMEDIATELY_AFTER = 0x01000;
1904 const LATER_WHILE_OPEN = 0x00100;
1905 const AFTER_CLOSE = 0x00010;
1906 /**#@-*/
1907
1908 /**
1909 * @var boolean if this is false, then the student is not allowed to review
1910 * anything about the attempt.
1911 */
1912 public $attempt = true;
1913
1914 /**
1915 * @var boolean if this is false, then the student is not allowed to review
1916 * anything about the attempt.
1917 */
1918 public $overallfeedback = self::VISIBLE;
1919
1920 /**
1921 * Set up the various options from the quiz settings, and a time constant.
0ff4bd08 1922 * @param object $quiz the quiz settings.
f7970e3c 1923 * @param int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
25302dee
TH
1924 * {@link LATER_WHILE_OPEN} or {@link AFTER_CLOSE} constants.
1925 * @return mod_quiz_display_options set up appropriately.
1926 */
1927 public static function make_from_quiz($quiz, $when) {
1928 $options = new self();
1929
1930 $options->attempt = self::extract($quiz->reviewattempt, $when, true, false);
1931 $options->correctness = self::extract($quiz->reviewcorrectness, $when);
25a03faa
TH
1932 $options->marks = self::extract($quiz->reviewmarks, $when,
1933 self::MARK_AND_MAX, self::MAX_ONLY);
25302dee
TH
1934 $options->feedback = self::extract($quiz->reviewspecificfeedback, $when);
1935 $options->generalfeedback = self::extract($quiz->reviewgeneralfeedback, $when);
1936 $options->rightanswer = self::extract($quiz->reviewrightanswer, $when);
1937 $options->overallfeedback = self::extract($quiz->reviewoverallfeedback, $when);
1938
1939 $options->numpartscorrect = $options->feedback;
e101ec9f 1940 $options->manualcomment = $options->feedback;
25302dee
TH
1941
1942 if ($quiz->questiondecimalpoints != -1) {
1943 $options->markdp = $quiz->questiondecimalpoints;
1944 } else {
1945 $options->markdp = $quiz->decimalpoints;
1946 }
1947
1948 return $options;
1949 }
1950
25a03faa
TH
1951 protected static function extract($bitmask, $bit,
1952 $whenset = self::VISIBLE, $whennotset = self::HIDDEN) {
25302dee
TH
1953 if ($bitmask & $bit) {
1954 return $whenset;
1955 } else {
1956 return $whennotset;
1957 }
1958 }
1959}
1960
25302dee
TH
1961/**
1962 * A {@link qubaid_condition} for finding all the question usages belonging to
1963 * a particular quiz.
1964 *
f7970e3c
TH
1965 * @copyright 2010 The Open University
1966 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25302dee 1967 */
6b5f24d3 1968class qubaids_for_quiz extends qubaid_join {
25302dee 1969 public function __construct($quizid, $includepreviews = true, $onlyfinished = false) {
6b5f24d3 1970 $where = 'quiza.quiz = :quizaquiz';
be18f589
TH
1971 $params = array('quizaquiz' => $quizid);
1972
25302dee
TH
1973 if (!$includepreviews) {
1974 $where .= ' AND preview = 0';
1975 }
be18f589 1976
25302dee 1977 if ($onlyfinished) {
81c53579 1978 $where .= ' AND state = :statefinished';
be18f589 1979 $params['statefinished'] = quiz_attempt::FINISHED;
25302dee
TH
1980 }
1981
be18f589 1982 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
25302dee
TH
1983 }
1984}
e1a2d0d9 1985
4c729982
AN
1986/**
1987 * A {@link qubaid_condition} for finding all the question usages belonging to a particular user and quiz combination.
1988 *
1989 * @copyright 2018 Andrew Nicols <andrwe@nicols.co.uk>
1990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1991 */
1992class qubaids_for_quiz_user extends qubaid_join {
1993 /**
1994 * Constructor for this qubaid.
1995 *
1996 * @param int $quizid The quiz to search.
1997 * @param int $userid The user to filter on
1998 * @param bool $includepreviews Whether to include preview attempts
1999 * @param bool $onlyfinished Whether to only include finished attempts or not
2000 */
2001 public function __construct($quizid, $userid, $includepreviews = true, $onlyfinished = false) {
2002 $where = 'quiza.quiz = :quizaquiz AND quiza.userid = :quizauserid';
2003 $params = [
2004 'quizaquiz' => $quizid,
2005 'quizauserid' => $userid,
2006 ];
2007
2008 if (!$includepreviews) {
2009 $where .= ' AND preview = 0';
2010 }
2011
2012 if ($onlyfinished) {
2013 $where .= ' AND state = :statefinished';
2014 $params['statefinished'] = quiz_attempt::FINISHED;
2015 }
2016
be18f589 2017 parent::__construct('{quiz_attempts} quiza', 'quiza.uniqueid', $where, $params);
25302dee
TH
2018 }
2019}
e1a2d0d9
CC
2020
2021/**
2022 * Creates a textual representation of a question for display.
2023 *
2024 * @param object $question A question object from the database questions table
2025 * @param bool $showicon If true, show the question's icon with the question. False by default.
2026 * @param bool $showquestiontext If true (default), show question text after question name.
2027 * If false, show only question name.
2028 * @return string
2029 */
2030function quiz_question_tostring($question, $showicon = false, $showquestiontext = true) {
2031 $result = '';
2032
2033 $name = shorten_text(format_string($question->name), 200);
2034 if ($showicon) {
2035 $name .= print_question_icon($question) . ' ' . $name;
2036 }
2037 $result .= html_writer::span($name, 'questionname');
2038
2039 if ($showquestiontext) {
2040 $questiontext = question_utils::to_plain_text($question->questiontext,
2041 $question->questiontextformat, array('noclean' => true, 'para' => false));
2042 $questiontext = shorten_text($questiontext, 200);
2043 if ($questiontext) {
2044 $result .= ' ' . html_writer::span(s($questiontext), 'questiontext');
2045 }
2046 }
2047
2048 return $result;
2049}
16fa272e
TH
2050
2051/**
2052 * Verify that the question exists, and the user has permission to use it.
2053 * Does not return. Throws an exception if the question cannot be used.
2054 * @param int $questionid The id of the question.
2055 */
2056function quiz_require_question_use($questionid) {
2057 global $DB;
2058 $question = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
2059 question_require_capability_on($question, 'use');
2060}
2061
2062/**
2063 * Verify that the question exists, and the user has permission to use it.
2064 * @param object $quiz the quiz settings.
2065 * @param int $slot which question in the quiz to test.
2066 * @return bool whether the user can use this question.
2067 */
2068function quiz_has_question_use($quiz, $slot) {
2069 global $DB;
2070 $question = $DB->get_record_sql("
2071 SELECT q.*
2072 FROM {quiz_slots} slot
2073 JOIN {question} q ON q.id = slot.questionid
2074 WHERE slot.quizid = ? AND slot.slot = ?", array($quiz->id, $slot));
2075 if (!$question) {
2076 return false;
2077 }
2078 return question_has_capability_on($question, 'use');
2079}
2080
2081/**
2082 * Add a question to a quiz
2083 *
2084 * Adds a question to a quiz by updating $quiz as well as the
2085 * quiz and quiz_slots tables. It also adds a page break if required.
2086 * @param int $questionid The id of the question to be added
2087 * @param object $quiz The extended quiz object as used by edit.php
2088 * This is updated by this function
2089 * @param int $page Which page in quiz to add the question on. If 0 (default),
2090 * add at the end
2091 * @param float $maxmark The maximum mark to set for this question. (Optional,
2092 * defaults to question.defaultmark.
2093 * @return bool false if the question was already in the quiz
2094 */
2095function quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null) {
2096 global $DB;
4fa49cc6
SR
2097
2098 // Make sue the question is not of the "random" type.
2099 $questiontype = $DB->get_field('question', 'qtype', array('id' => $questionid));
2100 if ($questiontype == 'random') {
2101 throw new coding_exception(
2102 'Adding "random" questions via quiz_add_quiz_question() is deprecated. Please use quiz_add_random_questions().'
2103 );
2104 }
2105
16fa272e
TH
2106 $slots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id),
2107 'slot', 'questionid, slot, page, id');
2108 if (array_key_exists($questionid, $slots)) {
2109 return false;
2110 }
2111
2112 $trans = $DB->start_delegated_transaction();
2113
2114 $maxpage = 1;
2115 $numonlastpage = 0;
2116 foreach ($slots as $slot) {
2117 if ($slot->page > $maxpage) {
2118 $maxpage = $slot->page;
2119 $numonlastpage = 1;
2120 } else {
2121 $numonlastpage += 1;
2122 }
2123 }
2124
2125 // Add the new question instance.
2126 $slot = new stdClass();
2127 $slot->quizid = $quiz->id;
2128 $slot->questionid = $questionid;
2129
2130 if ($maxmark !== null) {
2131 $slot->maxmark = $maxmark;
2132 } else {
2133 $slot->maxmark = $DB->get_field('question', 'defaultmark', array('id' => $questionid));
2134 }
2135
2136 if (is_int($page) && $page >= 1) {
2137 // Adding on a given page.
2138 $lastslotbefore = 0;
2139 foreach (array_reverse($slots) as $otherslot) {
2140 if ($otherslot->page > $page) {
2141 $DB->set_field('quiz_slots', 'slot', $otherslot->slot + 1, array('id' => $otherslot->id));
2142 } else {
2143 $lastslotbefore = $otherslot->slot;
2144 break;
2145 }
2146 }
2147 $slot->slot = $lastslotbefore + 1;
2148 $slot->page = min($page, $maxpage + 1);
2149
6c73dd95 2150 quiz_update_section_firstslots($quiz->id, 1, max($lastslotbefore, 1));
5d949702 2151
16fa272e
TH
2152 } else {
2153 $lastslot = end($slots);
2154 if ($lastslot) {
2155 $slot->slot = $lastslot->slot + 1;
2156 } else {
2157 $slot->slot = 1;
2158 }
2159 if ($quiz->questionsperpage && $numonlastpage >= $quiz->questionsperpage) {
2160 $slot->page = $maxpage + 1;
2161 } else {
2162 $slot->page = $maxpage;
2163 }
2164 }
2165
2166 $DB->insert_record('quiz_slots', $slot);
2167 $trans->allow_commit();
2168}
2169
6c73dd95
TH
2170/**
2171 * Move all the section headings in a certain slot range by a certain offset.
2172 *
2173 * @param int $quizid the id of a quiz
2174 * @param int $direction amount to adjust section heading positions. Normally +1 or -1.
2175 * @param int $afterslot adjust headings that start after this slot.
2176 * @param int|null $beforeslot optionally, only adjust headings before this slot.
2177 */
2178function quiz_update_section_firstslots($quizid, $direction, $afterslot, $beforeslot = null) {
2179 global $DB;
2180 $where = 'quizid = ? AND firstslot > ?';
2181 $params = [$direction, $quizid, $afterslot];
2182 if ($beforeslot) {
2183 $where .= ' AND firstslot < ?';
2184 $params[] = $beforeslot;
2185 }
2186 $firstslotschanges = $DB->get_records_select_menu('quiz_sections',
2187 $where, $params, '', 'firstslot, firstslot + ?');
2188 update_field_with_unique_index('quiz_sections', 'firstslot', $firstslotschanges, ['quizid' => $quizid]);
2189}
2190
16fa272e
TH
2191/**
2192 * Add a random question to the quiz at a given point.
4fa49cc6 2193 * @param stdClass $quiz the quiz settings.
16fa272e
TH
2194 * @param int $addonpage the page on which to add the question.
2195 * @param int $categoryid the question category to add the question from.
2196 * @param int $number the number of random questions to add.
2197 * @param bool $includesubcategories whether to include questoins from subcategories.
4f964a1c 2198 * @param int[] $tagids Array of tagids. The question that will be picked randomly should be tagged with all these tags.
16fa272e
TH
2199 */
2200function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,
4f964a1c 2201 $includesubcategories, $tagids = []) {
16fa272e
TH
2202 global $DB;
2203
2204 $category = $DB->get_record('question_categories', array('id' => $categoryid));
2205 if (!$category) {
2206 print_error('invalidcategoryid', 'error');
2207 }
2208
2209 $catcontext = context::instance_by_id($category->contextid);
2210 require_capability('moodle/question:useall', $catcontext);
2211
d62793fd 2212 $tags = \core_tag_tag::get_bulk($tagids, 'id, name');
4f964a1c 2213 $tagstrings = [];
d62793fd
SR
2214 foreach ($tags as $tag) {
2215 $tagstrings[] = "{$tag->id},{$tag->name}";
4f964a1c 2216 }
4fa49cc6 2217
16fa272e
TH
2218 // Find existing random questions in this category that are
2219 // not used by any quiz.
4fa49cc6
SR
2220 $existingquestions = $DB->get_records_sql(
2221 "SELECT q.id, q.qtype FROM {question} q
2222 WHERE qtype = 'random'
2223 AND category = ?
2224 AND " . $DB->sql_compare_text('questiontext') . " = ?
2225 AND NOT EXISTS (
2226 SELECT *
2227 FROM {quiz_slots}
2228 WHERE questionid = q.id)
4f964a1c 2229 ORDER BY id", array($category->id, $includesubcategories ? '1' : '0'));
4fa49cc6
SR
2230
2231 for ($i = 0; $i < $number; $i++) {
2232 // Take as many of orphaned "random" questions as needed.
2233 if (!$question = array_shift($existingquestions)) {
2234 $form = new stdClass();
4fa49cc6 2235 $form->category = $category->id . ',' . $category->contextid;
4f964a1c
SR
2236 $form->includesubcategories = $includesubcategories;
2237 $form->fromtags = $tagstrings;
4fa49cc6
SR
2238 $form->defaultmark = 1;
2239 $form->hidden = 1;
2240 $form->stamp = make_unique_id_code(); // Set the unique code (not to be changed).
2241 $question = new stdClass();
2242 $question->qtype = 'random';
2243 $question = question_bank::get_qtype('random')->save_question($question, $form);
2244 if (!isset($question->id)) {
2245 print_error('cannotinsertrandomquestion', 'quiz');
2246 }
16fa272e 2247 }
16fa272e 2248
4fa49cc6
SR
2249 $randomslotdata = new stdClass();
2250 $randomslotdata->quizid = $quiz->id;
2251 $randomslotdata->questionid = $question->id;
2252 $randomslotdata->questioncategoryid = $categoryid;
2253 $randomslotdata->includingsubcategories = $includesubcategories ? 1 : 0;
4fa49cc6
SR
2254 $randomslotdata->maxmark = 1;
2255
2256 $randomslot = new \mod_quiz\local\structure\slot_random($randomslotdata);
2257 $randomslot->set_quiz($quiz);
d62793fd 2258 $randomslot->set_tags($tags);
4fa49cc6 2259 $randomslot->insert($addonpage);
16fa272e
TH
2260 }
2261}
19429de4
JL
2262
2263/**
2264 * Mark the activity completed (if required) and trigger the course_module_viewed event.
2265 *
2266 * @param stdClass $quiz quiz object
2267 * @param stdClass $course course object
2268 * @param stdClass $cm course module object
2269 * @param stdClass $context context object
2270 * @since Moodle 3.1
2271 */
2272function quiz_view($quiz, $course, $cm, $context) {
2273
2274 $params = array(
2275 'objectid' => $quiz->id,
2276 'context' => $context
2277 );
2278
2279 $event = \mod_quiz\event\course_module_viewed::create($params);
2280 $event->add_record_snapshot('quiz', $quiz);
2281 $event->trigger();
2282
2283 // Completion.
2284 $completion = new completion_info($course);
2285 $completion->set_module_viewed($cm);
0057c2ce
JL
2286}
2287
2288/**
2289 * Validate permissions for creating a new attempt and start a new preview attempt if required.
2290 *
2291 * @param quiz $quizobj quiz object
2292 * @param quiz_access_manager $accessmanager quiz access manager
2293 * @param bool $forcenew whether was required to start a new preview attempt
2294 * @param int $page page to jump to in the attempt
2295 * @param bool $redirect whether to redirect or throw exceptions (for web or ws usage)
2296 * @return array an array containing the attempt information, access error messages and the page to jump to in the attempt
2297 * @throws moodle_quiz_exception
2298 * @since Moodle 3.1
2299 */
2300function quiz_validate_new_attempt(quiz $quizobj, quiz_access_manager $accessmanager, $forcenew, $page, $redirect) {
2301 global $DB, $USER;
2302 $timenow = time();
2303
2304 if ($quizobj->is_preview_user() && $forcenew) {
2305 $accessmanager->current_attempt_finished();
2306 }
2307
2308 // Check capabilities.
2309 if (!$quizobj->is_preview_user()) {
2310 $quizobj->require_capability('mod/quiz:attempt');
2311 }
2312
2313 // Check to see if a new preview was requested.
2314 if ($quizobj->is_preview_user() && $forcenew) {
2315 // To force the creation of a new preview, we mark the current attempt (if any)
2316 // as finished. It will then automatically be deleted below.
2317 $DB->set_field('quiz_attempts', 'state', quiz_attempt::FINISHED,
2318 array('quiz' => $quizobj->get_quizid(), 'userid' => $USER->id));
2319 }
2320
2321 // Look for an existing attempt.
2322 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $USER->id, 'all', true);
2323 $lastattempt = end($attempts);
2324
2325 $attemptnumber = null;
2326 // If an in-progress attempt exists, check password then redirect to it.
2327 if ($lastattempt && ($lastattempt->state == quiz_attempt::IN_PROGRESS ||
2328 $lastattempt->state == quiz_attempt::OVERDUE)) {
2329 $currentattemptid = $lastattempt->id;
2330 $messages = $accessmanager->prevent_access();
2331
2332 // If the attempt is now overdue, deal with that.
2333 $quizobj->create_attempt_object($lastattempt)->handle_if_time_expired($timenow, true);
2334
2335 // And, if the attempt is now no longer in progress, redirect to the appropriate place.
2336 if ($lastattempt->state == quiz_attempt::ABANDONED || $lastattempt->state == quiz_attempt::FINISHED) {
2337 if ($redirect) {
2338 redirect($quizobj->review_url($lastattempt->id));
2339 } else {
2340 throw new moodle_quiz_exception($quizobj, 'attemptalreadyclosed');
2341 }
2342 }
2343
2344 // If the page number was not explicitly in the URL, go to the current page.
2345 if ($page == -1) {
2346 $page = $lastattempt->currentpage;
2347 }
2348
2349 } else {
2350 while ($lastattempt && $lastattempt->preview) {
2351 $lastattempt = array_pop($attempts);
2352 }
19429de4 2353
0057c2ce
JL
2354 // Get number for the next or unfinished attempt.
2355 if ($lastattempt) {
2356 $attemptnumber = $lastattempt->attempt + 1;
2357 } else {
2358 $lastattempt = false;
2359 $attemptnumber = 1;
2360 }
2361 $currentattemptid = null;
2362
2363 $messages = $accessmanager->prevent_access() +
2364 $accessmanager->prevent_new_attempt(count($attempts), $lastattempt);
2365
2366 if ($page == -1) {
2367 $page = 0;
2368 }
2369 }
2370 return array($currentattemptid, $attemptnumber, $lastattempt, $messages, $page);
2371}
2372
2373/**
2374 * Prepare and start a new attempt deleting the previous preview attempts.
2375 *
2376 * @param quiz $quizobj quiz object
2377 * @param int $attemptnumber the attempt number
2378 * @param object $lastattempt last attempt object
8a972ab3 2379 * @param bool $offlineattempt whether is an offline attempt or not
0057c2ce
JL
2380 * @return object the new attempt
2381 * @since Moodle 3.1
2382 */
8a972ab3 2383function quiz_prepare_and_start_new_attempt(quiz $quizobj, $attemptnumber, $lastattempt, $offlineattempt = false) {
0057c2ce
JL
2384 global $DB, $USER;
2385
2386 // Delete any previous preview attempts belonging to this user.
2387 quiz_delete_previews($quizobj->get_quiz(), $USER->id);
2388
2389 $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
2390 $quba->set_preferred_behaviour($quizobj->get_quiz()->preferredbehaviour);
2391
2392 // Create the new attempt and initialize the question sessions
2393 $timenow = time(); // Update time now, in case the server is running really slowly.
2394 $attempt = quiz_create_attempt($quizobj, $attemptnumber, $lastattempt, $timenow, $quizobj->is_preview_user());
2395
2396 if (!($quizobj->get_quiz()->attemptonlast && $lastattempt)) {
2397 $attempt = quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow);
2398 } else {
2399 $attempt = quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt);
2400 }
2401
2402 $transaction = $DB->start_delegated_transaction();
2403
8a972ab3
JL
2404 // Init the timemodifiedoffline for offline attempts.
2405 if ($offlineattempt) {
2406 $attempt->timemodifiedoffline = $attempt->timemodified;
2407 }
0057c2ce
JL
2408 $attempt = quiz_attempt_save_started($quizobj, $quba, $attempt);
2409
2410 $transaction->allow_commit();
2411
2412 return $attempt;
19429de4 2413}
9aac9f70
RW
2414
2415/**
2416 * Check if the given calendar_event is either a user or group override
2417 * event for quiz.
2418 *
2419 * @param calendar_event $event The calendar event to check
2420 * @return bool
2421 */
2422function quiz_is_overriden_calendar_event(\calendar_event $event) {
2423 global $DB;
2424
2425 if (!isset($event->modulename)) {
2426 return false;
2427 }
2428
2429 if ($event->modulename != 'quiz') {
2430 return false;
2431 }
2432
2433 if (!isset($event->instance)) {
2434 return false;
2435 }
2436
2437 if (!isset($event->userid) && !isset($event->groupid)) {
2438 return false;
2439 }
2440
2441 $overrideparams = [
2442 'quiz' => $event->instance
2443 ];
2444
2445 if (isset($event->groupid)) {
2446 $overrideparams['groupid'] = $event->groupid;
2447 } else if (isset($event->userid)) {
2448 $overrideparams['userid'] = $event->userid;
2449 }
2450
2451 return $DB->record_exists('quiz_overrides', $overrideparams);
2452}
6650c66b 2453
2a1c9dac 2454/**
8f0f0a59
RW
2455 * Retrieves tag information for the given list of quiz slot ids.
2456 * Currently the only slots that have tags are random question slots.
2a1c9dac 2457 *
8f0f0a59
RW
2458 * Example:
2459 * If we have 3 slots with id 1, 2, and 3. The first slot has two tags, the second
2460 * has one tag, and the third has zero tags. The return structure will look like:
2461 * [
2462 * 1 => [
2463 * { ...tag data... },
2464 * { ...tag data... },
2465 * ],
2466 * 2 => [
2467 * { ...tag data... }
2468 * ],
2469 * 3 => []
2470 * ]
2471 *
2472 * @param int[] $slotids The list of id for the quiz slots.
2473 * @return array[] List of quiz_slot_tags records indexed by slot id.
66aa172c 2474 */
8f0f0a59 2475function quiz_retrieve_tags_for_slot_ids($slotids) {
66aa172c
SR
2476 global $DB;
2477
8f0f0a59
RW
2478 if (empty($slotids)) {
2479 return [];
2480 }
66aa172c 2481
8f0f0a59 2482 $slottags = $DB->get_records_list('quiz_slot_tags', 'slotid', $slotids);
66aa172c 2483 $tagsbyid = core_tag_tag::get_bulk(array_filter(array_column($slottags, 'tagid')), 'id, name');
66aa172c 2484 $tagsbyname = false; // It will be loaded later if required.
8f0f0a59
RW
2485 $emptytagids = array_reduce($slotids, function($carry, $slotid) {
2486 $carry[$slotid] = [];
2487 return $carry;
2488 }, []);
2489
2490 return array_reduce(
2491 $slottags,
2492 function($carry, $slottag) use ($slottags, $tagsbyid, $tagsbyname) {
2493 if (isset($tagsbyid[$slottag->tagid])) {
2494 // Make sure that we're returning the most updated tag name.
2495 $slottag->tagname = $tagsbyid[$slottag->tagid]->name;
66aa172c 2496 } else {
8f0f0a59
RW
2497 if ($tagsbyname === false) {
2498 // We were hoping that this query could be avoided, but life
2499 // showed its other side to us!
2500 $tagcollid = core_tag_area::get_collection('core', 'question');
2501 $tagsbyname = core_tag_tag::get_by_name_bulk(
2502 $tagcollid,
2503 array_column($slottags, 'tagname'),
2504 'id, name'
2505 );
2506 }
2507 if (isset($tagsbyname[$slottag->tagname])) {
2508 // Make sure that we're returning the current tag id that matches
2509 // the given tag name.
2510 $slottag->tagid = $tagsbyname[$slottag->tagname]->id;
2511 } else {
2512 // The tag does not exist anymore (neither the tag id nor the tag name
2513 // matches an existing tag).
2514 // We still need to include this row in the result as some callers might
2515 // be interested in these rows. An example is the editing forms that still
2516 // need to display tag names even if they don't exist anymore.
2517 $slottag->tagid = null;
2518 }
66aa172c 2519 }
66aa172c 2520
8f0f0a59
RW
2521 $carry[$slottag->slotid][] = $slottag;
2522 return $carry;
2523 },
2524 $emptytagids
2525 );
2526}
2527
2528/**
2529 * Retrieves tag information for the given quiz slot.
2530 * A quiz slot have some tags if and only if it is representing a random question by tags.
2531 *
2532 * @param int $slotid The id of the quiz slot.
2533 * @return stdClass[] List of quiz_slot_tags records.
2534 */
2535function quiz_retrieve_slot_tags($slotid) {
2536 $slottags = quiz_retrieve_tags_for_slot_ids([$slotid]);
2537 return $slottags[$slotid];
66aa172c
SR
2538}
2539
2540/**
2541 * Retrieves tag ids for the given quiz slot.
2542 * A quiz slot have some tags if and only if it is representing a random question by tags.
2543 *
2544 * @param int $slotid The id of the quiz slot.
2545 * @return int[]
2a1c9dac 2546 */
66aa172c
SR
2547function quiz_retrieve_slot_tag_ids($slotid) {
2548 $tags = quiz_retrieve_slot_tags($slotid);
76d1f12d
SR
2549
2550 // Only work with tags that exist.
66aa172c 2551 return array_filter(array_column($tags, 'tagid'));
f4695ec7 2552}
2553
2554/**
2555 * Get quiz attempt and handling error.
2556 *
2557 * @param int $attemptid the id of the current attempt.
2558 * @param int|null $cmid the course_module id for this quiz.
2559 * @return quiz_attempt $attemptobj all the data about the quiz attempt.
2560 * @throws moodle_exception
2561 */
2562function quiz_create_attempt_handling_errors($attemptid, $cmid = null) {
2563 try {
2564 $attempobj = quiz_attempt::create($attemptid);
2565 } catch (moodle_exception $e) {
2566 if (!empty($cmid)) {
2567 list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'quiz');
2568 $continuelink = new moodle_url('/mod/quiz/view.php', array('id' => $cmid));
2569 $context = context_module::instance($cm->id);
2570 if (has_capability('mod/quiz:preview', $context)) {
2571 throw new moodle_exception('attempterrorcontentchange', 'quiz', $continuelink);
2572 } else {
2573 throw new moodle_exception('attempterrorcontentchangeforuser', 'quiz', $continuelink);
2574 }
2575 } else {
2576 throw new moodle_exception('attempterrorinvalid', 'quiz');
2577 }
2578 }
2579 if (!empty($cmid) && $attempobj->get_cmid() != $cmid) {
2580 throw new moodle_exception('invalidcoursemodule');
2581 } else {
2582 return $attempobj;
2583 }
2584}