MDL-51834 auth,profile: locks custom fields based on auth settings
[moodle.git] / mod / quiz / attemptlib.php
blob2bab57bc3bf333d1793cf95d493622cd08740189
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 // Fields initialised in the constructor.
64 protected $course;
65 protected $cm;
66 protected $quiz;
67 protected $context;
69 // Fields set later if that data is needed.
70 protected $questions = null;
71 protected $accessmanager = null;
72 protected $ispreviewuser = null;
74 // Constructor =============================================================
75 /**
76 * Constructor, assuming we already have the necessary data loaded.
78 * @param object $quiz the row from the quiz table.
79 * @param object $cm the course_module object for this quiz.
80 * @param object $course the row from the course table for the course we belong to.
81 * @param bool $getcontext intended for testing - stops the constructor getting the context.
83 public function __construct($quiz, $cm, $course, $getcontext = true) {
84 $this->quiz = $quiz;
85 $this->cm = $cm;
86 $this->quiz->cmid = $this->cm->id;
87 $this->course = $course;
88 if ($getcontext && !empty($cm->id)) {
89 $this->context = context_module::instance($cm->id);
93 /**
94 * Static function to create a new quiz object for a specific user.
96 * @param int $quizid the the quiz id.
97 * @param int $userid the the userid.
98 * @return quiz the new quiz object
100 public static function create($quizid, $userid = null) {
101 global $DB;
103 $quiz = quiz_access_manager::load_quiz_and_settings($quizid);
104 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
105 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
107 // Update quiz with override information.
108 if ($userid) {
109 $quiz = quiz_update_effective_access($quiz, $userid);
112 return new quiz($quiz, $cm, $course);
116 * Create a {@link quiz_attempt} for an attempt at this quiz.
117 * @param object $attemptdata row from the quiz_attempts table.
118 * @return quiz_attempt the new quiz_attempt object.
120 public function create_attempt_object($attemptdata) {
121 return new quiz_attempt($attemptdata, $this->quiz, $this->cm, $this->course);
124 // Functions for loading more data =========================================
127 * Load just basic information about all the questions in this quiz.
129 public function preload_questions() {
130 $this->questions = question_preload_questions(null,
131 'slot.maxmark, slot.id AS slotid, slot.slot, slot.page',
132 '{quiz_slots} slot ON slot.quizid = :quizid AND q.id = slot.questionid',
133 array('quizid' => $this->quiz->id), 'slot.slot');
137 * Fully load some or all of the questions for this quiz. You must call
138 * {@link preload_questions()} first.
140 * @param array $questionids question ids of the questions to load. null for all.
142 public function load_questions($questionids = null) {
143 if ($this->questions === null) {
144 throw new coding_exception('You must call preload_questions before calling load_questions.');
146 if (is_null($questionids)) {
147 $questionids = array_keys($this->questions);
149 $questionstoprocess = array();
150 foreach ($questionids as $id) {
151 if (array_key_exists($id, $this->questions)) {
152 $questionstoprocess[$id] = $this->questions[$id];
155 get_question_options($questionstoprocess);
159 * Get an instance of the {@link \mod_quiz\structure} class for this quiz.
160 * @return \mod_quiz\structure describes the questions in the quiz.
162 public function get_structure() {
163 return \mod_quiz\structure::create_for_quiz($this);
166 // Simple getters ==========================================================
167 /** @return int the course id. */
168 public function get_courseid() {
169 return $this->course->id;
172 /** @return object the row of the course table. */
173 public function get_course() {
174 return $this->course;
177 /** @return int the quiz id. */
178 public function get_quizid() {
179 return $this->quiz->id;
182 /** @return object the row of the quiz table. */
183 public function get_quiz() {
184 return $this->quiz;
187 /** @return string the name of this quiz. */
188 public function get_quiz_name() {
189 return $this->quiz->name;
192 /** @return int the quiz navigation method. */
193 public function get_navigation_method() {
194 return $this->quiz->navmethod;
197 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
198 public function get_num_attempts_allowed() {
199 return $this->quiz->attempts;
202 /** @return int the course_module id. */
203 public function get_cmid() {
204 return $this->cm->id;
207 /** @return object the course_module object. */
208 public function get_cm() {
209 return $this->cm;
212 /** @return object the module context for this quiz. */
213 public function get_context() {
214 return $this->context;
218 * @return bool wether the current user is someone who previews the quiz,
219 * rather than attempting it.
221 public function is_preview_user() {
222 if (is_null($this->ispreviewuser)) {
223 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context);
225 return $this->ispreviewuser;
229 * @return whether any questions have been added to this quiz.
231 public function has_questions() {
232 if ($this->questions === null) {
233 $this->preload_questions();
235 return !empty($this->questions);
239 * @param int $id the question id.
240 * @return object the question object with that id.
242 public function get_question($id) {
243 return $this->questions[$id];
247 * @param array $questionids question ids of the questions to load. null for all.
249 public function get_questions($questionids = null) {
250 if (is_null($questionids)) {
251 $questionids = array_keys($this->questions);
253 $questions = array();
254 foreach ($questionids as $id) {
255 if (!array_key_exists($id, $this->questions)) {
256 throw new moodle_exception('cannotstartmissingquestion', 'quiz', $this->view_url());
258 $questions[$id] = $this->questions[$id];
259 $this->ensure_question_loaded($id);
261 return $questions;
265 * @param int $timenow the current time as a unix timestamp.
266 * @return quiz_access_manager and instance of the quiz_access_manager class
267 * for this quiz at this time.
269 public function get_access_manager($timenow) {
270 if (is_null($this->accessmanager)) {
271 $this->accessmanager = new quiz_access_manager($this, $timenow,
272 has_capability('mod/quiz:ignoretimelimits', $this->context, null, false));
274 return $this->accessmanager;
278 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
280 public function has_capability($capability, $userid = null, $doanything = true) {
281 return has_capability($capability, $this->context, $userid, $doanything);
285 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
287 public function require_capability($capability, $userid = null, $doanything = true) {
288 return require_capability($capability, $this->context, $userid, $doanything);
291 // URLs related to this attempt ============================================
293 * @return string the URL of this quiz's view page.
295 public function view_url() {
296 global $CFG;
297 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id;
301 * @return string the URL of this quiz's edit page.
303 public function edit_url() {
304 global $CFG;
305 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id;
309 * @param int $attemptid the id of an attempt.
310 * @param int $page optional page number to go to in the attempt.
311 * @return string the URL of that attempt.
313 public function attempt_url($attemptid, $page = 0) {
314 global $CFG;
315 $url = $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid;
316 if ($page) {
317 $url .= '&page=' . $page;
319 return $url;
323 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
325 public function start_attempt_url($page = 0) {
326 $params = array('cmid' => $this->cm->id, 'sesskey' => sesskey());
327 if ($page) {
328 $params['page'] = $page;
330 return new moodle_url('/mod/quiz/startattempt.php', $params);
334 * @param int $attemptid the id of an attempt.
335 * @return string the URL of the review of that attempt.
337 public function review_url($attemptid) {
338 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid));
342 * @param int $attemptid the id of an attempt.
343 * @return string the URL of the review of that attempt.
345 public function summary_url($attemptid) {
346 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $attemptid));
349 // Bits of content =========================================================
352 * @param bool $unfinished whether there is currently an unfinished attempt active.
353 * @return string if the quiz policies merit it, return a warning string to
354 * be displayed in a javascript alert on the start attempt button.
356 public function confirm_start_attempt_message($unfinished) {
357 if ($unfinished) {
358 return '';
361 if ($this->quiz->timelimit && $this->quiz->attempts) {
362 return get_string('confirmstartattempttimelimit', 'quiz', $this->quiz->attempts);
363 } else if ($this->quiz->timelimit) {
364 return get_string('confirmstarttimelimit', 'quiz');
365 } else if ($this->quiz->attempts) {
366 return get_string('confirmstartattemptlimit', 'quiz', $this->quiz->attempts);
369 return '';
373 * If $reviewoptions->attempt is false, meaning that students can't review this
374 * attempt at the moment, return an appropriate string explaining why.
376 * @param int $when One of the mod_quiz_display_options::DURING,
377 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
378 * @param bool $short if true, return a shorter string.
379 * @return string an appropraite message.
381 public function cannot_review_message($when, $short = false) {
383 if ($short) {
384 $langstrsuffix = 'short';
385 $dateformat = get_string('strftimedatetimeshort', 'langconfig');
386 } else {
387 $langstrsuffix = '';
388 $dateformat = '';
391 if ($when == mod_quiz_display_options::DURING ||
392 $when == mod_quiz_display_options::IMMEDIATELY_AFTER) {
393 return '';
394 } else if ($when == mod_quiz_display_options::LATER_WHILE_OPEN && $this->quiz->timeclose &&
395 $this->quiz->reviewattempt & mod_quiz_display_options::AFTER_CLOSE) {
396 return get_string('noreviewuntil' . $langstrsuffix, 'quiz',
397 userdate($this->quiz->timeclose, $dateformat));
398 } else {
399 return get_string('noreview' . $langstrsuffix, 'quiz');
404 * @param string $title the name of this particular quiz page.
405 * @return array the data that needs to be sent to print_header_simple as the $navigation
406 * parameter.
408 public function navigation($title) {
409 global $PAGE;
410 $PAGE->navbar->add($title);
411 return '';
414 // Private methods =========================================================
416 * Check that the definition of a particular question is loaded, and if not throw an exception.
417 * @param $id a questionid.
419 protected function ensure_question_loaded($id) {
420 if (isset($this->questions[$id]->_partiallyloaded)) {
421 throw new moodle_quiz_exception($this, 'questionnotloaded', $id);
428 * This class extends the quiz class to hold data about the state of a particular attempt,
429 * in addition to the data about the quiz.
431 * @copyright 2008 Tim Hunt
432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
433 * @since Moodle 2.0
435 class quiz_attempt {
437 /** @var string to identify the in progress state. */
438 const IN_PROGRESS = 'inprogress';
439 /** @var string to identify the overdue state. */
440 const OVERDUE = 'overdue';
441 /** @var string to identify the finished state. */
442 const FINISHED = 'finished';
443 /** @var string to identify the abandoned state. */
444 const ABANDONED = 'abandoned';
446 /** @var int maximum number of slots in the quiz for the review page to default to show all. */
447 const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL = 50;
449 // Basic data.
450 protected $quizobj;
451 protected $attempt;
453 /** @var question_usage_by_activity the question usage for this quiz attempt. */
454 protected $quba;
456 /** @var array page no => array of slot numbers on the page in order. */
457 protected $pagelayout;
459 /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */
460 protected $questionnumbers;
462 /** @var array slot => page number for this slot. */
463 protected $questionpages;
465 /** @var mod_quiz_display_options cache for the appropriate review options. */
466 protected $reviewoptions = null;
468 // Constructor =============================================================
470 * Constructor assuming we already have the necessary data loaded.
472 * @param object $attempt the row of the quiz_attempts table.
473 * @param object $quiz the quiz object for this attempt and user.
474 * @param object $cm the course_module object for this quiz.
475 * @param object $course the row from the course table for the course we belong to.
476 * @param bool $loadquestions (optional) if true, the default, load all the details
477 * of the state of each question. Else just set up the basic details of the attempt.
479 public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) {
480 $this->attempt = $attempt;
481 $this->quizobj = new quiz($quiz, $cm, $course);
483 if (!$loadquestions) {
484 return;
487 $this->quba = question_engine::load_questions_usage_by_activity($this->attempt->uniqueid);
488 $this->determine_layout();
489 $this->number_questions();
493 * Used by {create()} and {create_from_usage_id()}.
494 * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions).
496 protected static function create_helper($conditions) {
497 global $DB;
499 $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST);
500 $quiz = quiz_access_manager::load_quiz_and_settings($attempt->quiz);
501 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST);
502 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST);
504 // Update quiz with override information.
505 $quiz = quiz_update_effective_access($quiz, $attempt->userid);
507 return new quiz_attempt($attempt, $quiz, $cm, $course);
511 * Static function to create a new quiz_attempt object given an attemptid.
513 * @param int $attemptid the attempt id.
514 * @return quiz_attempt the new quiz_attempt object
516 public static function create($attemptid) {
517 return self::create_helper(array('id' => $attemptid));
521 * Static function to create a new quiz_attempt object given a usage id.
523 * @param int $usageid the attempt usage id.
524 * @return quiz_attempt the new quiz_attempt object
526 public static function create_from_usage_id($usageid) {
527 return self::create_helper(array('uniqueid' => $usageid));
531 * @param string $state one of the state constants like IN_PROGRESS.
532 * @return string the human-readable state name.
534 public static function state_name($state) {
535 return quiz_attempt_state_name($state);
539 * Parse attempt->layout to populate the other arrays the represent the layout.
541 protected function determine_layout() {
542 $this->pagelayout = array();
544 // Break up the layout string into pages.
545 $pagelayouts = explode(',0', $this->attempt->layout);
547 // Strip off any empty last page (normally there is one).
548 if (end($pagelayouts) == '') {
549 array_pop($pagelayouts);
552 // File the ids into the arrays.
553 $this->pagelayout = array();
554 foreach ($pagelayouts as $page => $pagelayout) {
555 $pagelayout = trim($pagelayout, ',');
556 if ($pagelayout == '') {
557 continue;
559 $this->pagelayout[$page] = explode(',', $pagelayout);
564 * Work out the number to display for each question/slot.
566 protected function number_questions() {
567 $number = 1;
568 foreach ($this->pagelayout as $page => $slots) {
569 foreach ($slots as $slot) {
570 if ($length = $this->is_real_question($slot)) {
571 $this->questionnumbers[$slot] = $number;
572 $number += $length;
573 } else {
574 $this->questionnumbers[$slot] = get_string('infoshort', 'quiz');
576 $this->questionpages[$slot] = $page;
582 * If the given page number is out of range (before the first page, or after
583 * the last page, chnage it to be within range).
584 * @param int $page the requested page number.
585 * @return int a safe page number to use.
587 public function force_page_number_into_range($page) {
588 return min(max($page, 0), count($this->pagelayout) - 1);
591 // Simple getters ==========================================================
592 public function get_quiz() {
593 return $this->quizobj->get_quiz();
596 public function get_quizobj() {
597 return $this->quizobj;
600 /** @return int the course id. */
601 public function get_courseid() {
602 return $this->quizobj->get_courseid();
605 /** @return int the course id. */
606 public function get_course() {
607 return $this->quizobj->get_course();
610 /** @return int the quiz id. */
611 public function get_quizid() {
612 return $this->quizobj->get_quizid();
615 /** @return string the name of this quiz. */
616 public function get_quiz_name() {
617 return $this->quizobj->get_quiz_name();
620 /** @return int the quiz navigation method. */
621 public function get_navigation_method() {
622 return $this->quizobj->get_navigation_method();
625 /** @return object the course_module object. */
626 public function get_cm() {
627 return $this->quizobj->get_cm();
630 /** @return object the course_module object. */
631 public function get_cmid() {
632 return $this->quizobj->get_cmid();
636 * @return bool wether the current user is someone who previews the quiz,
637 * rather than attempting it.
639 public function is_preview_user() {
640 return $this->quizobj->is_preview_user();
643 /** @return int the number of attempts allowed at this quiz (0 = infinite). */
644 public function get_num_attempts_allowed() {
645 return $this->quizobj->get_num_attempts_allowed();
648 /** @return int number fo pages in this quiz. */
649 public function get_num_pages() {
650 return count($this->pagelayout);
654 * @param int $timenow the current time as a unix timestamp.
655 * @return quiz_access_manager and instance of the quiz_access_manager class
656 * for this quiz at this time.
658 public function get_access_manager($timenow) {
659 return $this->quizobj->get_access_manager($timenow);
662 /** @return int the attempt id. */
663 public function get_attemptid() {
664 return $this->attempt->id;
667 /** @return int the attempt unique id. */
668 public function get_uniqueid() {
669 return $this->attempt->uniqueid;
672 /** @return object the row from the quiz_attempts table. */
673 public function get_attempt() {
674 return $this->attempt;
677 /** @return int the number of this attemp (is it this user's first, second, ... attempt). */
678 public function get_attempt_number() {
679 return $this->attempt->attempt;
682 /** @return string one of the quiz_attempt::IN_PROGRESS, FINISHED, OVERDUE or ABANDONED constants. */
683 public function get_state() {
684 return $this->attempt->state;
687 /** @return int the id of the user this attempt belongs to. */
688 public function get_userid() {
689 return $this->attempt->userid;
692 /** @return int the current page of the attempt. */
693 public function get_currentpage() {
694 return $this->attempt->currentpage;
697 public function get_sum_marks() {
698 return $this->attempt->sumgrades;
702 * @return bool whether this attempt has been finished (true) or is still
703 * in progress (false). Be warned that this is not just state == self::FINISHED,
704 * it also includes self::ABANDONED.
706 public function is_finished() {
707 return $this->attempt->state == self::FINISHED || $this->attempt->state == self::ABANDONED;
710 /** @return bool whether this attempt is a preview attempt. */
711 public function is_preview() {
712 return $this->attempt->preview;
716 * Is this someone dealing with their own attempt or preview?
718 * @return bool true => own attempt/preview. false => reviewing someone elses.
720 public function is_own_attempt() {
721 global $USER;
722 return $this->attempt->userid == $USER->id;
726 * @return bool whether this attempt is a preview belonging to the current user.
728 public function is_own_preview() {
729 global $USER;
730 return $this->is_own_attempt() &&
731 $this->is_preview_user() && $this->attempt->preview;
735 * Is the current user allowed to review this attempt. This applies when
736 * {@link is_own_attempt()} returns false.
737 * @return bool whether the review should be allowed.
739 public function is_review_allowed() {
740 if (!$this->has_capability('mod/quiz:viewreports')) {
741 return false;
744 $cm = $this->get_cm();
745 if ($this->has_capability('moodle/site:accessallgroups') ||
746 groups_get_activity_groupmode($cm) != SEPARATEGROUPS) {
747 return true;
750 // Check the users have at least one group in common.
751 $teachersgroups = groups_get_activity_allowed_groups($cm);
752 $studentsgroups = groups_get_all_groups(
753 $cm->course, $this->attempt->userid, $cm->groupingid);
754 return $teachersgroups && $studentsgroups &&
755 array_intersect(array_keys($teachersgroups), array_keys($studentsgroups));
759 * Has the student, in this attempt, engaged with the quiz in a non-trivial way?
760 * That is, is there any question worth a non-zero number of marks, where
761 * the student has made some response that we have saved?
762 * @return bool true if we have saved a response for at least one graded question.
764 public function has_response_to_at_least_one_graded_question() {
765 foreach ($this->quba->get_attempt_iterator() as $qa) {
766 if ($qa->get_max_mark() == 0) {
767 continue;
769 if ($qa->get_num_steps() > 1) {
770 return true;
773 return false;
777 * Get extra summary information about this attempt.
779 * Some behaviours may be able to provide interesting summary information
780 * about the attempt as a whole, and this method provides access to that data.
781 * To see how this works, try setting a quiz to one of the CBM behaviours,
782 * and then look at the extra information displayed at the top of the quiz
783 * review page once you have sumitted an attempt.
785 * In the return value, the array keys are identifiers of the form
786 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
787 * The values are arrays with two items, title and content. Each of these
788 * will be either a string, or a renderable.
790 * @param question_display_options $options the display options for this quiz attempt at this time.
791 * @return array as described above.
793 public function get_additional_summary_data(question_display_options $options) {
794 return $this->quba->get_summary_information($options);
798 * Get the overall feedback corresponding to a particular mark.
799 * @param $grade a particular grade.
801 public function get_overall_feedback($grade) {
802 return quiz_feedback_for_grade($grade, $this->get_quiz(),
803 $this->quizobj->get_context());
807 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
809 public function has_capability($capability, $userid = null, $doanything = true) {
810 return $this->quizobj->has_capability($capability, $userid, $doanything);
814 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
816 public function require_capability($capability, $userid = null, $doanything = true) {
817 return $this->quizobj->require_capability($capability, $userid, $doanything);
821 * Check the appropriate capability to see whether this user may review their own attempt.
822 * If not, prints an error.
824 public function check_review_capability() {
825 if ($this->get_attempt_state() == mod_quiz_display_options::IMMEDIATELY_AFTER) {
826 $capability = 'mod/quiz:attempt';
827 } else {
828 $capability = 'mod/quiz:reviewmyattempts';
831 // These next tests are in a slighly funny order. The point is that the
832 // common and most performance-critical case is students attempting a quiz
833 // so we want to check that permisison first.
835 if ($this->has_capability($capability)) {
836 // User has the permission that lets you do the quiz as a student. Fine.
837 return;
840 if ($this->has_capability('mod/quiz:viewreports') ||
841 $this->has_capability('mod/quiz:preview')) {
842 // User has the permission that lets teachers review. Fine.
843 return;
846 // They should not be here. Trigger the standard no-permission error
847 // but using the name of the student capability.
848 // We know this will fail. We just want the stadard exception thown.
849 $this->require_capability($capability);
853 * Checks whether a user may navigate to a particular slot
855 public function can_navigate_to($slot) {
856 switch ($this->get_navigation_method()) {
857 case QUIZ_NAVMETHOD_FREE:
858 return true;
859 break;
860 case QUIZ_NAVMETHOD_SEQ:
861 return false;
862 break;
864 return true;
868 * @return int one of the mod_quiz_display_options::DURING,
869 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
871 public function get_attempt_state() {
872 return quiz_attempt_state($this->get_quiz(), $this->attempt);
876 * Wrapper that the correct mod_quiz_display_options for this quiz at the
877 * moment.
879 * @return question_display_options the render options for this user on this attempt.
881 public function get_display_options($reviewing) {
882 if ($reviewing) {
883 if (is_null($this->reviewoptions)) {
884 $this->reviewoptions = quiz_get_review_options($this->get_quiz(),
885 $this->attempt, $this->quizobj->get_context());
886 if ($this->is_own_preview()) {
887 // It should always be possible for a teacher to review their
888 // own preview irrespective of the review options settings.
889 $this->reviewoptions->attempt = true;
892 return $this->reviewoptions;
894 } else {
895 $options = mod_quiz_display_options::make_from_quiz($this->get_quiz(),
896 mod_quiz_display_options::DURING);
897 $options->flags = quiz_get_flag_option($this->attempt, $this->quizobj->get_context());
898 return $options;
903 * Wrapper that the correct mod_quiz_display_options for this quiz at the
904 * moment.
906 * @param bool $reviewing true for review page, else attempt page.
907 * @param int $slot which question is being displayed.
908 * @param moodle_url $thispageurl to return to after the editing form is
909 * submitted or cancelled. If null, no edit link will be generated.
911 * @return question_display_options the render options for this user on this
912 * attempt, with extra info to generate an edit link, if applicable.
914 public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) {
915 $options = clone($this->get_display_options($reviewing));
917 if (!$thispageurl) {
918 return $options;
921 if (!($reviewing || $this->is_preview())) {
922 return $options;
925 $question = $this->quba->get_question($slot);
926 if (!question_has_capability_on($question, 'edit', $question->category)) {
927 return $options;
930 $options->editquestionparams['cmid'] = $this->get_cmid();
931 $options->editquestionparams['returnurl'] = $thispageurl;
933 return $options;
937 * @param int $page page number
938 * @return bool true if this is the last page of the quiz.
940 public function is_last_page($page) {
941 return $page == count($this->pagelayout) - 1;
945 * Return the list of question ids for either a given page of the quiz, or for the
946 * whole quiz.
948 * @param mixed $page string 'all' or integer page number.
949 * @return array the reqested list of question ids.
951 public function get_slots($page = 'all') {
952 if ($page === 'all') {
953 $numbers = array();
954 foreach ($this->pagelayout as $numbersonpage) {
955 $numbers = array_merge($numbers, $numbersonpage);
957 return $numbers;
958 } else {
959 return $this->pagelayout[$page];
964 * Get the question_attempt object for a particular question in this attempt.
965 * @param int $slot the number used to identify this question within this attempt.
966 * @return question_attempt
968 public function get_question_attempt($slot) {
969 return $this->quba->get_question_attempt($slot);
973 * Is a particular question in this attempt a real question, or something like a description.
974 * @param int $slot the number used to identify this question within this attempt.
975 * @return int whether that question is a real question. Actually returns the
976 * question length, which could theoretically be greater than one.
978 public function is_real_question($slot) {
979 return $this->quba->get_question($slot)->length;
983 * Is a particular question in this attempt a real question, or something like a description.
984 * @param int $slot the number used to identify this question within this attempt.
985 * @return bool whether that question is a real question.
987 public function is_question_flagged($slot) {
988 return $this->quba->get_question_attempt($slot)->is_flagged();
992 * @param int $slot the number used to identify this question within this attempt.
993 * @return string the displayed question number for the question in this slot.
994 * For example '1', '2', '3' or 'i'.
996 public function get_question_number($slot) {
997 return $this->questionnumbers[$slot];
1001 * @param int $slot the number used to identify this question within this attempt.
1002 * @return int the page of the quiz this question appears on.
1004 public function get_question_page($slot) {
1005 return $this->questionpages[$slot];
1009 * Return the grade obtained on a particular question, if the user is permitted
1010 * to see it. You must previously have called load_question_states to load the
1011 * state data about this question.
1013 * @param int $slot the number used to identify this question within this attempt.
1014 * @return string the formatted grade, to the number of decimal places specified
1015 * by the quiz.
1017 public function get_question_name($slot) {
1018 return $this->quba->get_question($slot)->name;
1022 * Return the grade obtained on a particular question, if the user is permitted
1023 * to see it. You must previously have called load_question_states to load the
1024 * state data about this question.
1026 * @param int $slot the number used to identify this question within this attempt.
1027 * @param bool $showcorrectness Whether right/partial/wrong states should
1028 * be distinguised.
1029 * @return string the formatted grade, to the number of decimal places specified
1030 * by the quiz.
1032 public function get_question_status($slot, $showcorrectness) {
1033 return $this->quba->get_question_state_string($slot, $showcorrectness);
1037 * Return the grade obtained on a particular question, if the user is permitted
1038 * to see it. You must previously have called load_question_states to load the
1039 * state data about this question.
1041 * @param int $slot the number used to identify this question within this attempt.
1042 * @param bool $showcorrectness Whether right/partial/wrong states should
1043 * be distinguised.
1044 * @return string class name for this state.
1046 public function get_question_state_class($slot, $showcorrectness) {
1047 return $this->quba->get_question_state_class($slot, $showcorrectness);
1051 * Return the grade obtained on a particular question.
1052 * You must previously have called load_question_states to load the state
1053 * data about this question.
1055 * @param int $slot the number used to identify this question within this attempt.
1056 * @return string the formatted grade, to the number of decimal places specified by the quiz.
1058 public function get_question_mark($slot) {
1059 return quiz_format_question_grade($this->get_quiz(), $this->quba->get_question_mark($slot));
1063 * Get the time of the most recent action performed on a question.
1064 * @param int $slot the number used to identify this question within this usage.
1065 * @return int timestamp.
1067 public function get_question_action_time($slot) {
1068 return $this->quba->get_question_action_time($slot);
1072 * Get the time remaining for an in-progress attempt, if the time is short
1073 * enought that it would be worth showing a timer.
1074 * @param int $timenow the time to consider as 'now'.
1075 * @return int|false the number of seconds remaining for this attempt.
1076 * False if there is no limit.
1078 public function get_time_left_display($timenow) {
1079 if ($this->attempt->state != self::IN_PROGRESS) {
1080 return false;
1082 return $this->get_access_manager($timenow)->get_time_left_display($this->attempt, $timenow);
1087 * @return int the time when this attempt was submitted. 0 if it has not been
1088 * submitted yet.
1090 public function get_submitted_date() {
1091 return $this->attempt->timefinish;
1095 * If the attempt is in an applicable state, work out the time by which the
1096 * student should next do something.
1097 * @return int timestamp by which the student needs to do something.
1099 public function get_due_date() {
1100 $deadlines = array();
1101 if ($this->quizobj->get_quiz()->timelimit) {
1102 $deadlines[] = $this->attempt->timestart + $this->quizobj->get_quiz()->timelimit;
1104 if ($this->quizobj->get_quiz()->timeclose) {
1105 $deadlines[] = $this->quizobj->get_quiz()->timeclose;
1107 if ($deadlines) {
1108 $duedate = min($deadlines);
1109 } else {
1110 return false;
1113 switch ($this->attempt->state) {
1114 case self::IN_PROGRESS:
1115 return $duedate;
1117 case self::OVERDUE:
1118 return $duedate + $this->quizobj->get_quiz()->graceperiod;
1120 default:
1121 throw new coding_exception('Unexpected state: ' . $this->attempt->state);
1125 // URLs related to this attempt ============================================
1127 * @return string quiz view url.
1129 public function view_url() {
1130 return $this->quizobj->view_url();
1134 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
1136 public function start_attempt_url($slot = null, $page = -1) {
1137 if ($page == -1 && !is_null($slot)) {
1138 $page = $this->get_question_page($slot);
1139 } else {
1140 $page = 0;
1142 return $this->quizobj->start_attempt_url($page);
1146 * @param int $slot if speified, the slot number of a specific question to link to.
1147 * @param int $page if specified, a particular page to link to. If not givem deduced
1148 * from $slot, or goes to the first page.
1149 * @param int $questionid a question id. If set, will add a fragment to the URL
1150 * to jump to a particuar question on the page.
1151 * @param int $thispage if not -1, the current page. Will cause links to other things on
1152 * this page to be output as only a fragment.
1153 * @return string the URL to continue this attempt.
1155 public function attempt_url($slot = null, $page = -1, $thispage = -1) {
1156 return $this->page_and_question_url('attempt', $slot, $page, false, $thispage);
1160 * @return string the URL of this quiz's summary page.
1162 public function summary_url() {
1163 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $this->attempt->id));
1167 * @return string the URL of this quiz's summary page.
1169 public function processattempt_url() {
1170 return new moodle_url('/mod/quiz/processattempt.php');
1174 * @param int $slot indicates which question to link to.
1175 * @param int $page if specified, the URL of this particular page of the attempt, otherwise
1176 * the URL will go to the first page. If -1, deduce $page from $slot.
1177 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page,
1178 * and $page will be ignored. If null, a sensible default will be chosen.
1179 * @param int $thispage if not -1, the current page. Will cause links to other things on
1180 * this page to be output as only a fragment.
1181 * @return string the URL to review this attempt.
1183 public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) {
1184 return $this->page_and_question_url('review', $slot, $page, $showall, $thispage);
1188 * By default, should this script show all questions on one page for this attempt?
1189 * @param string $script the script name, e.g. 'attempt', 'summary', 'review'.
1190 * @return whether show all on one page should be on by default.
1192 public function get_default_show_all($script) {
1193 return $script == 'review' && count($this->questionpages) < self::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL;
1196 // Bits of content =========================================================
1199 * If $reviewoptions->attempt is false, meaning that students can't review this
1200 * attempt at the moment, return an appropriate string explaining why.
1202 * @param bool $short if true, return a shorter string.
1203 * @return string an appropraite message.
1205 public function cannot_review_message($short = false) {
1206 return $this->quizobj->cannot_review_message(
1207 $this->get_attempt_state(), $short);
1211 * Initialise the JS etc. required all the questions on a page.
1212 * @param mixed $page a page number, or 'all'.
1214 public function get_html_head_contributions($page = 'all', $showall = false) {
1215 if ($showall) {
1216 $page = 'all';
1218 $result = '';
1219 foreach ($this->get_slots($page) as $slot) {
1220 $result .= $this->quba->render_question_head_html($slot);
1222 $result .= question_engine::initialise_js();
1223 return $result;
1227 * Initialise the JS etc. required by one question.
1228 * @param int $questionid the question id.
1230 public function get_question_html_head_contributions($slot) {
1231 return $this->quba->render_question_head_html($slot) .
1232 question_engine::initialise_js();
1236 * Print the HTML for the start new preview button, if the current user
1237 * is allowed to see one.
1239 public function restart_preview_button() {
1240 global $OUTPUT;
1241 if ($this->is_preview() && $this->is_preview_user()) {
1242 return $OUTPUT->single_button(new moodle_url(
1243 $this->start_attempt_url(), array('forcenew' => true)),
1244 get_string('startnewpreview', 'quiz'));
1245 } else {
1246 return '';
1251 * Generate the HTML that displayes the question in its current state, with
1252 * the appropriate display options.
1254 * @param int $id the id of a question in this quiz attempt.
1255 * @param bool $reviewing is the being printed on an attempt or a review page.
1256 * @param moodle_url $thispageurl the URL of the page this question is being printed on.
1257 * @return string HTML for the question in its current state.
1259 public function render_question($slot, $reviewing, $thispageurl = null) {
1260 return $this->quba->render_question($slot,
1261 $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl),
1262 $this->get_question_number($slot));
1266 * Like {@link render_question()} but displays the question at the past step
1267 * indicated by $seq, rather than showing the latest step.
1269 * @param int $id the id of a question in this quiz attempt.
1270 * @param int $seq the seq number of the past state to display.
1271 * @param bool $reviewing is the being printed on an attempt or a review page.
1272 * @param string $thispageurl the URL of the page this question is being printed on.
1273 * @return string HTML for the question in its current state.
1275 public function render_question_at_step($slot, $seq, $reviewing, $thispageurl = '') {
1276 return $this->quba->render_question_at_step($slot, $seq,
1277 $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl),
1278 $this->get_question_number($slot));
1282 * Wrapper round print_question from lib/questionlib.php.
1284 * @param int $id the id of a question in this quiz attempt.
1286 public function render_question_for_commenting($slot) {
1287 $options = $this->get_display_options(true);
1288 $options->hide_all_feedback();
1289 $options->manualcomment = question_display_options::EDITABLE;
1290 return $this->quba->render_question($slot, $options,
1291 $this->get_question_number($slot));
1295 * Check wheter access should be allowed to a particular file.
1297 * @param int $id the id of a question in this quiz attempt.
1298 * @param bool $reviewing is the being printed on an attempt or a review page.
1299 * @param string $thispageurl the URL of the page this question is being printed on.
1300 * @return string HTML for the question in its current state.
1302 public function check_file_access($slot, $reviewing, $contextid, $component,
1303 $filearea, $args, $forcedownload) {
1304 $options = $this->get_display_options($reviewing);
1306 // Check permissions - warning there is similar code in review.php and
1307 // reviewquestion.php. If you change on, change them all.
1308 if ($reviewing && $this->is_own_attempt() && !$options->attempt) {
1309 return false;
1312 if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) {
1313 return false;
1316 return $this->quba->check_file_access($slot, $options,
1317 $component, $filearea, $args, $forcedownload);
1321 * Get the navigation panel object for this attempt.
1323 * @param $panelclass The type of panel, quiz_attempt_nav_panel or quiz_review_nav_panel
1324 * @param $page the current page number.
1325 * @param $showall whether we are showing the whole quiz on one page. (Used by review.php)
1326 * @return quiz_nav_panel_base the requested object.
1328 public function get_navigation_panel(mod_quiz_renderer $output,
1329 $panelclass, $page, $showall = false) {
1330 $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall);
1332 $bc = new block_contents();
1333 $bc->attributes['id'] = 'mod_quiz_navblock';
1334 $bc->title = get_string('quiznavigation', 'quiz');
1335 $bc->content = $output->navigation_panel($panel);
1336 return $bc;
1340 * Given a URL containing attempt={this attempt id}, return an array of variant URLs
1341 * @param moodle_url $url a URL.
1342 * @return string HTML fragment. Comma-separated list of links to the other
1343 * attempts with the attempt number as the link text. The curent attempt is
1344 * included but is not a link.
1346 public function links_to_other_attempts(moodle_url $url) {
1347 $attempts = quiz_get_user_attempts($this->get_quiz()->id, $this->attempt->userid, 'all');
1348 if (count($attempts) <= 1) {
1349 return false;
1352 $links = new mod_quiz_links_to_other_attempts();
1353 foreach ($attempts as $at) {
1354 if ($at->id == $this->attempt->id) {
1355 $links->links[$at->attempt] = null;
1356 } else {
1357 $links->links[$at->attempt] = new moodle_url($url, array('attempt' => $at->id));
1360 return $links;
1363 // Methods for processing ==================================================
1366 * Check this attempt, to see if there are any state transitions that should
1367 * happen automatically. This function will update the attempt checkstatetime.
1368 * @param int $timestamp the timestamp that should be stored as the modifed
1369 * @param bool $studentisonline is the student currently interacting with Moodle?
1371 public function handle_if_time_expired($timestamp, $studentisonline) {
1372 global $DB;
1374 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt);
1376 if ($timeclose === false || $this->is_preview()) {
1377 $this->update_timecheckstate(null);
1378 return; // No time limit
1380 if ($timestamp < $timeclose) {
1381 $this->update_timecheckstate($timeclose);
1382 return; // Time has not yet expired.
1385 // If the attempt is already overdue, look to see if it should be abandoned ...
1386 if ($this->attempt->state == self::OVERDUE) {
1387 $timeoverdue = $timestamp - $timeclose;
1388 $graceperiod = $this->quizobj->get_quiz()->graceperiod;
1389 if ($timeoverdue >= $graceperiod) {
1390 $this->process_abandon($timestamp, $studentisonline);
1391 } else {
1392 // Overdue time has not yet expired
1393 $this->update_timecheckstate($timeclose + $graceperiod);
1395 return; // ... and we are done.
1398 if ($this->attempt->state != self::IN_PROGRESS) {
1399 $this->update_timecheckstate(null);
1400 return; // Attempt is already in a final state.
1403 // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired.
1404 // Transition to the appropriate state.
1405 switch ($this->quizobj->get_quiz()->overduehandling) {
1406 case 'autosubmit':
1407 $this->process_finish($timestamp, false);
1408 return;
1410 case 'graceperiod':
1411 $this->process_going_overdue($timestamp, $studentisonline);
1412 return;
1414 case 'autoabandon':
1415 $this->process_abandon($timestamp, $studentisonline);
1416 return;
1419 // This is an overdue attempt with no overdue handling defined, so just abandon.
1420 $this->process_abandon($timestamp, $studentisonline);
1421 return;
1425 * Process all the actions that were submitted as part of the current request.
1427 * @param int $timestamp the timestamp that should be stored as the modifed
1428 * time in the database for these actions. If null, will use the current time.
1429 * @param bool $becomingoverdue
1430 * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data, keys are slot
1431 * nos and values are arrays representing student responses which will be passed to
1432 * question_definition::prepare_simulated_post_data method and then have the
1433 * appropriate prefix added.
1435 public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) {
1436 global $DB;
1438 $transaction = $DB->start_delegated_transaction();
1440 if ($simulatedresponses !== null) {
1441 $simulatedpostdata = $this->quba->prepare_simulated_post_data($simulatedresponses);
1442 } else {
1443 $simulatedpostdata = null;
1446 $this->quba->process_all_actions($timestamp, $simulatedpostdata);
1447 question_engine::save_questions_usage_by_activity($this->quba);
1449 $this->attempt->timemodified = $timestamp;
1450 if ($this->attempt->state == self::FINISHED) {
1451 $this->attempt->sumgrades = $this->quba->get_total_mark();
1453 if ($becomingoverdue) {
1454 $this->process_going_overdue($timestamp, true);
1455 } else {
1456 $DB->update_record('quiz_attempts', $this->attempt);
1459 if (!$this->is_preview() && $this->attempt->state == self::FINISHED) {
1460 quiz_save_best_grade($this->get_quiz(), $this->get_userid());
1463 $transaction->allow_commit();
1467 * Process all the autosaved data that was part of the current request.
1469 * @param int $timestamp the timestamp that should be stored as the modifed
1470 * time in the database for these actions. If null, will use the current time.
1472 public function process_auto_save($timestamp) {
1473 global $DB;
1475 $transaction = $DB->start_delegated_transaction();
1477 $this->quba->process_all_autosaves($timestamp);
1478 question_engine::save_questions_usage_by_activity($this->quba);
1480 $transaction->allow_commit();
1484 * Update the flagged state for all question_attempts in this usage, if their
1485 * flagged state was changed in the request.
1487 public function save_question_flags() {
1488 global $DB;
1490 $transaction = $DB->start_delegated_transaction();
1491 $this->quba->update_question_flags();
1492 question_engine::save_questions_usage_by_activity($this->quba);
1493 $transaction->allow_commit();
1496 public function process_finish($timestamp, $processsubmitted) {
1497 global $DB;
1499 $transaction = $DB->start_delegated_transaction();
1501 if ($processsubmitted) {
1502 $this->quba->process_all_actions($timestamp);
1504 $this->quba->finish_all_questions($timestamp);
1506 question_engine::save_questions_usage_by_activity($this->quba);
1508 $this->attempt->timemodified = $timestamp;
1509 $this->attempt->timefinish = $timestamp;
1510 $this->attempt->sumgrades = $this->quba->get_total_mark();
1511 $this->attempt->state = self::FINISHED;
1512 $this->attempt->timecheckstate = null;
1513 $DB->update_record('quiz_attempts', $this->attempt);
1515 if (!$this->is_preview()) {
1516 quiz_save_best_grade($this->get_quiz(), $this->attempt->userid);
1518 // Trigger event.
1519 $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp);
1521 // Tell any access rules that care that the attempt is over.
1522 $this->get_access_manager($timestamp)->current_attempt_finished();
1525 $transaction->allow_commit();
1529 * Update this attempt timecheckstate if necessary.
1530 * @param int|null the timecheckstate
1532 public function update_timecheckstate($time) {
1533 global $DB;
1534 if ($this->attempt->timecheckstate !== $time) {
1535 $this->attempt->timecheckstate = $time;
1536 $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id'=>$this->attempt->id));
1541 * Mark this attempt as now overdue.
1542 * @param int $timestamp the time to deem as now.
1543 * @param bool $studentisonline is the student currently interacting with Moodle?
1545 public function process_going_overdue($timestamp, $studentisonline) {
1546 global $DB;
1548 $transaction = $DB->start_delegated_transaction();
1549 $this->attempt->timemodified = $timestamp;
1550 $this->attempt->state = self::OVERDUE;
1551 // If we knew the attempt close time, we could compute when the graceperiod ends.
1552 // Instead we'll just fix it up through cron.
1553 $this->attempt->timecheckstate = $timestamp;
1554 $DB->update_record('quiz_attempts', $this->attempt);
1556 $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp);
1558 $transaction->allow_commit();
1560 quiz_send_overdue_message($this);
1564 * Mark this attempt as abandoned.
1565 * @param int $timestamp the time to deem as now.
1566 * @param bool $studentisonline is the student currently interacting with Moodle?
1568 public function process_abandon($timestamp, $studentisonline) {
1569 global $DB;
1571 $transaction = $DB->start_delegated_transaction();
1572 $this->attempt->timemodified = $timestamp;
1573 $this->attempt->state = self::ABANDONED;
1574 $this->attempt->timecheckstate = null;
1575 $DB->update_record('quiz_attempts', $this->attempt);
1577 $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp);
1579 $transaction->allow_commit();
1583 * Fire a state transition event.
1584 * the same event information.
1585 * @param string $eventclass the event class name.
1586 * @param int $timestamp the timestamp to include in the event.
1587 * @return void
1589 protected function fire_state_transition_event($eventclass, $timestamp) {
1590 global $USER;
1591 $quizrecord = $this->get_quiz();
1592 $params = array(
1593 'context' => $this->get_quizobj()->get_context(),
1594 'courseid' => $this->get_courseid(),
1595 'objectid' => $this->attempt->id,
1596 'relateduserid' => $this->attempt->userid,
1597 'other' => array(
1598 'submitterid' => CLI_SCRIPT ? null : $USER->id,
1599 'quizid' => $quizrecord->id
1603 $event = $eventclass::create($params);
1604 $event->add_record_snapshot('quiz', $this->get_quiz());
1605 $event->add_record_snapshot('quiz_attempts', $this->get_attempt());
1606 $event->trigger();
1610 * Print the fields of the comment form for questions in this attempt.
1611 * @param $slot which question to output the fields for.
1612 * @param $prefix Prefix to add to all field names.
1614 public function question_print_comment_fields($slot, $prefix) {
1615 // Work out a nice title.
1616 $student = get_record('user', 'id', $this->get_userid());
1617 $a = new object();
1618 $a->fullname = fullname($student, true);
1619 $a->attempt = $this->get_attempt_number();
1621 question_print_comment_fields($this->quba->get_question_attempt($slot),
1622 $prefix, $this->get_display_options(true)->markdp,
1623 get_string('gradingattempt', 'quiz_grading', $a));
1626 // Private methods =========================================================
1629 * Get a URL for a particular question on a particular page of the quiz.
1630 * Used by {@link attempt_url()} and {@link review_url()}.
1632 * @param string $script. Used in the URL like /mod/quiz/$script.php
1633 * @param int $slot identifies the specific question on the page to jump to.
1634 * 0 to just use the $page parameter.
1635 * @param int $page -1 to look up the page number from the slot, otherwise
1636 * the page number to go to.
1637 * @param bool|null $showall if true, return a URL with showall=1, and not page number.
1638 * if null, then an intelligent default will be chosen.
1639 * @param int $thispage the page we are currently on. Links to questions on this
1640 * page will just be a fragment #q123. -1 to disable this.
1641 * @return The requested URL.
1643 protected function page_and_question_url($script, $slot, $page, $showall, $thispage) {
1645 $defaultshowall = $this->get_default_show_all($script);
1646 if ($showall === null && ($page == 0 || $page == -1)) {
1647 $showall = $defaultshowall;
1650 // Fix up $page.
1651 if ($page == -1) {
1652 if ($slot !== null && !$showall) {
1653 $page = $this->get_question_page($slot);
1654 } else {
1655 $page = 0;
1659 if ($showall) {
1660 $page = 0;
1663 // Add a fragment to scroll down to the question.
1664 $fragment = '';
1665 if ($slot !== null) {
1666 if ($slot == reset($this->pagelayout[$page])) {
1667 // First question on page, go to top.
1668 $fragment = '#';
1669 } else {
1670 $fragment = '#q' . $slot;
1674 // Work out the correct start to the URL.
1675 if ($thispage == $page) {
1676 return new moodle_url($fragment);
1678 } else {
1679 $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment,
1680 array('attempt' => $this->attempt->id));
1681 if ($page == 0 && $showall != $defaultshowall) {
1682 $url->param('showall', (int) $showall);
1683 } else if ($page > 0) {
1684 $url->param('page', $page);
1686 return $url;
1693 * Represents a single link in the navigation panel.
1695 * @copyright 2011 The Open University
1696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1697 * @since Moodle 2.1
1699 class quiz_nav_question_button implements renderable {
1700 /** @var string id="..." to add to the HTML for this button. */
1701 public $id;
1702 /** @var string number to display in this button. Either the question number of 'i'. */
1703 public $number;
1704 /** @var string class to add to the class="" attribute to represnt the question state. */
1705 public $stateclass;
1706 /** @var string Textual description of the question state, e.g. to use as a tool tip. */
1707 public $statestring;
1708 /** @var int the page number this question is on. */
1709 public $page;
1710 /** @var bool true if this question is on the current page. */
1711 public $currentpage;
1712 /** @var bool true if this question has been flagged. */
1713 public $flagged;
1714 /** @var moodle_url the link this button goes to, or null if there should not be a link. */
1715 public $url;
1720 * Represents the navigation panel, and builds a {@link block_contents} to allow
1721 * it to be output.
1723 * @copyright 2008 Tim Hunt
1724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1725 * @since Moodle 2.0
1727 abstract class quiz_nav_panel_base {
1728 /** @var quiz_attempt */
1729 protected $attemptobj;
1730 /** @var question_display_options */
1731 protected $options;
1732 /** @var integer */
1733 protected $page;
1734 /** @var boolean */
1735 protected $showall;
1737 public function __construct(quiz_attempt $attemptobj,
1738 question_display_options $options, $page, $showall) {
1739 $this->attemptobj = $attemptobj;
1740 $this->options = $options;
1741 $this->page = $page;
1742 $this->showall = $showall;
1745 public function get_question_buttons() {
1746 $buttons = array();
1747 foreach ($this->attemptobj->get_slots() as $slot) {
1748 $qa = $this->attemptobj->get_question_attempt($slot);
1749 $showcorrectness = $this->options->correctness && $qa->has_marks();
1751 $button = new quiz_nav_question_button();
1752 $button->id = 'quiznavbutton' . $slot;
1753 $button->number = $this->attemptobj->get_question_number($slot);
1754 $button->stateclass = $qa->get_state_class($showcorrectness);
1755 $button->navmethod = $this->attemptobj->get_navigation_method();
1756 if (!$showcorrectness && $button->stateclass == 'notanswered') {
1757 $button->stateclass = 'complete';
1759 $button->statestring = $this->get_state_string($qa, $showcorrectness);
1760 $button->page = $this->attemptobj->get_question_page($slot);
1761 $button->currentpage = $this->showall || $button->page == $this->page;
1762 $button->flagged = $qa->is_flagged();
1763 $button->url = $this->get_question_url($slot);
1764 $buttons[] = $button;
1767 return $buttons;
1770 protected function get_state_string(question_attempt $qa, $showcorrectness) {
1771 if ($qa->get_question()->length > 0) {
1772 return $qa->get_state_string($showcorrectness);
1775 // Special case handling for 'information' items.
1776 if ($qa->get_state() == question_state::$todo) {
1777 return get_string('notyetviewed', 'quiz');
1778 } else {
1779 return get_string('viewed', 'quiz');
1783 public function render_before_button_bits(mod_quiz_renderer $output) {
1784 return '';
1787 abstract public function render_end_bits(mod_quiz_renderer $output);
1789 protected function render_restart_preview_link($output) {
1790 if (!$this->attemptobj->is_own_preview()) {
1791 return '';
1793 return $output->restart_preview_button(new moodle_url(
1794 $this->attemptobj->start_attempt_url(), array('forcenew' => true)));
1797 protected abstract function get_question_url($slot);
1799 public function user_picture() {
1800 global $DB;
1801 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_NONE) {
1802 return null;
1804 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid()));
1805 $userpicture = new user_picture($user);
1806 $userpicture->courseid = $this->attemptobj->get_courseid();
1807 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_LARGE) {
1808 $userpicture->size = true;
1810 return $userpicture;
1814 * Return 'allquestionsononepage' as CSS class name when $showall is set,
1815 * otherwise, return 'multipages' as CSS class name.
1816 * @return string, CSS class name
1818 public function get_button_container_class() {
1819 // Quiz navigation is set on 'Show all questions on one page'.
1820 if ($this->showall) {
1821 return 'allquestionsononepage';
1823 // Quiz navigation is set on 'Show one page at a time'.
1824 return 'multipages';
1830 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page.
1832 * @copyright 2008 Tim Hunt
1833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1834 * @since Moodle 2.0
1836 class quiz_attempt_nav_panel extends quiz_nav_panel_base {
1837 public function get_question_url($slot) {
1838 if ($this->attemptobj->can_navigate_to($slot)) {
1839 return $this->attemptobj->attempt_url($slot, -1, $this->page);
1840 } else {
1841 return null;
1845 public function render_before_button_bits(mod_quiz_renderer $output) {
1846 return html_writer::tag('div', get_string('navnojswarning', 'quiz'),
1847 array('id' => 'quiznojswarning'));
1850 public function render_end_bits(mod_quiz_renderer $output) {
1851 return html_writer::link($this->attemptobj->summary_url(),
1852 get_string('endtest', 'quiz'), array('class' => 'endtestlink')) .
1853 $output->countdown_timer($this->attemptobj, time()) .
1854 $this->render_restart_preview_link($output);
1860 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page.
1862 * @copyright 2008 Tim Hunt
1863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1864 * @since Moodle 2.0
1866 class quiz_review_nav_panel extends quiz_nav_panel_base {
1867 public function get_question_url($slot) {
1868 return $this->attemptobj->review_url($slot, -1, $this->showall, $this->page);
1871 public function render_end_bits(mod_quiz_renderer $output) {
1872 $html = '';
1873 if ($this->attemptobj->get_num_pages() > 1) {
1874 if ($this->showall) {
1875 $html .= html_writer::link($this->attemptobj->review_url(null, 0, false),
1876 get_string('showeachpage', 'quiz'));
1877 } else {
1878 $html .= html_writer::link($this->attemptobj->review_url(null, 0, true),
1879 get_string('showall', 'quiz'));
1882 $html .= $output->finish_review_link($this->attemptobj);
1883 $html .= $this->render_restart_preview_link($output);
1884 return $html;