Merge branch 'MDL-53858' of git://github.com/timhunt/moodle
[moodle.git] / mod / quiz / attemptlib.php
CommitLineData
36e413e3 1<?php
d18675a8 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/>.
16
36e413e3 17/**
d18675a8 18 * Back-end code for handling data about quizzes and the current user's attempt.
19 *
20 * There are classes for loading all the information about a quiz and attempts,
21 * and for displaying the navigation panel.
22 *
34b7d838
TH
23 * @package mod_quiz
24 * @copyright 2008 onwards Tim Hunt
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d18675a8 26 */
36e413e3 27
36e413e3 28
a17b297d 29defined('MOODLE_INTERNAL') || die();
a1eb3a44
TH
30
31
36e413e3 32/**
b10c38a3 33 * Class for quiz exceptions. Just saves a couple of arguments on the
34 * constructor for a moodle_exception.
d18675a8 35 *
34b7d838
TH
36 * @copyright 2008 Tim Hunt
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.0
36e413e3 39 */
40class moodle_quiz_exception extends moodle_exception {
25a03faa 41 public function __construct($quizobj, $errorcode, $a = null, $link = '', $debuginfo = null) {
36e413e3 42 if (!$link) {
43 $link = $quizobj->view_url();
44 }
45 parent::__construct($errorcode, 'quiz', $link, $a, $debuginfo);
46 }
47}
48
f7970e3c 49
b10c38a3 50/**
d18675a8 51 * A class encapsulating a quiz and the questions it contains, and making the
52 * information available to scripts like view.php.
53 *
54 * Initially, it only loads a minimal amout of information about each question - loading
55 * extra information only when necessary or when asked. The class tracks which questions
56 * are loaded.
57 *
f7970e3c
TH
58 * @copyright 2008 Tim Hunt
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 * @since Moodle 2.0
b10c38a3 61 */
36e413e3 62class quiz {
5d949702 63 /** @var stdClass the course settings from the database. */
36e413e3 64 protected $course;
5d949702 65 /** @var stdClass the course_module settings from the database. */
36e413e3 66 protected $cm;
5d949702 67 /** @var stdClass the quiz settings from the database. */
36e413e3 68 protected $quiz;
5d949702 69 /** @var context the quiz context. */
36e413e3 70 protected $context;
7b6757b0 71
5d949702 72 /** @var array of questions augmented with slot information. */
78e7a3dd 73 protected $questions = null;
5d949702
K
74 /** @var array of quiz_section rows. */
75 protected $sections = null;
76 /** @var quiz_access_manager the access manager for this quiz. */
36e413e3 77 protected $accessmanager = null;
5d949702 78 /** @var bool whether the current user has capability mod/quiz:preview. */
b10c38a3 79 protected $ispreviewuser = null;
36e413e3 80
9e83f3d1 81 // Constructor =============================================================
b10c38a3 82 /**
83 * Constructor, assuming we already have the necessary data loaded.
84 *
85 * @param object $quiz the row from the quiz table.
86 * @param object $cm the course_module object for this quiz.
87 * @param object $course the row from the course table for the course we belong to.
f7970e3c 88 * @param bool $getcontext intended for testing - stops the constructor getting the context.
b10c38a3 89 */
c7df5006 90 public function __construct($quiz, $cm, $course, $getcontext = true) {
36e413e3 91 $this->quiz = $quiz;
92 $this->cm = $cm;
a18ba12c 93 $this->quiz->cmid = $this->cm->id;
36e413e3 94 $this->course = $course;
739b0711 95 if ($getcontext && !empty($cm->id)) {
c492a78e 96 $this->context = context_module::instance($cm->id);
739b0711 97 }
36e413e3 98 }
99
990650f9
TH
100 /**
101 * Static function to create a new quiz object for a specific user.
102 *
f7970e3c
TH
103 * @param int $quizid the the quiz id.
104 * @param int $userid the the userid.
a88ba570 105 * @return quiz the new quiz object
990650f9 106 */
e1a2d0d9 107 public static function create($quizid, $userid = null) {
990650f9
TH
108 global $DB;
109
dd70d561 110 $quiz = quiz_access_manager::load_quiz_and_settings($quizid);
74df2951 111 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
88f0eb15 112 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
990650f9 113
9e83f3d1 114 // Update quiz with override information.
e1a2d0d9
CC
115 if ($userid) {
116 $quiz = quiz_update_effective_access($quiz, $userid);
117 }
990650f9
TH
118
119 return new quiz($quiz, $cm, $course);
120 }
121
34b7d838
TH
122 /**
123 * Create a {@link quiz_attempt} for an attempt at this quiz.
124 * @param object $attemptdata row from the quiz_attempts table.
125 * @return quiz_attempt the new quiz_attempt object.
126 */
127 public function create_attempt_object($attemptdata) {
128 return new quiz_attempt($attemptdata, $this->quiz, $this->cm, $this->course);
129 }
130
9e83f3d1 131 // Functions for loading more data =========================================
78e7a3dd 132
d18675a8 133 /**
134 * Load just basic information about all the questions in this quiz.
135 */
78e7a3dd 136 public function preload_questions() {
ccba5b88
TH
137 $this->questions = question_preload_questions(null,
138 'slot.maxmark, slot.id AS slotid, slot.slot, slot.page',
139 '{quiz_slots} slot ON slot.quizid = :quizid AND q.id = slot.questionid',
140 array('quizid' => $this->quiz->id), 'slot.slot');
36e413e3 141 }
142
25a03faa
TH
143 /**
144 * Fully load some or all of the questions for this quiz. You must call
145 * {@link preload_questions()} first.
36e413e3 146 *
78e7a3dd 147 * @param array $questionids question ids of the questions to load. null for all.
36e413e3 148 */
78e7a3dd 149 public function load_questions($questionids = null) {
ccba5b88
TH
150 if ($this->questions === null) {
151 throw new coding_exception('You must call preload_questions before calling load_questions.');
152 }
78e7a3dd 153 if (is_null($questionids)) {
ccba5b88 154 $questionids = array_keys($this->questions);
78e7a3dd 155 }
156 $questionstoprocess = array();
157 foreach ($questionids as $id) {
a1eb3a44
TH
158 if (array_key_exists($id, $this->questions)) {
159 $questionstoprocess[$id] = $this->questions[$id];
160 }
36e413e3 161 }
a8a8ec51 162 get_question_options($questionstoprocess);
36e413e3 163 }
164
e1a2d0d9
CC
165 /**
166 * Get an instance of the {@link \mod_quiz\structure} class for this quiz.
167 * @return \mod_quiz\structure describes the questions in the quiz.
168 */
169 public function get_structure() {
170 return \mod_quiz\structure::create_for_quiz($this);
171 }
172
9e83f3d1 173 // Simple getters ==========================================================
f7970e3c 174 /** @return int the course id. */
36e413e3 175 public function get_courseid() {
176 return $this->course->id;
177 }
178
78e7a3dd 179 /** @return object the row of the course table. */
180 public function get_course() {
181 return $this->course;
182 }
183
f7970e3c 184 /** @return int the quiz id. */
36e413e3 185 public function get_quizid() {
186 return $this->quiz->id;
187 }
188
b10c38a3 189 /** @return object the row of the quiz table. */
36e413e3 190 public function get_quiz() {
191 return $this->quiz;
192 }
193
b10c38a3 194 /** @return string the name of this quiz. */
36e413e3 195 public function get_quiz_name() {
196 return $this->quiz->name;
197 }
198
33c8d37b
CF
199 /** @return int the quiz navigation method. */
200 public function get_navigation_method() {
201 return $this->quiz->navmethod;
202 }
203
f7970e3c 204 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
b9b3aa94 205 public function get_num_attempts_allowed() {
206 return $this->quiz->attempts;
207 }
208
f7970e3c 209 /** @return int the course_module id. */
36e413e3 210 public function get_cmid() {
211 return $this->cm->id;
212 }
213
b10c38a3 214 /** @return object the course_module object. */
36e413e3 215 public function get_cm() {
216 return $this->cm;
217 }
218
a1eb3a44
TH
219 /** @return object the module context for this quiz. */
220 public function get_context() {
221 return $this->context;
222 }
223
b10c38a3 224 /**
f7970e3c 225 * @return bool wether the current user is someone who previews the quiz,
b10c38a3 226 * rather than attempting it.
227 */
228 public function is_preview_user() {
229 if (is_null($this->ispreviewuser)) {
230 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context);
231 }
232 return $this->ispreviewuser;
233 }
234
78e7a3dd 235 /**
a1eb3a44 236 * @return whether any questions have been added to this quiz.
78e7a3dd 237 */
a1eb3a44 238 public function has_questions() {
ccba5b88
TH
239 if ($this->questions === null) {
240 $this->preload_questions();
241 }
242 return !empty($this->questions);
78e7a3dd 243 }
244
b10c38a3 245 /**
f7970e3c 246 * @param int $id the question id.
b10c38a3 247 * @return object the question object with that id.
248 */
36e413e3 249 public function get_question($id) {
36e413e3 250 return $this->questions[$id];
251 }
252
78e7a3dd 253 /**
254 * @param array $questionids question ids of the questions to load. null for all.
255 */
256 public function get_questions($questionids = null) {
257 if (is_null($questionids)) {
ccba5b88 258 $questionids = array_keys($this->questions);
78e7a3dd 259 }
260 $questions = array();
261 foreach ($questionids as $id) {
a1eb3a44
TH
262 if (!array_key_exists($id, $this->questions)) {
263 throw new moodle_exception('cannotstartmissingquestion', 'quiz', $this->view_url());
264 }
78e7a3dd 265 $questions[$id] = $this->questions[$id];
266 $this->ensure_question_loaded($id);
267 }
268 return $questions;
269 }
270
b10c38a3 271 /**
5d949702
K
272 * Get all the sections in this quiz.
273 * @return array 0, 1, 2, ... => quiz_sections row from the database.
274 */
275 public function get_sections() {
276 global $DB;
277 if ($this->sections === null) {
278 $this->sections = array_values($DB->get_records('quiz_sections',
279 array('quizid' => $this->get_quizid()), 'firstslot'));
280 }
281 return $this->sections;
282 }
283
284 /**
285 * Return quiz_access_manager and instance of the quiz_access_manager class
286 * for this quiz at this time.
f7970e3c 287 * @param int $timenow the current time as a unix timestamp.
25a03faa
TH
288 * @return quiz_access_manager and instance of the quiz_access_manager class
289 * for this quiz at this time.
b10c38a3 290 */
36e413e3 291 public function get_access_manager($timenow) {
292 if (is_null($this->accessmanager)) {
78e7a3dd 293 $this->accessmanager = new quiz_access_manager($this, $timenow,
25a03faa 294 has_capability('mod/quiz:ignoretimelimits', $this->context, null, false));
36e413e3 295 }
296 return $this->accessmanager;
297 }
298
78e7a3dd 299 /**
300 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
301 */
25a03faa 302 public function has_capability($capability, $userid = null, $doanything = true) {
78e7a3dd 303 return has_capability($capability, $this->context, $userid, $doanything);
304 }
305
306 /**
307 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
308 */
25a03faa 309 public function require_capability($capability, $userid = null, $doanything = true) {
78e7a3dd 310 return require_capability($capability, $this->context, $userid, $doanything);
311 }
312
9e83f3d1 313 // URLs related to this attempt ============================================
b10c38a3 314 /**
315 * @return string the URL of this quiz's view page.
316 */
36e413e3 317 public function view_url() {
318 global $CFG;
319 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id;
320 }
321
78e7a3dd 322 /**
323 * @return string the URL of this quiz's edit page.
324 */
325 public function edit_url() {
326 global $CFG;
327 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id;
328 }
329
330 /**
f7970e3c 331 * @param int $attemptid the id of an attempt.
da729916 332 * @param int $page optional page number to go to in the attempt.
78e7a3dd 333 * @return string the URL of that attempt.
334 */
da729916 335 public function attempt_url($attemptid, $page = 0) {
78e7a3dd 336 global $CFG;
da729916
TH
337 $url = $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid;
338 if ($page) {
339 $url .= '&page=' . $page;
340 }
341 return $url;
78e7a3dd 342 }
343
344 /**
345 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
346 */
da729916
TH
347 public function start_attempt_url($page = 0) {
348 $params = array('cmid' => $this->cm->id, 'sesskey' => sesskey());
349 if ($page) {
350 $params['page'] = $page;
351 }
352 return new moodle_url('/mod/quiz/startattempt.php', $params);
78e7a3dd 353 }
354
355 /**
f7970e3c 356 * @param int $attemptid the id of an attempt.
78e7a3dd 357 * @return string the URL of the review of that attempt.
358 */
359 public function review_url($attemptid) {
ea9dbf24 360 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid));
78e7a3dd 361 }
362
34b7d838
TH
363 /**
364 * @param int $attemptid the id of an attempt.
365 * @return string the URL of the review of that attempt.
366 */
367 public function summary_url($attemptid) {
368 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $attemptid));
369 }
370
9e83f3d1 371 // Bits of content =========================================================
36e413e3 372
d755b0f5 373 /**
1f0f4131
TH
374 * @param bool $notused not used.
375 * @return string an empty string.
376 * @deprecated since 3.1. This sort of functionality is now entirely handled by quiz access rules.
d755b0f5 377 */
1f0f4131
TH
378 public function confirm_start_attempt_message($notused) {
379 debugging('confirm_start_attempt_message is deprecated. ' .
380 'This sort of functionality is now entirely handled by quiz access rules.');
d755b0f5
TH
381 return '';
382 }
383
384 /**
385 * If $reviewoptions->attempt is false, meaning that students can't review this
386 * attempt at the moment, return an appropriate string explaining why.
387 *
388 * @param int $when One of the mod_quiz_display_options::DURING,
389 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
390 * @param bool $short if true, return a shorter string.
391 * @return string an appropraite message.
392 */
393 public function cannot_review_message($when, $short = false) {
394
395 if ($short) {
396 $langstrsuffix = 'short';
397 $dateformat = get_string('strftimedatetimeshort', 'langconfig');
398 } else {
399 $langstrsuffix = '';
400 $dateformat = '';
401 }
402
403 if ($when == mod_quiz_display_options::DURING ||
404 $when == mod_quiz_display_options::IMMEDIATELY_AFTER) {
405 return '';
406 } else if ($when == mod_quiz_display_options::LATER_WHILE_OPEN && $this->quiz->timeclose &&
407 $this->quiz->reviewattempt & mod_quiz_display_options::AFTER_CLOSE) {
408 return get_string('noreviewuntil' . $langstrsuffix, 'quiz',
409 userdate($this->quiz->timeclose, $dateformat));
410 } else {
411 return get_string('noreview' . $langstrsuffix, 'quiz');
412 }
413 }
414
b10c38a3 415 /**
416 * @param string $title the name of this particular quiz page.
417 * @return array the data that needs to be sent to print_header_simple as the $navigation
418 * parameter.
419 */
36e413e3 420 public function navigation($title) {
2698e9c1 421 global $PAGE;
422 $PAGE->navbar->add($title);
423 return '';
36e413e3 424 }
425
9e83f3d1 426 // Private methods =========================================================
d18675a8 427 /**
25a03faa
TH
428 * Check that the definition of a particular question is loaded, and if not throw an exception.
429 * @param $id a questionid.
d18675a8 430 */
78e7a3dd 431 protected function ensure_question_loaded($id) {
432 if (isset($this->questions[$id]->_partiallyloaded)) {
36e413e3 433 throw new moodle_quiz_exception($this, 'questionnotloaded', $id);
434 }
435 }
b6c53841
JL
436
437 /**
438 * Return all the question types used in this quiz.
439 *
440 * @param boolean $includepotential if the quiz include random questions, setting this flag to true will make the function to
441 * return all the possible question types in the random questions category
442 * @return array a sorted array including the different question types
443 * @since Moodle 3.1
444 */
445 public function get_all_question_types_used($includepotential = false) {
446 $questiontypes = array();
447
448 // To control if we need to look in categories for questions.
449 $qcategories = array();
450
451 // We must be careful with random questions, if we find a random question we must assume that the quiz may content
452 // any of the questions in the referenced category (or subcategories).
453 foreach ($this->get_questions() as $questiondata) {
454 if ($questiondata->qtype == 'random' and $includepotential) {
455 $includesubcategories = (bool) $questiondata->questiontext;
456 if (!isset($qcategories[$questiondata->category])) {
457 $qcategories[$questiondata->category] = false;
458 }
459 if ($includesubcategories) {
460 $qcategories[$questiondata->category] = true;
461 }
462 } else {
463 if (!in_array($questiondata->qtype, $questiontypes)) {
464 $questiontypes[] = $questiondata->qtype;
465 }
466 }
467 }
468
469 if (!empty($qcategories)) {
470 // We have to look for all the question types in these categories.
471 $categoriestolook = array();
472 foreach ($qcategories as $cat => $includesubcats) {
473 if ($includesubcats) {
474 $categoriestolook = array_merge($categoriestolook, question_categorylist($cat));
475 } else {
476 $categoriestolook[] = $cat;
477 }
478 }
479 $questiontypesincategories = question_bank::get_all_question_types_in_categories($categoriestolook);
480 $questiontypes = array_merge($questiontypes, $questiontypesincategories);
481 }
482 $questiontypes = array_unique($questiontypes);
483 sort($questiontypes);
484
485 return $questiontypes;
486 }
36e413e3 487}
488
f7970e3c 489
b10c38a3 490/**
491 * This class extends the quiz class to hold data about the state of a particular attempt,
492 * in addition to the data about the quiz.
d18675a8 493 *
f7970e3c
TH
494 * @copyright 2008 Tim Hunt
495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
496 * @since Moodle 2.0
b10c38a3 497 */
a1eb3a44 498class quiz_attempt {
2de9be52
TH
499
500 /** @var string to identify the in progress state. */
501 const IN_PROGRESS = 'inprogress';
502 /** @var string to identify the overdue state. */
503 const OVERDUE = 'overdue';
504 /** @var string to identify the finished state. */
505 const FINISHED = 'finished';
506 /** @var string to identify the abandoned state. */
507 const ABANDONED = 'abandoned';
508
097dbfe1
TH
509 /** @var int maximum number of slots in the quiz for the review page to default to show all. */
510 const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL = 50;
511
441d284a 512 /** @var quiz object containing the quiz settings. */
a1eb3a44 513 protected $quizobj;
441d284a
TH
514
515 /** @var stdClass the quiz_attempts row. */
36e413e3 516 protected $attempt;
517
32953f37 518 /** @var question_usage_by_activity the question usage for this quiz attempt. */
2de9be52 519 protected $quba;
32953f37 520
5d949702
K
521 /**
522 * @var array of slot information. These objects contain ->slot (int),
523 * ->requireprevious (bool), ->questionids (int) the original question for random questions,
524 * ->firstinsection (bool), ->section (stdClass from $this->sections).
525 * This does not contain page - get that from {@link get_question_page()} -
526 * or maxmark - get that from $this->quba.
527 */
441d284a
TH
528 protected $slots;
529
5d949702
K
530 /** @var array of quiz_sections rows, with a ->lastslot field added. */
531 protected $sections;
532
32953f37
TH
533 /** @var array page no => array of slot numbers on the page in order. */
534 protected $pagelayout;
535
536 /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */
537 protected $questionnumbers;
538
539 /** @var array slot => page number for this slot. */
540 protected $questionpages;
541
542 /** @var mod_quiz_display_options cache for the appropriate review options. */
4fc3d7e5 543 protected $reviewoptions = null;
36e413e3 544
9e83f3d1 545 // Constructor =============================================================
b10c38a3 546 /**
990650f9
TH
547 * Constructor assuming we already have the necessary data loaded.
548 *
549 * @param object $attempt the row of the quiz_attempts table.
550 * @param object $quiz the quiz object for this attempt and user.
551 * @param object $cm the course_module object for this quiz.
552 * @param object $course the row from the course table for the course we belong to.
08502b57
TH
553 * @param bool $loadquestions (optional) if true, the default, load all the details
554 * of the state of each question. Else just set up the basic details of the attempt.
990650f9 555 */
08502b57 556 public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) {
441d284a
TH
557 global $DB;
558
990650f9 559 $this->attempt = $attempt;
a1eb3a44 560 $this->quizobj = new quiz($quiz, $cm, $course);
08502b57
TH
561
562 if (!$loadquestions) {
563 return;
564 }
565
a1eb3a44 566 $this->quba = question_engine::load_questions_usage_by_activity($this->attempt->uniqueid);
441d284a
TH
567 $this->slots = $DB->get_records('quiz_slots',
568 array('quizid' => $this->get_quizid()), 'slot',
5d949702
K
569 'slot, requireprevious, questionid');
570 $this->sections = array_values($DB->get_records('quiz_sections',
571 array('quizid' => $this->get_quizid()), 'firstslot'));
441d284a 572
5d949702 573 $this->link_sections_and_slots();
a1eb3a44
TH
574 $this->determine_layout();
575 $this->number_questions();
990650f9
TH
576 }
577
578 /**
56e82d99
TH
579 * Used by {create()} and {create_from_usage_id()}.
580 * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions).
b10c38a3 581 */
c7df5006 582 protected static function create_helper($conditions) {
36e413e3 583 global $DB;
990650f9 584
88f0eb15 585 $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST);
dd70d561 586 $quiz = quiz_access_manager::load_quiz_and_settings($attempt->quiz);
74df2951 587 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
88f0eb15 588 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
a1eb3a44 589
9e83f3d1 590 // Update quiz with override information.
990650f9
TH
591 $quiz = quiz_update_effective_access($quiz, $attempt->userid);
592
593 return new quiz_attempt($attempt, $quiz, $cm, $course);
36e413e3 594 }
595
56e82d99
TH
596 /**
597 * Static function to create a new quiz_attempt object given an attemptid.
598 *
f7970e3c 599 * @param int $attemptid the attempt id.
56e82d99
TH
600 * @return quiz_attempt the new quiz_attempt object
601 */
c7df5006 602 public static function create($attemptid) {
56e82d99
TH
603 return self::create_helper(array('id' => $attemptid));
604 }
605
606 /**
607 * Static function to create a new quiz_attempt object given a usage id.
608 *
f7970e3c 609 * @param int $usageid the attempt usage id.
56e82d99
TH
610 * @return quiz_attempt the new quiz_attempt object
611 */
c7df5006 612 public static function create_from_usage_id($usageid) {
56e82d99
TH
613 return self::create_helper(array('uniqueid' => $usageid));
614 }
615
b39b5d77
TH
616 /**
617 * @param string $state one of the state constants like IN_PROGRESS.
618 * @return string the human-readable state name.
619 */
620 public static function state_name($state) {
be18f589 621 return quiz_attempt_state_name($state);
b39b5d77
TH
622 }
623
5d949702
K
624 /**
625 * Let each slot know which section it is part of.
626 */
627 protected function link_sections_and_slots() {
628 foreach ($this->sections as $i => $section) {
629 if (isset($this->sections[$i + 1])) {
630 $section->lastslot = $this->sections[$i + 1]->firstslot - 1;
631 } else {
632 $section->lastslot = count($this->slots);
633 }
634 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
635 $this->slots[$slot]->section = $section;
636 }
637 }
638 }
639
097dbfe1
TH
640 /**
641 * Parse attempt->layout to populate the other arrays the represent the layout.
642 */
643 protected function determine_layout() {
a1eb3a44
TH
644 $this->pagelayout = array();
645
646 // Break up the layout string into pages.
ccba5b88 647 $pagelayouts = explode(',0', $this->attempt->layout);
a1eb3a44
TH
648
649 // Strip off any empty last page (normally there is one).
650 if (end($pagelayouts) == '') {
651 array_pop($pagelayouts);
36e413e3 652 }
a1eb3a44
TH
653
654 // File the ids into the arrays.
5d949702
K
655 // Tracking which is the first slot in each section in this attempt is
656 // trickier than you might guess, since the slots in this section
657 // may be shuffled, so $section->firstslot (the lowest numbered slot in
658 // the section) may not be the first one.
659 $unseensections = $this->sections;
a1eb3a44
TH
660 $this->pagelayout = array();
661 foreach ($pagelayouts as $page => $pagelayout) {
662 $pagelayout = trim($pagelayout, ',');
663 if ($pagelayout == '') {
664 continue;
665 }
666 $this->pagelayout[$page] = explode(',', $pagelayout);
5d949702
K
667 foreach ($this->pagelayout[$page] as $slot) {
668 $sectionkey = array_search($this->slots[$slot]->section, $unseensections);
669 if ($sectionkey !== false) {
670 $this->slots[$slot]->firstinsection = true;
671 unset($unseensections[$sectionkey]);
672 } else {
673 $this->slots[$slot]->firstinsection = false;
674 }
675 }
78e7a3dd 676 }
a1eb3a44
TH
677 }
678
097dbfe1
TH
679 /**
680 * Work out the number to display for each question/slot.
681 */
682 protected function number_questions() {
a1eb3a44
TH
683 $number = 1;
684 foreach ($this->pagelayout as $page => $slots) {
685 foreach ($slots as $slot) {
097dbfe1 686 if ($length = $this->is_real_question($slot)) {
32953f37 687 $this->questionnumbers[$slot] = $number;
097dbfe1 688 $number += $length;
a1eb3a44 689 } else {
32953f37 690 $this->questionnumbers[$slot] = get_string('infoshort', 'quiz');
a1eb3a44 691 }
32953f37 692 $this->questionpages[$slot] = $page;
a1eb3a44 693 }
36e413e3 694 }
81d833ad 695 }
696
ff2ec2cb
TH
697 /**
698 * If the given page number is out of range (before the first page, or after
699 * the last page, chnage it to be within range).
700 * @param int $page the requested page number.
701 * @return int a safe page number to use.
702 */
703 public function force_page_number_into_range($page) {
704 return min(max($page, 0), count($this->pagelayout) - 1);
705 }
706
9e83f3d1 707 // Simple getters ==========================================================
a1eb3a44
TH
708 public function get_quiz() {
709 return $this->quizobj->get_quiz();
710 }
711
712 public function get_quizobj() {
713 return $this->quizobj;
714 }
715
f7970e3c 716 /** @return int the course id. */
a1eb3a44
TH
717 public function get_courseid() {
718 return $this->quizobj->get_courseid();
719 }
720
f7970e3c 721 /** @return int the course id. */
a1eb3a44
TH
722 public function get_course() {
723 return $this->quizobj->get_course();
724 }
725
f7970e3c 726 /** @return int the quiz id. */
a1eb3a44
TH
727 public function get_quizid() {
728 return $this->quizobj->get_quizid();
729 }
730
731 /** @return string the name of this quiz. */
732 public function get_quiz_name() {
733 return $this->quizobj->get_quiz_name();
734 }
735
33c8d37b
CF
736 /** @return int the quiz navigation method. */
737 public function get_navigation_method() {
738 return $this->quizobj->get_navigation_method();
739 }
740
a1eb3a44
TH
741 /** @return object the course_module object. */
742 public function get_cm() {
743 return $this->quizobj->get_cm();
744 }
745
746 /** @return object the course_module object. */
747 public function get_cmid() {
748 return $this->quizobj->get_cmid();
749 }
750
d18675a8 751 /**
f7970e3c 752 * @return bool wether the current user is someone who previews the quiz,
a1eb3a44 753 * rather than attempting it.
d18675a8 754 */
a1eb3a44
TH
755 public function is_preview_user() {
756 return $this->quizobj->is_preview_user();
757 }
758
f7970e3c 759 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
a1eb3a44
TH
760 public function get_num_attempts_allowed() {
761 return $this->quizobj->get_num_attempts_allowed();
762 }
763
f7970e3c 764 /** @return int number fo pages in this quiz. */
a1eb3a44
TH
765 public function get_num_pages() {
766 return count($this->pagelayout);
36e413e3 767 }
768
d18675a8 769 /**
f7970e3c 770 * @param int $timenow the current time as a unix timestamp.
25a03faa
TH
771 * @return quiz_access_manager and instance of the quiz_access_manager class
772 * for this quiz at this time.
d18675a8 773 */
a1eb3a44
TH
774 public function get_access_manager($timenow) {
775 return $this->quizobj->get_access_manager($timenow);
b55797b8 776 }
777
f7970e3c 778 /** @return int the attempt id. */
36e413e3 779 public function get_attemptid() {
780 return $this->attempt->id;
781 }
782
f7970e3c 783 /** @return int the attempt unique id. */
766df8f7 784 public function get_uniqueid() {
785 return $this->attempt->uniqueid;
786 }
787
b10c38a3 788 /** @return object the row from the quiz_attempts table. */
36e413e3 789 public function get_attempt() {
790 return $this->attempt;
791 }
792
f7970e3c 793 /** @return int the number of this attemp (is it this user's first, second, ... attempt). */
78e7a3dd 794 public function get_attempt_number() {
795 return $this->attempt->attempt;
796 }
797
96e5168c 798 /** @return string one of the quiz_attempt::IN_PROGRESS, FINISHED, OVERDUE or ABANDONED constants. */
2de9be52
TH
799 public function get_state() {
800 return $this->attempt->state;
801 }
802
f7970e3c 803 /** @return int the id of the user this attempt belongs to. */
36e413e3 804 public function get_userid() {
805 return $this->attempt->userid;
806 }
c5fd1682 807
5db82949
CF
808 /** @return int the current page of the attempt. */
809 public function get_currentpage() {
810 return $this->attempt->currentpage;
811 }
36e413e3 812
2de9be52
TH
813 public function get_sum_marks() {
814 return $this->attempt->sumgrades;
815 }
816
25a03faa
TH
817 /**
818 * @return bool whether this attempt has been finished (true) or is still
34b7d838
TH
819 * in progress (false). Be warned that this is not just state == self::FINISHED,
820 * it also includes self::ABANDONED.
25a03faa 821 */
36e413e3 822 public function is_finished() {
34b7d838 823 return $this->attempt->state == self::FINISHED || $this->attempt->state == self::ABANDONED;
36e413e3 824 }
825
f7970e3c 826 /** @return bool whether this attempt is a preview attempt. */
4fc3d7e5 827 public function is_preview() {
828 return $this->attempt->preview;
829 }
830
b55797b8 831 /**
857e2a6f 832 * Is this someone dealing with their own attempt or preview?
7b6757b0 833 *
857e2a6f 834 * @return bool true => own attempt/preview. false => reviewing someone elses.
b55797b8 835 */
836 public function is_own_attempt() {
837 global $USER;
857e2a6f 838 return $this->attempt->userid == $USER->id;
b55797b8 839 }
840
b3782c71
TH
841 /**
842 * @return bool whether this attempt is a preview belonging to the current user.
843 */
844 public function is_own_preview() {
845 global $USER;
857e2a6f 846 return $this->is_own_attempt() &&
b3782c71
TH
847 $this->is_preview_user() && $this->attempt->preview;
848 }
849
8032cd79
TH
850 /**
851 * Is the current user allowed to review this attempt. This applies when
852 * {@link is_own_attempt()} returns false.
853 * @return bool whether the review should be allowed.
854 */
855 public function is_review_allowed() {
856 if (!$this->has_capability('mod/quiz:viewreports')) {
857 return false;
858 }
859
860 $cm = $this->get_cm();
861 if ($this->has_capability('moodle/site:accessallgroups') ||
862 groups_get_activity_groupmode($cm) != SEPARATEGROUPS) {
863 return true;
864 }
865
866 // Check the users have at least one group in common.
867 $teachersgroups = groups_get_activity_allowed_groups($cm);
25a03faa
TH
868 $studentsgroups = groups_get_all_groups(
869 $cm->course, $this->attempt->userid, $cm->groupingid);
8032cd79
TH
870 return $teachersgroups && $studentsgroups &&
871 array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
872 }
873
1c2e05c0
TH
874 /**
875 * Has the student, in this attempt, engaged with the quiz in a non-trivial way?
876 * That is, is there any question worth a non-zero number of marks, where
877 * the student has made some response that we have saved?
878 * @return bool true if we have saved a response for at least one graded question.
879 */
880 public function has_response_to_at_least_one_graded_question() {
881 foreach ($this->quba->get_attempt_iterator() as $qa) {
882 if ($qa->get_max_mark() == 0) {
883 continue;
884 }
885 if ($qa->get_num_steps() > 1) {
886 return true;
887 }
888 }
889 return false;
890 }
891
474aa125
TH
892 /**
893 * Get extra summary information about this attempt.
894 *
895 * Some behaviours may be able to provide interesting summary information
896 * about the attempt as a whole, and this method provides access to that data.
897 * To see how this works, try setting a quiz to one of the CBM behaviours,
898 * and then look at the extra information displayed at the top of the quiz
899 * review page once you have sumitted an attempt.
900 *
901 * In the return value, the array keys are identifiers of the form
902 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
903 * The values are arrays with two items, title and content. Each of these
904 * will be either a string, or a renderable.
905 *
1c2e05c0 906 * @param question_display_options $options the display options for this quiz attempt at this time.
474aa125
TH
907 * @return array as described above.
908 */
909 public function get_additional_summary_data(question_display_options $options) {
910 return $this->quba->get_summary_information($options);
911 }
912
b2607ccc
TH
913 /**
914 * Get the overall feedback corresponding to a particular mark.
915 * @param $grade a particular grade.
916 */
917 public function get_overall_feedback($grade) {
918 return quiz_feedback_for_grade($grade, $this->get_quiz(),
2709ee45 919 $this->quizobj->get_context());
b2607ccc
TH
920 }
921
a1eb3a44
TH
922 /**
923 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
924 */
25a03faa 925 public function has_capability($capability, $userid = null, $doanything = true) {
a1eb3a44
TH
926 return $this->quizobj->has_capability($capability, $userid, $doanything);
927 }
928
929 /**
930 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
931 */
25a03faa 932 public function require_capability($capability, $userid = null, $doanything = true) {
a1eb3a44
TH
933 return $this->quizobj->require_capability($capability, $userid, $doanything);
934 }
935
96c7d771 936 /**
937 * Check the appropriate capability to see whether this user may review their own attempt.
938 * If not, prints an error.
939 */
940 public function check_review_capability() {
6a981b45
TH
941 if ($this->get_attempt_state() == mod_quiz_display_options::IMMEDIATELY_AFTER) {
942 $capability = 'mod/quiz:attempt';
943 } else {
944 $capability = 'mod/quiz:reviewmyattempts';
96c7d771 945 }
6a981b45
TH
946
947 // These next tests are in a slighly funny order. The point is that the
948 // common and most performance-critical case is students attempting a quiz
949 // so we want to check that permisison first.
950
951 if ($this->has_capability($capability)) {
952 // User has the permission that lets you do the quiz as a student. Fine.
953 return;
954 }
955
956 if ($this->has_capability('mod/quiz:viewreports') ||
957 $this->has_capability('mod/quiz:preview')) {
958 // User has the permission that lets teachers review. Fine.
959 return;
960 }
961
962 // They should not be here. Trigger the standard no-permission error
963 // but using the name of the student capability.
964 // We know this will fail. We just want the stadard exception thown.
965 $this->require_capability($capability);
96c7d771 966 }
967
33c8d37b
CF
968 /**
969 * Checks whether a user may navigate to a particular slot
970 */
971 public function can_navigate_to($slot) {
972 switch ($this->get_navigation_method()) {
973 case QUIZ_NAVMETHOD_FREE:
974 return true;
975 break;
976 case QUIZ_NAVMETHOD_SEQ:
977 return false;
978 break;
979 }
980 return true;
981 }
982
d18675a8 983 /**
f7970e3c 984 * @return int one of the mod_quiz_display_options::DURING,
a1eb3a44 985 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
d18675a8 986 */
a1eb3a44
TH
987 public function get_attempt_state() {
988 return quiz_attempt_state($this->get_quiz(), $this->attempt);
78e7a3dd 989 }
990
b10c38a3 991 /**
a1eb3a44
TH
992 * Wrapper that the correct mod_quiz_display_options for this quiz at the
993 * moment.
b10c38a3 994 *
a1eb3a44 995 * @return question_display_options the render options for this user on this attempt.
b10c38a3 996 */
a1eb3a44
TH
997 public function get_display_options($reviewing) {
998 if ($reviewing) {
999 if (is_null($this->reviewoptions)) {
7ee80cab 1000 $this->reviewoptions = quiz_get_review_options($this->get_quiz(),
a1eb3a44 1001 $this->attempt, $this->quizobj->get_context());
857e2a6f
TH
1002 if ($this->is_own_preview()) {
1003 // It should always be possible for a teacher to review their
1004 // own preview irrespective of the review options settings.
1005 $this->reviewoptions->attempt = true;
1006 }
a1eb3a44
TH
1007 }
1008 return $this->reviewoptions;
1009
1010 } else {
1011 $options = mod_quiz_display_options::make_from_quiz($this->get_quiz(),
1012 mod_quiz_display_options::DURING);
1013 $options->flags = quiz_get_flag_option($this->attempt, $this->quizobj->get_context());
1014 return $options;
36e413e3 1015 }
36e413e3 1016 }
1017
da729916
TH
1018 /**
1019 * Wrapper that the correct mod_quiz_display_options for this quiz at the
1020 * moment.
1021 *
1022 * @param bool $reviewing true for review page, else attempt page.
1023 * @param int $slot which question is being displayed.
1024 * @param moodle_url $thispageurl to return to after the editing form is
1025 * submitted or cancelled. If null, no edit link will be generated.
1026 *
1027 * @return question_display_options the render options for this user on this
1028 * attempt, with extra info to generate an edit link, if applicable.
1029 */
1030 public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) {
1031 $options = clone($this->get_display_options($reviewing));
1032
1033 if (!$thispageurl) {
1034 return $options;
1035 }
1036
1037 if (!($reviewing || $this->is_preview())) {
1038 return $options;
1039 }
1040
1041 $question = $this->quba->get_question($slot);
1042 if (!question_has_capability_on($question, 'edit', $question->category)) {
1043 return $options;
1044 }
1045
1046 $options->editquestionparams['cmid'] = $this->get_cmid();
1047 $options->editquestionparams['returnurl'] = $thispageurl;
1048
1049 return $options;
1050 }
1051
4fc3d7e5 1052 /**
a1eb3a44 1053 * @param int $page page number
f7970e3c 1054 * @return bool true if this is the last page of the quiz.
4fc3d7e5 1055 */
a1eb3a44
TH
1056 public function is_last_page($page) {
1057 return $page == count($this->pagelayout) - 1;
4fc3d7e5 1058 }
1059
b10c38a3 1060 /**
5e63b335 1061 * Return the list of slot numbers for either a given page of the quiz, or for the
a1eb3a44 1062 * whole quiz.
b10c38a3 1063 *
a1eb3a44 1064 * @param mixed $page string 'all' or integer page number.
5e63b335 1065 * @return array the requested list of slot numbers.
b10c38a3 1066 */
a1eb3a44 1067 public function get_slots($page = 'all') {
a1eb3a44
TH
1068 if ($page === 'all') {
1069 $numbers = array();
1070 foreach ($this->pagelayout as $numbersonpage) {
1071 $numbers = array_merge($numbers, $numbersonpage);
1072 }
1073 return $numbers;
1074 } else {
1075 return $this->pagelayout[$page];
1076 }
36e413e3 1077 }
1078
5e63b335
TH
1079 /**
1080 * Return the list of slot numbers for either a given page of the quiz, or for the
1081 * whole quiz.
1082 *
1083 * @param mixed $page string 'all' or integer page number.
1084 * @return array the requested list of slot numbers.
1085 */
1086 public function get_active_slots($page = 'all') {
1087 $activeslots = array();
1088 foreach ($this->get_slots($page) as $slot) {
1089 if (!$this->is_blocked_by_previous_question($slot)) {
1090 $activeslots[] = $slot;
1091 }
1092 }
1093 return $activeslots;
1094 }
1095
b10c38a3 1096 /**
a1eb3a44 1097 * Get the question_attempt object for a particular question in this attempt.
f7970e3c 1098 * @param int $slot the number used to identify this question within this attempt.
a1eb3a44 1099 * @return question_attempt
b10c38a3 1100 */
a1eb3a44
TH
1101 public function get_question_attempt($slot) {
1102 return $this->quba->get_question_attempt($slot);
1103 }
b10c38a3 1104
5e63b335
TH
1105 /**
1106 * Get the question_attempt object for a particular question in this attempt.
1107 * @param int $slot the number used to identify this question within this attempt.
1108 * @return question_attempt
1109 */
1110 public function all_question_attempts_originally_in_slot($slot) {
1111 $qas = array();
1112 foreach ($this->quba->get_attempt_iterator() as $qa) {
1113 if ($qa->get_metadata('originalslot') == $slot) {
1114 $qas[] = $qa;
1115 }
1116 }
1117 $qas[] = $this->quba->get_question_attempt($slot);
1118 return $qas;
1119 }
1120
a1eb3a44
TH
1121 /**
1122 * Is a particular question in this attempt a real question, or something like a description.
f7970e3c 1123 * @param int $slot the number used to identify this question within this attempt.
097dbfe1
TH
1124 * @return int whether that question is a real question. Actually returns the
1125 * question length, which could theoretically be greater than one.
a1eb3a44
TH
1126 */
1127 public function is_real_question($slot) {
097dbfe1 1128 return $this->quba->get_question($slot)->length;
36e413e3 1129 }
1130
62e76c67 1131 /**
a1eb3a44 1132 * Is a particular question in this attempt a real question, or something like a description.
f7970e3c
TH
1133 * @param int $slot the number used to identify this question within this attempt.
1134 * @return bool whether that question is a real question.
62e76c67 1135 */
a1eb3a44
TH
1136 public function is_question_flagged($slot) {
1137 return $this->quba->get_question_attempt($slot)->is_flagged();
62e76c67 1138 }
1139
36e413e3 1140 /**
441d284a
TH
1141 * Checks whether the question in this slot requires the previous question to have been completed.
1142 *
1143 * @param int $slot the number used to identify this question within this attempt.
1144 * @return bool whether the previous question must have been completed before this one can be seen.
1145 */
1146 public function is_blocked_by_previous_question($slot) {
5e63b335 1147 return $slot > 1 && isset($this->slots[$slot]) && $this->slots[$slot]->requireprevious &&
5d949702
K
1148 !$this->slots[$slot]->section->shufflequestions &&
1149 !$this->slots[$slot - 1]->section->shufflequestions &&
441d284a 1150 $this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ &&
5e63b335 1151 !$this->get_question_state($slot - 1)->is_finished() &&
441d284a
TH
1152 $this->quba->can_question_finish_during_attempt($slot - 1);
1153 }
1154
5e63b335
TH
1155 /**
1156 * Is it possible for this question to be re-started within this attempt?
1157 *
1158 * @param int $slot the number used to identify this question within this attempt.
1159 * @return whether the student should be given the option to restart this question now.
1160 */
1161 public function can_question_be_redone_now($slot) {
1162 return $this->get_quiz()->canredoquestions && !$this->is_finished() &&
1163 $this->get_question_state($slot)->is_finished();
1164 }
1165
1166 /**
1167 * Given a slot in this attempt, which may or not be a redone question, return the original slot.
1168 *
1169 * @param int $slot identifies a particular question in this attempt.
1170 * @return int the slot where this question was originally.
1171 */
1172 public function get_original_slot($slot) {
1173 $originalslot = $this->quba->get_question_attempt_metadata($slot, 'originalslot');
1174 if ($originalslot) {
1175 return $originalslot;
1176 } else {
1177 return $slot;
1178 }
1179 }
1180
441d284a
TH
1181 /**
1182 * Get the displayed question number for a slot.
f7970e3c 1183 * @param int $slot the number used to identify this question within this attempt.
32953f37
TH
1184 * @return string the displayed question number for the question in this slot.
1185 * For example '1', '2', '3' or 'i'.
36e413e3 1186 */
a1eb3a44 1187 public function get_question_number($slot) {
32953f37
TH
1188 return $this->questionnumbers[$slot];
1189 }
1190
1191 /**
5d949702
K
1192 * If the section heading, if any, that should come just before this slot.
1193 * @param int $slot identifies a particular question in this attempt.
1194 * @return string the required heading, or null if there is not one here.
1195 */
1196 public function get_heading_before_slot($slot) {
1197 if ($this->slots[$slot]->firstinsection) {
1198 return $this->slots[$slot]->section->heading;
1199 } else {
1200 return null;
1201 }
1202 }
1203
1204 /**
1205 * Return the page of the quiz where this question appears.
32953f37
TH
1206 * @param int $slot the number used to identify this question within this attempt.
1207 * @return int the page of the quiz this question appears on.
1208 */
1209 public function get_question_page($slot) {
1210 return $this->questionpages[$slot];
a1eb3a44
TH
1211 }
1212
1213 /**
25a03faa
TH
1214 * Return the grade obtained on a particular question, if the user is permitted
1215 * to see it. You must previously have called load_question_states to load the
1216 * state data about this question.
a1eb3a44 1217 *
f7970e3c 1218 * @param int $slot the number used to identify this question within this attempt.
25a03faa
TH
1219 * @return string the formatted grade, to the number of decimal places specified
1220 * by the quiz.
a1eb3a44
TH
1221 */
1222 public function get_question_name($slot) {
1223 return $this->quba->get_question($slot)->name;
1224 }
1225
5e63b335
TH
1226 /**
1227 * Return the {@link question_state} that this question is in.
1228 *
1229 * @param int $slot the number used to identify this question within this attempt.
1230 * @return question_state the state this question is in.
1231 */
1232 public function get_question_state($slot) {
1233 return $this->quba->get_question_state($slot);
1234 }
1235
a1eb3a44 1236 /**
25a03faa
TH
1237 * Return the grade obtained on a particular question, if the user is permitted
1238 * to see it. You must previously have called load_question_states to load the
1239 * state data about this question.
a1eb3a44 1240 *
f7970e3c
TH
1241 * @param int $slot the number used to identify this question within this attempt.
1242 * @param bool $showcorrectness Whether right/partial/wrong states should
a1eb3a44 1243 * be distinguised.
25a03faa
TH
1244 * @return string the formatted grade, to the number of decimal places specified
1245 * by the quiz.
a1eb3a44
TH
1246 */
1247 public function get_question_status($slot, $showcorrectness) {
1248 return $this->quba->get_question_state_string($slot, $showcorrectness);
1249 }
1250
97cdc1de
TH
1251 /**
1252 * Return the grade obtained on a particular question, if the user is permitted
1253 * to see it. You must previously have called load_question_states to load the
1254 * state data about this question.
1255 *
1256 * @param int $slot the number used to identify this question within this attempt.
1257 * @param bool $showcorrectness Whether right/partial/wrong states should
1258 * be distinguised.
1259 * @return string class name for this state.
1260 */
1261 public function get_question_state_class($slot, $showcorrectness) {
1262 return $this->quba->get_question_state_class($slot, $showcorrectness);
1263 }
1264
a1eb3a44
TH
1265 /**
1266 * Return the grade obtained on a particular question.
1267 * You must previously have called load_question_states to load the state
1268 * data about this question.
1269 *
f7970e3c 1270 * @param int $slot the number used to identify this question within this attempt.
a1eb3a44
TH
1271 * @return string the formatted grade, to the number of decimal places specified by the quiz.
1272 */
b2607ccc 1273 public function get_question_mark($slot) {
a1eb3a44
TH
1274 return quiz_format_question_grade($this->get_quiz(), $this->quba->get_question_mark($slot));
1275 }
1276
1277 /**
1278 * Get the time of the most recent action performed on a question.
f7970e3c
TH
1279 * @param int $slot the number used to identify this question within this usage.
1280 * @return int timestamp.
a1eb3a44
TH
1281 */
1282 public function get_question_action_time($slot) {
1283 return $this->quba->get_question_action_time($slot);
36e413e3 1284 }
1285
1d57e4fe
JL
1286 /**
1287 * Return the question type name for a given slot within the current attempt.
1288 *
1289 * @param int $slot the number used to identify this question within this attempt.
1290 * @return string the question type name
1291 * @since Moodle 3.1
1292 */
1293 public function get_question_type_name($slot) {
1294 return $this->quba->get_question($slot)->get_type_name();
1295 }
1296
2b2b6458
TH
1297 /**
1298 * Get the time remaining for an in-progress attempt, if the time is short
1299 * enought that it would be worth showing a timer.
1300 * @param int $timenow the time to consider as 'now'.
1301 * @return int|false the number of seconds remaining for this attempt.
1302 * False if there is no limit.
1303 */
8e771aed 1304 public function get_time_left_display($timenow) {
2b2b6458
TH
1305 if ($this->attempt->state != self::IN_PROGRESS) {
1306 return false;
1307 }
8e771aed 1308 return $this->get_access_manager($timenow)->get_time_left_display($this->attempt, $timenow);
2b2b6458 1309 }
2de9be52 1310
8e771aed 1311
2de9be52
TH
1312 /**
1313 * @return int the time when this attempt was submitted. 0 if it has not been
1314 * submitted yet.
1315 */
1316 public function get_submitted_date() {
1317 return $this->attempt->timefinish;
1318 }
1319
1320 /**
1321 * If the attempt is in an applicable state, work out the time by which the
1322 * student should next do something.
1323 * @return int timestamp by which the student needs to do something.
1324 */
9e83f3d1 1325 public function get_due_date() {
2b2b6458
TH
1326 $deadlines = array();
1327 if ($this->quizobj->get_quiz()->timelimit) {
1328 $deadlines[] = $this->attempt->timestart + $this->quizobj->get_quiz()->timelimit;
1329 }
1330 if ($this->quizobj->get_quiz()->timeclose) {
1331 $deadlines[] = $this->quizobj->get_quiz()->timeclose;
1332 }
1333 if ($deadlines) {
1334 $duedate = min($deadlines);
1335 } else {
1336 return false;
1337 }
2de9be52 1338
2b2b6458 1339 switch ($this->attempt->state) {
2de9be52 1340 case self::IN_PROGRESS:
2b2b6458 1341 return $duedate;
2de9be52
TH
1342
1343 case self::OVERDUE:
2b2b6458 1344 return $duedate + $this->quizobj->get_quiz()->graceperiod;
2de9be52
TH
1345
1346 default:
2b2b6458 1347 throw new coding_exception('Unexpected state: ' . $this->attempt->state);
2de9be52
TH
1348 }
1349 }
1350
9e83f3d1 1351 // URLs related to this attempt ============================================
b10c38a3 1352 /**
a1eb3a44
TH
1353 * @return string quiz view url.
1354 */
1355 public function view_url() {
1356 return $this->quizobj->view_url();
1357 }
1358
1359 /**
1360 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
1361 */
da729916
TH
1362 public function start_attempt_url($slot = null, $page = -1) {
1363 if ($page == -1 && !is_null($slot)) {
32953f37 1364 $page = $this->get_question_page($slot);
da729916
TH
1365 } else {
1366 $page = 0;
1367 }
1368 return $this->quizobj->start_attempt_url($page);
a1eb3a44
TH
1369 }
1370
1371 /**
f7970e3c
TH
1372 * @param int $slot if speified, the slot number of a specific question to link to.
1373 * @param int $page if specified, a particular page to link to. If not givem deduced
a1eb3a44 1374 * from $slot, or goes to the first page.
f7970e3c 1375 * @param int $questionid a question id. If set, will add a fragment to the URL
b10c38a3 1376 * to jump to a particuar question on the page.
f7970e3c 1377 * @param int $thispage if not -1, the current page. Will cause links to other things on
d18675a8 1378 * this page to be output as only a fragment.
b10c38a3 1379 * @return string the URL to continue this attempt.
1380 */
56e82d99 1381 public function attempt_url($slot = null, $page = -1, $thispage = -1) {
a1eb3a44 1382 return $this->page_and_question_url('attempt', $slot, $page, false, $thispage);
36e413e3 1383 }
1384
b10c38a3 1385 /**
1386 * @return string the URL of this quiz's summary page.
1387 */
36e413e3 1388 public function summary_url() {
a1eb3a44 1389 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $this->attempt->id));
36e413e3 1390 }
1391
9f9eec1e 1392 /**
1393 * @return string the URL of this quiz's summary page.
1394 */
1395 public function processattempt_url() {
a1eb3a44 1396 return new moodle_url('/mod/quiz/processattempt.php');
9f9eec1e 1397 }
1398
b10c38a3 1399 /**
f7970e3c
TH
1400 * @param int $slot indicates which question to link to.
1401 * @param int $page if specified, the URL of this particular page of the attempt, otherwise
a1eb3a44 1402 * the URL will go to the first page. If -1, deduce $page from $slot.
097dbfe1
TH
1403 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
1404 * and $page will be ignored. If null, a sensible default will be chosen.
f7970e3c 1405 * @param int $thispage if not -1, the current page. Will cause links to other things on
d18675a8 1406 * this page to be output as only a fragment.
b10c38a3 1407 * @return string the URL to review this attempt.
1408 */
097dbfe1 1409 public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) {
a1eb3a44 1410 return $this->page_and_question_url('review', $slot, $page, $showall, $thispage);
78e7a3dd 1411 }
1412
097dbfe1
TH
1413 /**
1414 * By default, should this script show all questions on one page for this attempt?
1415 * @param string $script the script name, e.g. 'attempt', 'summary', 'review'.
1416 * @return whether show all on one page should be on by default.
1417 */
1418 public function get_default_show_all($script) {
1419 return $script == 'review' && count($this->questionpages) < self::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL;
1420 }
1421
9e83f3d1 1422 // Bits of content =========================================================
a1eb3a44 1423
d755b0f5
TH
1424 /**
1425 * If $reviewoptions->attempt is false, meaning that students can't review this
1426 * attempt at the moment, return an appropriate string explaining why.
1427 *
1428 * @param bool $short if true, return a shorter string.
1429 * @return string an appropraite message.
1430 */
1431 public function cannot_review_message($short = false) {
1432 return $this->quizobj->cannot_review_message(
1433 $this->get_attempt_state(), $short);
1434 }
1435
d18675a8 1436 /**
ff2ec2cb 1437 * Initialise the JS etc. required all the questions on a page.
d18675a8 1438 * @param mixed $page a page number, or 'all'.
1439 */
a1eb3a44
TH
1440 public function get_html_head_contributions($page = 'all', $showall = false) {
1441 if ($showall) {
1442 $page = 'all';
1443 }
1444 $result = '';
1445 foreach ($this->get_slots($page) as $slot) {
1446 $result .= $this->quba->render_question_head_html($slot);
1447 }
1448 $result .= question_engine::initialise_js();
1449 return $result;
78e7a3dd 1450 }
1451
d18675a8 1452 /**
1453 * Initialise the JS etc. required by one question.
f7970e3c 1454 * @param int $questionid the question id.
d18675a8 1455 */
a1eb3a44
TH
1456 public function get_question_html_head_contributions($slot) {
1457 return $this->quba->render_question_head_html($slot) .
1458 question_engine::initialise_js();
b826bcef 1459 }
1460
d18675a8 1461 /**
3c6185e9
TH
1462 * Print the HTML for the start new preview button, if the current user
1463 * is allowed to see one.
1464 */
1465 public function restart_preview_button() {
1466 global $OUTPUT;
1467 if ($this->is_preview() && $this->is_preview_user()) {
1468 return $OUTPUT->single_button(new moodle_url(
1469 $this->start_attempt_url(), array('forcenew' => true)),
1470 get_string('startnewpreview', 'quiz'));
1471 } else {
1472 return '';
1473 }
36e413e3 1474 }
1475
aafdb447 1476 /**
a1eb3a44
TH
1477 * Generate the HTML that displayes the question in its current state, with
1478 * the appropriate display options.
aafdb447 1479 *
5e63b335 1480 * @param int $slot identifies the question in the attempt.
f7970e3c 1481 * @param bool $reviewing is the being printed on an attempt or a review page.
5e63b335 1482 * @param mod_quiz_renderer $renderer the quiz renderer.
da729916 1483 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
a1eb3a44 1484 * @return string HTML for the question in its current state.
aafdb447 1485 */
5e63b335 1486 public function render_question($slot, $reviewing, mod_quiz_renderer $renderer, $thispageurl = null) {
441d284a
TH
1487 if ($this->is_blocked_by_previous_question($slot)) {
1488 $placeholderqa = $this->make_blocked_question_placeholder($slot);
1489
1490 $displayoptions = $this->get_display_options($reviewing);
1491 $displayoptions->manualcomment = question_display_options::HIDDEN;
1492 $displayoptions->history = question_display_options::HIDDEN;
1493 $displayoptions->readonly = true;
1494
1495 return html_writer::div($placeholderqa->render($displayoptions,
5e63b335 1496 $this->get_question_number($this->get_original_slot($slot))),
441d284a
TH
1497 'mod_quiz-blocked_question_warning');
1498 }
1499
5e63b335
TH
1500 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, null);
1501 }
1502
1503 /**
1504 * Helper used by {@link render_question()} and {@link render_question_at_step()}.
1505 *
1506 * @param int $slot identifies the question in the attempt.
1507 * @param bool $reviewing is the being printed on an attempt or a review page.
1508 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1509 * @param mod_quiz_renderer $renderer the quiz renderer.
1510 * @param int|null $seq the seq number of the past state to display.
1511 * @return string HTML fragment.
1512 */
1513 protected function render_question_helper($slot, $reviewing, $thispageurl, mod_quiz_renderer $renderer, $seq) {
1514 $originalslot = $this->get_original_slot($slot);
1515 $number = $this->get_question_number($originalslot);
1516 $displayoptions = $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl);
1517
1518 if ($slot != $originalslot) {
1519 $originalmaxmark = $this->get_question_attempt($slot)->get_max_mark();
1520 $this->get_question_attempt($slot)->set_max_mark($this->get_question_attempt($originalslot)->get_max_mark());
1521 }
1522
1523 if ($this->can_question_be_redone_now($slot)) {
1524 $displayoptions->extrainfocontent = $renderer->redo_question_button(
1525 $slot, $displayoptions->readonly);
1526 }
1527
1528 if ($displayoptions->history && $displayoptions->questionreviewlink) {
1529 $links = $this->links_to_other_redos($slot, $displayoptions->questionreviewlink);
1530 if ($links) {
1531 $displayoptions->extrahistorycontent = html_writer::tag('p',
1532 get_string('redoesofthisquestion', 'quiz', $renderer->render($links)));
1533 }
1534 }
1535
1536 if ($seq === null) {
1537 $output = $this->quba->render_question($slot, $displayoptions, $number);
1538 } else {
1539 $output = $this->quba->render_question_at_step($slot, $seq, $displayoptions, $number);
1540 }
1541
1542 if ($slot != $originalslot) {
1543 $this->get_question_attempt($slot)->set_max_mark($originalmaxmark);
1544 }
1545
1546 return $output;
a1eb3a44 1547 }
fb6dcdab 1548
441d284a
TH
1549 /**
1550 * Create a fake question to be displayed in place of a question that is blocked
1551 * until the previous question has been answered.
1552 *
5e63b335 1553 * @param int $slot int slot number of the question to replace.
441d284a
TH
1554 * @return question_definition the placeholde question.
1555 */
1556 protected function make_blocked_question_placeholder($slot) {
1557 $replacedquestion = $this->get_question_attempt($slot)->get_question();
1558
1559 question_bank::load_question_definition_classes('description');
1560 $question = new qtype_description_question();
1561 $question->id = $replacedquestion->id;
1562 $question->category = null;
1563 $question->parent = 0;
1564 $question->qtype = question_bank::get_qtype('description');
1565 $question->name = '';
1566 $question->questiontext = get_string('questiondependsonprevious', 'quiz');
1567 $question->questiontextformat = FORMAT_HTML;
1568 $question->generalfeedback = '';
1569 $question->defaultmark = $this->quba->get_question_max_mark($slot);
1570 $question->length = $replacedquestion->length;
1571 $question->penalty = 0;
1572 $question->stamp = '';
1573 $question->version = 0;
1574 $question->hidden = 0;
1575 $question->timecreated = null;
1576 $question->timemodified = null;
1577 $question->createdby = null;
1578 $question->modifiedby = null;
1579
1580 $placeholderqa = new question_attempt($question, $this->quba->get_id(),
1581 null, $this->quba->get_question_max_mark($slot));
1582 $placeholderqa->set_slot($slot);
1583 $placeholderqa->start($this->get_quiz()->preferredbehaviour, 1);
1584 $placeholderqa->set_flagged($this->is_question_flagged($slot));
1585 return $placeholderqa;
1586 }
1587
a1eb3a44
TH
1588 /**
1589 * Like {@link render_question()} but displays the question at the past step
1590 * indicated by $seq, rather than showing the latest step.
1591 *
f7970e3c
TH
1592 * @param int $id the id of a question in this quiz attempt.
1593 * @param int $seq the seq number of the past state to display.
1594 * @param bool $reviewing is the being printed on an attempt or a review page.
5e63b335 1595 * @param mod_quiz_renderer $renderer the quiz renderer.
a1eb3a44
TH
1596 * @param string $thispageurl the URL of the page this question is being printed on.
1597 * @return string HTML for the question in its current state.
1598 */
5e63b335
TH
1599 public function render_question_at_step($slot, $seq, $reviewing, mod_quiz_renderer $renderer, $thispageurl = '') {
1600 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, $seq);
a1eb3a44
TH
1601 }
1602
1603 /**
1604 * Wrapper round print_question from lib/questionlib.php.
1605 *
f7970e3c 1606 * @param int $id the id of a question in this quiz attempt.
a1eb3a44
TH
1607 */
1608 public function render_question_for_commenting($slot) {
1609 $options = $this->get_display_options(true);
1610 $options->hide_all_feedback();
1611 $options->manualcomment = question_display_options::EDITABLE;
25a03faa 1612 return $this->quba->render_question($slot, $options,
32953f37 1613 $this->get_question_number($slot));
78e7a3dd 1614 }
1615
a1eb3a44
TH
1616 /**
1617 * Check wheter access should be allowed to a particular file.
1618 *
f7970e3c
TH
1619 * @param int $id the id of a question in this quiz attempt.
1620 * @param bool $reviewing is the being printed on an attempt or a review page.
a1eb3a44
TH
1621 * @param string $thispageurl the URL of the page this question is being printed on.
1622 * @return string HTML for the question in its current state.
1623 */
56e82d99 1624 public function check_file_access($slot, $reviewing, $contextid, $component,
fe6ce234 1625 $filearea, $args, $forcedownload) {
857e2a6f
TH
1626 $options = $this->get_display_options($reviewing);
1627
1628 // Check permissions - warning there is similar code in review.php and
1629 // reviewquestion.php. If you change on, change them all.
1630 if ($reviewing && $this->is_own_attempt() && !$options->attempt) {
1631 return false;
1632 }
1633
1634 if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) {
1635 return false;
1636 }
1637
1638 return $this->quba->check_file_access($slot, $options,
56e82d99 1639 $component, $filearea, $args, $forcedownload);
fe6ce234
DC
1640 }
1641
d18675a8 1642 /**
1643 * Get the navigation panel object for this attempt.
1644 *
1645 * @param $panelclass The type of panel, quiz_attempt_nav_panel or quiz_review_nav_panel
1646 * @param $page the current page number.
1647 * @param $showall whether we are showing the whole quiz on one page. (Used by review.php)
1648 * @return quiz_nav_panel_base the requested object.
1649 */
b3782c71
TH
1650 public function get_navigation_panel(mod_quiz_renderer $output,
1651 $panelclass, $page, $showall = false) {
a1eb3a44 1652 $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall);
b3782c71
TH
1653
1654 $bc = new block_contents();
83f93ec4 1655 $bc->attributes['id'] = 'mod_quiz_navblock';
5b444ee9
TH
1656 $bc->attributes['role'] = 'navigation';
1657 $bc->attributes['aria-labelled-by'] = 'mod_quiz_navblock_title';
1658 $bc->title = html_writer::span(get_string('quiznavigation', 'quiz'), '', array('id' => 'mod_quiz_navblock_title'));
b3782c71
TH
1659 $bc->content = $output->navigation_panel($panel);
1660 return $bc;
3c168fbb 1661 }
36e413e3 1662
d18675a8 1663 /**
5e63b335
TH
1664 * Return an array of variant URLs to other attempts at this quiz.
1665 *
1666 * The $url passed in must contain an attempt parameter.
1667 *
1668 * The {@link mod_quiz_links_to_other_attempts} object returned contains an
1669 * array with keys that are the attempt number, 1, 2, 3.
1670 * The array values are either a {@link moodle_url} with the attmept parameter
1671 * updated to point to the attempt id of the other attempt, or null corresponding
1672 * to the current attempt number.
1673 *
b3782c71 1674 * @param moodle_url $url a URL.
5e63b335 1675 * @return mod_quiz_links_to_other_attempts containing array int => null|moodle_url.
d18675a8 1676 */
b3782c71 1677 public function links_to_other_attempts(moodle_url $url) {
a1eb3a44 1678 $attempts = quiz_get_user_attempts($this->get_quiz()->id, $this->attempt->userid, 'all');
f88fb62c 1679 if (count($attempts) <= 1) {
1680 return false;
1681 }
b3782c71
TH
1682
1683 $links = new mod_quiz_links_to_other_attempts();
b55797b8 1684 foreach ($attempts as $at) {
1685 if ($at->id == $this->attempt->id) {
b3782c71 1686 $links->links[$at->attempt] = null;
b55797b8 1687 } else {
b3782c71 1688 $links->links[$at->attempt] = new moodle_url($url, array('attempt' => $at->id));
b55797b8 1689 }
1690 }
b3782c71 1691 return $links;
b55797b8 1692 }
1693
5e63b335
TH
1694 /**
1695 * Return an array of variant URLs to other redos of the question in a particular slot.
1696 *
1697 * The $url passed in must contain a slot parameter.
1698 *
1699 * The {@link mod_quiz_links_to_other_attempts} object returned contains an
1700 * array with keys that are the redo number, 1, 2, 3.
1701 * The array values are either a {@link moodle_url} with the slot parameter
1702 * updated to point to the slot that has that redo of this question; or null
1703 * corresponding to the redo identified by $slot.
1704 *
1705 * @param int $slot identifies a question in this attempt.
1706 * @param moodle_url $baseurl the base URL to modify to generate each link.
1707 * @return mod_quiz_links_to_other_attempts|null containing array int => null|moodle_url,
1708 * or null if the question in this slot has not been redone.
1709 */
1710 public function links_to_other_redos($slot, moodle_url $baseurl) {
1711 $originalslot = $this->get_original_slot($slot);
1712
1713 $qas = $this->all_question_attempts_originally_in_slot($originalslot);
1714 if (count($qas) <= 1) {
1715 return null;
1716 }
1717
1718 $links = new mod_quiz_links_to_other_attempts();
1719 $index = 1;
1720 foreach ($qas as $qa) {
1721 if ($qa->get_slot() == $slot) {
1722 $links->links[$index] = null;
1723 } else {
1724 $url = new moodle_url($baseurl, array('slot' => $qa->get_slot()));
1725 $links->links[$index] = new action_link($url, $index,
1726 new popup_action('click', $url, 'reviewquestion',
1727 array('width' => 450, 'height' => 650)),
1728 array('title' => get_string('reviewresponse', 'question')));
1729 }
1730 $index++;
1731 }
1732 return $links;
1733 }
1734
a1eb3a44
TH
1735 // Methods for processing ==================================================
1736
34b7d838
TH
1737 /**
1738 * Check this attempt, to see if there are any state transitions that should
8e771aed 1739 * happen automatically. This function will update the attempt checkstatetime.
34b7d838 1740 * @param int $timestamp the timestamp that should be stored as the modifed
a403bce0 1741 * @param bool $studentisonline is the student currently interacting with Moodle?
34b7d838 1742 */
a403bce0 1743 public function handle_if_time_expired($timestamp, $studentisonline) {
34b7d838
TH
1744 global $DB;
1745
8e771aed 1746 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt);
a403bce0 1747
8e771aed
MP
1748 if ($timeclose === false || $this->is_preview()) {
1749 $this->update_timecheckstate(null);
1750 return; // No time limit
1751 }
1752 if ($timestamp < $timeclose) {
1753 $this->update_timecheckstate($timeclose);
34b7d838
TH
1754 return; // Time has not yet expired.
1755 }
1756
1757 // If the attempt is already overdue, look to see if it should be abandoned ...
9e83f3d1 1758 if ($this->attempt->state == self::OVERDUE) {
8e771aed
MP
1759 $timeoverdue = $timestamp - $timeclose;
1760 $graceperiod = $this->quizobj->get_quiz()->graceperiod;
1761 if ($timeoverdue >= $graceperiod) {
a403bce0 1762 $this->process_abandon($timestamp, $studentisonline);
8e771aed
MP
1763 } else {
1764 // Overdue time has not yet expired
1765 $this->update_timecheckstate($timeclose + $graceperiod);
34b7d838 1766 }
34b7d838
TH
1767 return; // ... and we are done.
1768 }
1769
9e83f3d1 1770 if ($this->attempt->state != self::IN_PROGRESS) {
8e771aed 1771 $this->update_timecheckstate(null);
34b7d838
TH
1772 return; // Attempt is already in a final state.
1773 }
1774
1775 // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired.
1776 // Transition to the appropriate state.
1777 switch ($this->quizobj->get_quiz()->overduehandling) {
1778 case 'autosubmit':
1779 $this->process_finish($timestamp, false);
1780 return;
1781
1782 case 'graceperiod':
a403bce0 1783 $this->process_going_overdue($timestamp, $studentisonline);
34b7d838
TH
1784 return;
1785
1786 case 'autoabandon':
a403bce0 1787 $this->process_abandon($timestamp, $studentisonline);
34b7d838
TH
1788 return;
1789 }
8e771aed
MP
1790
1791 // This is an overdue attempt with no overdue handling defined, so just abandon.
1792 $this->process_abandon($timestamp, $studentisonline);
1793 return;
34b7d838
TH
1794 }
1795
d18675a8 1796 /**
a1eb3a44
TH
1797 * Process all the actions that were submitted as part of the current request.
1798 *
388f0473
JP
1799 * @param int $timestamp the timestamp that should be stored as the modifed
1800 * time in the database for these actions. If null, will use the current time.
1801 * @param bool $becomingoverdue
1802 * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data, keys are slot
1803 * nos and values are arrays representing student responses which will be passed to
1804 * question_definition::prepare_simulated_post_data method and then have the
1805 * appropriate prefix added.
1806 */
1807 public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) {
8f37f7fb 1808 global $DB;
34b7d838
TH
1809
1810 $transaction = $DB->start_delegated_transaction();
1811
388f0473
JP
1812 if ($simulatedresponses !== null) {
1813 $simulatedpostdata = $this->quba->prepare_simulated_post_data($simulatedresponses);
1814 } else {
1815 $simulatedpostdata = null;
1816 }
1817
1818 $this->quba->process_all_actions($timestamp, $simulatedpostdata);
a1eb3a44
TH
1819 question_engine::save_questions_usage_by_activity($this->quba);
1820
1821 $this->attempt->timemodified = $timestamp;
34b7d838 1822 if ($this->attempt->state == self::FINISHED) {
a1eb3a44
TH
1823 $this->attempt->sumgrades = $this->quba->get_total_mark();
1824 }
34b7d838 1825 if ($becomingoverdue) {
a403bce0
TH
1826 $this->process_going_overdue($timestamp, true);
1827 } else {
1828 $DB->update_record('quiz_attempts', $this->attempt);
34b7d838 1829 }
88f0eb15 1830
9e83f3d1 1831 if (!$this->is_preview() && $this->attempt->state == self::FINISHED) {
a1eb3a44 1832 quiz_save_best_grade($this->get_quiz(), $this->get_userid());
766df8f7 1833 }
34b7d838
TH
1834
1835 $transaction->allow_commit();
766df8f7 1836 }
1837
1700bd4d 1838 /**
5e63b335
TH
1839 * Replace a question in an attempt with a new attempt at the same qestion.
1840 * @param int $slot the questoin to restart.
1841 * @param int $timestamp the timestamp to record for this action.
1700bd4d 1842 */
5e63b335 1843 public function process_redo_question($slot, $timestamp) {
1700bd4d
K
1844 global $DB;
1845
5e63b335
TH
1846 if (!$this->can_question_be_redone_now($slot)) {
1847 throw new coding_exception('Attempt to restart the question in slot ' . $slot .
1848 ' when it is not in a state to be restarted.');
1849 }
1700bd4d 1850
5e63b335
TH
1851 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
1852 $this->get_quizid(), $this->get_userid());
1700bd4d 1853
5e63b335 1854 $transaction = $DB->start_delegated_transaction();
1700bd4d 1855
293f5d1b 1856 // Choose the replacement question.
5e63b335
TH
1857 $questiondata = $DB->get_record('question',
1858 array('id' => $this->slots[$slot]->questionid));
1859 if ($questiondata->qtype != 'random') {
1860 $newqusetionid = $questiondata->id;
1861 } else {
1862 $randomloader = new \core_question\bank\random_question_loader($qubaids, array());
1863 $newqusetionid = $randomloader->get_next_question_id($questiondata->category,
1864 (bool) $questiondata->questiontext);
1865 if ($newqusetionid === null) {
1866 throw new moodle_exception('notenoughrandomquestions', 'quiz',
1867 $quizobj->view_url(), $questiondata);
1868 }
1700bd4d 1869 }
1700bd4d 1870
293f5d1b 1871 // Add the question to the usage. It is important we do this before we choose a variant.
5e63b335 1872 $newquestion = question_bank::load_question($newqusetionid);
293f5d1b
TH
1873 $newslot = $this->quba->add_question_in_place_of_other($slot, $newquestion);
1874
1875 // Choose the variant.
5e63b335
TH
1876 if ($newquestion->get_num_variants() == 1) {
1877 $variant = 1;
1878 } else {
1879 $variantstrategy = new core_question\engine\variants\least_used_strategy(
1880 $this->quba, $qubaids);
1881 $variant = $variantstrategy->choose_variant($newquestion->get_num_variants(),
1882 $newquestion->get_variants_selection_seed());
1700bd4d 1883 }
5e63b335 1884
293f5d1b
TH
1885 // Start the question.
1886 $this->quba->start_question($slot, $variant);
5e63b335
TH
1887 $this->quba->set_max_mark($newslot, 0);
1888 $this->quba->set_question_attempt_metadata($newslot, 'originalslot', $slot);
1889 question_engine::save_questions_usage_by_activity($this->quba);
1890
1891 $transaction->allow_commit();
1700bd4d
K
1892 }
1893
59570888
TH
1894 /**
1895 * Process all the autosaved data that was part of the current request.
1896 *
1897 * @param int $timestamp the timestamp that should be stored as the modifed
1898 * time in the database for these actions. If null, will use the current time.
1899 */
1900 public function process_auto_save($timestamp) {
1901 global $DB;
1902
1903 $transaction = $DB->start_delegated_transaction();
1904
1905 $this->quba->process_all_autosaves($timestamp);
1906 question_engine::save_questions_usage_by_activity($this->quba);
1907
1908 $transaction->allow_commit();
1909 }
1910
d18675a8 1911 /**
a1eb3a44
TH
1912 * Update the flagged state for all question_attempts in this usage, if their
1913 * flagged state was changed in the request.
d18675a8 1914 */
a1eb3a44 1915 public function save_question_flags() {
4be550c5
TH
1916 global $DB;
1917
34b7d838 1918 $transaction = $DB->start_delegated_transaction();
a1eb3a44
TH
1919 $this->quba->update_question_flags();
1920 question_engine::save_questions_usage_by_activity($this->quba);
34b7d838 1921 $transaction->allow_commit();
a1eb3a44 1922 }
e8f99abc 1923
34b7d838 1924 public function process_finish($timestamp, $processsubmitted) {
a403bce0 1925 global $DB;
34b7d838
TH
1926
1927 $transaction = $DB->start_delegated_transaction();
1928
1929 if ($processsubmitted) {
1930 $this->quba->process_all_actions($timestamp);
1931 }
a1eb3a44 1932 $this->quba->finish_all_questions($timestamp);
e8f99abc 1933
a1eb3a44 1934 question_engine::save_questions_usage_by_activity($this->quba);
e8f99abc 1935
a1eb3a44
TH
1936 $this->attempt->timemodified = $timestamp;
1937 $this->attempt->timefinish = $timestamp;
1938 $this->attempt->sumgrades = $this->quba->get_total_mark();
a403bce0 1939 $this->attempt->state = self::FINISHED;
8e771aed 1940 $this->attempt->timecheckstate = null;
88f0eb15 1941 $DB->update_record('quiz_attempts', $this->attempt);
766df8f7 1942
a1eb3a44 1943 if (!$this->is_preview()) {
704f062b 1944 quiz_save_best_grade($this->get_quiz(), $this->attempt->userid);
cbb8b55c 1945
9e83f3d1 1946 // Trigger event.
d900f1dc 1947 $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp);
cbb8b55c 1948
987c2d49
TH
1949 // Tell any access rules that care that the attempt is over.
1950 $this->get_access_manager($timestamp)->current_attempt_finished();
36e413e3 1951 }
34b7d838
TH
1952
1953 $transaction->allow_commit();
1954 }
1955
8e771aed
MP
1956 /**
1957 * Update this attempt timecheckstate if necessary.
1958 * @param int|null the timecheckstate
1959 */
1960 public function update_timecheckstate($time) {
1961 global $DB;
1962 if ($this->attempt->timecheckstate !== $time) {
1963 $this->attempt->timecheckstate = $time;
5d949702 1964 $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id' => $this->attempt->id));
8e771aed
MP
1965 }
1966 }
1967
34b7d838
TH
1968 /**
1969 * Mark this attempt as now overdue.
1970 * @param int $timestamp the time to deem as now.
a403bce0 1971 * @param bool $studentisonline is the student currently interacting with Moodle?
34b7d838 1972 */
a403bce0
TH
1973 public function process_going_overdue($timestamp, $studentisonline) {
1974 global $DB;
1975
1976 $transaction = $DB->start_delegated_transaction();
1977 $this->attempt->timemodified = $timestamp;
1978 $this->attempt->state = self::OVERDUE;
8e771aed
MP
1979 // If we knew the attempt close time, we could compute when the graceperiod ends.
1980 // Instead we'll just fix it up through cron.
1981 $this->attempt->timecheckstate = $timestamp;
a403bce0
TH
1982 $DB->update_record('quiz_attempts', $this->attempt);
1983
0a8b091d 1984 $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp);
a403bce0
TH
1985
1986 $transaction->allow_commit();
1c2e05c0
TH
1987
1988 quiz_send_overdue_message($this);
34b7d838
TH
1989 }
1990
1991 /**
1992 * Mark this attempt as abandoned.
1993 * @param int $timestamp the time to deem as now.
a403bce0 1994 * @param bool $studentisonline is the student currently interacting with Moodle?
34b7d838 1995 */
a403bce0
TH
1996 public function process_abandon($timestamp, $studentisonline) {
1997 global $DB;
1998
1999 $transaction = $DB->start_delegated_transaction();
2000 $this->attempt->timemodified = $timestamp;
2001 $this->attempt->state = self::ABANDONED;
8e771aed 2002 $this->attempt->timecheckstate = null;
a403bce0
TH
2003 $DB->update_record('quiz_attempts', $this->attempt);
2004
d900f1dc 2005 $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp);
a403bce0
TH
2006
2007 $transaction->allow_commit();
2008 }
2009
2010 /**
2011 * Fire a state transition event.
d900f1dc
FM
2012 * the same event information.
2013 * @param string $eventclass the event class name.
a403bce0 2014 * @param int $timestamp the timestamp to include in the event.
d900f1dc 2015 * @return void
a403bce0 2016 */
d900f1dc 2017 protected function fire_state_transition_event($eventclass, $timestamp) {
a403bce0 2018 global $USER;
fdc729ea 2019 $quizrecord = $this->get_quiz();
d900f1dc
FM
2020 $params = array(
2021 'context' => $this->get_quizobj()->get_context(),
2022 'courseid' => $this->get_courseid(),
2023 'objectid' => $this->attempt->id,
2024 'relateduserid' => $this->attempt->userid,
2025 'other' => array(
fdc729ea
RT
2026 'submitterid' => CLI_SCRIPT ? null : $USER->id,
2027 'quizid' => $quizrecord->id
d900f1dc
FM
2028 )
2029 );
2030
2031 $event = $eventclass::create($params);
2032 $event->add_record_snapshot('quiz', $this->get_quiz());
2033 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2034 $event->trigger();
36e413e3 2035 }
78e7a3dd 2036
9e83f3d1 2037 // Private methods =========================================================
a1eb3a44 2038
78e7a3dd 2039 /**
d18675a8 2040 * Get a URL for a particular question on a particular page of the quiz.
2041 * Used by {@link attempt_url()} and {@link review_url()}.
78e7a3dd 2042 *
d18675a8 2043 * @param string $script. Used in the URL like /mod/quiz/$script.php
25a03faa
TH
2044 * @param int $slot identifies the specific question on the page to jump to.
2045 * 0 to just use the $page parameter.
2046 * @param int $page -1 to look up the page number from the slot, otherwise
2047 * the page number to go to.
097dbfe1
TH
2048 * @param bool|null $showall if true, return a URL with showall=1, and not page number.
2049 * if null, then an intelligent default will be chosen.
f7970e3c 2050 * @param int $thispage the page we are currently on. Links to questions on this
d18675a8 2051 * page will just be a fragment #q123. -1 to disable this.
2052 * @return The requested URL.
78e7a3dd 2053 */
a1eb3a44 2054 protected function page_and_question_url($script, $slot, $page, $showall, $thispage) {
097dbfe1
TH
2055
2056 $defaultshowall = $this->get_default_show_all($script);
2057 if ($showall === null && ($page == 0 || $page == -1)) {
2058 $showall = $defaultshowall;
2059 }
2060
9e83f3d1 2061 // Fix up $page.
3c168fbb 2062 if ($page == -1) {
097dbfe1 2063 if ($slot !== null && !$showall) {
32953f37 2064 $page = $this->get_question_page($slot);
78e7a3dd 2065 } else {
2066 $page = 0;
2067 }
2068 }
a1eb3a44 2069
78e7a3dd 2070 if ($showall) {
2071 $page = 0;
2072 }
d18675a8 2073
fb6dcdab 2074 // Add a fragment to scroll down to the question.
a1eb3a44 2075 $fragment = '';
097dbfe1 2076 if ($slot !== null) {
a1eb3a44 2077 if ($slot == reset($this->pagelayout[$page])) {
d4a03c00 2078 // First question on page, go to top.
a1eb3a44 2079 $fragment = '#';
d4a03c00 2080 } else {
a1eb3a44 2081 $fragment = '#q' . $slot;
d4a03c00 2082 }
78e7a3dd 2083 }
d18675a8 2084
a1eb3a44
TH
2085 // Work out the correct start to the URL.
2086 if ($thispage == $page) {
2087 return new moodle_url($fragment);
36e413e3 2088
36e413e3 2089 } else {
a1eb3a44
TH
2090 $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment,
2091 array('attempt' => $this->attempt->id));
097dbfe1
TH
2092 if ($page == 0 && $showall != $defaultshowall) {
2093 $url->param('showall', (int) $showall);
a1eb3a44
TH
2094 } else if ($page > 0) {
2095 $url->param('page', $page);
2096 }
2097 return $url;
36e413e3 2098 }
2099 }
4911b5b2
JL
2100
2101 /**
2102 * Process responses during an attempt at a quiz.
2103 *
2104 * @param int $timenow time when the processing started
2105 * @param bool $finishattempt whether to finish the attempt or not
2106 * @param bool $timeup true if form was submitted by timer
2107 * @param int $thispage current page number
2108 * @return string the attempt state once the data has been processed
2109 * @since Moodle 3.1
2110 * @throws moodle_exception
2111 */
2112 public function process_attempt($timenow, $finishattempt, $timeup, $thispage) {
2113 global $DB;
2114
2115 $transaction = $DB->start_delegated_transaction();
2116
2117 // If there is only a very small amount of time left, there is no point trying
2118 // to show the student another page of the quiz. Just finish now.
2119 $graceperiodmin = null;
2120 $accessmanager = $this->get_access_manager($timenow);
2121 $timeclose = $accessmanager->get_end_time($this->get_attempt());
2122
2123 // Don't enforce timeclose for previews.
2124 if ($this->is_preview()) {
2125 $timeclose = false;
2126 }
2127 $toolate = false;
2128 if ($timeclose !== false && $timenow > $timeclose - QUIZ_MIN_TIME_TO_CONTINUE) {
2129 $timeup = true;
2130 $graceperiodmin = get_config('quiz', 'graceperiodmin');
2131 if ($timenow > $timeclose + $graceperiodmin) {
2132 $toolate = true;
2133 }
2134 }
2135
2136 // If time is running out, trigger the appropriate action.
2137 $becomingoverdue = false;
2138 $becomingabandoned = false;
2139 if ($timeup) {
2140 if ($this->get_quiz()->overduehandling == 'graceperiod') {
2141 if (is_null($graceperiodmin)) {
2142 $graceperiodmin = get_config('quiz', 'graceperiodmin');
2143 }
2144 if ($timenow > $timeclose + $this->get_quiz()->graceperiod + $graceperiodmin) {
2145 // Grace period has run out.
2146 $finishattempt = true;
2147 $becomingabandoned = true;
2148 } else {
2149 $becomingoverdue = true;
2150 }
2151 } else {
2152 $finishattempt = true;
2153 }
2154 }
2155
2156 // Don't log - we will end with a redirect to a page that is logged.
2157
2158 if (!$finishattempt) {
2159 // Just process the responses for this page and go to the next page.
2160 if (!$toolate) {
2161 try {
2162 $this->process_submitted_actions($timenow, $becomingoverdue);
2163
2164 } catch (question_out_of_sequence_exception $e) {
2165 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2166 $this->attempt_url(null, $thispage));
2167
2168 } catch (Exception $e) {
2169 // This sucks, if we display our own custom error message, there is no way
2170 // to display the original stack trace.
2171 $debuginfo = '';
2172 if (!empty($e->debuginfo)) {
2173 $debuginfo = $e->debuginfo;
2174 }
2175 throw new moodle_exception('errorprocessingresponses', 'question',
2176 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2177 }
2178
2179 if (!$becomingoverdue) {
2180 foreach ($this->get_slots() as $slot) {
2181 if (optional_param('redoslot' . $slot, false, PARAM_BOOL)) {
2182 $this->process_redo_question($slot, $timenow);
2183 }
2184 }
2185 }
2186
2187 } else {
2188 // The student is too late.
2189 $this->process_going_overdue($timenow, true);
2190 }
2191
2192 $transaction->allow_commit();
2193
2194 return $becomingoverdue ? self::OVERDUE : self::IN_PROGRESS;
2195 }
2196
2197 // Update the quiz attempt record.
2198 try {
2199 if ($becomingabandoned) {
2200 $this->process_abandon($timenow, true);
2201 } else {
2202 $this->process_finish($timenow, !$toolate);
2203 }
2204
2205 } catch (question_out_of_sequence_exception $e) {
2206 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2207 $this->attempt_url(null, $thispage));
2208
2209 } catch (Exception $e) {
2210 // This sucks, if we display our own custom error message, there is no way
2211 // to display the original stack trace.
2212 $debuginfo = '';
2213 if (!empty($e->debuginfo)) {
2214 $debuginfo = $e->debuginfo;
2215 }
2216 throw new moodle_exception('errorprocessingresponses', 'question',
2217 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2218 }
2219
2220 // Send the user to the review page.
2221 $transaction->allow_commit();
2222
2223 return $becomingabandoned ? self::ABANDONED : self::FINISHED;
2224 }
2225
899983ee
JL
2226 /**
2227 * Check a page access to see if is an out of sequence access.
2228 *
2229 * @param int $page page number
2230 * @return boolean false is is an out of sequence access, true otherwise.
2231 * @since Moodle 3.1
2232 */
2233 public function check_page_access($page) {
2234 global $DB;
2235
2236 if ($this->get_currentpage() != $page) {
2237 if ($this->get_navigation_method() == QUIZ_NAVMETHOD_SEQ && $this->get_currentpage() > $page) {
2238 return false;
2239 }
2240 }
2241 return true;
2242 }
2243
2244 /**
2245 * Update attempt page.
2246 *
2247 * @param int $page page number
2248 * @return boolean true if everything was ok, false otherwise (out of sequence access).
2249 * @since Moodle 3.1
2250 */
2251 public function set_currentpage($page) {
2252 global $DB;
2253
2254 if ($this->check_page_access($page)) {
2255 $DB->set_field('quiz_attempts', 'currentpage', $page, array('id' => $this->get_attemptid()));
2256 return true;
2257 }
2258 return false;
2259 }
2260
2261 /**
2262 * Trigger the attempt_viewed event.
2263 *
2264 * @since Moodle 3.1
2265 */
2266 public function fire_attempt_viewed_event() {
2267 $params = array(
2268 'objectid' => $this->get_attemptid(),
2269 'relateduserid' => $this->get_userid(),
2270 'courseid' => $this->get_courseid(),
2271 'context' => context_module::instance($this->get_cmid()),
2272 'other' => array(
2273 'quizid' => $this->get_quizid()
2274 )
2275 );
2276 $event = \mod_quiz\event\attempt_viewed::create($params);
2277 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2278 $event->trigger();
2279 }
2280
d9ef6ae0
JL
2281 /**
2282 * Trigger the attempt_summary_viewed event.
2283 *
2284 * @since Moodle 3.1
2285 */
2286 public function fire_attempt_summary_viewed_event() {
2287
2288 $params = array(
2289 'objectid' => $this->get_attemptid(),
2290 'relateduserid' => $this->get_userid(),
2291 'courseid' => $this->get_courseid(),
2292 'context' => context_module::instance($this->get_cmid()),
2293 'other' => array(
2294 'quizid' => $this->get_quizid()
2295 )
2296 );
2297 $event = \mod_quiz\event\attempt_summary_viewed::create($params);
2298 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2299 $event->trigger();
2300 }
2301
3e5c19a0
JL
2302 /**
2303 * Trigger the attempt_reviewed event.
2304 *
2305 * @since Moodle 3.1
2306 */
2307 public function fire_attempt_reviewed_event() {
2308
2309 $params = array(
2310 'objectid' => $this->get_attemptid(),
2311 'relateduserid' => $this->get_userid(),
2312 'courseid' => $this->get_courseid(),
2313 'context' => context_module::instance($this->get_cmid()),
2314 'other' => array(
2315 'quizid' => $this->get_quizid()
2316 )
2317 );
2318 $event = \mod_quiz\event\attempt_reviewed::create($params);
2319 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2320 $event->trigger();
2321 }
2322
36e413e3 2323}
3c168fbb 2324
f7970e3c 2325
5d949702
K
2326/**
2327 * Represents a heading in the navigation panel.
2328 *
2329 * @copyright 2015 The Open University
2330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2331 * @since Moodle 2.9
2332 */
2333class quiz_nav_section_heading implements renderable {
2334 /** @var string the heading text. */
2335 public $heading;
2336
2337 /**
2338 * Constructor.
2339 * @param string $heading the heading text
2340 */
2341 public function __construct($heading) {
2342 $this->heading = $heading;
2343 }
2344}
2345
2346
b3782c71
TH
2347/**
2348 * Represents a single link in the navigation panel.
2349 *
2350 * @copyright 2011 The Open University
2351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2352 * @since Moodle 2.1
2353 */
2354class quiz_nav_question_button implements renderable {
2e4e8d16 2355 /** @var string id="..." to add to the HTML for this button. */
b3782c71 2356 public $id;
2e4e8d16 2357 /** @var string number to display in this button. Either the question number of 'i'. */
b3782c71 2358 public $number;
2e4e8d16 2359 /** @var string class to add to the class="" attribute to represnt the question state. */
b3782c71 2360 public $stateclass;
2e4e8d16 2361 /** @var string Textual description of the question state, e.g. to use as a tool tip. */
b3782c71 2362 public $statestring;
2e4e8d16
TH
2363 /** @var int the page number this question is on. */
2364 public $page;
2365 /** @var bool true if this question is on the current page. */
b3782c71 2366 public $currentpage;
2e4e8d16 2367 /** @var bool true if this question has been flagged. */
b3782c71 2368 public $flagged;
2e4e8d16 2369 /** @var moodle_url the link this button goes to, or null if there should not be a link. */
b3782c71
TH
2370 public $url;
2371}
2372
2373
d18675a8 2374/**
2375 * Represents the navigation panel, and builds a {@link block_contents} to allow
2376 * it to be output.
2377 *
f7970e3c
TH
2378 * @copyright 2008 Tim Hunt
2379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2380 * @since Moodle 2.0
d18675a8 2381 */
3c168fbb 2382abstract class quiz_nav_panel_base {
38c9edd0 2383 /** @var quiz_attempt */
3c168fbb 2384 protected $attemptobj;
38c9edd0 2385 /** @var question_display_options */
3c168fbb 2386 protected $options;
38c9edd0 2387 /** @var integer */
3c168fbb 2388 protected $page;
38c9edd0 2389 /** @var boolean */
d18675a8 2390 protected $showall;
3c168fbb 2391
a1eb3a44
TH
2392 public function __construct(quiz_attempt $attemptobj,
2393 question_display_options $options, $page, $showall) {
38c9edd0
TH
2394 $this->attemptobj = $attemptobj;
2395 $this->options = $options;
2396 $this->page = $page;
2397 $this->showall = $showall;
3c168fbb 2398 }
2399
5d949702
K
2400 /**
2401 * Get the buttons and section headings to go in the quiz navigation block.
2402 * @return renderable[] the buttons, possibly interleaved with section headings.
2403 */
b3782c71
TH
2404 public function get_question_buttons() {
2405 $buttons = array();
a1eb3a44 2406 foreach ($this->attemptobj->get_slots() as $slot) {
5d949702
K
2407 if ($heading = $this->attemptobj->get_heading_before_slot($slot)) {
2408 $buttons[] = new quiz_nav_section_heading(format_string($heading));
2409 }
2410
a1eb3a44
TH
2411 $qa = $this->attemptobj->get_question_attempt($slot);
2412 $showcorrectness = $this->options->correctness && $qa->has_marks();
a1eb3a44 2413
b3782c71
TH
2414 $button = new quiz_nav_question_button();
2415 $button->id = 'quiznavbutton' . $slot;
32953f37 2416 $button->number = $this->attemptobj->get_question_number($slot);
97cdc1de 2417 $button->stateclass = $qa->get_state_class($showcorrectness);
33c8d37b 2418 $button->navmethod = $this->attemptobj->get_navigation_method();
b3782c71
TH
2419 if (!$showcorrectness && $button->stateclass == 'notanswered') {
2420 $button->stateclass = 'complete';
2421 }
79a46626 2422 $button->statestring = $this->get_state_string($qa, $showcorrectness);
2e4e8d16
TH
2423 $button->page = $this->attemptobj->get_question_page($slot);
2424 $button->currentpage = $this->showall || $button->page == $this->page;
b3782c71
TH
2425 $button->flagged = $qa->is_flagged();
2426 $button->url = $this->get_question_url($slot);
377ce993
TH
2427 if ($this->attemptobj->is_blocked_by_previous_question($slot)) {
2428 $button->url = null;
2429 $button->stateclass = 'blocked';
2430 $button->statestring = get_string('questiondependsonprevious', 'quiz');
2431 }
b3782c71 2432 $buttons[] = $button;
a1eb3a44
TH
2433 }
2434
b3782c71 2435 return $buttons;
c752264f 2436 }
2437
79a46626 2438 protected function get_state_string(question_attempt $qa, $showcorrectness) {
0eafc988 2439 if ($qa->get_question()->length > 0) {
79a46626
TH
2440 return $qa->get_state_string($showcorrectness);
2441 }
2442
2443 // Special case handling for 'information' items.
2444 if ($qa->get_state() == question_state::$todo) {
2445 return get_string('notyetviewed', 'quiz');
2446 } else {
2447 return get_string('viewed', 'quiz');
2448 }
2449 }
2450
b3782c71 2451 public function render_before_button_bits(mod_quiz_renderer $output) {
d18675a8 2452 return '';
2453 }
3c168fbb 2454
0eb253f7
TH
2455 abstract public function render_end_bits(mod_quiz_renderer $output);
2456
2457 protected function render_restart_preview_link($output) {
b3782c71
TH
2458 if (!$this->attemptobj->is_own_preview()) {
2459 return '';
2460 }
2461 return $output->restart_preview_button(new moodle_url(
2462 $this->attemptobj->start_attempt_url(), array('forcenew' => true)));
2463 }
3c168fbb 2464
c7df5006 2465 protected abstract function get_question_url($slot);
d18675a8 2466
b3782c71
TH
2467 public function user_picture() {
2468 global $DB;
1ecd3c30 2469 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_NONE) {
e28bbd89
TH
2470 return null;
2471 }
a733c4b9 2472 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid()));
b3782c71
TH
2473 $userpicture = new user_picture($user);
2474 $userpicture->courseid = $this->attemptobj->get_courseid();
1ecd3c30
JA
2475 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_LARGE) {
2476 $userpicture->size = true;
2477 }
b3782c71 2478 return $userpicture;
3c168fbb 2479 }
0328341f
K
2480
2481 /**
2482 * Return 'allquestionsononepage' as CSS class name when $showall is set,
2483 * otherwise, return 'multipages' as CSS class name.
2484 * @return string, CSS class name
2485 */
2486 public function get_button_container_class() {
2487 // Quiz navigation is set on 'Show all questions on one page'.
2488 if ($this->showall) {
2489 return 'allquestionsononepage';
2490 }
2491 // Quiz navigation is set on 'Show one page at a time'.
2492 return 'multipages';
2493 }
3c168fbb 2494}
2495
f7970e3c 2496
d18675a8 2497/**
2498 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page.
2499 *
f7970e3c
TH
2500 * @copyright 2008 Tim Hunt
2501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2502 * @since Moodle 2.0
d18675a8 2503 */
3c168fbb 2504class quiz_attempt_nav_panel extends quiz_nav_panel_base {
b3782c71 2505 public function get_question_url($slot) {
33c8d37b
CF
2506 if ($this->attemptobj->can_navigate_to($slot)) {
2507 return $this->attemptobj->attempt_url($slot, -1, $this->page);
2508 } else {
2509 return null;
2510 }
3c168fbb 2511 }
2512
b3782c71
TH
2513 public function render_before_button_bits(mod_quiz_renderer $output) {
2514 return html_writer::tag('div', get_string('navnojswarning', 'quiz'),
2515 array('id' => 'quiznojswarning'));
3c168fbb 2516 }
2517
b3782c71
TH
2518 public function render_end_bits(mod_quiz_renderer $output) {
2519 return html_writer::link($this->attemptobj->summary_url(),
c9272e87 2520 get_string('endtest', 'quiz'), array('class' => 'endtestlink')) .
2b2b6458 2521 $output->countdown_timer($this->attemptobj, time()) .
0eb253f7 2522 $this->render_restart_preview_link($output);
3c168fbb 2523 }
2524}
2525
f7970e3c 2526
d18675a8 2527/**
2528 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page.
2529 *
f7970e3c
TH
2530 * @copyright 2008 Tim Hunt
2531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2532 * @since Moodle 2.0
d18675a8 2533 */
3c168fbb 2534class quiz_review_nav_panel extends quiz_nav_panel_base {
b3782c71 2535 public function get_question_url($slot) {
a1eb3a44 2536 return $this->attemptobj->review_url($slot, -1, $this->showall, $this->page);
3c168fbb 2537 }
2538
b3782c71 2539 public function render_end_bits(mod_quiz_renderer $output) {
d18675a8 2540 $html = '';
2541 if ($this->attemptobj->get_num_pages() > 1) {
2542 if ($this->showall) {
b3782c71
TH
2543 $html .= html_writer::link($this->attemptobj->review_url(null, 0, false),
2544 get_string('showeachpage', 'quiz'));
d18675a8 2545 } else {
b3782c71
TH
2546 $html .= html_writer::link($this->attemptobj->review_url(null, 0, true),
2547 get_string('showall', 'quiz'));
d18675a8 2548 }
2549 }
d869de66 2550 $html .= $output->finish_review_link($this->attemptobj);
0eb253f7 2551 $html .= $this->render_restart_preview_link($output);
3c168fbb 2552 return $html;
2553 }
2554}