MDL-63497 mod_feedback: Add support for removal of context users
[moodle.git] / mod / quiz / attemptlib.php
blob00e1eb1b010ab84c37c7c00991a13c8a1ecd2c12
1 <?php
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.
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/>.
17 /**
18 * Back-end code for handling data about quizzes and the current user's attempt.
20 * There are classes for loading all the information about a quiz and attempts,
21 * and for displaying the navigation panel.
23 * @package mod_quiz
24 * @copyright 2008 onwards Tim Hunt
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 /**
33 * Class for quiz exceptions. Just saves a couple of arguments on the
34 * constructor for a moodle_exception.
36 * @copyright 2008 Tim Hunt
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.0
40 class moodle_quiz_exception extends moodle_exception {
41 public function __construct($quizobj, $errorcode, $a = null, $link = '', $debuginfo = null) {
42 if (!$link) {
43 $link = $quizobj->view_url();
45 parent::__construct($errorcode, 'quiz', $link, $a, $debuginfo);
50 /**
51 * A class encapsulating a quiz and the questions it contains, and making the
52 * information available to scripts like view.php.
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.
58 * @copyright 2008 Tim Hunt
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 * @since Moodle 2.0
62 class quiz {
63 /** @var stdClass the course settings from the database. */
64 protected $course;
65 /** @var stdClass the course_module settings from the database. */
66 protected $cm;
67 /** @var stdClass the quiz settings from the database. */
68 protected $quiz;
69 /** @var context the quiz context. */
70 protected $context;
72 /** @var array of questions augmented with slot information. */
73 protected $questions = null;
74 /** @var array of quiz_section rows. */
75 protected $sections = null;
76 /** @var quiz_access_manager the access manager for this quiz. */
77 protected $accessmanager = null;
78 /** @var bool whether the current user has capability mod/quiz:preview. */
79 protected $ispreviewuser = null;
81 // Constructor =============================================================
82 /**
83 * Constructor, assuming we already have the necessary data loaded.
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.
88 * @param bool $getcontext intended for testing - stops the constructor getting the context.
90 public function __construct($quiz, $cm, $course, $getcontext = true) {
91 $this->quiz = $quiz;
92 $this->cm = $cm;
93 $this->quiz->cmid = $this->cm->id;
94 $this->course = $course;
95 if ($getcontext && !empty($cm->id)) {
96 $this->context = context_module::instance($cm->id);
101 * Static function to create a new quiz object for a specific user.
103 * @param int $quizid the the quiz id.
104 * @param int $userid the the userid.
105 * @return quiz the new quiz object
107 public static function create($quizid, $userid = null) {
108 global $DB;
110 $quiz = quiz_access_manager::load_quiz_and_settings($quizid);
111 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
112 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
114 // Update quiz with override information.
115 if ($userid) {
116 $quiz = quiz_update_effective_access($quiz, $userid);
119 return new quiz($quiz, $cm, $course);
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.
127 public function create_attempt_object($attemptdata) {
128 return new quiz_attempt($attemptdata, $this->quiz, $this->cm, $this->course);
131 // Functions for loading more data =========================================
134 * Load just basic information about all the questions in this quiz.
136 public function preload_questions() {
137 $this->questions = question_preload_questions(null,
138 'slot.maxmark, slot.id AS slotid, slot.slot, slot.page,
139 slot.questioncategoryid AS randomfromcategory,
140 slot.includingsubcategories AS randomincludingsubcategories',
141 '{quiz_slots} slot ON slot.quizid = :quizid AND q.id = slot.questionid',
142 array('quizid' => $this->quiz->id), 'slot.slot');
146 * Fully load some or all of the questions for this quiz. You must call
147 * {@link preload_questions()} first.
149 * @param array $questionids question ids of the questions to load. null for all.
151 public function load_questions($questionids = null) {
152 if ($this->questions === null) {
153 throw new coding_exception('You must call preload_questions before calling load_questions.');
155 if (is_null($questionids)) {
156 $questionids = array_keys($this->questions);
158 $questionstoprocess = array();
159 foreach ($questionids as $id) {
160 if (array_key_exists($id, $this->questions)) {
161 $questionstoprocess[$id] = $this->questions[$id];
164 get_question_options($questionstoprocess);
168 * Get an instance of the {@link \mod_quiz\structure} class for this quiz.
169 * @return \mod_quiz\structure describes the questions in the quiz.
171 public function get_structure() {
172 return \mod_quiz\structure::create_for_quiz($this);
175 // Simple getters ==========================================================
176 /** @return int the course id. */
177 public function get_courseid() {
178 return $this->course->id;
181 /** @return object the row of the course table. */
182 public function get_course() {
183 return $this->course;
186 /** @return int the quiz id. */
187 public function get_quizid() {
188 return $this->quiz->id;
191 /** @return object the row of the quiz table. */
192 public function get_quiz() {
193 return $this->quiz;
196 /** @return string the name of this quiz. */
197 public function get_quiz_name() {
198 return $this->quiz->name;
201 /** @return int the quiz navigation method. */
202 public function get_navigation_method() {
203 return $this->quiz->navmethod;
206 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
207 public function get_num_attempts_allowed() {
208 return $this->quiz->attempts;
211 /** @return int the course_module id. */
212 public function get_cmid() {
213 return $this->cm->id;
216 /** @return object the course_module object. */
217 public function get_cm() {
218 return $this->cm;
221 /** @return object the module context for this quiz. */
222 public function get_context() {
223 return $this->context;
227 * @return bool wether the current user is someone who previews the quiz,
228 * rather than attempting it.
230 public function is_preview_user() {
231 if (is_null($this->ispreviewuser)) {
232 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context);
234 return $this->ispreviewuser;
238 * @return whether any questions have been added to this quiz.
240 public function has_questions() {
241 if ($this->questions === null) {
242 $this->preload_questions();
244 return !empty($this->questions);
248 * @param int $id the question id.
249 * @return object the question object with that id.
251 public function get_question($id) {
252 return $this->questions[$id];
256 * @param array $questionids question ids of the questions to load. null for all.
258 public function get_questions($questionids = null) {
259 if (is_null($questionids)) {
260 $questionids = array_keys($this->questions);
262 $questions = array();
263 foreach ($questionids as $id) {
264 if (!array_key_exists($id, $this->questions)) {
265 throw new moodle_exception('cannotstartmissingquestion', 'quiz', $this->view_url());
267 $questions[$id] = $this->questions[$id];
268 $this->ensure_question_loaded($id);
270 return $questions;
274 * Get all the sections in this quiz.
275 * @return array 0, 1, 2, ... => quiz_sections row from the database.
277 public function get_sections() {
278 global $DB;
279 if ($this->sections === null) {
280 $this->sections = array_values($DB->get_records('quiz_sections',
281 array('quizid' => $this->get_quizid()), 'firstslot'));
283 return $this->sections;
287 * Return quiz_access_manager and instance of the quiz_access_manager class
288 * for this quiz at this time.
289 * @param int $timenow the current time as a unix timestamp.
290 * @return quiz_access_manager and instance of the quiz_access_manager class
291 * for this quiz at this time.
293 public function get_access_manager($timenow) {
294 if (is_null($this->accessmanager)) {
295 $this->accessmanager = new quiz_access_manager($this, $timenow,
296 has_capability('mod/quiz:ignoretimelimits', $this->context, null, false));
298 return $this->accessmanager;
302 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
304 public function has_capability($capability, $userid = null, $doanything = true) {
305 return has_capability($capability, $this->context, $userid, $doanything);
309 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
311 public function require_capability($capability, $userid = null, $doanything = true) {
312 return require_capability($capability, $this->context, $userid, $doanything);
315 // URLs related to this attempt ============================================
317 * @return string the URL of this quiz's view page.
319 public function view_url() {
320 global $CFG;
321 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id;
325 * @return string the URL of this quiz's edit page.
327 public function edit_url() {
328 global $CFG;
329 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id;
333 * @param int $attemptid the id of an attempt.
334 * @param int $page optional page number to go to in the attempt.
335 * @return string the URL of that attempt.
337 public function attempt_url($attemptid, $page = 0) {
338 global $CFG;
339 $url = $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid;
340 if ($page) {
341 $url .= '&page=' . $page;
343 $url .= '&cmid=' . $this->get_cmid();
344 return $url;
348 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
350 public function start_attempt_url($page = 0) {
351 $params = array('cmid' => $this->cm->id, 'sesskey' => sesskey());
352 if ($page) {
353 $params['page'] = $page;
355 return new moodle_url('/mod/quiz/startattempt.php', $params);
359 * @param int $attemptid the id of an attempt.
360 * @return string the URL of the review of that attempt.
362 public function review_url($attemptid) {
363 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid, 'cmid' => $this->get_cmid()));
367 * @param int $attemptid the id of an attempt.
368 * @return string the URL of the review of that attempt.
370 public function summary_url($attemptid) {
371 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $attemptid, 'cmid' => $this->get_cmid()));
374 // Bits of content =========================================================
377 * @param bool $notused not used.
378 * @return string an empty string.
379 * @deprecated since 3.1. This sort of functionality is now entirely handled by quiz access rules.
381 public function confirm_start_attempt_message($notused) {
382 debugging('confirm_start_attempt_message is deprecated. ' .
383 'This sort of functionality is now entirely handled by quiz access rules.');
384 return '';
388 * If $reviewoptions->attempt is false, meaning that students can't review this
389 * attempt at the moment, return an appropriate string explaining why.
391 * @param int $when One of the mod_quiz_display_options::DURING,
392 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
393 * @param bool $short if true, return a shorter string.
394 * @return string an appropraite message.
396 public function cannot_review_message($when, $short = false) {
398 if ($short) {
399 $langstrsuffix = 'short';
400 $dateformat = get_string('strftimedatetimeshort', 'langconfig');
401 } else {
402 $langstrsuffix = '';
403 $dateformat = '';
406 if ($when == mod_quiz_display_options::DURING ||
407 $when == mod_quiz_display_options::IMMEDIATELY_AFTER) {
408 return '';
409 } else if ($when == mod_quiz_display_options::LATER_WHILE_OPEN && $this->quiz->timeclose &&
410 $this->quiz->reviewattempt & mod_quiz_display_options::AFTER_CLOSE) {
411 return get_string('noreviewuntil' . $langstrsuffix, 'quiz',
412 userdate($this->quiz->timeclose, $dateformat));
413 } else {
414 return get_string('noreview' . $langstrsuffix, 'quiz');
419 * @param string $title the name of this particular quiz page.
420 * @return array the data that needs to be sent to print_header_simple as the $navigation
421 * parameter.
423 public function navigation($title) {
424 global $PAGE;
425 $PAGE->navbar->add($title);
426 return '';
429 // Private methods =========================================================
431 * Check that the definition of a particular question is loaded, and if not throw an exception.
432 * @param $id a questionid.
434 protected function ensure_question_loaded($id) {
435 if (isset($this->questions[$id]->_partiallyloaded)) {
436 throw new moodle_quiz_exception($this, 'questionnotloaded', $id);
441 * Return all the question types used in this quiz.
443 * @param boolean $includepotential if the quiz include random questions, setting this flag to true will make the function to
444 * return all the possible question types in the random questions category
445 * @return array a sorted array including the different question types
446 * @since Moodle 3.1
448 public function get_all_question_types_used($includepotential = false) {
449 $questiontypes = array();
451 // To control if we need to look in categories for questions.
452 $qcategories = array();
454 // We must be careful with random questions, if we find a random question we must assume that the quiz may content
455 // any of the questions in the referenced category (or subcategories).
456 foreach ($this->get_questions() as $questiondata) {
457 if ($questiondata->qtype == 'random' and $includepotential) {
458 $includesubcategories = (bool) $questiondata->questiontext;
459 if (!isset($qcategories[$questiondata->category])) {
460 $qcategories[$questiondata->category] = false;
462 if ($includesubcategories) {
463 $qcategories[$questiondata->category] = true;
465 } else {
466 if (!in_array($questiondata->qtype, $questiontypes)) {
467 $questiontypes[] = $questiondata->qtype;
472 if (!empty($qcategories)) {
473 // We have to look for all the question types in these categories.
474 $categoriestolook = array();
475 foreach ($qcategories as $cat => $includesubcats) {
476 if ($includesubcats) {
477 $categoriestolook = array_merge($categoriestolook, question_categorylist($cat));
478 } else {
479 $categoriestolook[] = $cat;
482 $questiontypesincategories = question_bank::get_all_question_types_in_categories($categoriestolook);
483 $questiontypes = array_merge($questiontypes, $questiontypesincategories);
485 $questiontypes = array_unique($questiontypes);
486 sort($questiontypes);
488 return $questiontypes;
494 * This class extends the quiz class to hold data about the state of a particular attempt,
495 * in addition to the data about the quiz.
497 * @copyright 2008 Tim Hunt
498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
499 * @since Moodle 2.0
501 class quiz_attempt {
503 /** @var string to identify the in progress state. */
504 const IN_PROGRESS = 'inprogress';
505 /** @var string to identify the overdue state. */
506 const OVERDUE = 'overdue';
507 /** @var string to identify the finished state. */
508 const FINISHED = 'finished';
509 /** @var string to identify the abandoned state. */
510 const ABANDONED = 'abandoned';
512 /** @var int maximum number of slots in the quiz for the review page to default to show all. */
513 const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL = 50;
515 /** @var quiz object containing the quiz settings. */
516 protected $quizobj;
518 /** @var stdClass the quiz_attempts row. */
519 protected $attempt;
521 /** @var question_usage_by_activity the question usage for this quiz attempt. */
522 protected $quba;
525 * @var array of slot information. These objects contain ->slot (int),
526 * ->requireprevious (bool), ->questionids (int) the original question for random questions,
527 * ->firstinsection (bool), ->section (stdClass from $this->sections).
528 * This does not contain page - get that from {@link get_question_page()} -
529 * or maxmark - get that from $this->quba.
531 protected $slots;
533 /** @var array of quiz_sections rows, with a ->lastslot field added. */
534 protected $sections;
536 /** @var array page no => array of slot numbers on the page in order. */
537 protected $pagelayout;
539 /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */
540 protected $questionnumbers;
542 /** @var array slot => page number for this slot. */
543 protected $questionpages;
545 /** @var mod_quiz_display_options cache for the appropriate review options. */
546 protected $reviewoptions = null;
548 // Constructor =============================================================
550 * Constructor assuming we already have the necessary data loaded.
552 * @param object $attempt the row of the quiz_attempts table.
553 * @param object $quiz the quiz object for this attempt and user.
554 * @param object $cm the course_module object for this quiz.
555 * @param object $course the row from the course table for the course we belong to.
556 * @param bool $loadquestions (optional) if true, the default, load all the details
557 * of the state of each question. Else just set up the basic details of the attempt.
559 public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) {
560 global $DB;
562 $this->attempt = $attempt;
563 $this->quizobj = new quiz($quiz, $cm, $course);
565 if (!$loadquestions) {
566 return;
569 $this->quba = question_engine::load_questions_usage_by_activity($this->attempt->uniqueid);
570 $this->slots = $DB->get_records('quiz_slots',
571 array('quizid' => $this->get_quizid()), 'slot',
572 'slot, requireprevious, questionid, includingsubcategories');
573 $this->sections = array_values($DB->get_records('quiz_sections',
574 array('quizid' => $this->get_quizid()), 'firstslot'));
576 $this->link_sections_and_slots();
577 $this->determine_layout();
578 $this->number_questions();
582 * Used by {create()} and {create_from_usage_id()}.
583 * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions).
585 protected static function create_helper($conditions) {
586 global $DB;
588 $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST);
589 $quiz = quiz_access_manager::load_quiz_and_settings($attempt->quiz);
590 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
591 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
593 // Update quiz with override information.
594 $quiz = quiz_update_effective_access($quiz, $attempt->userid);
596 return new quiz_attempt($attempt, $quiz, $cm, $course);
600 * Static function to create a new quiz_attempt object given an attemptid.
602 * @param int $attemptid the attempt id.
603 * @return quiz_attempt the new quiz_attempt object
605 public static function create($attemptid) {
606 return self::create_helper(array('id' => $attemptid));
610 * Static function to create a new quiz_attempt object given a usage id.
612 * @param int $usageid the attempt usage id.
613 * @return quiz_attempt the new quiz_attempt object
615 public static function create_from_usage_id($usageid) {
616 return self::create_helper(array('uniqueid' => $usageid));
620 * @param string $state one of the state constants like IN_PROGRESS.
621 * @return string the human-readable state name.
623 public static function state_name($state) {
624 return quiz_attempt_state_name($state);
628 * Let each slot know which section it is part of.
630 protected function link_sections_and_slots() {
631 foreach ($this->sections as $i => $section) {
632 if (isset($this->sections[$i + 1])) {
633 $section->lastslot = $this->sections[$i + 1]->firstslot - 1;
634 } else {
635 $section->lastslot = count($this->slots);
637 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) {
638 $this->slots[$slot]->section = $section;
644 * Parse attempt->layout to populate the other arrays the represent the layout.
646 protected function determine_layout() {
647 $this->pagelayout = array();
649 // Break up the layout string into pages.
650 $pagelayouts = explode(',0', $this->attempt->layout);
652 // Strip off any empty last page (normally there is one).
653 if (end($pagelayouts) == '') {
654 array_pop($pagelayouts);
657 // File the ids into the arrays.
658 // Tracking which is the first slot in each section in this attempt is
659 // trickier than you might guess, since the slots in this section
660 // may be shuffled, so $section->firstslot (the lowest numbered slot in
661 // the section) may not be the first one.
662 $unseensections = $this->sections;
663 $this->pagelayout = array();
664 foreach ($pagelayouts as $page => $pagelayout) {
665 $pagelayout = trim($pagelayout, ',');
666 if ($pagelayout == '') {
667 continue;
669 $this->pagelayout[$page] = explode(',', $pagelayout);
670 foreach ($this->pagelayout[$page] as $slot) {
671 $sectionkey = array_search($this->slots[$slot]->section, $unseensections);
672 if ($sectionkey !== false) {
673 $this->slots[$slot]->firstinsection = true;
674 unset($unseensections[$sectionkey]);
675 } else {
676 $this->slots[$slot]->firstinsection = false;
683 * Work out the number to display for each question/slot.
685 protected function number_questions() {
686 $number = 1;
687 foreach ($this->pagelayout as $page => $slots) {
688 foreach ($slots as $slot) {
689 if ($length = $this->is_real_question($slot)) {
690 $this->questionnumbers[$slot] = $number;
691 $number += $length;
692 } else {
693 $this->questionnumbers[$slot] = get_string('infoshort', 'quiz');
695 $this->questionpages[$slot] = $page;
701 * If the given page number is out of range (before the first page, or after
702 * the last page, chnage it to be within range).
703 * @param int $page the requested page number.
704 * @return int a safe page number to use.
706 public function force_page_number_into_range($page) {
707 return min(max($page, 0), count($this->pagelayout) - 1);
710 // Simple getters ==========================================================
711 public function get_quiz() {
712 return $this->quizobj->get_quiz();
715 public function get_quizobj() {
716 return $this->quizobj;
719 /** @return int the course id. */
720 public function get_courseid() {
721 return $this->quizobj->get_courseid();
724 /** @return int the course id. */
725 public function get_course() {
726 return $this->quizobj->get_course();
729 /** @return int the quiz id. */
730 public function get_quizid() {
731 return $this->quizobj->get_quizid();
734 /** @return string the name of this quiz. */
735 public function get_quiz_name() {
736 return $this->quizobj->get_quiz_name();
739 /** @return int the quiz navigation method. */
740 public function get_navigation_method() {
741 return $this->quizobj->get_navigation_method();
744 /** @return object the course_module object. */
745 public function get_cm() {
746 return $this->quizobj->get_cm();
749 /** @return object the course_module object. */
750 public function get_cmid() {
751 return $this->quizobj->get_cmid();
755 * @return bool wether the current user is someone who previews the quiz,
756 * rather than attempting it.
758 public function is_preview_user() {
759 return $this->quizobj->is_preview_user();
762 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
763 public function get_num_attempts_allowed() {
764 return $this->quizobj->get_num_attempts_allowed();
767 /** @return int number fo pages in this quiz. */
768 public function get_num_pages() {
769 return count($this->pagelayout);
773 * @param int $timenow the current time as a unix timestamp.
774 * @return quiz_access_manager and instance of the quiz_access_manager class
775 * for this quiz at this time.
777 public function get_access_manager($timenow) {
778 return $this->quizobj->get_access_manager($timenow);
781 /** @return int the attempt id. */
782 public function get_attemptid() {
783 return $this->attempt->id;
786 /** @return int the attempt unique id. */
787 public function get_uniqueid() {
788 return $this->attempt->uniqueid;
791 /** @return object the row from the quiz_attempts table. */
792 public function get_attempt() {
793 return $this->attempt;
796 /** @return int the number of this attemp (is it this user's first, second, ... attempt). */
797 public function get_attempt_number() {
798 return $this->attempt->attempt;
801 /** @return string one of the quiz_attempt::IN_PROGRESS, FINISHED, OVERDUE or ABANDONED constants. */
802 public function get_state() {
803 return $this->attempt->state;
806 /** @return int the id of the user this attempt belongs to. */
807 public function get_userid() {
808 return $this->attempt->userid;
811 /** @return int the current page of the attempt. */
812 public function get_currentpage() {
813 return $this->attempt->currentpage;
816 public function get_sum_marks() {
817 return $this->attempt->sumgrades;
821 * @return bool whether this attempt has been finished (true) or is still
822 * in progress (false). Be warned that this is not just state == self::FINISHED,
823 * it also includes self::ABANDONED.
825 public function is_finished() {
826 return $this->attempt->state == self::FINISHED || $this->attempt->state == self::ABANDONED;
829 /** @return bool whether this attempt is a preview attempt. */
830 public function is_preview() {
831 return $this->attempt->preview;
835 * Is this someone dealing with their own attempt or preview?
837 * @return bool true => own attempt/preview. false => reviewing someone elses.
839 public function is_own_attempt() {
840 global $USER;
841 return $this->attempt->userid == $USER->id;
845 * @return bool whether this attempt is a preview belonging to the current user.
847 public function is_own_preview() {
848 global $USER;
849 return $this->is_own_attempt() &&
850 $this->is_preview_user() && $this->attempt->preview;
854 * Is the current user allowed to review this attempt. This applies when
855 * {@link is_own_attempt()} returns false.
856 * @return bool whether the review should be allowed.
858 public function is_review_allowed() {
859 if (!$this->has_capability('mod/quiz:viewreports')) {
860 return false;
863 $cm = $this->get_cm();
864 if ($this->has_capability('moodle/site:accessallgroups') ||
865 groups_get_activity_groupmode($cm) != SEPARATEGROUPS) {
866 return true;
869 // Check the users have at least one group in common.
870 $teachersgroups = groups_get_activity_allowed_groups($cm);
871 $studentsgroups = groups_get_all_groups(
872 $cm->course, $this->attempt->userid, $cm->groupingid);
873 return $teachersgroups && $studentsgroups &&
874 array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
878 * Has the student, in this attempt, engaged with the quiz in a non-trivial way?
879 * That is, is there any question worth a non-zero number of marks, where
880 * the student has made some response that we have saved?
881 * @return bool true if we have saved a response for at least one graded question.
883 public function has_response_to_at_least_one_graded_question() {
884 foreach ($this->quba->get_attempt_iterator() as $qa) {
885 if ($qa->get_max_mark() == 0) {
886 continue;
888 if ($qa->get_num_steps() > 1) {
889 return true;
892 return false;
896 * Get extra summary information about this attempt.
898 * Some behaviours may be able to provide interesting summary information
899 * about the attempt as a whole, and this method provides access to that data.
900 * To see how this works, try setting a quiz to one of the CBM behaviours,
901 * and then look at the extra information displayed at the top of the quiz
902 * review page once you have sumitted an attempt.
904 * In the return value, the array keys are identifiers of the form
905 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
906 * The values are arrays with two items, title and content. Each of these
907 * will be either a string, or a renderable.
909 * @param question_display_options $options the display options for this quiz attempt at this time.
910 * @return array as described above.
912 public function get_additional_summary_data(question_display_options $options) {
913 return $this->quba->get_summary_information($options);
917 * Get the overall feedback corresponding to a particular mark.
918 * @param $grade a particular grade.
920 public function get_overall_feedback($grade) {
921 return quiz_feedback_for_grade($grade, $this->get_quiz(),
922 $this->quizobj->get_context());
926 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
928 public function has_capability($capability, $userid = null, $doanything = true) {
929 return $this->quizobj->has_capability($capability, $userid, $doanything);
933 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
935 public function require_capability($capability, $userid = null, $doanything = true) {
936 return $this->quizobj->require_capability($capability, $userid, $doanything);
940 * Check the appropriate capability to see whether this user may review their own attempt.
941 * If not, prints an error.
943 public function check_review_capability() {
944 if ($this->get_attempt_state() == mod_quiz_display_options::IMMEDIATELY_AFTER) {
945 $capability = 'mod/quiz:attempt';
946 } else {
947 $capability = 'mod/quiz:reviewmyattempts';
950 // These next tests are in a slighly funny order. The point is that the
951 // common and most performance-critical case is students attempting a quiz
952 // so we want to check that permisison first.
954 if ($this->has_capability($capability)) {
955 // User has the permission that lets you do the quiz as a student. Fine.
956 return;
959 if ($this->has_capability('mod/quiz:viewreports') ||
960 $this->has_capability('mod/quiz:preview')) {
961 // User has the permission that lets teachers review. Fine.
962 return;
965 // They should not be here. Trigger the standard no-permission error
966 // but using the name of the student capability.
967 // We know this will fail. We just want the stadard exception thown.
968 $this->require_capability($capability);
972 * Checks whether a user may navigate to a particular slot
974 public function can_navigate_to($slot) {
975 switch ($this->get_navigation_method()) {
976 case QUIZ_NAVMETHOD_FREE:
977 return true;
978 break;
979 case QUIZ_NAVMETHOD_SEQ:
980 return false;
981 break;
983 return true;
987 * @return int one of the mod_quiz_display_options::DURING,
988 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
990 public function get_attempt_state() {
991 return quiz_attempt_state($this->get_quiz(), $this->attempt);
995 * Wrapper that the correct mod_quiz_display_options for this quiz at the
996 * moment.
998 * @return question_display_options the render options for this user on this attempt.
1000 public function get_display_options($reviewing) {
1001 if ($reviewing) {
1002 if (is_null($this->reviewoptions)) {
1003 $this->reviewoptions = quiz_get_review_options($this->get_quiz(),
1004 $this->attempt, $this->quizobj->get_context());
1005 if ($this->is_own_preview()) {
1006 // It should always be possible for a teacher to review their
1007 // own preview irrespective of the review options settings.
1008 $this->reviewoptions->attempt = true;
1011 return $this->reviewoptions;
1013 } else {
1014 $options = mod_quiz_display_options::make_from_quiz($this->get_quiz(),
1015 mod_quiz_display_options::DURING);
1016 $options->flags = quiz_get_flag_option($this->attempt, $this->quizobj->get_context());
1017 return $options;
1022 * Wrapper that the correct mod_quiz_display_options for this quiz at the
1023 * moment.
1025 * @param bool $reviewing true for review page, else attempt page.
1026 * @param int $slot which question is being displayed.
1027 * @param moodle_url $thispageurl to return to after the editing form is
1028 * submitted or cancelled. If null, no edit link will be generated.
1030 * @return question_display_options the render options for this user on this
1031 * attempt, with extra info to generate an edit link, if applicable.
1033 public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) {
1034 $options = clone($this->get_display_options($reviewing));
1036 if (!$thispageurl) {
1037 return $options;
1040 if (!($reviewing || $this->is_preview())) {
1041 return $options;
1044 $question = $this->quba->get_question($slot);
1045 if (!question_has_capability_on($question, 'edit', $question->category)) {
1046 return $options;
1049 $options->editquestionparams['cmid'] = $this->get_cmid();
1050 $options->editquestionparams['returnurl'] = $thispageurl;
1052 return $options;
1056 * @param int $page page number
1057 * @return bool true if this is the last page of the quiz.
1059 public function is_last_page($page) {
1060 return $page == count($this->pagelayout) - 1;
1064 * Return the list of slot numbers for either a given page of the quiz, or for the
1065 * whole quiz.
1067 * @param mixed $page string 'all' or integer page number.
1068 * @return array the requested list of slot numbers.
1070 public function get_slots($page = 'all') {
1071 if ($page === 'all') {
1072 $numbers = array();
1073 foreach ($this->pagelayout as $numbersonpage) {
1074 $numbers = array_merge($numbers, $numbersonpage);
1076 return $numbers;
1077 } else {
1078 return $this->pagelayout[$page];
1083 * Return the list of slot numbers for either a given page of the quiz, or for the
1084 * whole quiz.
1086 * @param mixed $page string 'all' or integer page number.
1087 * @return array the requested list of slot numbers.
1089 public function get_active_slots($page = 'all') {
1090 $activeslots = array();
1091 foreach ($this->get_slots($page) as $slot) {
1092 if (!$this->is_blocked_by_previous_question($slot)) {
1093 $activeslots[] = $slot;
1096 return $activeslots;
1100 * Helper method for unit tests. Get the underlying question usage object.
1101 * @return question_usage_by_activity the usage.
1103 public function get_question_usage() {
1104 if (!(PHPUNIT_TEST || defined('BEHAT_TEST'))) {
1105 throw new coding_exception('get_question_usage is only for use in unit tests. ' .
1106 'For other operations, use the quiz_attempt api, or extend it properly.');
1108 return $this->quba;
1112 * Get the question_attempt object for a particular question in this attempt.
1113 * @param int $slot the number used to identify this question within this attempt.
1114 * @return question_attempt
1116 public function get_question_attempt($slot) {
1117 return $this->quba->get_question_attempt($slot);
1121 * Get the question_attempt object for a particular question in this attempt.
1122 * @param int $slot the number used to identify this question within this attempt.
1123 * @return question_attempt
1125 public function all_question_attempts_originally_in_slot($slot) {
1126 $qas = array();
1127 foreach ($this->quba->get_attempt_iterator() as $qa) {
1128 if ($qa->get_metadata('originalslot') == $slot) {
1129 $qas[] = $qa;
1132 $qas[] = $this->quba->get_question_attempt($slot);
1133 return $qas;
1137 * Is a particular question in this attempt a real question, or something like a description.
1138 * @param int $slot the number used to identify this question within this attempt.
1139 * @return int whether that question is a real question. Actually returns the
1140 * question length, which could theoretically be greater than one.
1142 public function is_real_question($slot) {
1143 return $this->quba->get_question($slot)->length;
1147 * Is a particular question in this attempt a real question, or something like a description.
1148 * @param int $slot the number used to identify this question within this attempt.
1149 * @return bool whether that question is a real question.
1151 public function is_question_flagged($slot) {
1152 return $this->quba->get_question_attempt($slot)->is_flagged();
1156 * Checks whether the question in this slot requires the previous question to have been completed.
1158 * @param int $slot the number used to identify this question within this attempt.
1159 * @return bool whether the previous question must have been completed before this one can be seen.
1161 public function is_blocked_by_previous_question($slot) {
1162 return $slot > 1 && isset($this->slots[$slot]) && $this->slots[$slot]->requireprevious &&
1163 !$this->slots[$slot]->section->shufflequestions &&
1164 !$this->slots[$slot - 1]->section->shufflequestions &&
1165 $this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ &&
1166 !$this->get_question_state($slot - 1)->is_finished() &&
1167 $this->quba->can_question_finish_during_attempt($slot - 1);
1171 * Is it possible for this question to be re-started within this attempt?
1173 * @param int $slot the number used to identify this question within this attempt.
1174 * @return whether the student should be given the option to restart this question now.
1176 public function can_question_be_redone_now($slot) {
1177 return $this->get_quiz()->canredoquestions && !$this->is_finished() &&
1178 $this->get_question_state($slot)->is_finished();
1182 * Given a slot in this attempt, which may or not be a redone question, return the original slot.
1184 * @param int $slot identifies a particular question in this attempt.
1185 * @return int the slot where this question was originally.
1187 public function get_original_slot($slot) {
1188 $originalslot = $this->quba->get_question_attempt_metadata($slot, 'originalslot');
1189 if ($originalslot) {
1190 return $originalslot;
1191 } else {
1192 return $slot;
1197 * Get the displayed question number for a slot.
1198 * @param int $slot the number used to identify this question within this attempt.
1199 * @return string the displayed question number for the question in this slot.
1200 * For example '1', '2', '3' or 'i'.
1202 public function get_question_number($slot) {
1203 return $this->questionnumbers[$slot];
1207 * If the section heading, if any, that should come just before this slot.
1208 * @param int $slot identifies a particular question in this attempt.
1209 * @return string the required heading, or null if there is not one here.
1211 public function get_heading_before_slot($slot) {
1212 if ($this->slots[$slot]->firstinsection) {
1213 return $this->slots[$slot]->section->heading;
1214 } else {
1215 return null;
1220 * Return the page of the quiz where this question appears.
1221 * @param int $slot the number used to identify this question within this attempt.
1222 * @return int the page of the quiz this question appears on.
1224 public function get_question_page($slot) {
1225 return $this->questionpages[$slot];
1229 * Return the grade obtained on a particular question, if the user is permitted
1230 * to see it. You must previously have called load_question_states to load the
1231 * state data about this question.
1233 * @param int $slot the number used to identify this question within this attempt.
1234 * @return string the formatted grade, to the number of decimal places specified
1235 * by the quiz.
1237 public function get_question_name($slot) {
1238 return $this->quba->get_question($slot)->name;
1242 * Return the {@link question_state} that this question is in.
1244 * @param int $slot the number used to identify this question within this attempt.
1245 * @return question_state the state this question is in.
1247 public function get_question_state($slot) {
1248 return $this->quba->get_question_state($slot);
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.
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 the formatted grade, to the number of decimal places specified
1260 * by the quiz.
1262 public function get_question_status($slot, $showcorrectness) {
1263 return $this->quba->get_question_state_string($slot, $showcorrectness);
1267 * Return the grade obtained on a particular question, if the user is permitted
1268 * to see it. You must previously have called load_question_states to load the
1269 * state data about this question.
1271 * @param int $slot the number used to identify this question within this attempt.
1272 * @param bool $showcorrectness Whether right/partial/wrong states should
1273 * be distinguised.
1274 * @return string class name for this state.
1276 public function get_question_state_class($slot, $showcorrectness) {
1277 return $this->quba->get_question_state_class($slot, $showcorrectness);
1281 * Return the grade obtained on a particular question.
1282 * You must previously have called load_question_states to load the state
1283 * data about this question.
1285 * @param int $slot the number used to identify this question within this attempt.
1286 * @return string the formatted grade, to the number of decimal places specified by the quiz.
1288 public function get_question_mark($slot) {
1289 return quiz_format_question_grade($this->get_quiz(), $this->quba->get_question_mark($slot));
1293 * Get the time of the most recent action performed on a question.
1294 * @param int $slot the number used to identify this question within this usage.
1295 * @return int timestamp.
1297 public function get_question_action_time($slot) {
1298 return $this->quba->get_question_action_time($slot);
1302 * Return the question type name for a given slot within the current attempt.
1304 * @param int $slot the number used to identify this question within this attempt.
1305 * @return string the question type name
1306 * @since Moodle 3.1
1308 public function get_question_type_name($slot) {
1309 return $this->quba->get_question($slot)->get_type_name();
1313 * Get the time remaining for an in-progress attempt, if the time is short
1314 * enought that it would be worth showing a timer.
1315 * @param int $timenow the time to consider as 'now'.
1316 * @return int|false the number of seconds remaining for this attempt.
1317 * False if there is no limit.
1319 public function get_time_left_display($timenow) {
1320 if ($this->attempt->state != self::IN_PROGRESS) {
1321 return false;
1323 return $this->get_access_manager($timenow)->get_time_left_display($this->attempt, $timenow);
1328 * @return int the time when this attempt was submitted. 0 if it has not been
1329 * submitted yet.
1331 public function get_submitted_date() {
1332 return $this->attempt->timefinish;
1336 * If the attempt is in an applicable state, work out the time by which the
1337 * student should next do something.
1338 * @return int timestamp by which the student needs to do something.
1340 public function get_due_date() {
1341 $deadlines = array();
1342 if ($this->quizobj->get_quiz()->timelimit) {
1343 $deadlines[] = $this->attempt->timestart + $this->quizobj->get_quiz()->timelimit;
1345 if ($this->quizobj->get_quiz()->timeclose) {
1346 $deadlines[] = $this->quizobj->get_quiz()->timeclose;
1348 if ($deadlines) {
1349 $duedate = min($deadlines);
1350 } else {
1351 return false;
1354 switch ($this->attempt->state) {
1355 case self::IN_PROGRESS:
1356 return $duedate;
1358 case self::OVERDUE:
1359 return $duedate + $this->quizobj->get_quiz()->graceperiod;
1361 default:
1362 throw new coding_exception('Unexpected state: ' . $this->attempt->state);
1366 // URLs related to this attempt ============================================
1368 * @return string quiz view url.
1370 public function view_url() {
1371 return $this->quizobj->view_url();
1375 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
1377 public function start_attempt_url($slot = null, $page = -1) {
1378 if ($page == -1 && !is_null($slot)) {
1379 $page = $this->get_question_page($slot);
1380 } else {
1381 $page = 0;
1383 return $this->quizobj->start_attempt_url($page);
1387 * @param int $slot if speified, the slot number of a specific question to link to.
1388 * @param int $page if specified, a particular page to link to. If not givem deduced
1389 * from $slot, or goes to the first page.
1390 * @param int $questionid a question id. If set, will add a fragment to the URL
1391 * to jump to a particuar question on the page.
1392 * @param int $thispage if not -1, the current page. Will cause links to other things on
1393 * this page to be output as only a fragment.
1394 * @return string the URL to continue this attempt.
1396 public function attempt_url($slot = null, $page = -1, $thispage = -1) {
1397 return $this->page_and_question_url('attempt', $slot, $page, false, $thispage);
1401 * @return string the URL of this quiz's summary page.
1403 public function summary_url() {
1404 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $this->attempt->id, 'cmid' => $this->get_cmid()));
1408 * @return string the URL of this quiz's summary page.
1410 public function processattempt_url() {
1411 return new moodle_url('/mod/quiz/processattempt.php');
1415 * @param int $slot indicates which question to link to.
1416 * @param int $page if specified, the URL of this particular page of the attempt, otherwise
1417 * the URL will go to the first page. If -1, deduce $page from $slot.
1418 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
1419 * and $page will be ignored. If null, a sensible default will be chosen.
1420 * @param int $thispage if not -1, the current page. Will cause links to other things on
1421 * this page to be output as only a fragment.
1422 * @return string the URL to review this attempt.
1424 public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) {
1425 return $this->page_and_question_url('review', $slot, $page, $showall, $thispage);
1429 * By default, should this script show all questions on one page for this attempt?
1430 * @param string $script the script name, e.g. 'attempt', 'summary', 'review'.
1431 * @return whether show all on one page should be on by default.
1433 public function get_default_show_all($script) {
1434 return $script == 'review' && count($this->questionpages) < self::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL;
1437 // Bits of content =========================================================
1440 * If $reviewoptions->attempt is false, meaning that students can't review this
1441 * attempt at the moment, return an appropriate string explaining why.
1443 * @param bool $short if true, return a shorter string.
1444 * @return string an appropraite message.
1446 public function cannot_review_message($short = false) {
1447 return $this->quizobj->cannot_review_message(
1448 $this->get_attempt_state(), $short);
1452 * Initialise the JS etc. required all the questions on a page.
1453 * @param mixed $page a page number, or 'all'.
1455 public function get_html_head_contributions($page = 'all', $showall = false) {
1456 if ($showall) {
1457 $page = 'all';
1459 $result = '';
1460 foreach ($this->get_slots($page) as $slot) {
1461 $result .= $this->quba->render_question_head_html($slot);
1463 $result .= question_engine::initialise_js();
1464 return $result;
1468 * Initialise the JS etc. required by one question.
1469 * @param int $questionid the question id.
1471 public function get_question_html_head_contributions($slot) {
1472 return $this->quba->render_question_head_html($slot) .
1473 question_engine::initialise_js();
1477 * Print the HTML for the start new preview button, if the current user
1478 * is allowed to see one.
1480 public function restart_preview_button() {
1481 global $OUTPUT;
1482 if ($this->is_preview() && $this->is_preview_user()) {
1483 return $OUTPUT->single_button(new moodle_url(
1484 $this->start_attempt_url(), array('forcenew' => true)),
1485 get_string('startnewpreview', 'quiz'));
1486 } else {
1487 return '';
1492 * Generate the HTML that displayes the question in its current state, with
1493 * the appropriate display options.
1495 * @param int $slot identifies the question in the attempt.
1496 * @param bool $reviewing is the being printed on an attempt or a review page.
1497 * @param mod_quiz_renderer $renderer the quiz renderer.
1498 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1499 * @return string HTML for the question in its current state.
1501 public function render_question($slot, $reviewing, mod_quiz_renderer $renderer, $thispageurl = null) {
1502 if ($this->is_blocked_by_previous_question($slot)) {
1503 $placeholderqa = $this->make_blocked_question_placeholder($slot);
1505 $displayoptions = $this->get_display_options($reviewing);
1506 $displayoptions->manualcomment = question_display_options::HIDDEN;
1507 $displayoptions->history = question_display_options::HIDDEN;
1508 $displayoptions->readonly = true;
1510 return html_writer::div($placeholderqa->render($displayoptions,
1511 $this->get_question_number($this->get_original_slot($slot))),
1512 'mod_quiz-blocked_question_warning');
1515 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, null);
1519 * Helper used by {@link render_question()} and {@link render_question_at_step()}.
1521 * @param int $slot identifies the question in the attempt.
1522 * @param bool $reviewing is the being printed on an attempt or a review page.
1523 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1524 * @param mod_quiz_renderer $renderer the quiz renderer.
1525 * @param int|null $seq the seq number of the past state to display.
1526 * @return string HTML fragment.
1528 protected function render_question_helper($slot, $reviewing, $thispageurl, mod_quiz_renderer $renderer, $seq) {
1529 $originalslot = $this->get_original_slot($slot);
1530 $number = $this->get_question_number($originalslot);
1531 $displayoptions = $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl);
1533 if ($slot != $originalslot) {
1534 $originalmaxmark = $this->get_question_attempt($slot)->get_max_mark();
1535 $this->get_question_attempt($slot)->set_max_mark($this->get_question_attempt($originalslot)->get_max_mark());
1538 if ($this->can_question_be_redone_now($slot)) {
1539 $displayoptions->extrainfocontent = $renderer->redo_question_button(
1540 $slot, $displayoptions->readonly);
1543 if ($displayoptions->history && $displayoptions->questionreviewlink) {
1544 $links = $this->links_to_other_redos($slot, $displayoptions->questionreviewlink);
1545 if ($links) {
1546 $displayoptions->extrahistorycontent = html_writer::tag('p',
1547 get_string('redoesofthisquestion', 'quiz', $renderer->render($links)));
1551 if ($seq === null) {
1552 $output = $this->quba->render_question($slot, $displayoptions, $number);
1553 } else {
1554 $output = $this->quba->render_question_at_step($slot, $seq, $displayoptions, $number);
1557 if ($slot != $originalslot) {
1558 $this->get_question_attempt($slot)->set_max_mark($originalmaxmark);
1561 return $output;
1565 * Create a fake question to be displayed in place of a question that is blocked
1566 * until the previous question has been answered.
1568 * @param int $slot int slot number of the question to replace.
1569 * @return question_definition the placeholde question.
1571 protected function make_blocked_question_placeholder($slot) {
1572 $replacedquestion = $this->get_question_attempt($slot)->get_question();
1574 question_bank::load_question_definition_classes('description');
1575 $question = new qtype_description_question();
1576 $question->id = $replacedquestion->id;
1577 $question->category = null;
1578 $question->parent = 0;
1579 $question->qtype = question_bank::get_qtype('description');
1580 $question->name = '';
1581 $question->questiontext = get_string('questiondependsonprevious', 'quiz');
1582 $question->questiontextformat = FORMAT_HTML;
1583 $question->generalfeedback = '';
1584 $question->defaultmark = $this->quba->get_question_max_mark($slot);
1585 $question->length = $replacedquestion->length;
1586 $question->penalty = 0;
1587 $question->stamp = '';
1588 $question->version = 0;
1589 $question->hidden = 0;
1590 $question->timecreated = null;
1591 $question->timemodified = null;
1592 $question->createdby = null;
1593 $question->modifiedby = null;
1595 $placeholderqa = new question_attempt($question, $this->quba->get_id(),
1596 null, $this->quba->get_question_max_mark($slot));
1597 $placeholderqa->set_slot($slot);
1598 $placeholderqa->start($this->get_quiz()->preferredbehaviour, 1);
1599 $placeholderqa->set_flagged($this->is_question_flagged($slot));
1600 return $placeholderqa;
1604 * Like {@link render_question()} but displays the question at the past step
1605 * indicated by $seq, rather than showing the latest step.
1607 * @param int $id the id of a question in this quiz attempt.
1608 * @param int $seq the seq number of the past state to display.
1609 * @param bool $reviewing is the being printed on an attempt or a review page.
1610 * @param mod_quiz_renderer $renderer the quiz renderer.
1611 * @param string $thispageurl the URL of the page this question is being printed on.
1612 * @return string HTML for the question in its current state.
1614 public function render_question_at_step($slot, $seq, $reviewing, mod_quiz_renderer $renderer, $thispageurl = '') {
1615 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, $seq);
1619 * Wrapper round print_question from lib/questionlib.php.
1621 * @param int $id the id of a question in this quiz attempt.
1623 public function render_question_for_commenting($slot) {
1624 $options = $this->get_display_options(true);
1625 $options->hide_all_feedback();
1626 $options->manualcomment = question_display_options::EDITABLE;
1627 return $this->quba->render_question($slot, $options,
1628 $this->get_question_number($slot));
1632 * Check wheter access should be allowed to a particular file.
1634 * @param int $id the id of a question in this quiz attempt.
1635 * @param bool $reviewing is the being printed on an attempt or a review page.
1636 * @param string $thispageurl the URL of the page this question is being printed on.
1637 * @return string HTML for the question in its current state.
1639 public function check_file_access($slot, $reviewing, $contextid, $component,
1640 $filearea, $args, $forcedownload) {
1641 $options = $this->get_display_options($reviewing);
1643 // Check permissions - warning there is similar code in review.php and
1644 // reviewquestion.php. If you change on, change them all.
1645 if ($reviewing && $this->is_own_attempt() && !$options->attempt) {
1646 return false;
1649 if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) {
1650 return false;
1653 return $this->quba->check_file_access($slot, $options,
1654 $component, $filearea, $args, $forcedownload);
1658 * Get the navigation panel object for this attempt.
1660 * @param $panelclass The type of panel, quiz_attempt_nav_panel or quiz_review_nav_panel
1661 * @param $page the current page number.
1662 * @param $showall whether we are showing the whole quiz on one page. (Used by review.php)
1663 * @return quiz_nav_panel_base the requested object.
1665 public function get_navigation_panel(mod_quiz_renderer $output,
1666 $panelclass, $page, $showall = false) {
1667 $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall);
1669 $bc = new block_contents();
1670 $bc->attributes['id'] = 'mod_quiz_navblock';
1671 $bc->attributes['role'] = 'navigation';
1672 $bc->attributes['aria-labelledby'] = 'mod_quiz_navblock_title';
1673 $bc->title = html_writer::span(get_string('quiznavigation', 'quiz'), '', array('id' => 'mod_quiz_navblock_title'));
1674 $bc->content = $output->navigation_panel($panel);
1675 return $bc;
1679 * Return an array of variant URLs to other attempts at this quiz.
1681 * The $url passed in must contain an attempt parameter.
1683 * The {@link mod_quiz_links_to_other_attempts} object returned contains an
1684 * array with keys that are the attempt number, 1, 2, 3.
1685 * The array values are either a {@link moodle_url} with the attmept parameter
1686 * updated to point to the attempt id of the other attempt, or null corresponding
1687 * to the current attempt number.
1689 * @param moodle_url $url a URL.
1690 * @return mod_quiz_links_to_other_attempts containing array int => null|moodle_url.
1692 public function links_to_other_attempts(moodle_url $url) {
1693 $attempts = quiz_get_user_attempts($this->get_quiz()->id, $this->attempt->userid, 'all');
1694 if (count($attempts) <= 1) {
1695 return false;
1698 $links = new mod_quiz_links_to_other_attempts();
1699 foreach ($attempts as $at) {
1700 if ($at->id == $this->attempt->id) {
1701 $links->links[$at->attempt] = null;
1702 } else {
1703 $links->links[$at->attempt] = new moodle_url($url, array('attempt' => $at->id));
1706 return $links;
1710 * Return an array of variant URLs to other redos of the question in a particular slot.
1712 * The $url passed in must contain a slot parameter.
1714 * The {@link mod_quiz_links_to_other_attempts} object returned contains an
1715 * array with keys that are the redo number, 1, 2, 3.
1716 * The array values are either a {@link moodle_url} with the slot parameter
1717 * updated to point to the slot that has that redo of this question; or null
1718 * corresponding to the redo identified by $slot.
1720 * @param int $slot identifies a question in this attempt.
1721 * @param moodle_url $baseurl the base URL to modify to generate each link.
1722 * @return mod_quiz_links_to_other_attempts|null containing array int => null|moodle_url,
1723 * or null if the question in this slot has not been redone.
1725 public function links_to_other_redos($slot, moodle_url $baseurl) {
1726 $originalslot = $this->get_original_slot($slot);
1728 $qas = $this->all_question_attempts_originally_in_slot($originalslot);
1729 if (count($qas) <= 1) {
1730 return null;
1733 $links = new mod_quiz_links_to_other_attempts();
1734 $index = 1;
1735 foreach ($qas as $qa) {
1736 if ($qa->get_slot() == $slot) {
1737 $links->links[$index] = null;
1738 } else {
1739 $url = new moodle_url($baseurl, array('slot' => $qa->get_slot()));
1740 $links->links[$index] = new action_link($url, $index,
1741 new popup_action('click', $url, 'reviewquestion',
1742 array('width' => 450, 'height' => 650)),
1743 array('title' => get_string('reviewresponse', 'question')));
1745 $index++;
1747 return $links;
1750 // Methods for processing ==================================================
1753 * Check this attempt, to see if there are any state transitions that should
1754 * happen automatically. This function will update the attempt checkstatetime.
1755 * @param int $timestamp the timestamp that should be stored as the modifed
1756 * @param bool $studentisonline is the student currently interacting with Moodle?
1758 public function handle_if_time_expired($timestamp, $studentisonline) {
1759 global $DB;
1761 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt);
1763 if ($timeclose === false || $this->is_preview()) {
1764 $this->update_timecheckstate(null);
1765 return; // No time limit
1767 if ($timestamp < $timeclose) {
1768 $this->update_timecheckstate($timeclose);
1769 return; // Time has not yet expired.
1772 // If the attempt is already overdue, look to see if it should be abandoned ...
1773 if ($this->attempt->state == self::OVERDUE) {
1774 $timeoverdue = $timestamp - $timeclose;
1775 $graceperiod = $this->quizobj->get_quiz()->graceperiod;
1776 if ($timeoverdue >= $graceperiod) {
1777 $this->process_abandon($timestamp, $studentisonline);
1778 } else {
1779 // Overdue time has not yet expired
1780 $this->update_timecheckstate($timeclose + $graceperiod);
1782 return; // ... and we are done.
1785 if ($this->attempt->state != self::IN_PROGRESS) {
1786 $this->update_timecheckstate(null);
1787 return; // Attempt is already in a final state.
1790 // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired.
1791 // Transition to the appropriate state.
1792 switch ($this->quizobj->get_quiz()->overduehandling) {
1793 case 'autosubmit':
1794 $this->process_finish($timestamp, false);
1795 return;
1797 case 'graceperiod':
1798 $this->process_going_overdue($timestamp, $studentisonline);
1799 return;
1801 case 'autoabandon':
1802 $this->process_abandon($timestamp, $studentisonline);
1803 return;
1806 // This is an overdue attempt with no overdue handling defined, so just abandon.
1807 $this->process_abandon($timestamp, $studentisonline);
1808 return;
1812 * Process all the actions that were submitted as part of the current request.
1814 * @param int $timestamp the timestamp that should be stored as the modifed
1815 * time in the database for these actions. If null, will use the current time.
1816 * @param bool $becomingoverdue
1817 * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data.
1818 * There are two formats supported here, for historical reasons. The newer approach is to pass an array created by
1819 * {@link core_question_generator::get_simulated_post_data_for_questions_in_usage()}.
1820 * the second is to pass an array slot no => contains arrays representing student
1821 * responses which will be passed to {@link question_definition::prepare_simulated_post_data()}.
1822 * This second method will probably get deprecated one day.
1824 public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) {
1825 global $DB;
1827 $transaction = $DB->start_delegated_transaction();
1829 if ($simulatedresponses !== null) {
1830 if (is_int(key($simulatedresponses))) {
1831 // Legacy approach. Should be removed one day.
1832 $simulatedpostdata = $this->quba->prepare_simulated_post_data($simulatedresponses);
1833 } else {
1834 $simulatedpostdata = $simulatedresponses;
1836 } else {
1837 $simulatedpostdata = null;
1840 $this->quba->process_all_actions($timestamp, $simulatedpostdata);
1841 question_engine::save_questions_usage_by_activity($this->quba);
1843 $this->attempt->timemodified = $timestamp;
1844 if ($this->attempt->state == self::FINISHED) {
1845 $this->attempt->sumgrades = $this->quba->get_total_mark();
1847 if ($becomingoverdue) {
1848 $this->process_going_overdue($timestamp, true);
1849 } else {
1850 $DB->update_record('quiz_attempts', $this->attempt);
1853 if (!$this->is_preview() && $this->attempt->state == self::FINISHED) {
1854 quiz_save_best_grade($this->get_quiz(), $this->get_userid());
1857 $transaction->allow_commit();
1861 * Replace a question in an attempt with a new attempt at the same qestion.
1862 * @param int $slot the questoin to restart.
1863 * @param int $timestamp the timestamp to record for this action.
1865 public function process_redo_question($slot, $timestamp) {
1866 global $DB;
1868 if (!$this->can_question_be_redone_now($slot)) {
1869 throw new coding_exception('Attempt to restart the question in slot ' . $slot .
1870 ' when it is not in a state to be restarted.');
1873 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts(
1874 $this->get_quizid(), $this->get_userid());
1876 $transaction = $DB->start_delegated_transaction();
1878 // Choose the replacement question.
1879 $questiondata = $DB->get_record('question',
1880 array('id' => $this->slots[$slot]->questionid));
1881 if ($questiondata->qtype != 'random') {
1882 $newqusetionid = $questiondata->id;
1883 } else {
1884 $tagids = quiz_retrieve_slot_tag_ids($this->slots[$slot]->id);
1886 $randomloader = new \core_question\bank\random_question_loader($qubaids, array());
1887 $newqusetionid = $randomloader->get_next_question_id($questiondata->category,
1888 (bool) $questiondata->questiontext, $tagids);
1889 if ($newqusetionid === null) {
1890 throw new moodle_exception('notenoughrandomquestions', 'quiz',
1891 $this->quizobj->view_url(), $questiondata);
1895 // Add the question to the usage. It is important we do this before we choose a variant.
1896 $newquestion = question_bank::load_question($newqusetionid);
1897 $newslot = $this->quba->add_question_in_place_of_other($slot, $newquestion);
1899 // Choose the variant.
1900 if ($newquestion->get_num_variants() == 1) {
1901 $variant = 1;
1902 } else {
1903 $variantstrategy = new core_question\engine\variants\least_used_strategy(
1904 $this->quba, $qubaids);
1905 $variant = $variantstrategy->choose_variant($newquestion->get_num_variants(),
1906 $newquestion->get_variants_selection_seed());
1909 // Start the question.
1910 $this->quba->start_question($slot, $variant);
1911 $this->quba->set_max_mark($newslot, 0);
1912 $this->quba->set_question_attempt_metadata($newslot, 'originalslot', $slot);
1913 question_engine::save_questions_usage_by_activity($this->quba);
1915 $transaction->allow_commit();
1919 * Process all the autosaved data that was part of the current request.
1921 * @param int $timestamp the timestamp that should be stored as the modifed
1922 * time in the database for these actions. If null, will use the current time.
1924 public function process_auto_save($timestamp) {
1925 global $DB;
1927 $transaction = $DB->start_delegated_transaction();
1929 $this->quba->process_all_autosaves($timestamp);
1930 question_engine::save_questions_usage_by_activity($this->quba);
1932 $transaction->allow_commit();
1936 * Update the flagged state for all question_attempts in this usage, if their
1937 * flagged state was changed in the request.
1939 public function save_question_flags() {
1940 global $DB;
1942 $transaction = $DB->start_delegated_transaction();
1943 $this->quba->update_question_flags();
1944 question_engine::save_questions_usage_by_activity($this->quba);
1945 $transaction->allow_commit();
1948 public function process_finish($timestamp, $processsubmitted) {
1949 global $DB;
1951 $transaction = $DB->start_delegated_transaction();
1953 if ($processsubmitted) {
1954 $this->quba->process_all_actions($timestamp);
1956 $this->quba->finish_all_questions($timestamp);
1958 question_engine::save_questions_usage_by_activity($this->quba);
1960 $this->attempt->timemodified = $timestamp;
1961 $this->attempt->timefinish = $timestamp;
1962 $this->attempt->sumgrades = $this->quba->get_total_mark();
1963 $this->attempt->state = self::FINISHED;
1964 $this->attempt->timecheckstate = null;
1965 $DB->update_record('quiz_attempts', $this->attempt);
1967 if (!$this->is_preview()) {
1968 quiz_save_best_grade($this->get_quiz(), $this->attempt->userid);
1970 // Trigger event.
1971 $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp);
1973 // Tell any access rules that care that the attempt is over.
1974 $this->get_access_manager($timestamp)->current_attempt_finished();
1977 $transaction->allow_commit();
1981 * Update this attempt timecheckstate if necessary.
1982 * @param int|null the timecheckstate
1984 public function update_timecheckstate($time) {
1985 global $DB;
1986 if ($this->attempt->timecheckstate !== $time) {
1987 $this->attempt->timecheckstate = $time;
1988 $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id' => $this->attempt->id));
1993 * Mark this attempt as now overdue.
1994 * @param int $timestamp the time to deem as now.
1995 * @param bool $studentisonline is the student currently interacting with Moodle?
1997 public function process_going_overdue($timestamp, $studentisonline) {
1998 global $DB;
2000 $transaction = $DB->start_delegated_transaction();
2001 $this->attempt->timemodified = $timestamp;
2002 $this->attempt->state = self::OVERDUE;
2003 // If we knew the attempt close time, we could compute when the graceperiod ends.
2004 // Instead we'll just fix it up through cron.
2005 $this->attempt->timecheckstate = $timestamp;
2006 $DB->update_record('quiz_attempts', $this->attempt);
2008 $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp);
2010 $transaction->allow_commit();
2012 quiz_send_overdue_message($this);
2016 * Mark this attempt as abandoned.
2017 * @param int $timestamp the time to deem as now.
2018 * @param bool $studentisonline is the student currently interacting with Moodle?
2020 public function process_abandon($timestamp, $studentisonline) {
2021 global $DB;
2023 $transaction = $DB->start_delegated_transaction();
2024 $this->attempt->timemodified = $timestamp;
2025 $this->attempt->state = self::ABANDONED;
2026 $this->attempt->timecheckstate = null;
2027 $DB->update_record('quiz_attempts', $this->attempt);
2029 $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp);
2031 $transaction->allow_commit();
2035 * Fire a state transition event.
2036 * the same event information.
2037 * @param string $eventclass the event class name.
2038 * @param int $timestamp the timestamp to include in the event.
2039 * @return void
2041 protected function fire_state_transition_event($eventclass, $timestamp) {
2042 global $USER;
2043 $quizrecord = $this->get_quiz();
2044 $params = array(
2045 'context' => $this->get_quizobj()->get_context(),
2046 'courseid' => $this->get_courseid(),
2047 'objectid' => $this->attempt->id,
2048 'relateduserid' => $this->attempt->userid,
2049 'other' => array(
2050 'submitterid' => CLI_SCRIPT ? null : $USER->id,
2051 'quizid' => $quizrecord->id
2055 $event = $eventclass::create($params);
2056 $event->add_record_snapshot('quiz', $this->get_quiz());
2057 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2058 $event->trigger();
2061 // Private methods =========================================================
2064 * Get a URL for a particular question on a particular page of the quiz.
2065 * Used by {@link attempt_url()} and {@link review_url()}.
2067 * @param string $script. Used in the URL like /mod/quiz/$script.php
2068 * @param int $slot identifies the specific question on the page to jump to.
2069 * 0 to just use the $page parameter.
2070 * @param int $page -1 to look up the page number from the slot, otherwise
2071 * the page number to go to.
2072 * @param bool|null $showall if true, return a URL with showall=1, and not page number.
2073 * if null, then an intelligent default will be chosen.
2074 * @param int $thispage the page we are currently on. Links to questions on this
2075 * page will just be a fragment #q123. -1 to disable this.
2076 * @return The requested URL.
2078 protected function page_and_question_url($script, $slot, $page, $showall, $thispage) {
2080 $defaultshowall = $this->get_default_show_all($script);
2081 if ($showall === null && ($page == 0 || $page == -1)) {
2082 $showall = $defaultshowall;
2085 // Fix up $page.
2086 if ($page == -1) {
2087 if ($slot !== null && !$showall) {
2088 $page = $this->get_question_page($slot);
2089 } else {
2090 $page = 0;
2094 if ($showall) {
2095 $page = 0;
2098 // Add a fragment to scroll down to the question.
2099 $fragment = '';
2100 if ($slot !== null) {
2101 if ($slot == reset($this->pagelayout[$page])) {
2102 // First question on page, go to top.
2103 $fragment = '#';
2104 } else {
2105 $fragment = '#q' . $slot;
2109 // Work out the correct start to the URL.
2110 if ($thispage == $page) {
2111 return new moodle_url($fragment);
2113 } else {
2114 $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment,
2115 array('attempt' => $this->attempt->id, 'cmid' => $this->get_cmid()));
2116 if ($page == 0 && $showall != $defaultshowall) {
2117 $url->param('showall', (int) $showall);
2118 } else if ($page > 0) {
2119 $url->param('page', $page);
2121 return $url;
2126 * Process responses during an attempt at a quiz.
2128 * @param int $timenow time when the processing started
2129 * @param bool $finishattempt whether to finish the attempt or not
2130 * @param bool $timeup true if form was submitted by timer
2131 * @param int $thispage current page number
2132 * @return string the attempt state once the data has been processed
2133 * @since Moodle 3.1
2134 * @throws moodle_exception
2136 public function process_attempt($timenow, $finishattempt, $timeup, $thispage) {
2137 global $DB;
2139 $transaction = $DB->start_delegated_transaction();
2141 // If there is only a very small amount of time left, there is no point trying
2142 // to show the student another page of the quiz. Just finish now.
2143 $graceperiodmin = null;
2144 $accessmanager = $this->get_access_manager($timenow);
2145 $timeclose = $accessmanager->get_end_time($this->get_attempt());
2147 // Don't enforce timeclose for previews.
2148 if ($this->is_preview()) {
2149 $timeclose = false;
2151 $toolate = false;
2152 if ($timeclose !== false && $timenow > $timeclose - QUIZ_MIN_TIME_TO_CONTINUE) {
2153 $timeup = true;
2154 $graceperiodmin = get_config('quiz', 'graceperiodmin');
2155 if ($timenow > $timeclose + $graceperiodmin) {
2156 $toolate = true;
2160 // If time is running out, trigger the appropriate action.
2161 $becomingoverdue = false;
2162 $becomingabandoned = false;
2163 if ($timeup) {
2164 if ($this->get_quiz()->overduehandling == 'graceperiod') {
2165 if (is_null($graceperiodmin)) {
2166 $graceperiodmin = get_config('quiz', 'graceperiodmin');
2168 if ($timenow > $timeclose + $this->get_quiz()->graceperiod + $graceperiodmin) {
2169 // Grace period has run out.
2170 $finishattempt = true;
2171 $becomingabandoned = true;
2172 } else {
2173 $becomingoverdue = true;
2175 } else {
2176 $finishattempt = true;
2180 // Don't log - we will end with a redirect to a page that is logged.
2182 if (!$finishattempt) {
2183 // Just process the responses for this page and go to the next page.
2184 if (!$toolate) {
2185 try {
2186 $this->process_submitted_actions($timenow, $becomingoverdue);
2188 } catch (question_out_of_sequence_exception $e) {
2189 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2190 $this->attempt_url(null, $thispage));
2192 } catch (Exception $e) {
2193 // This sucks, if we display our own custom error message, there is no way
2194 // to display the original stack trace.
2195 $debuginfo = '';
2196 if (!empty($e->debuginfo)) {
2197 $debuginfo = $e->debuginfo;
2199 throw new moodle_exception('errorprocessingresponses', 'question',
2200 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2203 if (!$becomingoverdue) {
2204 foreach ($this->get_slots() as $slot) {
2205 if (optional_param('redoslot' . $slot, false, PARAM_BOOL)) {
2206 $this->process_redo_question($slot, $timenow);
2211 } else {
2212 // The student is too late.
2213 $this->process_going_overdue($timenow, true);
2216 $transaction->allow_commit();
2218 return $becomingoverdue ? self::OVERDUE : self::IN_PROGRESS;
2221 // Update the quiz attempt record.
2222 try {
2223 if ($becomingabandoned) {
2224 $this->process_abandon($timenow, true);
2225 } else {
2226 $this->process_finish($timenow, !$toolate);
2229 } catch (question_out_of_sequence_exception $e) {
2230 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2231 $this->attempt_url(null, $thispage));
2233 } catch (Exception $e) {
2234 // This sucks, if we display our own custom error message, there is no way
2235 // to display the original stack trace.
2236 $debuginfo = '';
2237 if (!empty($e->debuginfo)) {
2238 $debuginfo = $e->debuginfo;
2240 throw new moodle_exception('errorprocessingresponses', 'question',
2241 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2244 // Send the user to the review page.
2245 $transaction->allow_commit();
2247 return $becomingabandoned ? self::ABANDONED : self::FINISHED;
2251 * Check a page access to see if is an out of sequence access.
2253 * @param int $page page number
2254 * @return boolean false is is an out of sequence access, true otherwise.
2255 * @since Moodle 3.1
2257 public function check_page_access($page) {
2258 global $DB;
2260 if ($this->get_currentpage() != $page) {
2261 if ($this->get_navigation_method() == QUIZ_NAVMETHOD_SEQ && $this->get_currentpage() > $page) {
2262 return false;
2265 return true;
2269 * Update attempt page.
2271 * @param int $page page number
2272 * @return boolean true if everything was ok, false otherwise (out of sequence access).
2273 * @since Moodle 3.1
2275 public function set_currentpage($page) {
2276 global $DB;
2278 if ($this->check_page_access($page)) {
2279 $DB->set_field('quiz_attempts', 'currentpage', $page, array('id' => $this->get_attemptid()));
2280 return true;
2282 return false;
2286 * Trigger the attempt_viewed event.
2288 * @since Moodle 3.1
2290 public function fire_attempt_viewed_event() {
2291 $params = array(
2292 'objectid' => $this->get_attemptid(),
2293 'relateduserid' => $this->get_userid(),
2294 'courseid' => $this->get_courseid(),
2295 'context' => context_module::instance($this->get_cmid()),
2296 'other' => array(
2297 'quizid' => $this->get_quizid()
2300 $event = \mod_quiz\event\attempt_viewed::create($params);
2301 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2302 $event->trigger();
2306 * Trigger the attempt_summary_viewed event.
2308 * @since Moodle 3.1
2310 public function fire_attempt_summary_viewed_event() {
2312 $params = array(
2313 'objectid' => $this->get_attemptid(),
2314 'relateduserid' => $this->get_userid(),
2315 'courseid' => $this->get_courseid(),
2316 'context' => context_module::instance($this->get_cmid()),
2317 'other' => array(
2318 'quizid' => $this->get_quizid()
2321 $event = \mod_quiz\event\attempt_summary_viewed::create($params);
2322 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2323 $event->trigger();
2327 * Trigger the attempt_reviewed event.
2329 * @since Moodle 3.1
2331 public function fire_attempt_reviewed_event() {
2333 $params = array(
2334 'objectid' => $this->get_attemptid(),
2335 'relateduserid' => $this->get_userid(),
2336 'courseid' => $this->get_courseid(),
2337 'context' => context_module::instance($this->get_cmid()),
2338 'other' => array(
2339 'quizid' => $this->get_quizid()
2342 $event = \mod_quiz\event\attempt_reviewed::create($params);
2343 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2344 $event->trigger();
2348 * Update the timemodifiedoffline attempt field.
2349 * This function should be used only when web services are being used.
2351 * @param int $time time stamp
2352 * @return boolean false if the field is not updated because web services aren't being used.
2353 * @since Moodle 3.2
2355 public function set_offline_modified_time($time) {
2356 global $DB;
2358 // Update the timemodifiedoffline field only if web services are being used.
2359 if (WS_SERVER) {
2360 $this->attempt->timemodifiedoffline = $time;
2361 return true;
2363 return false;
2370 * Represents a heading in the navigation panel.
2372 * @copyright 2015 The Open University
2373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2374 * @since Moodle 2.9
2376 class quiz_nav_section_heading implements renderable {
2377 /** @var string the heading text. */
2378 public $heading;
2381 * Constructor.
2382 * @param string $heading the heading text
2384 public function __construct($heading) {
2385 $this->heading = $heading;
2391 * Represents a single link in the navigation panel.
2393 * @copyright 2011 The Open University
2394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2395 * @since Moodle 2.1
2397 class quiz_nav_question_button implements renderable {
2398 /** @var string id="..." to add to the HTML for this button. */
2399 public $id;
2400 /** @var string number to display in this button. Either the question number of 'i'. */
2401 public $number;
2402 /** @var string class to add to the class="" attribute to represnt the question state. */
2403 public $stateclass;
2404 /** @var string Textual description of the question state, e.g. to use as a tool tip. */
2405 public $statestring;
2406 /** @var int the page number this question is on. */
2407 public $page;
2408 /** @var bool true if this question is on the current page. */
2409 public $currentpage;
2410 /** @var bool true if this question has been flagged. */
2411 public $flagged;
2412 /** @var moodle_url the link this button goes to, or null if there should not be a link. */
2413 public $url;
2418 * Represents the navigation panel, and builds a {@link block_contents} to allow
2419 * it to be output.
2421 * @copyright 2008 Tim Hunt
2422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2423 * @since Moodle 2.0
2425 abstract class quiz_nav_panel_base {
2426 /** @var quiz_attempt */
2427 protected $attemptobj;
2428 /** @var question_display_options */
2429 protected $options;
2430 /** @var integer */
2431 protected $page;
2432 /** @var boolean */
2433 protected $showall;
2435 public function __construct(quiz_attempt $attemptobj,
2436 question_display_options $options, $page, $showall) {
2437 $this->attemptobj = $attemptobj;
2438 $this->options = $options;
2439 $this->page = $page;
2440 $this->showall = $showall;
2444 * Get the buttons and section headings to go in the quiz navigation block.
2445 * @return renderable[] the buttons, possibly interleaved with section headings.
2447 public function get_question_buttons() {
2448 $buttons = array();
2449 foreach ($this->attemptobj->get_slots() as $slot) {
2450 if ($heading = $this->attemptobj->get_heading_before_slot($slot)) {
2451 $buttons[] = new quiz_nav_section_heading(format_string($heading));
2454 $qa = $this->attemptobj->get_question_attempt($slot);
2455 $showcorrectness = $this->options->correctness && $qa->has_marks();
2457 $button = new quiz_nav_question_button();
2458 $button->id = 'quiznavbutton' . $slot;
2459 $button->number = $this->attemptobj->get_question_number($slot);
2460 $button->stateclass = $qa->get_state_class($showcorrectness);
2461 $button->navmethod = $this->attemptobj->get_navigation_method();
2462 if (!$showcorrectness && $button->stateclass == 'notanswered') {
2463 $button->stateclass = 'complete';
2465 $button->statestring = $this->get_state_string($qa, $showcorrectness);
2466 $button->page = $this->attemptobj->get_question_page($slot);
2467 $button->currentpage = $this->showall || $button->page == $this->page;
2468 $button->flagged = $qa->is_flagged();
2469 $button->url = $this->get_question_url($slot);
2470 if ($this->attemptobj->is_blocked_by_previous_question($slot)) {
2471 $button->url = null;
2472 $button->stateclass = 'blocked';
2473 $button->statestring = get_string('questiondependsonprevious', 'quiz');
2475 $buttons[] = $button;
2478 return $buttons;
2481 protected function get_state_string(question_attempt $qa, $showcorrectness) {
2482 if ($qa->get_question()->length > 0) {
2483 return $qa->get_state_string($showcorrectness);
2486 // Special case handling for 'information' items.
2487 if ($qa->get_state() == question_state::$todo) {
2488 return get_string('notyetviewed', 'quiz');
2489 } else {
2490 return get_string('viewed', 'quiz');
2494 public function render_before_button_bits(mod_quiz_renderer $output) {
2495 return '';
2498 abstract public function render_end_bits(mod_quiz_renderer $output);
2500 protected function render_restart_preview_link($output) {
2501 if (!$this->attemptobj->is_own_preview()) {
2502 return '';
2504 return $output->restart_preview_button(new moodle_url(
2505 $this->attemptobj->start_attempt_url(), array('forcenew' => true)));
2508 protected abstract function get_question_url($slot);
2510 public function user_picture() {
2511 global $DB;
2512 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_NONE) {
2513 return null;
2515 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid()));
2516 $userpicture = new user_picture($user);
2517 $userpicture->courseid = $this->attemptobj->get_courseid();
2518 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_LARGE) {
2519 $userpicture->size = true;
2521 return $userpicture;
2525 * Return 'allquestionsononepage' as CSS class name when $showall is set,
2526 * otherwise, return 'multipages' as CSS class name.
2527 * @return string, CSS class name
2529 public function get_button_container_class() {
2530 // Quiz navigation is set on 'Show all questions on one page'.
2531 if ($this->showall) {
2532 return 'allquestionsononepage';
2534 // Quiz navigation is set on 'Show one page at a time'.
2535 return 'multipages';
2541 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page.
2543 * @copyright 2008 Tim Hunt
2544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2545 * @since Moodle 2.0
2547 class quiz_attempt_nav_panel extends quiz_nav_panel_base {
2548 public function get_question_url($slot) {
2549 if ($this->attemptobj->can_navigate_to($slot)) {
2550 return $this->attemptobj->attempt_url($slot, -1, $this->page);
2551 } else {
2552 return null;
2556 public function render_before_button_bits(mod_quiz_renderer $output) {
2557 return html_writer::tag('div', get_string('navnojswarning', 'quiz'),
2558 array('id' => 'quiznojswarning'));
2561 public function render_end_bits(mod_quiz_renderer $output) {
2562 return html_writer::link($this->attemptobj->summary_url(),
2563 get_string('endtest', 'quiz'), array('class' => 'endtestlink')) .
2564 $output->countdown_timer($this->attemptobj, time()) .
2565 $this->render_restart_preview_link($output);
2571 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page.
2573 * @copyright 2008 Tim Hunt
2574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2575 * @since Moodle 2.0
2577 class quiz_review_nav_panel extends quiz_nav_panel_base {
2578 public function get_question_url($slot) {
2579 return $this->attemptobj->review_url($slot, -1, $this->showall, $this->page);
2582 public function render_end_bits(mod_quiz_renderer $output) {
2583 $html = '';
2584 if ($this->attemptobj->get_num_pages() > 1) {
2585 if ($this->showall) {
2586 $html .= html_writer::link($this->attemptobj->review_url(null, 0, false),
2587 get_string('showeachpage', 'quiz'));
2588 } else {
2589 $html .= html_writer::link($this->attemptobj->review_url(null, 0, true),
2590 get_string('showall', 'quiz'));
2593 $html .= $output->finish_review_link($this->attemptobj);
2594 $html .= $this->render_restart_preview_link($output);
2595 return $html;