mod_quiz MDL-26178 it let you try to preview a quiz with several empty pages.
[moodle.git] / mod / quiz / attemptlib.php
CommitLineData
36e413e3 1<?php
d18675a8 2
3// This file is part of Moodle - http://moodle.org/
4//
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.
9//
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.
14//
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/>.
17
36e413e3 18/**
d18675a8 19 * Back-end code for handling data about quizzes and the current user's attempt.
20 *
21 * There are classes for loading all the information about a quiz and attempts,
22 * and for displaying the navigation panel.
23 *
24 * @package quiz
25 * @copyright 2008 onwards Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
36e413e3 28
36e413e3 29
30/**
b10c38a3 31 * Class for quiz exceptions. Just saves a couple of arguments on the
32 * constructor for a moodle_exception.
d18675a8 33 *
34 * @copyright 2008 Tim Hunt
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 * @since Moodle 2.0
36e413e3 37 */
38class moodle_quiz_exception extends moodle_exception {
39 function __construct($quizobj, $errorcode, $a = NULL, $link = '', $debuginfo = null) {
40 if (!$link) {
41 $link = $quizobj->view_url();
42 }
43 parent::__construct($errorcode, 'quiz', $link, $a, $debuginfo);
44 }
45}
46
b10c38a3 47/**
d18675a8 48 * A class encapsulating a quiz and the questions it contains, and making the
49 * information available to scripts like view.php.
50 *
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
53 * are loaded.
54 *
55 * @copyright 2008 Tim Hunt
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 * @since Moodle 2.0
b10c38a3 58 */
36e413e3 59class quiz {
60 // Fields initialised in the constructor.
61 protected $course;
62 protected $cm;
63 protected $quiz;
64 protected $context;
78e7a3dd 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.
7b6757b0 67
36e413e3 68 // Fields set later if that data is needed.
78e7a3dd 69 protected $questions = null;
36e413e3 70 protected $accessmanager = null;
b10c38a3 71 protected $ispreviewuser = null;
36e413e3 72
73 // Constructor =========================================================================
b10c38a3 74 /**
75 * Constructor, assuming we already have the necessary data loaded.
76 *
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.
739b0711 80 * @param boolean $getcontext intended for testing - stops the constructor getting the context.
b10c38a3 81 */
739b0711 82 function __construct($quiz, $cm, $course, $getcontext = true) {
36e413e3 83 $this->quiz = $quiz;
84 $this->cm = $cm;
a18ba12c 85 $this->quiz->cmid = $this->cm->id;
36e413e3 86 $this->course = $course;
739b0711 87 if ($getcontext && !empty($cm->id)) {
88 $this->context = get_context_instance(CONTEXT_MODULE, $cm->id);
89 }
78e7a3dd 90 $this->determine_layout();
36e413e3 91 }
92
990650f9
TH
93 /**
94 * Static function to create a new quiz object for a specific user.
95 *
96 * @param integer $quizid the the quiz id.
97 * @param integer $userid the the userid.
a88ba570 98 * @return quiz the new quiz object
990650f9
TH
99 */
100 static public function create($quizid, $userid) {
101 global $DB;
102
103 if (!$quiz = $DB->get_record('quiz', array('id' => $quizid))) {
104 throw new moodle_exception('invalidquizid', 'quiz');
105 }
106 if (!$course = $DB->get_record('course', array('id' => $quiz->course))) {
107 throw new moodle_exception('invalidcoursemodule');
108 }
109 if (!$cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id)) {
110 throw new moodle_exception('invalidcoursemodule');
111 }
112
113 // Update quiz with override information
114 $quiz = quiz_update_effective_access($quiz, $userid);
115
116 return new quiz($quiz, $cm, $course);
117 }
118
36e413e3 119 // Functions for loading more data =====================================================
d18675a8 120 /**
121 * Convenience method. Calls {@link load_questions()} with the list of
122 * question ids for a given page.
123 *
124 * @param integer $page a page number.
125 */
36e413e3 126 public function load_questions_on_page($page) {
78e7a3dd 127 $this->load_questions($this->pagequestionids[$page]);
128 }
129
d18675a8 130 /**
131 * Load just basic information about all the questions in this quiz.
132 */
78e7a3dd 133 public function preload_questions() {
134 if (empty($this->questionids)) {
135 throw new moodle_quiz_exception($this, 'noquestions', $this->edit_url());
136 }
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();
36e413e3 142 }
143
81d833ad 144 /**
d18675a8 145 * Fully load some or all of the questions for this quiz. You must call {@link preload_questions()} first.
36e413e3 146 *
78e7a3dd 147 * @param array $questionids question ids of the questions to load. null for all.
36e413e3 148 */
78e7a3dd 149 public function load_questions($questionids = null) {
150 if (is_null($questionids)) {
151 $questionids = $this->questionids;
152 }
153 $questionstoprocess = array();
154 foreach ($questionids as $id) {
155 $questionstoprocess[$id] = $this->questions[$id];
36e413e3 156 }
78e7a3dd 157 if (!get_question_options($questionstoprocess)) {
158 throw new moodle_quiz_exception($this, 'loadingquestionsfailed', implode(', ', $questionids));
36e413e3 159 }
36e413e3 160 }
161
162 // Simple getters ======================================================================
b10c38a3 163 /** @return integer the course id. */
36e413e3 164 public function get_courseid() {
165 return $this->course->id;
166 }
167
78e7a3dd 168 /** @return object the row of the course table. */
169 public function get_course() {
170 return $this->course;
171 }
172
b10c38a3 173 /** @return integer the quiz id. */
36e413e3 174 public function get_quizid() {
175 return $this->quiz->id;
176 }
177
b10c38a3 178 /** @return object the row of the quiz table. */
36e413e3 179 public function get_quiz() {
180 return $this->quiz;
181 }
182
b10c38a3 183 /** @return string the name of this quiz. */
36e413e3 184 public function get_quiz_name() {
185 return $this->quiz->name;
186 }
187
b9b3aa94 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;
191 }
192
b10c38a3 193 /** @return integer the course_module id. */
36e413e3 194 public function get_cmid() {
195 return $this->cm->id;
196 }
197
b10c38a3 198 /** @return object the course_module object. */
36e413e3 199 public function get_cm() {
200 return $this->cm;
201 }
202
b10c38a3 203 /**
7b6757b0 204 * @return boolean wether the current user is someone who previews the quiz,
b10c38a3 205 * rather than attempting it.
206 */
207 public function is_preview_user() {
208 if (is_null($this->ispreviewuser)) {
209 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context);
210 }
211 return $this->ispreviewuser;
212 }
213
78e7a3dd 214 /**
215 * @return integer number fo pages in this quiz.
216 */
217 public function get_num_pages() {
218 return count($this->pagequestionids);
219 }
7b6757b0 220
78e7a3dd 221
222 /**
223 * @param int $page page number
224 * @return boolean true if this is the last page of the quiz.
225 */
226 public function is_last_page($page) {
227 return $page == count($this->pagequestionids) - 1;
228 }
229
b10c38a3 230 /**
231 * @param integer $id the question id.
232 * @return object the question object with that id.
233 */
36e413e3 234 public function get_question($id) {
36e413e3 235 return $this->questions[$id];
236 }
237
78e7a3dd 238 /**
239 * @param array $questionids question ids of the questions to load. null for all.
240 */
241 public function get_questions($questionids = null) {
242 if (is_null($questionids)) {
243 $questionids = $this->questionids;
244 }
245 $questions = array();
246 foreach ($questionids as $id) {
247 $questions[$id] = $this->questions[$id];
248 $this->ensure_question_loaded($id);
249 }
250 return $questions;
251 }
252
253 /**
7b6757b0 254 * Return the list of question ids for either a given page of the quiz, or for the
78e7a3dd 255 * whole quiz.
256 *
257 * @param mixed $page string 'all' or integer page number.
258 * @return array the reqested list of question ids.
259 */
260 public function get_question_ids($page = 'all') {
793f3a0e 261 if ($page === 'all') {
78e7a3dd 262 $list = $this->questionids;
263 } else {
e153801c 264 $list = $this->pagequestionids[$page];
78e7a3dd 265 }
266 // Clone the array, so our private arrays cannot be modified.
267 $result = array();
268 foreach ($list as $id) {
269 $result[] = $id;
270 }
271 return $result;
272 }
273
b10c38a3 274 /**
275 * @param integer $timenow the current time as a unix timestamp.
ff065f96 276 * @return quiz_access_manager and instance of the quiz_access_manager class for this quiz at this time.
b10c38a3 277 */
36e413e3 278 public function get_access_manager($timenow) {
279 if (is_null($this->accessmanager)) {
78e7a3dd 280 $this->accessmanager = new quiz_access_manager($this, $timenow,
36e413e3 281 has_capability('mod/quiz:ignoretimelimits', $this->context, NULL, false));
282 }
283 return $this->accessmanager;
284 }
285
fe6ce234
DC
286 public function get_overall_feedback($grade) {
287 return quiz_feedback_for_grade($grade, $this->quiz, $this->context, $this->cm);
288 }
289
78e7a3dd 290 /**
291 * Wrapper round the has_capability funciton that automatically passes in the quiz context.
292 */
293 public function has_capability($capability, $userid = NULL, $doanything = true) {
294 return has_capability($capability, $this->context, $userid, $doanything);
295 }
296
297 /**
298 * Wrapper round the require_capability funciton that automatically passes in the quiz context.
299 */
300 public function require_capability($capability, $userid = NULL, $doanything = true) {
301 return require_capability($capability, $this->context, $userid, $doanything);
302 }
303
36e413e3 304 // URLs related to this attempt ========================================================
b10c38a3 305 /**
306 * @return string the URL of this quiz's view page.
307 */
36e413e3 308 public function view_url() {
309 global $CFG;
310 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id;
311 }
312
78e7a3dd 313 /**
314 * @return string the URL of this quiz's edit page.
315 */
316 public function edit_url() {
317 global $CFG;
318 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id;
319 }
320
321 /**
322 * @param integer $attemptid the id of an attempt.
323 * @return string the URL of that attempt.
324 */
325 public function attempt_url($attemptid) {
326 global $CFG;
3c168fbb 327 return $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid;
78e7a3dd 328 }
329
330 /**
331 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter.
332 */
333 public function start_attempt_url() {
c68287a9
TH
334 return new moodle_url('/mod/quiz/startattempt.php',
335 array('cmid' => $this->cm->id, 'sesskey' => sesskey()));
78e7a3dd 336 }
337
338 /**
339 * @param integer $attemptid the id of an attempt.
340 * @return string the URL of the review of that attempt.
341 */
342 public function review_url($attemptid) {
ea9dbf24 343 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid));
78e7a3dd 344 }
345
36e413e3 346 // Bits of content =====================================================================
36e413e3 347
b10c38a3 348 /**
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
351 * parameter.
352 */
36e413e3 353 public function navigation($title) {
2698e9c1 354 global $PAGE;
355 $PAGE->navbar->add($title);
356 return '';
36e413e3 357 }
358
359 // Private methods =====================================================================
d18675a8 360 /**
361 * Check that the definition of a particular question is loaded, and if not throw an exception.
362 * @param $id a questionid.
363 */
78e7a3dd 364 protected function ensure_question_loaded($id) {
365 if (isset($this->questions[$id]->_partiallyloaded)) {
36e413e3 366 throw new moodle_quiz_exception($this, 'questionnotloaded', $id);
367 }
368 }
78e7a3dd 369
d18675a8 370 /**
371 * Populate {@link $questionids} and {@link $pagequestionids} from the layout.
372 */
373 protected function determine_layout() {
78e7a3dd 374 $this->questionids = array();
375 $this->pagequestionids = array();
376
377 // Get the appropriate layout string (from quiz or attempt).
2cb01c92 378 $layout = quiz_clean_layout($this->get_layout_string(), true);
78e7a3dd 379 if (empty($layout)) {
380 // Nothing to do.
381 return;
382 }
383
384 // Break up the layout string into pages.
2cb01c92 385 $pagelayouts = explode(',0', $layout);
78e7a3dd 386
387 // Strip off any empty last page (normally there is one).
388 if (end($pagelayouts) == '') {
389 array_pop($pagelayouts);
390 }
391
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;
401 }
402 }
403 }
404
d18675a8 405 /**
406 * Number the questions, adding a _number field to each one.
407 */
78e7a3dd 408 private function number_questions() {
409 $number = 1;
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;
415 } else {
416 $this->questions[$id]->_number = get_string('infoshort', 'quiz');
417 }
418 $this->questions[$id]->_page = $page;
419 }
420 }
421 }
422
423 /**
424 * @return string the layout of this quiz. Used by number_questions to
7b6757b0 425 * work out which questions are on which pages.
78e7a3dd 426 */
427 protected function get_layout_string() {
428 return $this->quiz->questions;
429 }
36e413e3 430}
431
b10c38a3 432/**
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.
d18675a8 435 *
436 * @copyright 2008 Tim Hunt
437 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
438 * @since Moodle 2.0
b10c38a3 439 */
36e413e3 440class quiz_attempt extends quiz {
441 // Fields initialised in the constructor.
442 protected $attempt;
443
444 // Fields set later if that data is needed.
36e413e3 445 protected $states = array();
4fc3d7e5 446 protected $reviewoptions = null;
36e413e3 447
448 // Constructor =========================================================================
b10c38a3 449 /**
990650f9
TH
450 * Constructor assuming we already have the necessary data loaded.
451 *
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.
456 */
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();
462 }
463
464 /**
465 * Static function to create a new quiz_attempt object given an attemptid.
b10c38a3 466 *
990650f9 467 * @param integer $attemptid the attempt id.
f23f98dd 468 * @return quiz_attempt the new quiz_attempt object
b10c38a3 469 */
990650f9 470 static public function create($attemptid) {
36e413e3 471 global $DB;
990650f9
TH
472
473 if (!$attempt = quiz_load_attempt($attemptid)) {
36e413e3 474 throw new moodle_exception('invalidattemptid', 'quiz');
475 }
990650f9 476 if (!$quiz = $DB->get_record('quiz', array('id' => $attempt->quiz))) {
36e413e3 477 throw new moodle_exception('invalidquizid', 'quiz');
478 }
479 if (!$course = $DB->get_record('course', array('id' => $quiz->course))) {
480 throw new moodle_exception('invalidcoursemodule');
481 }
482 if (!$cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id)) {
483 throw new moodle_exception('invalidcoursemodule');
484 }
990650f9
TH
485 // Update quiz with override information
486 $quiz = quiz_update_effective_access($quiz, $attempt->userid);
487
488 return new quiz_attempt($attempt, $quiz, $cm, $course);
36e413e3 489 }
490
491 // Functions for loading more data =====================================================
36e413e3 492 /**
78e7a3dd 493 * Load the state of a number of questions that have already been loaded.
36e413e3 494 *
78e7a3dd 495 * @param array $questionids question ids to process. Blank = all.
36e413e3 496 */
78e7a3dd 497 public function load_question_states($questionids = null) {
498 if (is_null($questionids)) {
499 $questionids = $this->questionids;
36e413e3 500 }
78e7a3dd 501 $questionstoprocess = array();
502 foreach ($questionids as $id) {
503 $this->ensure_question_loaded($id);
504 $questionstoprocess[$id] = $this->questions[$id];
505 }
40d1feeb 506 if (!question_load_states($questionstoprocess, $this->states,
81d833ad 507 $this->quiz, $this->attempt)) {
36e413e3 508 throw new moodle_quiz_exception($this, 'cannotrestore');
509 }
81d833ad 510 }
511
d18675a8 512 /**
513 * Load basic information about the state of each question.
514 *
515 * This is enough to, for example, show the state of each question in the
516 * navigation panel, but only takes one DB query.
517 */
81d833ad 518 public function preload_question_states() {
519 if (empty($this->questionids)) {
520 throw new moodle_quiz_exception($this, 'noquestions', $this->edit_url());
521 }
522 $this->states = question_preload_states($this->attempt->uniqueid);
523 if (!$this->states) {
524 $this->states = array();
525 }
36e413e3 526 }
527
d18675a8 528 /**
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.
532 *
533 * @param $questionid the question id
534 * @param $stateid the id of the particular state to load.
535 */
b55797b8 536 public function load_specific_question_state($questionid, $stateid) {
537 global $DB;
538 $state = question_load_specific_state($this->questions[$questionid],
539 $this->quiz, $this->attempt, $stateid);
540 if ($state === false) {
541 throw new moodle_quiz_exception($this, 'invalidstateid');
542 }
543 $this->states[$questionid] = $state;
544 }
545
36e413e3 546 // Simple getters ======================================================================
b10c38a3 547 /** @return integer the attempt id. */
36e413e3 548 public function get_attemptid() {
549 return $this->attempt->id;
550 }
551
766df8f7 552 /** @return integer the attempt unique id. */
553 public function get_uniqueid() {
554 return $this->attempt->uniqueid;
555 }
556
b10c38a3 557 /** @return object the row from the quiz_attempts table. */
36e413e3 558 public function get_attempt() {
559 return $this->attempt;
560 }
561
78e7a3dd 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;
565 }
566
b10c38a3 567 /** @return integer the id of the user this attempt belongs to. */
36e413e3 568 public function get_userid() {
569 return $this->attempt->userid;
570 }
571
aafdb447 572 /** @return boolean whether this attempt has been finished (true) or is still in progress (false). */
36e413e3 573 public function is_finished() {
574 return $this->attempt->timefinish != 0;
575 }
576
fe6ce234 577 /** @return boolean whether this attempt is a preview attempt. */
4fc3d7e5 578 public function is_preview() {
579 return $this->attempt->preview;
580 }
581
b55797b8 582 /**
583 * Is this a student dealing with their own attempt/teacher previewing,
584 * or someone with 'mod/quiz:viewreports' reviewing someone elses attempt.
7b6757b0 585 *
b55797b8 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.
588 */
589 public function is_own_attempt() {
590 global $USER;
591 return $this->attempt->userid == $USER->id &&
592 (!$this->is_preview_user() || $this->attempt->preview);
b55797b8 593 }
594
96c7d771 595 /**
596 * Check the appropriate capability to see whether this user may review their own attempt.
597 * If not, prints an error.
598 */
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');
603 } else {
604 $this->require_capability('mod/quiz:reviewmyattempts');
605 }
606 }
607 }
608
d18675a8 609 /**
610 * Get the current state of a question in the attempt.
611 *
612 * @param $questionid a questionid.
613 * @return object the state.
614 */
78e7a3dd 615 public function get_question_state($questionid) {
78e7a3dd 616 return $this->states[$questionid];
617 }
618
b10c38a3 619 /**
620 * Wrapper that calls quiz_get_reviewoptions with the appropriate arguments.
621 *
4fc3d7e5 622 * @return object the review options for this user on this attempt.
b10c38a3 623 */
36e413e3 624 public function get_review_options() {
625 if (is_null($this->reviewoptions)) {
626 $this->reviewoptions = quiz_get_reviewoptions($this->quiz, $this->attempt, $this->context);
627 }
628 return $this->reviewoptions;
629 }
630
4fc3d7e5 631 /**
632 * Wrapper that calls get_render_options with the appropriate arguments.
633 *
fe6ce234 634 * @param integer questionid the quetsion to get the render options for.
4fc3d7e5 635 * @return object the render options for this user on this attempt.
636 */
fe6ce234
DC
637 public function get_render_options($questionid) {
638 return quiz_get_renderoptions($this->quiz, $this->attempt, $this->context,
639 $this->get_question_state($questionid));
4fc3d7e5 640 }
641
b10c38a3 642 /**
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.
645 *
646 * @param mixed $page as for the @see{get_question_ids} method.
647 * @return quiz_attempt_question_iterator the requested iterator.
648 */
36e413e3 649 public function get_question_iterator($page = 'all') {
650 return new quiz_attempt_question_iterator($this, $page);
651 }
652
b10c38a3 653 /**
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.
656 *
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.
661 */
36e413e3 662 public function get_question_status($questionid) {
b10c38a3 663 $state = $this->states[$questionid];
664 switch ($state->event) {
665 case QUESTION_EVENTOPEN:
666 return 'open';
667
668 case QUESTION_EVENTSAVE:
669 case QUESTION_EVENTGRADE:
dee2bdc0 670 case QUESTION_EVENTSUBMIT:
66d07f81 671 return 'answered';
b10c38a3 672
673 case QUESTION_EVENTCLOSEANDGRADE:
674 case QUESTION_EVENTCLOSE:
675 case QUESTION_EVENTMANUALGRADE:
fe6ce234 676 $options = $this->get_render_options($questionid);
1aea04dc 677 if ($options->scores && $this->questions[$questionid]->maxgrade > 0) {
b10c38a3 678 return question_get_feedback_class($state->last_graded->raw_grade /
679 $this->questions[$questionid]->maxgrade);
680 } else {
681 return 'closed';
682 }
683
684 default:
685 $a = new stdClass;
686 $a->event = $state->event;
687 $a->questionid = $questionid;
688 $a->attemptid = $this->attempt->id;
689 throw new moodle_quiz_exception($this, 'errorunexpectedevent', $a);
690 }
36e413e3 691 }
692
62e76c67 693 /**
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.
696 */
697 public function is_question_flagged($questionid) {
62e76c67 698 $state = $this->states[$questionid];
699 return $state->flagged;
700 }
701
36e413e3 702 /**
b10c38a3 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.
36e413e3 705 *
b10c38a3 706 * @param integer $questionid question id of a question that belongs to this quiz.
36e413e3 707 * @return string the formatted grade, to the number of decimal places specified by the quiz.
708 */
709 public function get_question_score($questionid) {
fe6ce234 710 $options = $this->get_render_options($questionid);
36e413e3 711 if ($options->scores) {
84e628a0 712 return quiz_format_question_grade($this->quiz, $this->states[$questionid]->last_graded->grade);
36e413e3 713 } else {
714 return '';
715 }
716 }
717
718 // URLs related to this attempt ========================================================
b10c38a3 719 /**
78e7a3dd 720 * @param integer $questionid a question id. If set, will add a fragment to the URL
b10c38a3 721 * to jump to a particuar question on the page.
d18675a8 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.
b10c38a3 726 * @return string the URL to continue this attempt.
727 */
d18675a8 728 public function attempt_url($questionid = 0, $page = -1, $thispage = -1) {
729 return $this->page_and_question_url('attempt', $questionid, $page, false, $thispage);
36e413e3 730 }
731
b10c38a3 732 /**
733 * @return string the URL of this quiz's summary page.
734 */
36e413e3 735 public function summary_url() {
736 global $CFG;
737 return $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $this->attempt->id;
738 }
739
9f9eec1e 740 /**
741 * @return string the URL of this quiz's summary page.
742 */
743 public function processattempt_url() {
744 global $CFG;
745 return $CFG->wwwroot . '/mod/quiz/processattempt.php';
746 }
747
b10c38a3 748 /**
d18675a8 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.
b10c38a3 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.
b10c38a3 753 * @param boolean $showall if true, the URL will be to review the entire attempt on one page,
754 * and $page will be ignored.
d18675a8 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.
b10c38a3 757 * @return string the URL to review this attempt.
758 */
d18675a8 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);
78e7a3dd 761 }
762
763 // Bits of content =====================================================================
d18675a8 764 /**
765 * Initialise the JS etc. required all the questions on a page..
766 * @param mixed $page a page number, or 'all'.
767 */
78e7a3dd 768 public function get_html_head_contributions($page = 'all') {
d18675a8 769 global $PAGE;
ff065f96 770 question_get_html_head_contributions($this->get_question_ids($page), $this->questions, $this->states);
78e7a3dd 771 }
772
d18675a8 773 /**
774 * Initialise the JS etc. required by one question.
775 * @param integer $questionid the question id.
776 */
b826bcef 777 public function get_question_html_head_contributions($questionid) {
ff065f96 778 question_get_html_head_contributions(array($questionid), $this->questions, $this->states);
b826bcef 779 }
780
d18675a8 781 /**
782 * Print the HTML for the start new preview button.
783 */
78e7a3dd 784 public function print_restart_preview_button() {
39e37019 785 global $CFG, $OUTPUT;
786 echo $OUTPUT->container_start('controls');
c68287a9 787 $url = new moodle_url($this->start_attempt_url(), array('forcenew' => true));
5c2ed7e2 788 echo $OUTPUT->single_button($url, get_string('startagain', 'quiz'));
39e37019 789 echo $OUTPUT->container_end();
36e413e3 790 }
791
d18675a8 792 /**
793 * Return the HTML of the quiz timer.
794 * @return string HTML content.
795 */
692e0c33 796 public function get_timer_html() {
797 return '<div id="quiz-timer">' . get_string('timeleft', 'quiz') .
798 ' <span id="quiz-time-left"></span></div>';
799 }
800
aafdb447 801 /**
802 * Wrapper round print_question from lib/questionlib.php.
803 *
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.
807 */
808 public function print_question($id, $reviewing, $thispageurl = '') {
fb6dcdab
TH
809 global $CFG;
810
aafdb447 811 if ($reviewing) {
4fc3d7e5 812 $options = $this->get_review_options();
813 } else {
fe6ce234 814 $options = $this->get_render_options($id);
4fc3d7e5 815 }
db048665
TH
816 if ($thispageurl instanceof moodle_url) {
817 $thispageurl = $thispageurl->out(false);
818 }
aafdb447 819 if ($thispageurl) {
db048665 820 $this->quiz->thispageurl = str_replace($CFG->wwwroot, '', $thispageurl);
aafdb447 821 } else {
822 unset($thispageurl);
823 }
78e7a3dd 824 print_question($this->questions[$id], $this->states[$id], $this->questions[$id]->_number,
825 $this->quiz, $options);
826 }
827
fe6ce234
DC
828 public function check_file_access($questionid, $isreviewing, $contextid, $component,
829 $filearea, $args, $forcedownload) {
830 if ($isreviewing) {
831 $options = $this->get_review_options();
832 } else {
833 $options = $this->get_render_options($questionid);
834 }
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);
840 }
841
d18675a8 842 /**
843 * Triggers the sending of the notification emails at the end of this attempt.
844 */
78e7a3dd 845 public function quiz_send_notification_emails() {
846 quiz_send_notification_emails($this->course, $this->quiz, $this->attempt,
847 $this->context, $this->cm);
848 }
3c168fbb 849
d18675a8 850 /**
851 * Get the navigation panel object for this attempt.
852 *
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.
857 */
858 public function get_navigation_panel($panelclass, $page, $showall = false) {
859 $panel = new $panelclass($this, $this->get_review_options(), $page, $showall);
d4a03c00 860 return $panel->get_contents();
3c168fbb 861 }
36e413e3 862
d18675a8 863 /**
83192608 864 * Given a URL containing attempt={this attempt id}, return an array of variant URLs
d18675a8 865 * @param $url a URL.
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.
869 */
b55797b8 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');
f88fb62c 873 if (count($attempts) <= 1) {
874 return false;
875 }
b55797b8 876 $attemptlist = array();
877 foreach ($attempts as $at) {
878 if ($at->id == $this->attempt->id) {
879 $attemptlist[] = '<strong>' . $at->attempt . '</strong>';
880 } else {
881 $changedurl = preg_replace($search, 'attempt=' . $at->id, $url);
d4ad9adf 882 $attemptlist[] = '<a href="' . s($changedurl) . '">' . $at->attempt . '</a>';
b55797b8 883 }
884 }
885 return implode(', ', $attemptlist);
886 }
887
766df8f7 888 // Methods for processing manual comments ==============================================
d18675a8 889 /**
890 * Process a manual comment for a question in this attempt.
891 * @param $questionid
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).
897 */
a9efae50 898 public function process_comment($questionid, $comment, $commentformat, $grade) {
d18675a8 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.
766df8f7 902 $this->ensure_question_loaded($questionid);
903 $this->ensure_state_loaded($questionid);
904 $state = $this->states[$questionid];
905
906 $error = question_process_comment($this->questions[$questionid],
a9efae50 907 $state, $this->attempt, $comment, $commentformat, $grade);
766df8f7 908
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');
913 }
914 if (!quiz_save_best_grade($this->quiz, $this->attempt->userid)) {
915 $error = get_string('errorudpatingbestgrade', 'quiz');
916 }
917 }
918 return $error;
919 }
920
d18675a8 921 /**
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.
925 */
766df8f7 926 public function question_print_comment_fields($questionid, $prefix) {
e8f99abc 927 global $DB;
928
766df8f7 929 $this->ensure_question_loaded($questionid);
930 $this->ensure_state_loaded($questionid);
e8f99abc 931
932 /// Work out a nice title.
933 $student = $DB->get_record('user', array('id' => $this->get_userid()));
39790bd8 934 $a = new stdClass();
e8f99abc 935 $a->fullname = fullname($student, true);
936 $a->attempt = $this->get_attempt_number();
937
766df8f7 938 question_print_comment_fields($this->questions[$questionid],
e8f99abc 939 $this->states[$questionid], $prefix, $this->quiz, get_string('gradingattempt', 'quiz_grading', $a));
766df8f7 940 }
941
36e413e3 942 // Private methods =====================================================================
d18675a8 943 /**
944 * Check that the state of a particular question is loaded, and if not throw an exception.
945 * @param integer $id a question id.
946 */
36e413e3 947 private function ensure_state_loaded($id) {
81d833ad 948 if (!array_key_exists($id, $this->states) || isset($this->states[$id]->_partiallyloaded)) {
36e413e3 949 throw new moodle_quiz_exception($this, 'statenotloaded', $id);
950 }
951 }
78e7a3dd 952
953 /**
954 * @return string the layout of this quiz. Used by number_questions to
7b6757b0 955 * work out which questions are on which pages.
78e7a3dd 956 */
957 protected function get_layout_string() {
958 return $this->attempt->layout;
959 }
960
961 /**
d18675a8 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()}.
78e7a3dd 964 *
d18675a8 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.
78e7a3dd 972 */
d18675a8 973 protected function page_and_question_url($script, $questionid, $page, $showall, $thispage) {
974 global $CFG;
975
976 // Fix up $page
3c168fbb 977 if ($page == -1) {
d18675a8 978 if ($questionid && !$showall) {
78e7a3dd 979 $page = $this->questions[$questionid]->_page;
980 } else {
981 $page = 0;
982 }
983 }
984 if ($showall) {
985 $page = 0;
986 }
d18675a8 987
988 // Work out the correct start to the URL.
989 if ($thispage == $page) {
990 $url = '';
991 } else {
992 $url = $CFG->wwwroot . '/mod/quiz/' . $script . '.php?attempt=' . $this->attempt->id;
993 if ($showall) {
994 $url .= '&showall=1';
995 } else if ($page > 0) {
996 $url .= '&page=' . $page;
997 }
998 }
999
fb6dcdab 1000 // Add a fragment to scroll down to the question.
d4a03c00 1001 if ($questionid) {
1002 if ($questionid == reset($this->pagequestionids[$page])) {
1003 // First question on page, go to top.
d18675a8 1004 $url .= '#';
d4a03c00 1005 } else {
d18675a8 1006 $url .= '#q' . $questionid;
d4a03c00 1007 }
78e7a3dd 1008 }
d18675a8 1009
1010 return $url;
78e7a3dd 1011 }
36e413e3 1012}
1013
b10c38a3 1014/**
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.
d18675a8 1017 *
1018 * @copyright 2008 Tim Hunt
1019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1020 * @since Moodle 2.0
b10c38a3 1021 */
36e413e3 1022class quiz_attempt_question_iterator implements Iterator {
b10c38a3 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.
1025
1026 /**
1027 * Constructor. Normally, you don't want to call this directly. Instead call
1028 * quiz_attempt::get_question_iterator
1029 *
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}.
1032 */
36e413e3 1033 public function __construct(quiz_attempt $attemptobj, $page = 'all') {
1034 $this->attemptobj = $attemptobj;
36e413e3 1035 $this->questionids = $attemptobj->get_question_ids($page);
1036 }
1037
b10c38a3 1038 // Implementation of the Iterator interface ============================================
36e413e3 1039 public function rewind() {
1040 reset($this->questionids);
1041 }
1042
1043 public function current() {
1044 $id = current($this->questionids);
1045 if ($id) {
1046 return $this->attemptobj->get_question($id);
1047 } else {
1048 return false;
1049 }
1050 }
1051
1052 public function key() {
1053 $id = current($this->questionids);
1054 if ($id) {
78e7a3dd 1055 return $this->attemptobj->get_question($id)->_number;
36e413e3 1056 } else {
1057 return false;
1058 }
36e413e3 1059 }
1060
1061 public function next() {
1062 $id = next($this->questionids);
1063 if ($id) {
1064 return $this->attemptobj->get_question($id);
1065 } else {
1066 return false;
1067 }
1068 }
1069
1070 public function valid() {
1071 return $this->current() !== false;
1072 }
1073}
3c168fbb 1074
d18675a8 1075/**
1076 * Represents the navigation panel, and builds a {@link block_contents} to allow
1077 * it to be output.
1078 *
1079 * @copyright 2008 Tim Hunt
1080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1081 * @since Moodle 2.0
1082 */
3c168fbb 1083abstract class quiz_nav_panel_base {
38c9edd0 1084 /** @var quiz_attempt */
3c168fbb 1085 protected $attemptobj;
38c9edd0 1086 /** @var question_display_options */
3c168fbb 1087 protected $options;
38c9edd0 1088 /** @var integer */
3c168fbb 1089 protected $page;
38c9edd0 1090 /** @var boolean */
d18675a8 1091 protected $showall;
3c168fbb 1092
d18675a8 1093 public function __construct(quiz_attempt $attemptobj, $options, $page, $showall) {
38c9edd0
TH
1094 $this->attemptobj = $attemptobj;
1095 $this->options = $options;
1096 $this->page = $page;
1097 $this->showall = $showall;
3c168fbb 1098 }
1099
1100 protected function get_question_buttons() {
c752264f 1101 $html = '<div class="qn_buttons">' . "\n";
3c168fbb 1102 foreach ($this->attemptobj->get_question_iterator() as $number => $question) {
cf615522 1103 $html .= $this->get_question_button($number, $question) . "\n";
3c168fbb 1104 }
c752264f 1105 $html .= "</div>\n";
3c168fbb 1106 return $html;
1107 }
1108
d18675a8 1109 protected function get_question_button($number, $question) {
1110 $strstate = get_string($this->attemptobj->get_question_status($question->id), 'quiz');
a26246ea
TH
1111 $flagstate = '';
1112 if ($this->attemptobj->is_question_flagged($question->id)) {
1113 $flagstate = get_string('flagged', 'question');
1114 }
05d3c06e 1115 return '<a href="' . s($this->get_question_url($question)) .
d18675a8 1116 '" class="qnbutton ' . $this->get_question_state_classes($question) .
1117 '" id="quiznavbutton' . $question->id . '" title="' . $strstate . '">' .
a26246ea
TH
1118 $number . ' <span class="accesshide"> (' . $strstate . '
1119 <span class="flagstate">' . $flagstate . '</span>)</span></a>';
c752264f 1120 }
1121
d18675a8 1122 protected function get_before_button_bits() {
1123 return '';
1124 }
3c168fbb 1125
1126 abstract protected function get_end_bits();
1127
d18675a8 1128 abstract protected function get_question_url($question);
1129
a733c4b9 1130 protected function get_user_picture() {
39e37019 1131 global $DB, $OUTPUT;
a733c4b9 1132 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid()));
1133 $output = '';
1134 $output .= '<div id="user-picture" class="clearfix">';
812dbaf7 1135 $output .= $OUTPUT->user_picture($user, array('courseid'=>$this->attemptobj->get_courseid()));
a733c4b9 1136 $output .= ' ' . fullname($user);
1137 $output .= '</div>';
1138 return $output;
1139 }
1140
62e76c67 1141 protected function get_question_state_classes($question) {
1142 // The current status of the question.
1143 $classes = $this->attemptobj->get_question_status($question->id);
1144
1145 // Plus a marker for the current page.
d18675a8 1146 if ($this->showall || $question->_page == $this->page) {
62e76c67 1147 $classes .= ' thispage';
1148 }
1149
1150 // Plus a marker for flagged questions.
1151 if ($this->attemptobj->is_question_flagged($question->id)) {
1152 $classes .= ' flagged';
3c168fbb 1153 }
62e76c67 1154 return $classes;
3c168fbb 1155 }
1156
d4a03c00 1157 public function get_contents() {
d18675a8 1158 global $PAGE;
ff065f96 1159 $PAGE->requires->js_init_call('M.mod_quiz.nav.init', null, false, quiz_get_js_module());
d18675a8 1160
a733c4b9 1161 $content = '';
1162 if ($this->attemptobj->get_quiz()->showuserpicture) {
1163 $content .= $this->get_user_picture() . "\n";
1164 }
d18675a8 1165 $content .= $this->get_before_button_bits();
a733c4b9 1166 $content .= $this->get_question_buttons() . "\n";
1167 $content .= '<div class="othernav">' . "\n" . $this->get_end_bits() . "\n</div>\n";
d4a03c00 1168
1169 $bc = new block_contents();
1170 $bc->id = 'quiznavigation';
1171 $bc->title = get_string('quiznavigation', 'quiz');
1172 $bc->content = $content;
1173 return $bc;
3c168fbb 1174 }
1175}
1176
d18675a8 1177/**
1178 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page.
1179 *
1180 * @copyright 2008 Tim Hunt
1181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1182 * @since Moodle 2.0
1183 */
3c168fbb 1184class quiz_attempt_nav_panel extends quiz_nav_panel_base {
d18675a8 1185 protected function get_question_url($question) {
1186 return $this->attemptobj->attempt_url($question->id, -1, $this->page);
3c168fbb 1187 }
1188
d18675a8 1189 protected function get_before_button_bits() {
1190 return '<div id="quiznojswarning">' . get_string('navnojswarning', 'quiz') . "</div>\n";
3c168fbb 1191 }
1192
1193 protected function get_end_bits() {
d18675a8 1194 global $PAGE;
5533791a 1195 $output = '';
157434a5 1196 $output .= '<a href="' . s($this->attemptobj->summary_url()) . '" class="endtestlink">' . get_string('finishattemptdots', 'quiz') . '</a>';
692e0c33 1197 $output .= $this->attemptobj->get_timer_html();
5533791a 1198 return $output;
3c168fbb 1199 }
1200}
1201
d18675a8 1202/**
1203 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page.
1204 *
1205 * @copyright 2008 Tim Hunt
1206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1207 * @since Moodle 2.0
1208 */
3c168fbb 1209class quiz_review_nav_panel extends quiz_nav_panel_base {
d18675a8 1210 protected function get_question_url($question) {
1211 return $this->attemptobj->review_url($question->id, -1, $this->showall, $this->page);
3c168fbb 1212 }
1213
1214 protected function get_end_bits() {
d18675a8 1215 $html = '';
1216 if ($this->attemptobj->get_num_pages() > 1) {
1217 if ($this->showall) {
38c9edd0 1218 $html .= '<a href="' . s($this->attemptobj->review_url(0, 0, false)) . '">' . get_string('showeachpage', 'quiz') . '</a>';
d18675a8 1219 } else {
38c9edd0 1220 $html .= '<a href="' . s($this->attemptobj->review_url(0, 0, true)) . '">' . get_string('showall', 'quiz') . '</a>';
d18675a8 1221 }
1222 }
baef998b 1223 $accessmanager = $this->attemptobj->get_access_manager(time());
baef998b 1224 $html .= $accessmanager->print_finish_review_link($this->attemptobj->is_preview_user(), true);
3c168fbb 1225 return $html;
1226 }
1227}