3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Back-end code for handling data about quizzes and the current user's attempt.
21 * There are classes for loading all the information about a quiz and attempts,
22 * and for displaying the navigation panel.
25 * @copyright 2008 onwards Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 * Class for quiz exceptions. Just saves a couple of arguments on the
32 * constructor for a moodle_exception.
34 * @copyright 2008 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class moodle_quiz_exception extends moodle_exception {
39 function __construct($quizobj, $errorcode, $a = NULL, $link = '', $debuginfo = null) {
41 $link = $quizobj->view_url();
43 parent::__construct($errorcode, 'quiz', $link, $a, $debuginfo);
48 * A class encapsulating a quiz and the questions it contains, and making the
49 * information available to scripts like view.php.
51 * Initially, it only loads a minimal amout of information about each question - loading
52 * extra information only when necessary or when asked. The class tracks which questions
55 * @copyright 2008 Tim Hunt
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 // Fields initialised in the constructor.
65 protected $questionids; // All question ids in order that they appear in the quiz.
66 protected $pagequestionids; // array page no => array of questionids on the page in order.
68 // Fields set later if that data is needed.
69 protected $questions = null;
70 protected $accessmanager = null;
71 protected $ispreviewuser = null;
73 // Constructor =========================================================================
75 * Constructor, assuming we already have the necessary data loaded.
77 * @param object $quiz the row from the quiz table.
78 * @param object $cm the course_module object for this quiz.
79 * @param object $course the row from the course table for the course we belong to.
80 * @param boolean $getcontext intended for testing - stops the constructor getting the context.
82 function __construct($quiz, $cm, $course, $getcontext = true) {
85 $this->quiz->cmid = $this->cm->id;
86 $this->course = $course;
87 if ($getcontext && !empty($cm->id)) {
88 $this->context = get_context_instance(CONTEXT_MODULE, $cm->id);
90 $this->determine_layout();
94 * Static function to create a new quiz object for a specific user.
96 * @param integer $quizid the the quiz id.
97 * @param integer $userid the the userid.
98 * @return quiz the new quiz object
100 static public function create($quizid, $userid) {
103 if (!$quiz = $DB->get_record('quiz', array('id' => $quizid))) {
104 throw new moodle_exception('invalidquizid', 'quiz');
106 if (!$course = $DB->get_record('course', array('id' => $quiz->course))) {
107 throw new moodle_exception('invalidcoursemodule');
109 if (!$cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id)) {
110 throw new moodle_exception('invalidcoursemodule');
113 // Update quiz with override information
114 $quiz = quiz_update_effective_access($quiz, $userid);
116 return new quiz($quiz, $cm, $course);
119 // Functions for loading more data =====================================================
121 * Convenience method. Calls {@link load_questions()} with the list of
122 * question ids for a given page.
124 * @param integer $page a page number.
126 public function load_questions_on_page($page) {
127 $this->load_questions($this->pagequestionids[$page]);
131 * Load just basic information about all the questions in this quiz.
133 public function preload_questions() {
134 if (empty($this->questionids)) {
135 throw new moodle_quiz_exception($this, 'noquestions', $this->edit_url());
137 $this->questions = question_preload_questions($this->questionids,
138 'qqi.grade AS maxgrade, qqi.id AS instance',
139 '{quiz_question_instances} qqi ON qqi.quiz = :quizid AND q.id = qqi.question',
140 array('quizid' => $this->quiz->id));
141 $this->number_questions();
145 * Fully load some or all of the questions for this quiz. You must call {@link preload_questions()} first.
147 * @param array $questionids question ids of the questions to load. null for all.
149 public function load_questions($questionids = null) {
150 if (is_null($questionids)) {
151 $questionids = $this->questionids;
153 $questionstoprocess = array();
154 foreach ($questionids as $id) {
155 $questionstoprocess[$id] = $this->questions[$id];
157 if (!get_question_options($questionstoprocess)) {
158 throw new moodle_quiz_exception($this, 'loadingquestionsfailed', implode(', ', $questionids));
162 // Simple getters ======================================================================
163 /** @return integer the course id. */
164 public function get_courseid() {
165 return $this->course->id;
168 /** @return object the row of the course table. */
169 public function get_course() {
170 return $this->course;
173 /** @return integer the quiz id. */
174 public function get_quizid() {
175 return $this->quiz->id;
178 /** @return object the row of the quiz table. */
179 public function get_quiz() {
183 /** @return string the name of this quiz. */
184 public function get_quiz_name() {
185 return $this->quiz->name;
188 /** @return integer the number of attempts allowed at this quiz (0 = infinite). */
189 public function get_num_attempts_allowed() {
190 return $this->quiz->attempts;
193 /** @return integer the course_module id. */
194 public function get_cmid() {
195 return $this->cm->id;
198 /** @return object the course_module object. */
199 public function get_cm() {
204 * @return boolean wether the current user is someone who previews the quiz,
205 * rather than attempting it.
207 public function is_preview_user() {
208 if (is_null($this->ispreviewuser)) {
209 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context);
211 return $this->ispreviewuser;
215 * @return integer number fo pages in this quiz.
217 public function get_num_pages() {
218 return count($this->pagequestionids);
223 * @param int $page page number
224 * @return boolean true if this is the last page of the quiz.
226 public function is_last_page($page) {
227 return $page == count($this->pagequestionids) - 1;
231 * @param integer $id the question id.
232 * @return object the question object with that id.
234 public function get_question($id) {
235 return $this->questions[$id];
239 * @param array $questionids question ids of the questions to load. null for all.
241 public function get_questions($questionids = null) {
242 if (is_null($questionids)) {
243 $questionids = $this->questionids;
245 $questions = array();
246 foreach ($questionids as $id) {
247 $questions[$id] = $this->questions[$id];
248 $this->ensure_question_loaded($id);
254 * Return the list of question ids for either a given page of the quiz, or for the
257 * @param mixed $page string 'all' or integer page number.
258 * @return array the reqested list of question ids.
260 public function get_question_ids($page = 'all') {
261 if ($page === 'all') {
262 $list = $this->questionids;
264 $list = $this->pagequestionids[$page];
266 // Clone the array, so our private arrays cannot be modified.
268 foreach ($list as $id) {
275 * @param integer $timenow the current time as a unix timestamp.
276 * @return quiz_access_manager and instance of the quiz_access_manager class for this quiz at this time.
278 public function get_access_manager($timenow) {
279 if (is_null($this->accessmanager)) {
280 $this->accessmanager = new quiz_access_manager($this, $timenow,
281 has_capability('mod/quiz:ignoretimelimits', $this->context, NULL, false));
283 return $this->accessmanager;
286 public function get_overall_feedback($grade) {
287 return quiz_feedback_for_grade($grade, $this->quiz, $this->context, $this->cm);
291 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
293 public function has_capability($capability, $userid = NULL, $doanything = true) {
294 return has_capability($capability, $this->context, $userid, $doanything);
298 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
300 public function require_capability($capability, $userid = NULL, $doanything = true) {
301 return require_capability($capability, $this->context, $userid, $doanything);
304 // URLs related to this attempt ========================================================
306 * @return string the URL of this quiz's view page.
308 public function view_url() {
310 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id;
314 * @return string the URL of this quiz's edit page.
316 public function edit_url() {
318 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id;
322 * @param integer $attemptid the id of an attempt.
323 * @return string the URL of that attempt.
325 public function attempt_url($attemptid) {
327 return $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid;
331 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
333 public function start_attempt_url() {
334 return new moodle_url('/mod/quiz/startattempt.php',
335 array('cmid' => $this->cm->id, 'sesskey' => sesskey()));
339 * @param integer $attemptid the id of an attempt.
340 * @return string the URL of the review of that attempt.
342 public function review_url($attemptid) {
343 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid));
346 // Bits of content =====================================================================
349 * @param string $title the name of this particular quiz page.
350 * @return array the data that needs to be sent to print_header_simple as the $navigation
353 public function navigation($title) {
355 $PAGE->navbar->add($title);
359 // Private methods =====================================================================
361 * Check that the definition of a particular question is loaded, and if not throw an exception.
362 * @param $id a questionid.
364 protected function ensure_question_loaded($id) {
365 if (isset($this->questions[$id]->_partiallyloaded)) {
366 throw new moodle_quiz_exception($this, 'questionnotloaded', $id);
371 * Populate {@link $questionids} and {@link $pagequestionids} from the layout.
373 protected function determine_layout() {
374 $this->questionids = array();
375 $this->pagequestionids = array();
377 // Get the appropriate layout string (from quiz or attempt).
378 $layout = quiz_clean_layout($this->get_layout_string(), true);
379 if (empty($layout)) {
384 // Break up the layout string into pages.
385 $pagelayouts = explode(',0', $layout);
387 // Strip off any empty last page (normally there is one).
388 if (end($pagelayouts) == '') {
389 array_pop($pagelayouts);
392 // File the ids into the arrays.
393 $this->questionids = array();
394 $this->pagequestionids = array();
395 foreach ($pagelayouts as $page => $pagelayout) {
396 $pagelayout = trim($pagelayout, ',');
397 if ($pagelayout == '') continue;
398 $this->pagequestionids[$page] = explode(',', $pagelayout);
399 foreach ($this->pagequestionids[$page] as $id) {
400 $this->questionids[] = $id;
406 * Number the questions, adding a _number field to each one.
408 private function number_questions() {
410 foreach ($this->pagequestionids as $page => $questionids) {
411 foreach ($questionids as $id) {
412 if ($this->questions[$id]->length > 0) {
413 $this->questions[$id]->_number = $number;
414 $number += $this->questions[$id]->length;
416 $this->questions[$id]->_number = get_string('infoshort', 'quiz');
418 $this->questions[$id]->_page = $page;
424 * @return string the layout of this quiz. Used by number_questions to
425 * work out which questions are on which pages.
427 protected function get_layout_string() {
428 return $this->quiz->questions;
433 * This class extends the quiz class to hold data about the state of a particular attempt,
434 * in addition to the data about the quiz.
436 * @copyright 2008 Tim Hunt
437 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
440 class quiz_attempt extends quiz {
441 // Fields initialised in the constructor.
444 // Fields set later if that data is needed.
445 protected $states = array();
446 protected $reviewoptions = null;
448 // Constructor =========================================================================
450 * Constructor assuming we already have the necessary data loaded.
452 * @param object $attempt the row of the quiz_attempts table.
453 * @param object $quiz the quiz object for this attempt and user.
454 * @param object $cm the course_module object for this quiz.
455 * @param object $course the row from the course table for the course we belong to.
457 function __construct($attempt, $quiz, $cm, $course) {
458 $this->attempt = $attempt;
459 parent::__construct($quiz, $cm, $course);
460 $this->preload_questions();
461 $this->preload_question_states();
465 * Static function to create a new quiz_attempt object given an attemptid.
467 * @param integer $attemptid the attempt id.
468 * @return quiz_attempt the new quiz_attempt object
470 static public function create($attemptid) {
473 if (!$attempt = quiz_load_attempt($attemptid)) {
474 throw new moodle_exception('invalidattemptid', 'quiz');
476 if (!$quiz = $DB->get_record('quiz', array('id' => $attempt->quiz))) {
477 throw new moodle_exception('invalidquizid', 'quiz');
479 if (!$course = $DB->get_record('course', array('id' => $quiz->course))) {
480 throw new moodle_exception('invalidcoursemodule');
482 if (!$cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id)) {
483 throw new moodle_exception('invalidcoursemodule');
485 // Update quiz with override information
486 $quiz = quiz_update_effective_access($quiz, $attempt->userid);
488 return new quiz_attempt($attempt, $quiz, $cm, $course);
491 // Functions for loading more data =====================================================
493 * Load the state of a number of questions that have already been loaded.
495 * @param array $questionids question ids to process. Blank = all.
497 public function load_question_states($questionids = null) {
498 if (is_null($questionids)) {
499 $questionids = $this->questionids;
501 $questionstoprocess = array();
502 foreach ($questionids as $id) {
503 $this->ensure_question_loaded($id);
504 $questionstoprocess[$id] = $this->questions[$id];
506 if (!question_load_states($questionstoprocess, $this->states,
507 $this->quiz, $this->attempt)) {
508 throw new moodle_quiz_exception($this, 'cannotrestore');
513 * Load basic information about the state of each question.
515 * This is enough to, for example, show the state of each question in the
516 * navigation panel, but only takes one DB query.
518 public function preload_question_states() {
519 if (empty($this->questionids)) {
520 throw new moodle_quiz_exception($this, 'noquestions', $this->edit_url());
522 $this->states = question_preload_states($this->attempt->uniqueid);
523 if (!$this->states) {
524 $this->states = array();
529 * Load a particular state of a particular question. Used by the reviewquestion.php
530 * script to let the teacher walk through the entire sequence of a student's
531 * interaction with a question.
533 * @param $questionid the question id
534 * @param $stateid the id of the particular state to load.
536 public function load_specific_question_state($questionid, $stateid) {
538 $state = question_load_specific_state($this->questions[$questionid],
539 $this->quiz, $this->attempt->uniqueid, $stateid);
540 if ($state === false) {
541 throw new moodle_quiz_exception($this, 'invalidstateid');
543 $this->states[$questionid] = $state;
546 // Simple getters ======================================================================
547 /** @return integer the attempt id. */
548 public function get_attemptid() {
549 return $this->attempt->id;
552 /** @return integer the attempt unique id. */
553 public function get_uniqueid() {
554 return $this->attempt->uniqueid;
557 /** @return object the row from the quiz_attempts table. */
558 public function get_attempt() {
559 return $this->attempt;
562 /** @return integer the number of this attemp (is it this user's first, second, ... attempt). */
563 public function get_attempt_number() {
564 return $this->attempt->attempt;
567 /** @return integer the id of the user this attempt belongs to. */
568 public function get_userid() {
569 return $this->attempt->userid;
572 /** @return boolean whether this attempt has been finished (true) or is still in progress (false). */
573 public function is_finished() {
574 return $this->attempt->timefinish != 0;
577 /** @return boolean whether this attempt is a preview attempt. */
578 public function is_preview() {
579 return $this->attempt->preview;
583 * Is this a student dealing with their own attempt/teacher previewing,
584 * or someone with 'mod/quiz:viewreports' reviewing someone elses attempt.
586 * @return boolean whether this situation should be treated as someone looking at their own
587 * attempt. The distinction normally only matters when an attempt is being reviewed.
589 public function is_own_attempt() {
591 return $this->attempt->userid == $USER->id &&
592 (!$this->is_preview_user() || $this->attempt->preview);
596 * Check the appropriate capability to see whether this user may review their own attempt.
597 * If not, prints an error.
599 public function check_review_capability() {
600 if (!$this->has_capability('mod/quiz:viewreports')) {
601 if ($this->get_review_options()->quizstate == QUIZ_STATE_IMMEDIATELY) {
602 $this->require_capability('mod/quiz:attempt');
604 $this->require_capability('mod/quiz:reviewmyattempts');
610 * Get the current state of a question in the attempt.
612 * @param $questionid a questionid.
613 * @return object the state.
615 public function get_question_state($questionid) {
616 return $this->states[$questionid];
620 * Wrapper that calls quiz_get_reviewoptions with the appropriate arguments.
622 * @return object the review options for this user on this attempt.
624 public function get_review_options() {
625 if (is_null($this->reviewoptions)) {
626 $this->reviewoptions = quiz_get_reviewoptions($this->quiz, $this->attempt, $this->context);
628 return $this->reviewoptions;
632 * Wrapper that calls get_render_options with the appropriate arguments.
634 * @param integer questionid the quetsion to get the render options for.
635 * @return object the render options for this user on this attempt.
637 public function get_render_options($questionid) {
638 return quiz_get_renderoptions($this->quiz, $this->attempt, $this->context,
639 $this->get_question_state($questionid));
643 * Get a quiz_attempt_question_iterator for either a page of the quiz, or a whole quiz.
644 * You must have called load_questions with an appropriate argument first.
646 * @param mixed $page as for the @see{get_question_ids} method.
647 * @return quiz_attempt_question_iterator the requested iterator.
649 public function get_question_iterator($page = 'all') {
650 return new quiz_attempt_question_iterator($this, $page);
654 * Return a summary of the current state of a question in this attempt. You must previously
655 * have called load_question_states to load the state data about this question.
657 * @param integer $questionid question id of a question that belongs to this quiz.
658 * @return string a brief string (that could be used as a CSS class name, for example)
659 * that describes the current state of a question in this attempt. Possible results are:
660 * open|saved|closed|correct|partiallycorrect|incorrect.
662 public function get_question_status($questionid) {
663 $state = $this->states[$questionid];
664 switch ($state->event) {
665 case QUESTION_EVENTOPEN:
668 case QUESTION_EVENTSAVE:
669 case QUESTION_EVENTGRADE:
670 case QUESTION_EVENTSUBMIT:
673 case QUESTION_EVENTCLOSEANDGRADE:
674 case QUESTION_EVENTCLOSE:
675 case QUESTION_EVENTMANUALGRADE:
676 $options = $this->get_render_options($questionid);
677 if ($options->scores && $this->questions[$questionid]->maxgrade > 0) {
678 return question_get_feedback_class($state->last_graded->raw_grade /
679 $this->questions[$questionid]->maxgrade);
686 $a->event = $state->event;
687 $a->questionid = $questionid;
688 $a->attemptid = $this->attempt->id;
689 throw new moodle_quiz_exception($this, 'errorunexpectedevent', $a);
694 * @param integer $questionid question id of a question that belongs to this quiz.
695 * @return boolean whether this question hss been flagged by the attempter.
697 public function is_question_flagged($questionid) {
698 $state = $this->states[$questionid];
699 return $state->flagged;
703 * Return the grade obtained on a particular question, if the user is permitted to see it.
704 * You must previously have called load_question_states to load the state data about this question.
706 * @param integer $questionid question id of a question that belongs to this quiz.
707 * @return string the formatted grade, to the number of decimal places specified by the quiz.
709 public function get_question_score($questionid) {
710 $options = $this->get_render_options($questionid);
711 if ($options->scores) {
712 return quiz_format_question_grade($this->quiz, $this->states[$questionid]->last_graded->grade);
718 // URLs related to this attempt ========================================================
720 * @param integer $questionid a question id. If set, will add a fragment to the URL
721 * to jump to a particuar question on the page.
722 * @param integer $page if specified, the URL of this particular page of the attempt, otherwise
723 * the URL will go to the first page. If -1, deduce $page from $questionid.
724 * @param integer $thispage if not -1, the current page. Will cause links to other things on
725 * this page to be output as only a fragment.
726 * @return string the URL to continue this attempt.
728 public function attempt_url($questionid = 0, $page = -1, $thispage = -1) {
729 return $this->page_and_question_url('attempt', $questionid, $page, false, $thispage);
733 * @return string the URL of this quiz's summary page.
735 public function summary_url() {
737 return $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $this->attempt->id;
741 * @return string the URL of this quiz's summary page.
743 public function processattempt_url() {
745 return $CFG->wwwroot . '/mod/quiz/processattempt.php';
749 * @param integer $questionid a question id. If set, will add a fragment to the URL
750 * to jump to a particuar question on the page. If -1, deduce $page from $questionid.
751 * @param integer $page if specified, the URL of this particular page of the attempt, otherwise
752 * the URL will go to the first page.
753 * @param boolean $showall if true, the URL will be to review the entire attempt on one page,
754 * and $page will be ignored.
755 * @param integer $thispage if not -1, the current page. Will cause links to other things on
756 * this page to be output as only a fragment.
757 * @return string the URL to review this attempt.
759 public function review_url($questionid = 0, $page = -1, $showall = false, $thispage = -1) {
760 return $this->page_and_question_url('review', $questionid, $page, $showall, $thispage);
763 // Bits of content =====================================================================
765 * Initialise the JS etc. required all the questions on a page..
766 * @param mixed $page a page number, or 'all'.
768 public function get_html_head_contributions($page = 'all') {
770 question_get_html_head_contributions($this->get_question_ids($page), $this->questions, $this->states);
774 * Initialise the JS etc. required by one question.
775 * @param integer $questionid the question id.
777 public function get_question_html_head_contributions($questionid) {
778 question_get_html_head_contributions(array($questionid), $this->questions, $this->states);
782 * Print the HTML for the start new preview button.
784 public function print_restart_preview_button() {
785 global $CFG, $OUTPUT;
786 echo $OUTPUT->container_start('controls');
787 $url = new moodle_url($this->start_attempt_url(), array('forcenew' => true));
788 echo $OUTPUT->single_button($url, get_string('startagain', 'quiz'));
789 echo $OUTPUT->container_end();
793 * Return the HTML of the quiz timer.
794 * @return string HTML content.
796 public function get_timer_html() {
797 return '<div id="quiz-timer">' . get_string('timeleft', 'quiz') .
798 ' <span id="quiz-time-left"></span></div>';
802 * Wrapper round print_question from lib/questionlib.php.
804 * @param integer $id the id of a question in this quiz attempt.
805 * @param boolean $reviewing is the being printed on an attempt or a review page.
806 * @param string $thispageurl the URL of the page this question is being printed on.
808 public function print_question($id, $reviewing, $thispageurl = '') {
812 $options = $this->get_review_options();
814 $options = $this->get_render_options($id);
816 if ($thispageurl instanceof moodle_url) {
817 $thispageurl = $thispageurl->out(false);
820 $this->quiz->thispageurl = str_replace($CFG->wwwroot, '', $thispageurl);
824 print_question($this->questions[$id], $this->states[$id], $this->questions[$id]->_number,
825 $this->quiz, $options);
828 public function check_file_access($questionid, $isreviewing, $contextid, $component,
829 $filearea, $args, $forcedownload) {
831 $options = $this->get_review_options();
833 $options = $this->get_render_options($questionid);
835 // XXX: mulitichoice type needs quiz id to get maxgrade
836 $options->quizid = $this->attempt->quiz;
837 return question_check_file_access($this->questions[$questionid],
838 $this->get_question_state($questionid), $options, $contextid,
839 $component, $filearea, $args, $forcedownload);
843 * Triggers the sending of the notification emails at the end of this attempt.
845 public function quiz_send_notification_emails() {
846 quiz_send_notification_emails($this->course, $this->quiz, $this->attempt,
847 $this->context, $this->cm);
851 * Get the navigation panel object for this attempt.
853 * @param $panelclass The type of panel, quiz_attempt_nav_panel or quiz_review_nav_panel
854 * @param $page the current page number.
855 * @param $showall whether we are showing the whole quiz on one page. (Used by review.php)
856 * @return quiz_nav_panel_base the requested object.
858 public function get_navigation_panel($panelclass, $page, $showall = false) {
859 $panel = new $panelclass($this, $this->get_review_options(), $page, $showall);
860 return $panel->get_contents();
864 * Given a URL containing attempt={this attempt id}, return an array of variant URLs
866 * @return string HTML fragment. Comma-separated list of links to the other
867 * attempts with the attempt number as the link text. The curent attempt is
868 * included but is not a link.
870 public function links_to_other_attempts($url) {
871 $search = '/\battempt=' . $this->attempt->id . '\b/';
872 $attempts = quiz_get_user_attempts($this->quiz->id, $this->attempt->userid, 'all');
873 if (count($attempts) <= 1) {
876 $attemptlist = array();
877 foreach ($attempts as $at) {
878 if ($at->id == $this->attempt->id) {
879 $attemptlist[] = '<strong>' . $at->attempt . '</strong>';
881 $changedurl = preg_replace($search, 'attempt=' . $at->id, $url);
882 $attemptlist[] = '<a href="' . s($changedurl) . '">' . $at->attempt . '</a>';
885 return implode(', ', $attemptlist);
888 // Methods for processing manual comments ==============================================
890 * Process a manual comment for a question in this attempt.
892 * @param integer $questionid the question id
893 * @param string $comment the new comment from the teacher.
894 * @param mixed $grade the grade the teacher assigned, or '' to not change the grade.
895 * @return mixed true on success, a string error message if a problem is detected
896 * (for example score out of range).
898 public function process_comment($questionid, $comment, $commentformat, $grade) {
899 // I am not sure it is a good idea to have update methods here - this
900 // class is only about getting data out of the question engine, and
901 // helping to display it, apart from this.
902 $this->ensure_question_loaded($questionid);
903 $this->ensure_state_loaded($questionid);
904 $state = $this->states[$questionid];
906 $error = question_process_comment($this->questions[$questionid],
907 $state, $this->attempt, $comment, $commentformat, $grade);
909 // If the state was update (successfully), save the changes.
910 if (!is_string($error) && $state->changed) {
911 if (!save_question_session($this->questions[$questionid], $state)) {
912 $error = get_string('errorudpatingquestionsession', 'quiz');
914 if (!quiz_save_best_grade($this->quiz, $this->attempt->userid)) {
915 $error = get_string('errorudpatingbestgrade', 'quiz');
922 * Print the fields of the comment form for questions in this attempt.
923 * @param $questionid a question id.
924 * @param $prefix Prefix to add to all field names.
926 public function question_print_comment_fields($questionid, $prefix) {
929 $this->ensure_question_loaded($questionid);
930 $this->ensure_state_loaded($questionid);
932 /// Work out a nice title.
933 $student = $DB->get_record('user', array('id' => $this->get_userid()));
935 $a->fullname = fullname($student, true);
936 $a->attempt = $this->get_attempt_number();
938 question_print_comment_fields($this->questions[$questionid],
939 $this->states[$questionid], $prefix, $this->quiz, get_string('gradingattempt', 'quiz_grading', $a));
942 // Private methods =====================================================================
944 * Check that the state of a particular question is loaded, and if not throw an exception.
945 * @param integer $id a question id.
947 private function ensure_state_loaded($id) {
948 if (!array_key_exists($id, $this->states) || isset($this->states[$id]->_partiallyloaded)) {
949 throw new moodle_quiz_exception($this, 'statenotloaded', $id);
954 * @return string the layout of this quiz. Used by number_questions to
955 * work out which questions are on which pages.
957 protected function get_layout_string() {
958 return $this->attempt->layout;
962 * Get a URL for a particular question on a particular page of the quiz.
963 * Used by {@link attempt_url()} and {@link review_url()}.
965 * @param string $script. Used in the URL like /mod/quiz/$script.php
966 * @param integer $questionid the id of a particular question on the page to jump to. 0 to just use the $page parameter.
967 * @param integer $page -1 to look up the page number from the questionid, otherwise the page number to go to.
968 * @param boolean $showall if true, return a URL with showall=1, and not page number
969 * @param integer $thispage the page we are currently on. Links to questoins on this
970 * page will just be a fragment #q123. -1 to disable this.
971 * @return The requested URL.
973 protected function page_and_question_url($script, $questionid, $page, $showall, $thispage) {
978 if ($questionid && !$showall) {
979 $page = $this->questions[$questionid]->_page;
988 // Work out the correct start to the URL.
989 if ($thispage == $page) {
992 $url = $CFG->wwwroot . '/mod/quiz/' . $script . '.php?attempt=' . $this->attempt->id;
994 $url .= '&showall=1';
995 } else if ($page > 0) {
996 $url .= '&page=' . $page;
1000 // Add a fragment to scroll down to the question.
1002 if ($questionid == reset($this->pagequestionids[$page])) {
1003 // First question on page, go to top.
1006 $url .= '#q' . $questionid;
1015 * A PHP Iterator for conviniently looping over the questions in a quiz. The keys are the question
1016 * numbers (with 'i' for descriptions) and the values are the question objects.
1018 * @copyright 2008 Tim Hunt
1019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1022 class quiz_attempt_question_iterator implements Iterator {
1023 private $attemptobj; // Reference to the quiz_attempt object we provide access to.
1024 private $questionids; // Array of the question ids within that attempt we are iterating over.
1027 * Constructor. Normally, you don't want to call this directly. Instead call
1028 * quiz_attempt::get_question_iterator
1030 * @param quiz_attempt $attemptobj the quiz_attempt object we will be providing access to.
1031 * @param mixed $page as for @see{quiz_attempt::get_question_iterator}.
1033 public function __construct(quiz_attempt $attemptobj, $page = 'all') {
1034 $this->attemptobj = $attemptobj;
1035 $this->questionids = $attemptobj->get_question_ids($page);
1038 // Implementation of the Iterator interface ============================================
1039 public function rewind() {
1040 reset($this->questionids);
1043 public function current() {
1044 $id = current($this->questionids);
1046 return $this->attemptobj->get_question($id);
1052 public function key() {
1053 $id = current($this->questionids);
1055 return $this->attemptobj->get_question($id)->_number;
1061 public function next() {
1062 $id = next($this->questionids);
1064 return $this->attemptobj->get_question($id);
1070 public function valid() {
1071 return $this->current() !== false;
1076 * Represents the navigation panel, and builds a {@link block_contents} to allow
1079 * @copyright 2008 Tim Hunt
1080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1083 abstract class quiz_nav_panel_base {
1084 /** @var quiz_attempt */
1085 protected $attemptobj;
1086 /** @var question_display_options */
1093 public function __construct(quiz_attempt $attemptobj, $options, $page, $showall) {
1094 $this->attemptobj = $attemptobj;
1095 $this->options = $options;
1096 $this->page = $page;
1097 $this->showall = $showall;
1100 protected function get_question_buttons() {
1101 $html = '<div class="qn_buttons">' . "\n";
1102 foreach ($this->attemptobj->get_question_iterator() as $number => $question) {
1103 $html .= $this->get_question_button($number, $question) . "\n";
1105 $html .= "</div>\n";
1109 protected function get_question_button($number, $question) {
1110 $strstate = get_string($this->attemptobj->get_question_status($question->id), 'quiz');
1112 if ($this->attemptobj->is_question_flagged($question->id)) {
1113 $flagstate = get_string('flagged', 'question');
1115 return '<a href="' . s($this->get_question_url($question)) .
1116 '" class="qnbutton ' . $this->get_question_state_classes($question) .
1117 '" id="quiznavbutton' . $question->id . '" title="' . $strstate . '">' .
1118 $number . ' <span class="accesshide"> (' . $strstate . '
1119 <span class="flagstate">' . $flagstate . '</span>)</span></a>';
1122 protected function get_before_button_bits() {
1126 abstract protected function get_end_bits();
1128 abstract protected function get_question_url($question);
1130 protected function get_user_picture() {
1131 global $DB, $OUTPUT;
1132 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid()));
1134 $output .= '<div id="user-picture" class="clearfix">';
1135 $output .= $OUTPUT->user_picture($user, array('courseid'=>$this->attemptobj->get_courseid()));
1136 $output .= ' ' . fullname($user);
1137 $output .= '</div>';
1141 protected function get_question_state_classes($question) {
1142 // The current status of the question.
1143 $classes = $this->attemptobj->get_question_status($question->id);
1145 // Plus a marker for the current page.
1146 if ($this->showall || $question->_page == $this->page) {
1147 $classes .= ' thispage';
1150 // Plus a marker for flagged questions.
1151 if ($this->attemptobj->is_question_flagged($question->id)) {
1152 $classes .= ' flagged';
1157 public function get_contents() {
1159 $PAGE->requires->js_init_call('M.mod_quiz.nav.init', null, false, quiz_get_js_module());
1162 if ($this->attemptobj->get_quiz()->showuserpicture) {
1163 $content .= $this->get_user_picture() . "\n";
1165 $content .= $this->get_before_button_bits();
1166 $content .= $this->get_question_buttons() . "\n";
1167 $content .= '<div class="othernav">' . "\n" . $this->get_end_bits() . "\n</div>\n";
1169 $bc = new block_contents();
1170 $bc->id = 'quiznavigation';
1171 $bc->title = get_string('quiznavigation', 'quiz');
1172 $bc->content = $content;
1178 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page.
1180 * @copyright 2008 Tim Hunt
1181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1184 class quiz_attempt_nav_panel extends quiz_nav_panel_base {
1185 protected function get_question_url($question) {
1186 return $this->attemptobj->attempt_url($question->id, -1, $this->page);
1189 protected function get_before_button_bits() {
1190 return '<div id="quiznojswarning">' . get_string('navnojswarning', 'quiz') . "</div>\n";
1193 protected function get_end_bits() {
1196 $output .= '<a href="' . s($this->attemptobj->summary_url()) . '" class="endtestlink">' . get_string('finishattemptdots', 'quiz') . '</a>';
1197 $output .= $this->attemptobj->get_timer_html();
1203 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page.
1205 * @copyright 2008 Tim Hunt
1206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1209 class quiz_review_nav_panel extends quiz_nav_panel_base {
1210 protected function get_question_url($question) {
1211 return $this->attemptobj->review_url($question->id, -1, $this->showall, $this->page);
1214 protected function get_end_bits() {
1216 if ($this->attemptobj->get_num_pages() > 1) {
1217 if ($this->showall) {
1218 $html .= '<a href="' . s($this->attemptobj->review_url(0, 0, false)) . '">' . get_string('showeachpage', 'quiz') . '</a>';
1220 $html .= '<a href="' . s($this->attemptobj->review_url(0, 0, true)) . '">' . get_string('showall', 'quiz') . '</a>';
1223 $accessmanager = $this->attemptobj->get_access_manager(time());
1224 $html .= $accessmanager->print_finish_review_link($this->attemptobj->is_preview_user(), true);