2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
26 use mod_quiz\output\links_to_other_attempts
;
27 use mod_quiz\output\renderer
;
28 use mod_quiz\question\bank\qbank_helper
;
29 use mod_quiz\question\display_options
;
33 use qtype_description_question
;
36 use question_display_options
;
38 use question_out_of_sequence_exception
;
40 use question_usage_by_activity
;
44 * This class represents one user's attempt at a particular quiz.
47 * @copyright 2008 Tim Hunt
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 /** @var string to identify the in progress state. */
53 const IN_PROGRESS
= 'inprogress';
54 /** @var string to identify the overdue state. */
55 const OVERDUE
= 'overdue';
56 /** @var string to identify the finished state. */
57 const FINISHED
= 'finished';
58 /** @var string to identify the abandoned state. */
59 const ABANDONED
= 'abandoned';
61 /** @var int maximum number of slots in the quiz for the review page to default to show all. */
62 const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL
= 50;
64 /** @var int amount of time considered 'immedately after the attempt', in seconds. */
65 const IMMEDIATELY_AFTER_PERIOD
= 2 * MINSECS
;
67 /** @var quiz_settings object containing the quiz settings. */
70 /** @var stdClass the quiz_attempts row. */
73 /** @var question_usage_by_activity the question usage for this quiz attempt. */
77 * @var array of slot information. These objects contain ->slot (int),
78 * ->requireprevious (bool), ->questionids (int) the original question for random questions,
79 * ->firstinsection (bool), ->section (stdClass from $this->sections).
80 * This does not contain page - get that from {@see get_question_page()} -
81 * or maxmark - get that from $this->quba.
85 /** @var array of quiz_sections rows, with a ->lastslot field added. */
88 /** @var array page no => array of slot numbers on the page in order. */
89 protected $pagelayout;
91 /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */
92 protected $questionnumbers;
94 /** @var array slot => page number for this slot. */
95 protected $questionpages;
97 /** @var display_options cache for the appropriate review options. */
98 protected $reviewoptions = null;
100 // Constructor =============================================================.
102 * Constructor assuming we already have the necessary data loaded.
104 * @param stdClass $attempt the row of the quiz_attempts table.
105 * @param stdClass $quiz the quiz object for this attempt and user.
106 * @param cm_info $cm the course_module object for this quiz.
107 * @param stdClass $course the row from the course table for the course we belong to.
108 * @param bool $loadquestions (optional) if true, the default, load all the details
109 * of the state of each question. Else just set up the basic details of the attempt.
111 public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) {
112 $this->attempt
= $attempt;
113 $this->quizobj
= new quiz_settings($quiz, $cm, $course);
115 if ($loadquestions) {
116 $this->load_questions();
121 * Used by {create()} and {create_from_usage_id()}.
123 * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions).
124 * @return quiz_attempt the desired instance of this class.
126 protected static function create_helper($conditions) {
129 $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST
);
130 $quiz = access_manager
::load_quiz_and_settings($attempt->quiz
);
131 $course = get_course($quiz->course
);
132 $cm = get_coursemodule_from_instance('quiz', $quiz->id
, $course->id
, false, MUST_EXIST
);
134 // Update quiz with override information.
135 $quiz = quiz_update_effective_access($quiz, $attempt->userid
);
137 return new quiz_attempt($attempt, $quiz, $cm, $course);
141 * Static function to create a new quiz_attempt object given an attemptid.
143 * @param int $attemptid the attempt id.
144 * @return quiz_attempt the new quiz_attempt object
146 public static function create($attemptid) {
147 return self
::create_helper(['id' => $attemptid]);
151 * Static function to create a new quiz_attempt object given a usage id.
153 * @param int $usageid the attempt usage id.
154 * @return quiz_attempt the new quiz_attempt object
156 public static function create_from_usage_id($usageid) {
157 return self
::create_helper(['uniqueid' => $usageid]);
161 * Get a human-readable name for one of the quiz attempt states.
163 * @param string $state one of the state constants like IN_PROGRESS.
164 * @return string the human-readable state name.
166 public static function state_name($state) {
167 return quiz_attempt_state_name($state);
171 * This method can be called later if the object was constructed with $loadquestions = false.
173 public function load_questions() {
176 if (isset($this->quba
)) {
177 throw new coding_exception('This quiz attempt has already had the questions loaded.');
180 $this->quba
= question_engine
::load_questions_usage_by_activity($this->attempt
->uniqueid
);
181 $this->slots
= $DB->get_records('quiz_slots',
182 ['quizid' => $this->get_quizid()], 'slot', 'slot, id, requireprevious, displaynumber');
183 $this->sections
= array_values($DB->get_records('quiz_sections',
184 ['quizid' => $this->get_quizid()], 'firstslot'));
186 $this->link_sections_and_slots();
187 $this->determine_layout();
188 $this->number_questions();
192 * Preload all attempt step users to show in Response history.
194 public function preload_all_attempt_step_users(): void
{
195 $this->quba
->preload_all_step_users();
199 * Let each slot know which section it is part of.
201 protected function link_sections_and_slots() {
202 foreach ($this->sections
as $i => $section) {
203 if (isset($this->sections
[$i +
1])) {
204 $section->lastslot
= $this->sections
[$i +
1]->firstslot
- 1;
206 $section->lastslot
= count($this->slots
);
208 for ($slot = $section->firstslot
; $slot <= $section->lastslot
; $slot +
= 1) {
209 $this->slots
[$slot]->section
= $section;
215 * Parse attempt->layout to populate the other arrays that represent the layout.
217 protected function determine_layout() {
219 // Break up the layout string into pages.
220 $pagelayouts = explode(',0', $this->attempt
->layout
);
222 // Strip off any empty last page (normally there is one).
223 if (end($pagelayouts) == '') {
224 array_pop($pagelayouts);
227 // File the ids into the arrays.
228 // Tracking which is the first slot in each section in this attempt is
229 // trickier than you might guess, since the slots in this section
230 // may be shuffled, so $section->firstslot (the lowest numbered slot in
231 // the section) may not be the first one.
232 $unseensections = $this->sections
;
233 $this->pagelayout
= [];
234 foreach ($pagelayouts as $page => $pagelayout) {
235 $pagelayout = trim($pagelayout, ',');
236 if ($pagelayout == '') {
239 $this->pagelayout
[$page] = explode(',', $pagelayout);
240 foreach ($this->pagelayout
[$page] as $slot) {
241 $sectionkey = array_search($this->slots
[$slot]->section
, $unseensections);
242 if ($sectionkey !== false) {
243 $this->slots
[$slot]->firstinsection
= true;
244 unset($unseensections[$sectionkey]);
246 $this->slots
[$slot]->firstinsection
= false;
253 * Work out the number to display for each question/slot.
255 protected function number_questions() {
257 foreach ($this->pagelayout
as $page => $slots) {
258 foreach ($slots as $slot) {
259 if ($length = $this->is_real_question($slot)) {
260 // Whether question numbering is customised or is numeric and automatically incremented.
261 if ($this->slots
[$slot]->displaynumber
!== null && $this->slots
[$slot]->displaynumber
!== '' &&
262 !$this->slots
[$slot]->section
->shufflequestions
) {
263 $this->questionnumbers
[$slot] = $this->slots
[$slot]->displaynumber
;
265 $this->questionnumbers
[$slot] = (string) $number;
269 $this->questionnumbers
[$slot] = get_string('infoshort', 'quiz');
271 $this->questionpages
[$slot] = $page;
277 * If the given page number is out of range (before the first page, or after
278 * the last page, change it to be within range).
280 * @param int $page the requested page number.
281 * @return int a safe page number to use.
283 public function force_page_number_into_range($page) {
284 return min(max($page, 0), count($this->pagelayout
) - 1);
287 // Simple getters ==========================================================.
290 * Get the raw quiz settings object.
294 public function get_quiz() {
295 return $this->quizobj
->get_quiz();
299 * Get the {@see seb_quiz_settings} object for this quiz.
301 * @return quiz_settings
303 public function get_quizobj() {
304 return $this->quizobj
;
308 * Git the id of the course this quiz belongs to.
310 * @return int the course id.
312 public function get_courseid() {
313 return $this->quizobj
->get_courseid();
317 * Get the course settings object.
319 * @return stdClass the course settings object.
321 public function get_course() {
322 return $this->quizobj
->get_course();
328 * @return int the quiz id.
330 public function get_quizid() {
331 return $this->quizobj
->get_quizid();
335 * Get the name of this quiz.
337 * @return string Quiz name, directly from the database (format_string must be called before output).
339 public function get_quiz_name() {
340 return $this->quizobj
->get_quiz_name();
344 * Get the quiz navigation method.
346 * @return int QUIZ_NAVMETHOD_FREE or QUIZ_NAVMETHOD_SEQ.
348 public function get_navigation_method() {
349 return $this->quizobj
->get_navigation_method();
353 * Get the course_module for this quiz.
355 * @return cm_info the course_module object.
357 public function get_cm() {
358 return $this->quizobj
->get_cm();
362 * Get the course-module id.
364 * @return int the course_module id.
366 public function get_cmid() {
367 return $this->quizobj
->get_cmid();
371 * Get the quiz context.
373 * @return context_module the context of the quiz this attempt belongs to.
375 public function get_context(): context_module
{
376 return $this->quizobj
->get_context();
380 * Is the current user is someone who previews the quiz, rather than attempting it?
382 * @return bool true user is a preview user. False, if they can do real attempts.
384 public function is_preview_user() {
385 return $this->quizobj
->is_preview_user();
389 * Get the number of attempts the user is allowed at this quiz.
391 * @return int the number of attempts allowed at this quiz (0 = infinite).
393 public function get_num_attempts_allowed() {
394 return $this->quizobj
->get_num_attempts_allowed();
398 * Get the number of quizzes in the quiz attempt.
400 * @return int number pages.
402 public function get_num_pages() {
403 return count($this->pagelayout
);
407 * Get the access_manager for this quiz attempt.
409 * @param int $timenow the current time as a unix timestamp.
410 * @return access_manager and instance of the access_manager class
411 * for this quiz at this time.
413 public function get_access_manager($timenow) {
414 return $this->quizobj
->get_access_manager($timenow);
418 * Get the id of this attempt.
420 * @return int the attempt id.
422 public function get_attemptid() {
423 return $this->attempt
->id
;
427 * Get the question-usage id corresponding to this quiz attempt.
429 * @return int the attempt unique id.
431 public function get_uniqueid() {
432 return $this->attempt
->uniqueid
;
436 * Get the raw quiz attempt object.
438 * @return stdClass the row from the quiz_attempts table.
440 public function get_attempt() {
441 return $this->attempt
;
445 * Get the attempt number.
447 * @return int the number of this attempt (is it this user's first, second, ... attempt).
449 public function get_attempt_number() {
450 return $this->attempt
->attempt
;
454 * Get the state of this attempt.
456 * @return string {@see IN_PROGRESS}, {@see FINISHED}, {@see OVERDUE} or {@see ABANDONED}.
458 public function get_state() {
459 return $this->attempt
->state
;
463 * Get the id of the user this attempt belongs to.
464 * @return int user id.
466 public function get_userid() {
467 return $this->attempt
->userid
;
471 * Get the current page of the attempt
472 * @return int page number.
474 public function get_currentpage() {
475 return $this->attempt
->currentpage
;
479 * Get the total number of marks that the user had scored on all the questions.
483 public function get_sum_marks() {
484 return $this->attempt
->sumgrades
;
488 * Has this attempt been finished?
490 * States {@see FINISHED} and {@see ABANDONED} are both considered finished in this state.
491 * Other states are not.
495 public function is_finished() {
496 return $this->attempt
->state
== self
::FINISHED ||
$this->attempt
->state
== self
::ABANDONED
;
500 * Is this attempt a preview?
502 * @return bool true if it is.
504 public function is_preview() {
505 return $this->attempt
->preview
;
509 * Does this attempt belong to the current user?
511 * @return bool true => own attempt/preview. false => reviewing someone else's.
513 public function is_own_attempt() {
515 return $this->attempt
->userid
== $USER->id
;
519 * Is this attempt is a preview belonging to the current user.
521 * @return bool true if it is.
523 public function is_own_preview() {
524 return $this->is_own_attempt() &&
525 $this->is_preview_user() && $this->attempt
->preview
;
529 * Is the current user allowed to review this attempt. This applies when
530 * {@see is_own_attempt()} returns false.
532 * @return bool whether the review should be allowed.
534 public function is_review_allowed() {
535 if (!$this->has_capability('mod/quiz:viewreports')) {
539 $cm = $this->get_cm();
540 if ($this->has_capability('moodle/site:accessallgroups') ||
541 groups_get_activity_groupmode($cm) != SEPARATEGROUPS
) {
545 // Check the users have at least one group in common.
546 $teachersgroups = groups_get_activity_allowed_groups($cm);
547 $studentsgroups = groups_get_all_groups(
548 $cm->course
, $this->attempt
->userid
, $cm->groupingid
);
549 return $teachersgroups && $studentsgroups &&
550 array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
554 * Has the student, in this attempt, engaged with the quiz in a non-trivial way?
556 * That is, is there any question worth a non-zero number of marks, where
557 * the student has made some response that we have saved?
559 * @return bool true if we have saved a response for at least one graded question.
561 public function has_response_to_at_least_one_graded_question() {
562 foreach ($this->quba
->get_attempt_iterator() as $qa) {
563 if ($qa->get_max_mark() == 0) {
566 if ($qa->get_num_steps() > 1) {
574 * Do any questions in this attempt need to be graded manually?
576 * @return bool True if we have at least one question still needs manual grading.
578 public function requires_manual_grading(): bool {
579 return $this->quba
->get_total_mark() === null;
583 * Get extra summary information about this attempt.
585 * Some behaviours may be able to provide interesting summary information
586 * about the attempt as a whole, and this method provides access to that data.
587 * To see how this works, try setting a quiz to one of the CBM behaviours,
588 * and then look at the extra information displayed at the top of the quiz
589 * review page once you have submitted an attempt.
591 * In the return value, the array keys are identifiers of the form
592 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
593 * The values are arrays with two items, title and content. Each of these
594 * will be either a string, or a renderable.
596 * If this method is called before load_questions() is called, then an empty array is returned.
598 * @param question_display_options $options the display options for this quiz attempt at this time.
599 * @return array as described above.
601 public function get_additional_summary_data(question_display_options
$options) {
602 if (!isset($this->quba
)) {
605 return $this->quba
->get_summary_information($options);
609 * Get the overall feedback corresponding to a particular mark.
611 * @param number $grade a particular grade.
612 * @return string the feedback.
614 public function get_overall_feedback($grade) {
615 return quiz_feedback_for_grade($grade, $this->get_quiz(),
616 $this->quizobj
->get_context());
620 * Wrapper round the has_capability function that automatically passes in the quiz context.
622 * @param string $capability the name of the capability to check. For example mod/forum:view.
623 * @param int|null $userid A user id. If null checks the permissions of the current user.
624 * @param bool $doanything If false, ignore effect of admin role assignment.
625 * @return boolean true if the user has this capability, otherwise false.
627 public function has_capability($capability, $userid = null, $doanything = true) {
628 return $this->quizobj
->has_capability($capability, $userid, $doanything);
632 * Wrapper round the require_capability function that automatically passes in the quiz context.
634 * @param string $capability the name of the capability to check. For example mod/forum:view.
635 * @param int|null $userid A user id. If null checks the permissions of the current user.
636 * @param bool $doanything If false, ignore effect of admin role assignment.
638 public function require_capability($capability, $userid = null, $doanything = true) {
639 $this->quizobj
->require_capability($capability, $userid, $doanything);
643 * Check the appropriate capability to see whether this user may review their own attempt.
644 * If not, prints an error.
646 public function check_review_capability() {
647 if ($this->get_attempt_state() == display_options
::IMMEDIATELY_AFTER
) {
648 $capability = 'mod/quiz:attempt';
650 $capability = 'mod/quiz:reviewmyattempts';
653 // These next tests are in a slightly funny order. The point is that the
654 // common and most performance-critical case is students attempting a quiz,
655 // so we want to check that permission first.
657 if ($this->has_capability($capability)) {
658 // User has the permission that lets you do the quiz as a student. Fine.
662 if ($this->has_capability('mod/quiz:viewreports') ||
663 $this->has_capability('mod/quiz:preview')) {
664 // User has the permission that lets teachers review. Fine.
668 // They should not be here. Trigger the standard no-permission error
669 // but using the name of the student capability.
670 // We know this will fail. We just want the standard exception thrown.
671 $this->require_capability($capability);
675 * Checks whether a user may navigate to a particular slot.
677 * @param int $slot the target slot (currently does not affect the answer).
678 * @return bool true if the navigation should be allowed.
680 public function can_navigate_to($slot) {
681 if ($this->attempt
->state
== self
::OVERDUE
) {
682 // When the attempt is overdue, students can only see the
683 // attempt summary page and cannot navigate anywhere else.
687 return $this->get_navigation_method() == QUIZ_NAVMETHOD_FREE
;
691 * Get where we are time-wise in relation to this attempt and the quiz settings.
693 * @return int one of {@see display_options::DURING}, {@see display_options::IMMEDIATELY_AFTER},
694 * {@see display_options::LATER_WHILE_OPEN} or {@see display_options::AFTER_CLOSE}.
696 public function get_attempt_state() {
697 return quiz_attempt_state($this->get_quiz(), $this->attempt
);
701 * Wrapper that the correct display_options for this quiz at the
704 * @param bool $reviewing true for options when reviewing, false for when attempting.
705 * @return question_display_options the render options for this user on this attempt.
707 public function get_display_options($reviewing) {
709 if (is_null($this->reviewoptions
)) {
710 $this->reviewoptions
= quiz_get_review_options($this->get_quiz(),
711 $this->attempt
, $this->quizobj
->get_context());
712 if ($this->is_own_preview()) {
713 // It should always be possible for a teacher to review their
714 // own preview irrespective of the review options settings.
715 $this->reviewoptions
->attempt
= true;
718 return $this->reviewoptions
;
721 $options = display_options
::make_from_quiz($this->get_quiz(),
722 display_options
::DURING
);
723 $options->flags
= quiz_get_flag_option($this->attempt
, $this->quizobj
->get_context());
729 * Wrapper that the correct display_options for this quiz at the
732 * @param bool $reviewing true for review page, else attempt page.
733 * @param int $slot which question is being displayed.
734 * @param moodle_url $thispageurl to return to after the editing form is
735 * submitted or cancelled. If null, no edit link will be generated.
737 * @return question_display_options the render options for this user on this
738 * attempt, with extra info to generate an edit link, if applicable.
740 public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) {
741 $options = clone($this->get_display_options($reviewing));
747 if (!($reviewing ||
$this->is_preview())) {
751 $question = $this->quba
->get_question($slot, false);
752 if (!question_has_capability_on($question, 'edit', $question->category
)) {
756 $options->editquestionparams
['cmid'] = $this->get_cmid();
757 $options->editquestionparams
['returnurl'] = $thispageurl;
763 * Is a particular page the last one in the quiz?
765 * @param int $page a page number
766 * @return bool true if that is the last page of the quiz.
768 public function is_last_page($page) {
769 return $page == count($this->pagelayout
) - 1;
773 * Return the list of slot numbers for either a given page of the quiz, or for the
776 * @param mixed $page string 'all' or integer page number.
777 * @return array the requested list of slot numbers.
779 public function get_slots($page = 'all') {
780 if ($page === 'all') {
782 foreach ($this->pagelayout
as $numbersonpage) {
783 $numbers = array_merge($numbers, $numbersonpage);
787 return $this->pagelayout
[$page];
792 * Return the list of slot numbers for either a given page of the quiz, or for the
795 * @param mixed $page string 'all' or integer page number.
796 * @return array the requested list of slot numbers.
798 public function get_active_slots($page = 'all') {
800 foreach ($this->get_slots($page) as $slot) {
801 if (!$this->is_blocked_by_previous_question($slot)) {
802 $activeslots[] = $slot;
809 * Helper method for unit tests. Get the underlying question usage object.
811 * @return question_usage_by_activity the usage.
813 public function get_question_usage() {
814 if (!(PHPUNIT_TEST ||
defined('BEHAT_TEST'))) {
815 throw new coding_exception('get_question_usage is only for use in unit tests. ' .
816 'For other operations, use the quiz_attempt api, or extend it properly.');
822 * Get the question_attempt object for a particular question in this attempt.
824 * @param int $slot the number used to identify this question within this attempt.
825 * @return question_attempt the requested question_attempt.
827 public function get_question_attempt($slot) {
828 return $this->quba
->get_question_attempt($slot);
832 * Get all the question_attempt objects that have ever appeared in a given slot.
834 * This relates to the 'Try another question like this one' feature.
836 * @param int $slot the number used to identify this question within this attempt.
837 * @return question_attempt[] the attempts.
839 public function all_question_attempts_originally_in_slot($slot) {
841 foreach ($this->quba
->get_attempt_iterator() as $qa) {
842 if ($qa->get_metadata('originalslot') == $slot) {
846 $qas[] = $this->quba
->get_question_attempt($slot);
851 * Is a particular question in this attempt a real question, or something like a description.
853 * @param int $slot the number used to identify this question within this attempt.
854 * @return int whether that question is a real question. Actually returns the
855 * question length, which could theoretically be greater than one.
857 public function is_real_question($slot) {
858 return $this->quba
->get_question($slot, false)->length
;
862 * Is a particular question in this attempt a real question, or something like a description.
864 * @param int $slot the number used to identify this question within this attempt.
865 * @return bool whether that question is a real question.
867 public function is_question_flagged($slot) {
868 return $this->quba
->get_question_attempt($slot)->is_flagged();
872 * Checks whether the question in this slot requires the previous
873 * question to have been completed.
875 * @param int $slot the number used to identify this question within this attempt.
876 * @return bool whether the previous question must have been completed before
877 * this one can be seen.
879 public function is_blocked_by_previous_question($slot) {
880 return $slot > 1 && isset($this->slots
[$slot]) && $this->slots
[$slot]->requireprevious
&&
881 !$this->slots
[$slot]->section
->shufflequestions
&&
882 !$this->slots
[$slot - 1]->section
->shufflequestions
&&
883 $this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ
&&
884 !$this->get_question_state($slot - 1)->is_finished() &&
885 $this->quba
->can_question_finish_during_attempt($slot - 1);
889 * Is it possible for this question to be re-started within this attempt?
891 * @param int $slot the number used to identify this question within this attempt.
892 * @return bool whether the student should be given the option to restart this question now.
894 public function can_question_be_redone_now($slot) {
895 return $this->get_quiz()->canredoquestions
&& !$this->is_finished() &&
896 $this->get_question_state($slot)->is_finished();
900 * Given a slot in this attempt, which may or not be a redone question, return the original slot.
902 * @param int $slot identifies a particular question in this attempt.
903 * @return int the slot where this question was originally.
905 public function get_original_slot($slot) {
906 $originalslot = $this->quba
->get_question_attempt_metadata($slot, 'originalslot');
908 return $originalslot;
915 * Get the displayed question number for a slot.
917 * @param int $slot the number used to identify this question within this attempt.
918 * @return string the displayed question number for the question in this slot.
919 * For example '1', '2', '3' or 'i'.
921 public function get_question_number($slot): string {
922 return $this->questionnumbers
[$slot];
926 * If the section heading, if any, that should come just before this slot.
928 * @param int $slot identifies a particular question in this attempt.
929 * @return string|null the required heading, or null if there is not one here.
931 public function get_heading_before_slot($slot) {
932 if ($this->slots
[$slot]->firstinsection
) {
933 return $this->slots
[$slot]->section
->heading
;
940 * Return the page of the quiz where this question appears.
942 * @param int $slot the number used to identify this question within this attempt.
943 * @return int the page of the quiz this question appears on.
945 public function get_question_page($slot) {
946 return $this->questionpages
[$slot];
950 * Return the grade obtained on a particular question, if the user is permitted
951 * to see it. You must previously have called load_question_states to load the
952 * state data about this question.
954 * @param int $slot the number used to identify this question within this attempt.
955 * @return string the name of the question. Must be output through format_string.
957 public function get_question_name($slot) {
958 return $this->quba
->get_question($slot, false)->name
;
962 * Return the {@see question_state} that this question is in.
964 * @param int $slot the number used to identify this question within this attempt.
965 * @return question_state the state this question is in.
967 public function get_question_state($slot) {
968 return $this->quba
->get_question_state($slot);
972 * Return the grade obtained on a particular question, if the user is permitted
973 * to see it. You must previously have called load_question_states to load the
974 * state data about this question.
976 * @param int $slot the number used to identify this question within this attempt.
977 * @param bool $showcorrectness Whether right/partial/wrong states should
979 * @return string the formatted grade, to the number of decimal places specified
982 public function get_question_status($slot, $showcorrectness) {
983 return $this->quba
->get_question_state_string($slot, $showcorrectness);
987 * Return the grade obtained on a particular question, if the user is permitted
988 * to see it. You must previously have called load_question_states to load the
989 * state data about this question.
991 * @param int $slot the number used to identify this question within this attempt.
992 * @param bool $showcorrectness Whether right/partial/wrong states should
994 * @return string class name for this state.
996 public function get_question_state_class($slot, $showcorrectness) {
997 return $this->quba
->get_question_state_class($slot, $showcorrectness);
1001 * Return the grade obtained on a particular question.
1003 * You must previously have called load_question_states to load the state
1004 * data about this question.
1006 * @param int $slot the number used to identify this question within this attempt.
1007 * @return string the formatted grade, to the number of decimal places specified by the quiz.
1009 public function get_question_mark($slot) {
1010 return quiz_format_question_grade($this->get_quiz(), $this->quba
->get_question_mark($slot));
1014 * Get the time of the most recent action performed on a question.
1016 * @param int $slot the number used to identify this question within this usage.
1017 * @return int timestamp.
1019 public function get_question_action_time($slot) {
1020 return $this->quba
->get_question_action_time($slot);
1024 * Return the question type name for a given slot within the current attempt.
1026 * @param int $slot the number used to identify this question within this attempt.
1027 * @return string the question type name.
1029 public function get_question_type_name($slot) {
1030 return $this->quba
->get_question($slot, false)->get_type_name();
1034 * Get the time remaining for an in-progress attempt, if the time is short
1035 * enough that it would be worth showing a timer.
1037 * @param int $timenow the time to consider as 'now'.
1038 * @return int|false the number of seconds remaining for this attempt.
1039 * False if there is no limit.
1041 public function get_time_left_display($timenow) {
1042 if ($this->attempt
->state
!= self
::IN_PROGRESS
) {
1045 return $this->get_access_manager($timenow)->get_time_left_display($this->attempt
, $timenow);
1050 * Get the time when this attempt was submitted.
1052 * @return int timestamp, or 0 if it has not been submitted yet.
1054 public function get_submitted_date() {
1055 return $this->attempt
->timefinish
;
1059 * If the attempt is in an applicable state, work out the time by which the
1060 * student should next do something.
1062 * @return int timestamp by which the student needs to do something.
1064 public function get_due_date() {
1066 if ($this->quizobj
->get_quiz()->timelimit
) {
1067 $deadlines[] = $this->attempt
->timestart +
$this->quizobj
->get_quiz()->timelimit
;
1069 if ($this->quizobj
->get_quiz()->timeclose
) {
1070 $deadlines[] = $this->quizobj
->get_quiz()->timeclose
;
1073 $duedate = min($deadlines);
1078 switch ($this->attempt
->state
) {
1079 case self
::IN_PROGRESS
:
1083 return $duedate +
$this->quizobj
->get_quiz()->graceperiod
;
1086 throw new coding_exception('Unexpected state: ' . $this->attempt
->state
);
1090 // URLs related to this attempt ============================================.
1093 * Get the URL of this quiz's view.php page.
1095 * @return moodle_url quiz view url.
1097 public function view_url() {
1098 return $this->quizobj
->view_url();
1102 * Get the URL to start or continue an attempt.
1104 * @param int|null $slot which question in the attempt to go to after starting (optional).
1105 * @param int $page which page in the attempt to go to after starting.
1106 * @return moodle_url the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
1108 public function start_attempt_url($slot = null, $page = -1) {
1109 if ($page == -1 && !is_null($slot)) {
1110 $page = $this->get_question_page($slot);
1114 return $this->quizobj
->start_attempt_url($page);
1118 * Generates the title of the attempt page.
1120 * @param int $page the page number (starting with 0) in the attempt.
1121 * @return string attempt page title.
1123 public function attempt_page_title(int $page) : string {
1124 if ($this->get_num_pages() > 1) {
1125 $a = new stdClass();
1126 $a->name
= $this->get_quiz_name();
1127 $a->currentpage
= $page +
1;
1128 $a->totalpages
= $this->get_num_pages();
1129 $title = get_string('attempttitlepaged', 'quiz', $a);
1131 $title = get_string('attempttitle', 'quiz', $this->get_quiz_name());
1138 * Get the URL of a particular page within this attempt.
1140 * @param int|null $slot if specified, the slot number of a specific question to link to.
1141 * @param int $page if specified, a particular page to link to. If not given deduced
1142 * from $slot, or goes to the first page.
1143 * @param int $thispage if not -1, the current page. Will cause links to other things on
1144 * this page to be output as only a fragment.
1145 * @return moodle_url the URL to continue this attempt.
1147 public function attempt_url($slot = null, $page = -1, $thispage = -1) {
1148 return $this->page_and_question_url('attempt', $slot, $page, false, $thispage);
1152 * Generates the title of the summary page.
1154 * @return string summary page title.
1156 public function summary_page_title() : string {
1157 return get_string('attemptsummarytitle', 'quiz', $this->get_quiz_name());
1161 * Get the URL of the summary page of this attempt.
1163 * @return moodle_url the URL of this quiz's summary page.
1165 public function summary_url() {
1166 return new moodle_url('/mod/quiz/summary.php', ['attempt' => $this->attempt
->id
, 'cmid' => $this->get_cmid()]);
1170 * Get the URL to which the attempt data should be submitted.
1172 * @return moodle_url the URL of this quiz's summary page.
1174 public function processattempt_url() {
1175 return new moodle_url('/mod/quiz/processattempt.php');
1179 * Generates the title of the review page.
1181 * @param int $page the page number (starting with 0) in the attempt.
1182 * @param bool $showall whether the review page contains the entire attempt on one page.
1183 * @return string title of the review page.
1185 public function review_page_title(int $page, bool $showall = false) : string {
1186 if (!$showall && $this->get_num_pages() > 1) {
1187 $a = new stdClass();
1188 $a->name
= $this->get_quiz_name();
1189 $a->currentpage
= $page +
1;
1190 $a->totalpages
= $this->get_num_pages();
1191 $title = get_string('attemptreviewtitlepaged', 'quiz', $a);
1193 $title = get_string('attemptreviewtitle', 'quiz', $this->get_quiz_name());
1200 * Get the URL of a particular page in the review of this attempt.
1202 * @param int|null $slot indicates which question to link to.
1203 * @param int $page if specified, the URL of this particular page of the attempt, otherwise
1204 * the URL will go to the first page. If -1, deduce $page from $slot.
1205 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
1206 * and $page will be ignored. If null, a sensible default will be chosen.
1207 * @param int $thispage if not -1, the current page. Will cause links to other things on
1208 * this page to be output as only a fragment.
1209 * @return moodle_url the URL to review this attempt.
1211 public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) {
1212 return $this->page_and_question_url('review', $slot, $page, $showall, $thispage);
1216 * By default, should this script show all questions on one page for this attempt?
1218 * @param string $script the script name, e.g. 'attempt', 'summary', 'review'.
1219 * @return bool whether show all on one page should be on by default.
1221 public function get_default_show_all($script) {
1222 return $script === 'review' && count($this->questionpages
) < self
::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL
;
1225 // Bits of content =========================================================.
1228 * If $reviewoptions->attempt is false, meaning that students can't review this
1229 * attempt at the moment, return an appropriate string explaining why.
1231 * @param bool $short if true, return a shorter string.
1232 * @return string an appropriate message.
1234 public function cannot_review_message($short = false) {
1235 return $this->quizobj
->cannot_review_message(
1236 $this->get_attempt_state(), $short, $this->attempt
->timefinish
);
1240 * Initialise the JS etc. required all the questions on a page.
1242 * @param int|string $page a page number, or 'all'.
1243 * @param bool $showall if true, forces page number to all.
1244 * @return string HTML to output - mostly obsolete, will probably be an empty string.
1246 public function get_html_head_contributions($page = 'all', $showall = false) {
1251 foreach ($this->get_slots($page) as $slot) {
1252 $result .= $this->quba
->render_question_head_html($slot);
1254 $result .= question_engine
::initialise_js();
1259 * Initialise the JS etc. required by one question.
1261 * @param int $slot the question slot number.
1262 * @return string HTML to output - but this is mostly obsolete. Will probably be an empty string.
1264 public function get_question_html_head_contributions($slot) {
1265 return $this->quba
->render_question_head_html($slot) .
1266 question_engine
::initialise_js();
1270 * Print the HTML for the start new preview button, if the current user
1271 * is allowed to see one.
1273 * @return string HTML for the button.
1275 public function restart_preview_button() {
1277 if ($this->is_preview() && $this->is_preview_user()) {
1278 return $OUTPUT->single_button(new moodle_url(
1279 $this->start_attempt_url(), ['forcenew' => true]),
1280 get_string('startnewpreview', 'quiz'));
1287 * Generate the HTML that displays the question in its current state, with
1288 * the appropriate display options.
1290 * @param int $slot identifies the question in the attempt.
1291 * @param bool $reviewing is the being printed on an attempt or a review page.
1292 * @param renderer $renderer the quiz renderer.
1293 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1294 * @return string HTML for the question in its current state.
1296 public function render_question($slot, $reviewing, renderer
$renderer, $thispageurl = null) {
1297 if ($this->is_blocked_by_previous_question($slot)) {
1298 $placeholderqa = $this->make_blocked_question_placeholder($slot);
1300 $displayoptions = $this->get_display_options($reviewing);
1301 $displayoptions->manualcomment
= question_display_options
::HIDDEN
;
1302 $displayoptions->history
= question_display_options
::HIDDEN
;
1303 $displayoptions->readonly
= true;
1304 $displayoptions->versioninfo
= question_display_options
::HIDDEN
;
1306 return html_writer
::div($placeholderqa->render($displayoptions,
1307 $this->get_question_number($this->get_original_slot($slot))),
1308 'mod_quiz-blocked_question_warning');
1311 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, null);
1315 * Helper used by {@see render_question()} and {@see render_question_at_step()}.
1317 * @param int $slot identifies the question in the attempt.
1318 * @param bool $reviewing is the being printed on an attempt or a review page.
1319 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1320 * @param renderer $renderer the quiz renderer.
1321 * @param int|null $seq the seq number of the past state to display.
1322 * @return string HTML fragment.
1324 protected function render_question_helper($slot, $reviewing, $thispageurl,
1325 renderer
$renderer, $seq) {
1326 $originalslot = $this->get_original_slot($slot);
1327 $number = $this->get_question_number($originalslot);
1328 $displayoptions = $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl);
1330 if ($slot != $originalslot) {
1331 $originalmaxmark = $this->get_question_attempt($slot)->get_max_mark();
1332 $this->get_question_attempt($slot)->set_max_mark($this->get_question_attempt($originalslot)->get_max_mark());
1335 if ($this->can_question_be_redone_now($slot)) {
1336 $displayoptions->extrainfocontent
= $renderer->redo_question_button(
1337 $slot, $displayoptions->readonly
);
1340 if ($displayoptions->history
&& $displayoptions->questionreviewlink
) {
1341 $links = $this->links_to_other_redos($slot, $displayoptions->questionreviewlink
);
1343 $displayoptions->extrahistorycontent
= html_writer
::tag('p',
1344 get_string('redoesofthisquestion', 'quiz', $renderer->render($links)));
1348 if ($seq === null) {
1349 $output = $this->quba
->render_question($slot, $displayoptions, $number);
1351 $output = $this->quba
->render_question_at_step($slot, $seq, $displayoptions, $number);
1354 if ($slot != $originalslot) {
1355 $this->get_question_attempt($slot)->set_max_mark($originalmaxmark);
1362 * Create a fake question to be displayed in place of a question that is blocked
1363 * until the previous question has been answered.
1365 * @param int $slot int slot number of the question to replace.
1366 * @return question_attempt the placeholder question attempt.
1368 protected function make_blocked_question_placeholder($slot) {
1369 $replacedquestion = $this->get_question_attempt($slot)->get_question(false);
1371 question_bank
::load_question_definition_classes('description');
1372 $question = new qtype_description_question();
1373 $question->id
= $replacedquestion->id
;
1374 $question->category
= null;
1375 $question->parent
= 0;
1376 $question->qtype
= question_bank
::get_qtype('description');
1377 $question->name
= '';
1378 $question->questiontext
= get_string('questiondependsonprevious', 'quiz');
1379 $question->questiontextformat
= FORMAT_HTML
;
1380 $question->generalfeedback
= '';
1381 $question->defaultmark
= $this->quba
->get_question_max_mark($slot);
1382 $question->length
= $replacedquestion->length
;
1383 $question->penalty
= 0;
1384 $question->stamp
= '';
1385 $question->status
= \core_question\local\bank\question_version_status
::QUESTION_STATUS_READY
;
1386 $question->timecreated
= null;
1387 $question->timemodified
= null;
1388 $question->createdby
= null;
1389 $question->modifiedby
= null;
1391 $placeholderqa = new question_attempt($question, $this->quba
->get_id(),
1392 null, $this->quba
->get_question_max_mark($slot));
1393 $placeholderqa->set_slot($slot);
1394 $placeholderqa->start($this->get_quiz()->preferredbehaviour
, 1);
1395 $placeholderqa->set_flagged($this->is_question_flagged($slot));
1396 return $placeholderqa;
1400 * Like {@see render_question()} but displays the question at the past step
1401 * indicated by $seq, rather than showing the latest step.
1403 * @param int $slot the slot number of a question in this quiz attempt.
1404 * @param int $seq the seq number of the past state to display.
1405 * @param bool $reviewing is the being printed on an attempt or a review page.
1406 * @param renderer $renderer the quiz renderer.
1407 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1408 * @return string HTML for the question in its current state.
1410 public function render_question_at_step($slot, $seq, $reviewing,
1411 renderer
$renderer, $thispageurl = null) {
1412 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, $seq);
1416 * Wrapper round print_question from lib/questionlib.php.
1418 * @param int $slot the id of a question in this quiz attempt.
1419 * @return string HTML of the question.
1421 public function render_question_for_commenting($slot) {
1422 $options = $this->get_display_options(true);
1423 $options->generalfeedback
= question_display_options
::HIDDEN
;
1424 $options->manualcomment
= question_display_options
::EDITABLE
;
1425 return $this->quba
->render_question($slot, $options,
1426 $this->get_question_number($slot));
1430 * Check whether access should be allowed to a particular file.
1432 * @param int $slot the slot of a question in this quiz attempt.
1433 * @param bool $reviewing is the being printed on an attempt or a review page.
1434 * @param int $contextid the file context id from the request.
1435 * @param string $component the file component from the request.
1436 * @param string $filearea the file area from the request.
1437 * @param array $args extra part components from the request.
1438 * @param bool $forcedownload whether to force download.
1439 * @return bool true if the file can be accessed.
1441 public function check_file_access($slot, $reviewing, $contextid, $component,
1442 $filearea, $args, $forcedownload) {
1443 $options = $this->get_display_options($reviewing);
1445 // Check permissions - warning there is similar code in review.php and
1446 // reviewquestion.php. If you change on, change them all.
1447 if ($reviewing && $this->is_own_attempt() && !$options->attempt
) {
1451 if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) {
1455 return $this->quba
->check_file_access($slot, $options,
1456 $component, $filearea, $args, $forcedownload);
1460 * Get the navigation panel object for this attempt.
1462 * @param renderer $output the quiz renderer to use to output things.
1463 * @param string $panelclass The type of panel, navigation_panel_attempt::class or navigation_panel_review::class
1464 * @param int $page the current page number.
1465 * @param bool $showall whether we are showing the whole quiz on one page. (Used by review.php.)
1466 * @return block_contents the requested object.
1468 public function get_navigation_panel(renderer
$output,
1469 $panelclass, $page, $showall = false) {
1470 $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall);
1472 $bc = new block_contents();
1473 $bc->attributes
['id'] = 'mod_quiz_navblock';
1474 $bc->attributes
['role'] = 'navigation';
1475 $bc->title
= get_string('quiznavigation', 'quiz');
1476 $bc->content
= $output->navigation_panel($panel);
1481 * Return an array of variant URLs to other attempts at this quiz.
1483 * The $url passed in must contain an attempt parameter.
1485 * The {@see links_to_other_attempts} object returned contains an
1486 * array with keys that are the attempt number, 1, 2, 3.
1487 * The array values are either a {@see moodle_url} with the attempt parameter
1488 * updated to point to the attempt id of the other attempt, or null corresponding
1489 * to the current attempt number.
1491 * @param moodle_url $url a URL.
1492 * @return links_to_other_attempts|bool containing array int => null|moodle_url.
1495 public function links_to_other_attempts(moodle_url
$url) {
1496 $attempts = quiz_get_user_attempts($this->get_quiz()->id
, $this->attempt
->userid
, 'all');
1497 if (count($attempts) <= 1) {
1501 $links = new links_to_other_attempts();
1502 foreach ($attempts as $at) {
1503 if ($at->id
== $this->attempt
->id
) {
1504 $links->links
[$at->attempt
] = null;
1506 $links->links
[$at->attempt
] = new moodle_url($url, ['attempt' => $at->id
]);
1513 * Return an array of variant URLs to other redos of the question in a particular slot.
1515 * The $url passed in must contain a slot parameter.
1517 * The {@see links_to_other_attempts} object returned contains an
1518 * array with keys that are the redo number, 1, 2, 3.
1519 * The array values are either a {@see moodle_url} with the slot parameter
1520 * updated to point to the slot that has that redo of this question; or null
1521 * corresponding to the redo identified by $slot.
1523 * @param int $slot identifies a question in this attempt.
1524 * @param moodle_url $baseurl the base URL to modify to generate each link.
1525 * @return links_to_other_attempts|null containing array int => null|moodle_url,
1526 * or null if the question in this slot has not been redone.
1528 public function links_to_other_redos($slot, moodle_url
$baseurl) {
1529 $originalslot = $this->get_original_slot($slot);
1531 $qas = $this->all_question_attempts_originally_in_slot($originalslot);
1532 if (count($qas) <= 1) {
1536 $links = new links_to_other_attempts();
1538 foreach ($qas as $qa) {
1539 if ($qa->get_slot() == $slot) {
1540 $links->links
[$index] = null;
1542 $url = new moodle_url($baseurl, ['slot' => $qa->get_slot()]);
1543 $links->links
[$index] = new action_link($url, $index,
1544 new popup_action('click', $url, 'reviewquestion',
1545 ['width' => 450, 'height' => 650]),
1546 ['title' => get_string('reviewresponse', 'question')]);
1553 // Methods for processing ==================================================.
1556 * Check this attempt, to see if there are any state transitions that should
1557 * happen automatically. This function will update the attempt checkstatetime.
1558 * @param int $timestamp the timestamp that should be stored as the modified
1559 * @param bool $studentisonline is the student currently interacting with Moodle?
1561 public function handle_if_time_expired($timestamp, $studentisonline) {
1563 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt
);
1565 if ($timeclose === false ||
$this->is_preview()) {
1566 $this->update_timecheckstate(null);
1567 return; // No time limit.
1569 if ($timestamp < $timeclose) {
1570 $this->update_timecheckstate($timeclose);
1571 return; // Time has not yet expired.
1574 // If the attempt is already overdue, look to see if it should be abandoned ...
1575 if ($this->attempt
->state
== self
::OVERDUE
) {
1576 $timeoverdue = $timestamp - $timeclose;
1577 $graceperiod = $this->quizobj
->get_quiz()->graceperiod
;
1578 if ($timeoverdue >= $graceperiod) {
1579 $this->process_abandon($timestamp, $studentisonline);
1581 // Overdue time has not yet expired.
1582 $this->update_timecheckstate($timeclose +
$graceperiod);
1584 return; // ... and we are done.
1587 if ($this->attempt
->state
!= self
::IN_PROGRESS
) {
1588 $this->update_timecheckstate(null);
1589 return; // Attempt is already in a final state.
1592 // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired.
1593 // Transition to the appropriate state.
1594 switch ($this->quizobj
->get_quiz()->overduehandling
) {
1596 $this->process_finish($timestamp, false, $studentisonline ?
$timestamp : $timeclose, $studentisonline);
1600 $this->process_going_overdue($timestamp, $studentisonline);
1604 $this->process_abandon($timestamp, $studentisonline);
1608 // This is an overdue attempt with no overdue handling defined, so just abandon.
1609 $this->process_abandon($timestamp, $studentisonline);
1613 * Process all the actions that were submitted as part of the current request.
1615 * @param int $timestamp the timestamp that should be stored as the modified.
1616 * time in the database for these actions. If null, will use the current time.
1617 * @param bool $becomingoverdue
1618 * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data.
1619 * There are two formats supported here, for historical reasons. The newer approach is to pass an array created by
1620 * {@see core_question_generator::get_simulated_post_data_for_questions_in_usage()}.
1621 * the second is to pass an array slot no => contains arrays representing student
1622 * responses which will be passed to {@see question_definition::prepare_simulated_post_data()}.
1623 * This second method will probably get deprecated one day.
1625 public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) {
1628 $transaction = $DB->start_delegated_transaction();
1630 if ($simulatedresponses !== null) {
1631 if (is_int(key($simulatedresponses))) {
1632 // Legacy approach. Should be removed one day.
1633 $simulatedpostdata = $this->quba
->prepare_simulated_post_data($simulatedresponses);
1635 $simulatedpostdata = $simulatedresponses;
1638 $simulatedpostdata = null;
1641 $this->quba
->process_all_actions($timestamp, $simulatedpostdata);
1642 question_engine
::save_questions_usage_by_activity($this->quba
);
1644 $this->attempt
->timemodified
= $timestamp;
1645 if ($this->attempt
->state
== self
::FINISHED
) {
1646 $this->attempt
->sumgrades
= $this->quba
->get_total_mark();
1648 if ($becomingoverdue) {
1649 $this->process_going_overdue($timestamp, true);
1651 $DB->update_record('quiz_attempts', $this->attempt
);
1654 if (!$this->is_preview() && $this->attempt
->state
== self
::FINISHED
) {
1655 $this->recompute_final_grade();
1658 $transaction->allow_commit();
1662 * Replace a question in an attempt with a new attempt at the same question.
1664 * Well, for randomised questions, it won't be the same question, it will be
1665 * a different randomly selected pick from the available question.
1667 * @param int $slot the question to restart.
1668 * @param int $timestamp the timestamp to record for this action.
1670 public function process_redo_question($slot, $timestamp) {
1673 if (!$this->can_question_be_redone_now($slot)) {
1674 throw new coding_exception('Attempt to restart the question in slot ' . $slot .
1675 ' when it is not in a state to be restarted.');
1678 $qubaids = new \mod_quiz\question\
qubaids_for_users_attempts(
1679 $this->get_quizid(), $this->get_userid(), 'all', true);
1681 $transaction = $DB->start_delegated_transaction();
1683 // Add the question to the usage. It is important we do this before we choose a variant.
1684 $newquestionid = qbank_helper
::choose_question_for_redo($this->get_quizid(),
1685 $this->get_quizobj()->get_context(), $this->slots
[$slot]->id
, $qubaids);
1686 $newquestion = question_bank
::load_question($newquestionid, $this->get_quiz()->shuffleanswers
);
1687 $newslot = $this->quba
->add_question_in_place_of_other($slot, $newquestion);
1689 // Choose the variant.
1690 if ($newquestion->get_num_variants() == 1) {
1693 $variantstrategy = new \core_question\engine\variants\
least_used_strategy(
1694 $this->quba
, $qubaids);
1695 $variant = $variantstrategy->choose_variant($newquestion->get_num_variants(),
1696 $newquestion->get_variants_selection_seed());
1699 // Start the question.
1700 $this->quba
->start_question($slot, $variant);
1701 $this->quba
->set_max_mark($newslot, 0);
1702 $this->quba
->set_question_attempt_metadata($newslot, 'originalslot', $slot);
1703 question_engine
::save_questions_usage_by_activity($this->quba
);
1704 $this->fire_attempt_question_restarted_event($slot, $newquestion->id
);
1706 $transaction->allow_commit();
1710 * Process all the autosaved data that was part of the current request.
1712 * @param int $timestamp the timestamp that should be stored as the modified.
1713 * time in the database for these actions. If null, will use the current time.
1715 public function process_auto_save($timestamp) {
1718 $transaction = $DB->start_delegated_transaction();
1720 $this->quba
->process_all_autosaves($timestamp);
1721 question_engine
::save_questions_usage_by_activity($this->quba
);
1722 $this->fire_attempt_autosaved_event();
1724 $transaction->allow_commit();
1728 * Update the flagged state for all question_attempts in this usage, if their
1729 * flagged state was changed in the request.
1731 public function save_question_flags() {
1734 $transaction = $DB->start_delegated_transaction();
1735 $this->quba
->update_question_flags();
1736 question_engine
::save_questions_usage_by_activity($this->quba
);
1737 $transaction->allow_commit();
1741 * Submit the attempt.
1743 * The separate $timefinish argument should be used when the quiz attempt
1744 * is being processed asynchronously (for example when cron is submitting
1745 * attempts where the time has expired).
1747 * @param int $timestamp the time to record as last modified time.
1748 * @param bool $processsubmitted if true, and question responses in the current
1749 * POST request are stored to be graded, before the attempt is finished.
1750 * @param ?int $timefinish if set, use this as the finish time for the attempt.
1751 * (otherwise use $timestamp as the finish time as well).
1752 * @param bool $studentisonline is the student currently interacting with Moodle?
1754 public function process_finish($timestamp, $processsubmitted, $timefinish = null, $studentisonline = false) {
1757 $transaction = $DB->start_delegated_transaction();
1759 if ($processsubmitted) {
1760 $this->quba
->process_all_actions($timestamp);
1762 $this->quba
->finish_all_questions($timestamp);
1764 question_engine
::save_questions_usage_by_activity($this->quba
);
1766 $this->attempt
->timemodified
= $timestamp;
1767 $this->attempt
->timefinish
= $timefinish ??
$timestamp;
1768 $this->attempt
->sumgrades
= $this->quba
->get_total_mark();
1769 $this->attempt
->state
= self
::FINISHED
;
1770 $this->attempt
->timecheckstate
= null;
1771 $this->attempt
->gradednotificationsenttime
= null;
1773 if (!$this->requires_manual_grading() ||
1774 !has_capability('mod/quiz:emailnotifyattemptgraded', $this->get_quizobj()->get_context(),
1775 $this->get_userid())) {
1776 $this->attempt
->gradednotificationsenttime
= $this->attempt
->timefinish
;
1779 $DB->update_record('quiz_attempts', $this->attempt
);
1781 if (!$this->is_preview()) {
1782 $this->recompute_final_grade();
1785 $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp, $studentisonline);
1787 // Tell any access rules that care that the attempt is over.
1788 $this->get_access_manager($timestamp)->current_attempt_finished();
1791 $transaction->allow_commit();
1795 * Update this attempt timecheckstate if necessary.
1797 * @param int|null $time the timestamp to set.
1799 public function update_timecheckstate($time) {
1801 if ($this->attempt
->timecheckstate
!== $time) {
1802 $this->attempt
->timecheckstate
= $time;
1803 $DB->set_field('quiz_attempts', 'timecheckstate', $time, ['id' => $this->attempt
->id
]);
1808 * Needs to be called after this attempt's grade is changed, to update the overall quiz grade.
1810 protected function recompute_final_grade(): void
{
1811 $this->quizobj
->get_grade_calculator()->recompute_final_grade($this->get_userid());
1815 * Mark this attempt as now overdue.
1817 * @param int $timestamp the time to deem as now.
1818 * @param bool $studentisonline is the student currently interacting with Moodle?
1820 public function process_going_overdue($timestamp, $studentisonline) {
1823 $transaction = $DB->start_delegated_transaction();
1824 $this->attempt
->timemodified
= $timestamp;
1825 $this->attempt
->state
= self
::OVERDUE
;
1826 // If we knew the attempt close time, we could compute when the graceperiod ends.
1827 // Instead, we'll just fix it up through cron.
1828 $this->attempt
->timecheckstate
= $timestamp;
1829 $DB->update_record('quiz_attempts', $this->attempt
);
1831 $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp, $studentisonline);
1833 $transaction->allow_commit();
1835 quiz_send_overdue_message($this);
1839 * Mark this attempt as abandoned.
1841 * @param int $timestamp the time to deem as now.
1842 * @param bool $studentisonline is the student currently interacting with Moodle?
1844 public function process_abandon($timestamp, $studentisonline) {
1847 $transaction = $DB->start_delegated_transaction();
1848 $this->attempt
->timemodified
= $timestamp;
1849 $this->attempt
->state
= self
::ABANDONED
;
1850 $this->attempt
->timecheckstate
= null;
1851 $DB->update_record('quiz_attempts', $this->attempt
);
1853 $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp, $studentisonline);
1855 $transaction->allow_commit();
1859 * This method takes an attempt in the 'Never submitted' state, and reopens it.
1861 * If, for this student, time has not expired (perhaps, because an override has
1862 * been added, then the attempt is left open. Otherwise, it is immediately submitted
1865 * @param int $timestamp the time to deem as now.
1867 public function process_reopen_abandoned($timestamp) {
1870 // Verify that things are as we expect.
1871 if ($this->get_state() != self
::ABANDONED
) {
1872 throw new coding_exception('Can only reopen an attempt that was never submitted.');
1875 $transaction = $DB->start_delegated_transaction();
1876 $this->attempt
->timemodified
= $timestamp;
1877 $this->attempt
->state
= self
::IN_PROGRESS
;
1878 $this->attempt
->timecheckstate
= null;
1879 $DB->update_record('quiz_attempts', $this->attempt
);
1881 $this->fire_state_transition_event('\mod_quiz\event\attempt_reopened', $timestamp, false);
1883 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt
);
1884 if ($timeclose && $timestamp > $timeclose) {
1885 $this->process_finish($timestamp, false, $timeclose);
1888 $transaction->allow_commit();
1892 * Fire a state transition event.
1894 * @param string $eventclass the event class name.
1895 * @param int $timestamp the timestamp to include in the event.
1896 * @param bool $studentisonline is the student currently interacting with Moodle?
1898 protected function fire_state_transition_event($eventclass, $timestamp, $studentisonline) {
1900 $quizrecord = $this->get_quiz();
1902 'context' => $this->get_quizobj()->get_context(),
1903 'courseid' => $this->get_courseid(),
1904 'objectid' => $this->attempt
->id
,
1905 'relateduserid' => $this->attempt
->userid
,
1907 'submitterid' => CLI_SCRIPT ?
null : $USER->id
,
1908 'quizid' => $quizrecord->id
,
1909 'studentisonline' => $studentisonline
1912 $event = $eventclass::create($params);
1913 $event->add_record_snapshot('quiz', $this->get_quiz());
1914 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
1918 // Private methods =========================================================.
1921 * Get a URL for a particular question on a particular page of the quiz.
1922 * Used by {@see attempt_url()} and {@see review_url()}.
1924 * @param string $script e.g. 'attempt' or 'review'. Used in the URL like /mod/quiz/$script.php.
1925 * @param int $slot identifies the specific question on the page to jump to.
1926 * 0 to just use the $page parameter.
1927 * @param int $page -1 to look up the page number from the slot, otherwise
1928 * the page number to go to.
1929 * @param bool|null $showall if true, return a URL with showall=1, and not page number.
1930 * if null, then an intelligent default will be chosen.
1931 * @param int $thispage the page we are currently on. Links to questions on this
1932 * page will just be a fragment #q123. -1 to disable this.
1933 * @return moodle_url The requested URL.
1935 protected function page_and_question_url($script, $slot, $page, $showall, $thispage) {
1937 $defaultshowall = $this->get_default_show_all($script);
1938 if ($showall === null && ($page == 0 ||
$page == -1)) {
1939 $showall = $defaultshowall;
1944 if ($slot !== null && !$showall) {
1945 $page = $this->get_question_page($slot);
1955 // Add a fragment to scroll down to the question.
1957 if ($slot !== null) {
1958 if ($slot == reset($this->pagelayout
[$page]) && $thispage != $page) {
1959 // Changing the page, go to top.
1962 // Link to the question container.
1963 $qa = $this->get_question_attempt($slot);
1964 $fragment = '#' . $qa->get_outer_question_div_unique_id();
1968 // Work out the correct start to the URL.
1969 if ($thispage == $page) {
1970 return new moodle_url($fragment);
1973 $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment,
1974 ['attempt' => $this->attempt
->id
, 'cmid' => $this->get_cmid()]);
1975 if ($page == 0 && $showall != $defaultshowall) {
1976 $url->param('showall', (int) $showall);
1977 } else if ($page > 0) {
1978 $url->param('page', $page);
1985 * Process responses during an attempt at a quiz.
1987 * @param int $timenow time when the processing started.
1988 * @param bool $finishattempt whether to finish the attempt or not.
1989 * @param bool $timeup true if form was submitted by timer.
1990 * @param int $thispage current page number.
1991 * @return string the attempt state once the data has been processed.
1994 public function process_attempt($timenow, $finishattempt, $timeup, $thispage) {
1997 $transaction = $DB->start_delegated_transaction();
2000 $accessmanager = $this->get_access_manager($timenow);
2001 $timeclose = $accessmanager->get_end_time($this->get_attempt());
2002 $graceperiodmin = get_config('quiz', 'graceperiodmin');
2004 // Don't enforce timeclose for previews.
2005 if ($this->is_preview()) {
2009 // Check where we are in relation to the end time, if there is one.
2011 if ($timeclose !== false) {
2012 if ($timenow > $timeclose - QUIZ_MIN_TIME_TO_CONTINUE
) {
2013 // If there is only a very small amount of time left, there is no point trying
2014 // to show the student another page of the quiz. Just finish now.
2016 if ($timenow > $timeclose +
$graceperiodmin) {
2020 // If time is not close to expiring, then ignore the client-side timer's opinion
2021 // about whether time has expired. This can happen if the time limit has changed
2022 // since the student's previous interaction.
2027 // If time is running out, trigger the appropriate action.
2028 $becomingoverdue = false;
2029 $becomingabandoned = false;
2031 if ($this->get_quiz()->overduehandling
=== 'graceperiod') {
2032 if ($timenow > $timeclose +
$this->get_quiz()->graceperiod +
$graceperiodmin) {
2033 // Grace period has run out.
2034 $finishattempt = true;
2035 $becomingabandoned = true;
2037 $becomingoverdue = true;
2040 $finishattempt = true;
2044 if (!$finishattempt) {
2045 // Just process the responses for this page and go to the next page.
2048 $this->process_submitted_actions($timenow, $becomingoverdue);
2049 $this->fire_attempt_updated_event();
2050 } catch (question_out_of_sequence_exception
$e) {
2051 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2052 $this->attempt_url(null, $thispage));
2054 } catch (Exception
$e) {
2055 // This sucks, if we display our own custom error message, there is no way
2056 // to display the original stack trace.
2058 if (!empty($e->debuginfo
)) {
2059 $debuginfo = $e->debuginfo
;
2061 throw new moodle_exception('errorprocessingresponses', 'question',
2062 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2065 if (!$becomingoverdue) {
2066 foreach ($this->get_slots() as $slot) {
2067 if (optional_param('redoslot' . $slot, false, PARAM_BOOL
)) {
2068 $this->process_redo_question($slot, $timenow);
2074 // The student is too late.
2075 $this->process_going_overdue($timenow, true);
2078 $transaction->allow_commit();
2080 return $becomingoverdue ? self
::OVERDUE
: self
::IN_PROGRESS
;
2083 // Update the quiz attempt record.
2085 if ($becomingabandoned) {
2086 $this->process_abandon($timenow, true);
2088 if (!$toolate ||
$this->get_quiz()->overduehandling
=== 'graceperiod') {
2089 // Normally, we record the accurate finish time when the student is online.
2090 $finishtime = $timenow;
2092 // But, if there is no grade period, and the final responses were too
2093 // late to be processed, record the close time, to reduce confusion.
2094 $finishtime = $timeclose;
2096 $this->process_finish($timenow, !$toolate, $finishtime, true);
2099 } catch (question_out_of_sequence_exception
$e) {
2100 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question',
2101 $this->attempt_url(null, $thispage));
2103 } catch (Exception
$e) {
2104 // This sucks, if we display our own custom error message, there is no way
2105 // to display the original stack trace.
2107 if (!empty($e->debuginfo
)) {
2108 $debuginfo = $e->debuginfo
;
2110 throw new moodle_exception('errorprocessingresponses', 'question',
2111 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo);
2114 // Send the user to the review page.
2115 $transaction->allow_commit();
2117 return $becomingabandoned ? self
::ABANDONED
: self
::FINISHED
;
2121 * Check a page read access to see if is an out of sequence access.
2123 * If allownext is set then we also check whether access to the page
2124 * after the current one should be permitted.
2126 * @param int $page page number.
2127 * @param bool $allownext in case of a sequential navigation, can we go to next page ?
2128 * @return boolean false is an out of sequence access, true otherwise.
2131 public function check_page_access(int $page, bool $allownext = true): bool {
2132 if ($this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ
) {
2135 // Sequential access: allow access to the summary, current page or next page.
2136 // Or if the user review his/her attempt, see MDLQA-1523.
2138 ||
$page == $this->get_currentpage()
2139 ||
$allownext && ($page == $this->get_currentpage() +
1);
2143 * Update attempt page.
2145 * @param int $page page number.
2146 * @return boolean true if everything was ok, false otherwise (out of sequence access).
2149 public function set_currentpage($page) {
2152 if ($this->check_page_access($page)) {
2153 $DB->set_field('quiz_attempts', 'currentpage', $page, ['id' => $this->get_attemptid()]);
2160 * Trigger the attempt_viewed event.
2164 public function fire_attempt_viewed_event() {
2166 'objectid' => $this->get_attemptid(),
2167 'relateduserid' => $this->get_userid(),
2168 'courseid' => $this->get_courseid(),
2169 'context' => $this->get_context(),
2171 'quizid' => $this->get_quizid(),
2172 'page' => $this->get_currentpage()
2175 $event = \mod_quiz\event\attempt_viewed
::create($params);
2176 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2181 * Trigger the attempt_updated event.
2185 public function fire_attempt_updated_event(): void
{
2187 'objectid' => $this->get_attemptid(),
2188 'relateduserid' => $this->get_userid(),
2189 'courseid' => $this->get_courseid(),
2190 'context' => $this->get_context(),
2192 'quizid' => $this->get_quizid(),
2193 'page' => $this->get_currentpage()
2196 $event = \mod_quiz\event\attempt_updated
::create($params);
2197 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2202 * Trigger the attempt_autosaved event.
2206 public function fire_attempt_autosaved_event(): void
{
2208 'objectid' => $this->get_attemptid(),
2209 'relateduserid' => $this->get_userid(),
2210 'courseid' => $this->get_courseid(),
2211 'context' => $this->get_context(),
2213 'quizid' => $this->get_quizid(),
2214 'page' => $this->get_currentpage()
2217 $event = \mod_quiz\event\attempt_autosaved
::create($params);
2218 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2223 * Trigger the attempt_question_restarted event.
2225 * @param int $slot Slot number
2226 * @param int $newquestionid New question id.
2229 public function fire_attempt_question_restarted_event(int $slot, int $newquestionid): void
{
2231 'objectid' => $this->get_attemptid(),
2232 'relateduserid' => $this->get_userid(),
2233 'courseid' => $this->get_courseid(),
2234 'context' => $this->get_context(),
2236 'quizid' => $this->get_quizid(),
2237 'page' => $this->get_currentpage(),
2239 'newquestionid' => $newquestionid
2242 $event = \mod_quiz\event\attempt_question_restarted
::create($params);
2243 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2248 * Trigger the attempt_summary_viewed event.
2252 public function fire_attempt_summary_viewed_event() {
2255 'objectid' => $this->get_attemptid(),
2256 'relateduserid' => $this->get_userid(),
2257 'courseid' => $this->get_courseid(),
2258 'context' => $this->get_context(),
2260 'quizid' => $this->get_quizid()
2263 $event = \mod_quiz\event\attempt_summary_viewed
::create($params);
2264 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2269 * Trigger the attempt_reviewed event.
2273 public function fire_attempt_reviewed_event() {
2276 'objectid' => $this->get_attemptid(),
2277 'relateduserid' => $this->get_userid(),
2278 'courseid' => $this->get_courseid(),
2279 'context' => $this->get_context(),
2281 'quizid' => $this->get_quizid()
2284 $event = \mod_quiz\event\attempt_reviewed
::create($params);
2285 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2290 * Trigger the attempt manual grading completed event.
2292 public function fire_attempt_manual_grading_completed_event() {
2294 'objectid' => $this->get_attemptid(),
2295 'relateduserid' => $this->get_userid(),
2296 'courseid' => $this->get_courseid(),
2297 'context' => $this->get_context(),
2299 'quizid' => $this->get_quizid()
2303 $event = \mod_quiz\event\attempt_manual_grading_completed
::create($params);
2304 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
2309 * Update the timemodifiedoffline attempt field.
2311 * This function should be used only when web services are being used.
2313 * @param int $time time stamp.
2314 * @return boolean false if the field is not updated because web services aren't being used.
2317 public function set_offline_modified_time($time) {
2318 // Update the timemodifiedoffline field only if web services are being used.
2320 $this->attempt
->timemodifiedoffline
= $time;
2327 * Get the total number of unanswered questions in the attempt.
2331 public function get_number_of_unanswered_questions(): int {
2332 $totalunanswered = 0;
2333 foreach ($this->get_slots() as $slot) {
2334 if (!$this->is_real_question($slot)) {
2337 $questionstate = $this->get_question_state($slot);
2338 if ($questionstate == question_state
::$todo ||
$questionstate == question_state
::$invalid) {
2342 return $totalunanswered;