MDL-32188 quiz/question: behaviours can add to the review summary.
[moodle.git] / question / engine / questionattempt.php
CommitLineData
dcd03928 1<?php
dcd03928
TH
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.
13//
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/>.
16
17/**
18 * This file defines the question attempt class, and a few related classes.
19 *
20 * @package moodlecore
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26
27defined('MOODLE_INTERNAL') || die();
28
29
30/**
31 * Tracks an attempt at one particular question in a {@link question_usage_by_activity}.
32 *
33 * Most calling code should need to access objects of this class. They should be
34 * able to do everything through the usage interface. This class is an internal
35 * implementation detail of the question engine.
36 *
37 * Instances of this class correspond to rows in the question_attempts table, and
38 * a collection of {@link question_attempt_steps}. Question inteaction models and
39 * question types do work with question_attempt objects.
40 *
41 * @copyright 2009 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 */
44class question_attempt {
45 /**
46 * @var string this is a magic value that question types can return from
47 * {@link question_definition::get_expected_data()}.
48 */
49 const USE_RAW_DATA = 'use raw data';
50
51 /**
61cca0b7 52 * @var string special value used by manual grading because {@link PARAM_FLOAT}
dcd03928
TH
53 * converts '' to 0.
54 */
55 const PARAM_MARK = 'parammark';
56
57 /**
58 * @var string special value to indicate a response variable that is uploaded
59 * files.
60 */
61 const PARAM_FILES = 'paramfiles';
62
63 /**
64 * @var string special value to indicate a response variable that is uploaded
65 * files.
66 */
2d2018ab 67 const PARAM_RAW_FILES = 'paramrawfiles';
dcd03928
TH
68
69 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
70 protected $id = null;
71
72 /** @var integer|string the id of the question_usage_by_activity we belong to. */
73 protected $usageid;
74
75 /** @var integer the number used to identify this question_attempt within the usage. */
76 protected $slot = null;
77
78 /**
79 * @var question_behaviour the behaviour controlling this attempt.
80 * null until {@link start()} is called.
81 */
82 protected $behaviour = null;
83
84 /** @var question_definition the question this is an attempt at. */
85 protected $question;
86
1da821bb
TH
87 /** @var int which variant of the question to use. */
88 protected $variant;
89
dcd03928
TH
90 /** @var number the maximum mark that can be scored at this question. */
91 protected $maxmark;
92
93 /**
94 * @var number the minimum fraction that can be scored at this question, so
95 * the minimum mark is $this->minfraction * $this->maxmark.
96 */
97 protected $minfraction = null;
98
99 /**
100 * @var string plain text summary of the variant of the question the
101 * student saw. Intended for reporting purposes.
102 */
103 protected $questionsummary = null;
104
105 /**
106 * @var string plain text summary of the response the student gave.
107 * Intended for reporting purposes.
108 */
109 protected $responsesummary = null;
110
111 /**
112 * @var string plain text summary of the correct response to this question
113 * variant the student saw. The format should be similar to responsesummary.
114 * Intended for reporting purposes.
115 */
116 protected $rightanswer = null;
117
118 /** @var array of {@link question_attempt_step}s. The steps in this attempt. */
119 protected $steps = array();
120
0a606a2b
TH
121 /**
122 * @var question_attempt_step if, when we loaded the step from the DB, there was
123 * an autosaved step, we save a pointer to it here. (It is also added to the $steps array.)
124 */
125 protected $autosavedstep = null;
126
dcd03928
TH
127 /** @var boolean whether the user has flagged this attempt within the usage. */
128 protected $flagged = false;
129
130 /** @var question_usage_observer tracks changes to the useage this attempt is part of.*/
131 protected $observer;
132
133 /**#@+
134 * Constants used by the intereaction models to indicate whether the current
135 * pending step should be kept or discarded.
136 */
137 const KEEP = true;
138 const DISCARD = false;
139 /**#@-*/
140
141 /**
142 * Create a new {@link question_attempt}. Normally you should create question_attempts
143 * indirectly, by calling {@link question_usage_by_activity::add_question()}.
144 *
145 * @param question_definition $question the question this is an attempt at.
146 * @param int|string $usageid The id of the
147 * {@link question_usage_by_activity} we belong to. Used by {@link get_field_prefix()}.
148 * @param question_usage_observer $observer tracks changes to the useage this
149 * attempt is part of. (Optional, a {@link question_usage_null_observer} is
150 * used if one is not passed.
151 * @param number $maxmark the maximum grade for this question_attempt. If not
152 * passed, $question->defaultmark is used.
153 */
154 public function __construct(question_definition $question, $usageid,
155 question_usage_observer $observer = null, $maxmark = null) {
156 $this->question = $question;
157 $this->usageid = $usageid;
158 if (is_null($observer)) {
159 $observer = new question_usage_null_observer();
160 }
161 $this->observer = $observer;
162 if (!is_null($maxmark)) {
163 $this->maxmark = $maxmark;
164 } else {
165 $this->maxmark = $question->defaultmark;
166 }
167 }
168
f123d67f
TH
169 /**
170 * This method exists so that {@link question_attempt_with_restricted_history}
171 * can override it. You should not normally need to call it.
172 * @return question_attempt return ourself.
173 */
174 public function get_full_qa() {
175 return $this;
176 }
177
dcd03928
TH
178 /** @return question_definition the question this is an attempt at. */
179 public function get_question() {
180 return $this->question;
181 }
182
1da821bb
TH
183 /**
184 * Get the variant of the question being used in a given slot.
185 * @return int the variant number.
186 */
187 public function get_variant() {
188 return $this->variant;
189 }
190
dcd03928
TH
191 /**
192 * Set the number used to identify this question_attempt within the usage.
193 * For internal use only.
194 * @param int $slot
195 */
94815ccf 196 public function set_slot($slot) {
dcd03928
TH
197 $this->slot = $slot;
198 }
199
200 /** @return int the number used to identify this question_attempt within the usage. */
201 public function get_slot() {
202 return $this->slot;
203 }
204
205 /**
206 * @return int the id of row for this question_attempt, if it is stored in the
207 * database. null if not.
208 */
209 public function get_database_id() {
210 return $this->id;
211 }
212
213 /**
214 * For internal use only. Set the id of the corresponding database row.
215 * @param int $id the id of row for this question_attempt, if it is
216 * stored in the database.
217 */
218 public function set_database_id($id) {
219 $this->id = $id;
220 }
221
94815ccf
TH
222 /**
223 * You should almost certainly not call this method from your code. It is for
224 * internal use only.
225 * @param question_usage_observer that should be used to tracking changes made to this qa.
226 */
227 public function set_observer($observer) {
228 $this->observer = $observer;
229 }
230
dcd03928
TH
231 /** @return int|string the id of the {@link question_usage_by_activity} we belong to. */
232 public function get_usage_id() {
233 return $this->usageid;
234 }
235
236 /**
237 * Set the id of the {@link question_usage_by_activity} we belong to.
238 * For internal use only.
239 * @param int|string the new id.
240 */
241 public function set_usage_id($usageid) {
242 $this->usageid = $usageid;
243 }
244
245 /** @return string the name of the behaviour that is controlling this attempt. */
246 public function get_behaviour_name() {
247 return $this->behaviour->get_name();
248 }
249
250 /**
251 * For internal use only.
252 * @return question_behaviour the behaviour that is controlling this attempt.
253 */
254 public function get_behaviour() {
255 return $this->behaviour;
256 }
257
258 /**
259 * Set the flagged state of this question.
260 * @param bool $flagged the new state.
261 */
262 public function set_flagged($flagged) {
263 $this->flagged = $flagged;
264 $this->observer->notify_attempt_modified($this);
265 }
266
267 /** @return bool whether this question is currently flagged. */
268 public function is_flagged() {
269 return $this->flagged;
270 }
271
272 /**
273 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
274 * name) to use for the field that indicates whether this question is flagged.
275 *
276 * @return string The field name to use.
277 */
278 public function get_flag_field_name() {
279 return $this->get_control_field_name('flagged');
280 }
281
282 /**
283 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
284 * name) to use for a question_type variable belonging to this question_attempt.
285 *
286 * See the comment on {@link question_attempt_step} for an explanation of
287 * question type and behaviour variables.
288 *
289 * @param $varname The short form of the variable name.
290 * @return string The field name to use.
291 */
292 public function get_qt_field_name($varname) {
293 return $this->get_field_prefix() . $varname;
294 }
295
296 /**
297 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
298 * name) to use for a question_type variable belonging to this question_attempt.
299 *
300 * See the comment on {@link question_attempt_step} for an explanation of
301 * question type and behaviour variables.
302 *
303 * @param $varname The short form of the variable name.
304 * @return string The field name to use.
305 */
306 public function get_behaviour_field_name($varname) {
307 return $this->get_field_prefix() . '-' . $varname;
308 }
309
310 /**
311 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
312 * name) to use for a control variables belonging to this question_attempt.
313 *
314 * Examples are :sequencecheck and :flagged
315 *
316 * @param $varname The short form of the variable name.
317 * @return string The field name to use.
318 */
319 public function get_control_field_name($varname) {
320 return $this->get_field_prefix() . ':' . $varname;
321 }
322
323 /**
324 * Get the prefix added to variable names to give field names for this
325 * question attempt.
326 *
327 * You should not use this method directly. This is an implementation detail
328 * anyway, but if you must access it, use {@link question_usage_by_activity::get_field_prefix()}.
329 *
330 * @param $varname The short form of the variable name.
331 * @return string The field name to use.
332 */
333 public function get_field_prefix() {
334 return 'q' . $this->usageid . ':' . $this->slot . '_';
335 }
336
337 /**
338 * Get one of the steps in this attempt.
339 * For internal/test code use only.
340 * @param int $i the step number.
341 * @return question_attempt_step
342 */
343 public function get_step($i) {
344 if ($i < 0 || $i >= count($this->steps)) {
345 throw new coding_exception('Index out of bounds in question_attempt::get_step.');
346 }
347 return $this->steps[$i];
348 }
349
c7fbfe46
TH
350 /**
351 * Get the number of real steps in this attempt.
352 * This is put as a hidden field in the HTML, so that when we receive some
353 * data to process, then we can check that it came from the question
354 * in the state we are now it.
355 * @return int a number that summarises the current state of this question attempt.
356 */
357 public function get_sequence_check_count() {
358 $numrealsteps = $this->get_num_steps();
359 if ($this->has_autosaved_step()) {
360 $numrealsteps -= 1;
361 }
362 return $numrealsteps;
363 }
364
dcd03928
TH
365 /**
366 * Get the number of steps in this attempt.
367 * For internal/test code use only.
368 * @return int the number of steps we currently have.
369 */
370 public function get_num_steps() {
371 return count($this->steps);
372 }
373
374 /**
375 * Return the latest step in this question_attempt.
376 * For internal/test code use only.
377 * @return question_attempt_step
378 */
379 public function get_last_step() {
380 if (count($this->steps) == 0) {
381 return new question_null_step();
382 }
383 return end($this->steps);
384 }
385
0a606a2b
TH
386 /**
387 * @return boolean whether this question_attempt has autosaved data from
388 * some time in the past.
389 */
390 public function has_autosaved_step() {
391 return !is_null($this->autosavedstep);
392 }
393
dcd03928
TH
394 /**
395 * @return question_attempt_step_iterator for iterating over the steps in
396 * this attempt, in order.
397 */
398 public function get_step_iterator() {
399 return new question_attempt_step_iterator($this);
400 }
401
402 /**
403 * The same as {@link get_step_iterator()}. However, for a
404 * {@link question_attempt_with_restricted_history} this returns the full
405 * list of steps, while {@link get_step_iterator()} returns only the
406 * limited history.
407 * @return question_attempt_step_iterator for iterating over the steps in
408 * this attempt, in order.
409 */
410 public function get_full_step_iterator() {
411 return $this->get_step_iterator();
412 }
413
414 /**
415 * @return question_attempt_reverse_step_iterator for iterating over the steps in
416 * this attempt, in reverse order.
417 */
418 public function get_reverse_step_iterator() {
419 return new question_attempt_reverse_step_iterator($this);
420 }
421
422 /**
423 * Get the qt data from the latest step that has any qt data. Return $default
424 * array if it is no step has qt data.
425 *
426 * @param string $name the name of the variable to get.
427 * @param mixed default the value to return no step has qt data.
428 * (Optional, defaults to an empty array.)
429 * @return array|mixed the data, or $default if there is not any.
430 */
431 public function get_last_qt_data($default = array()) {
432 foreach ($this->get_reverse_step_iterator() as $step) {
433 $response = $step->get_qt_data();
434 if (!empty($response)) {
435 return $response;
436 }
437 }
438 return $default;
439 }
440
441 /**
442 * Get the last step with a particular question type varialbe set.
443 * @param string $name the name of the variable to get.
444 * @return question_attempt_step the last step, or a step with no variables
445 * if there was not a real step.
446 */
447 public function get_last_step_with_qt_var($name) {
448 foreach ($this->get_reverse_step_iterator() as $step) {
449 if ($step->has_qt_var($name)) {
450 return $step;
451 }
cc9fc649
HB
452 }
453 return new question_attempt_step_read_only();
454 }
455
456 /**
457 * Get the last step with a particular behaviour variable set.
458 * @param string $name the name of the variable to get.
459 * @return question_attempt_step the last step, or a step with no variables
460 * if there was not a real step.
461 */
462 public function get_last_step_with_behaviour_var($name) {
463 foreach ($this->get_reverse_step_iterator() as $step) {
464 if ($step->has_behaviour_var($name)) {
465 return $step;
466 }
dcd03928
TH
467 }
468 return new question_attempt_step_read_only();
469 }
470
471 /**
472 * Get the latest value of a particular question type variable. That is, get
473 * the value from the latest step that has it set. Return null if it is not
474 * set in any step.
475 *
476 * @param string $name the name of the variable to get.
477 * @param mixed default the value to return in the variable has never been set.
478 * (Optional, defaults to null.)
479 * @return mixed string value, or $default if it has never been set.
480 */
481 public function get_last_qt_var($name, $default = null) {
482 $step = $this->get_last_step_with_qt_var($name);
483 if ($step->has_qt_var($name)) {
484 return $step->get_qt_var($name);
485 } else {
486 return $default;
487 }
488 }
489
490 /**
491 * Get the latest set of files for a particular question type variable of
492 * type question_attempt::PARAM_FILES.
493 *
494 * @param string $name the name of the associated variable.
495 * @return array of {@link stored_files}.
496 */
497 public function get_last_qt_files($name, $contextid) {
498 foreach ($this->get_reverse_step_iterator() as $step) {
499 if ($step->has_qt_var($name)) {
500 return $step->get_qt_files($name, $contextid);
501 }
502 }
503 return array();
504 }
505
506 /**
507 * Get the URL of a file that belongs to a response variable of this
508 * question_attempt.
509 * @param stored_file $file the file to link to.
510 * @return string the URL of that file.
511 */
512 public function get_response_file_url(stored_file $file) {
513 return file_encode_url(new moodle_url('/pluginfile.php'), '/' . implode('/', array(
514 $file->get_contextid(),
515 $file->get_component(),
516 $file->get_filearea(),
517 $this->usageid,
518 $this->slot,
519 $file->get_itemid())) .
520 $file->get_filepath() . $file->get_filename(), true);
521 }
522
523 /**
524 * Prepare a draft file are for the files belonging the a response variable
525 * of this question attempt. The draft area is populated with the files from
526 * the most recent step having files.
527 *
528 * @param string $name the variable name the files belong to.
529 * @param int $contextid the id of the context the quba belongs to.
530 * @return int the draft itemid.
531 */
532 public function prepare_response_files_draft_itemid($name, $contextid) {
533 foreach ($this->get_reverse_step_iterator() as $step) {
534 if ($step->has_qt_var($name)) {
535 return $step->prepare_response_files_draft_itemid($name, $contextid);
536 }
537 }
538
539 // No files yet.
540 $draftid = 0; // Will be filled in by file_prepare_draft_area.
541 file_prepare_draft_area($draftid, $contextid, 'question', 'response_' . $name, null);
542 return $draftid;
543 }
544
545 /**
546 * Get the latest value of a particular behaviour variable. That is,
547 * get the value from the latest step that has it set. Return null if it is
548 * not set in any step.
549 *
550 * @param string $name the name of the variable to get.
551 * @param mixed default the value to return in the variable has never been set.
552 * (Optional, defaults to null.)
553 * @return mixed string value, or $default if it has never been set.
554 */
555 public function get_last_behaviour_var($name, $default = null) {
556 foreach ($this->get_reverse_step_iterator() as $step) {
557 if ($step->has_behaviour_var($name)) {
558 return $step->get_behaviour_var($name);
559 }
560 }
561 return $default;
562 }
563
564 /**
565 * Get the current state of this question attempt. That is, the state of the
566 * latest step.
567 * @return question_state
568 */
569 public function get_state() {
570 return $this->get_last_step()->get_state();
571 }
572
573 /**
574 * @param bool $showcorrectness Whether right/partial/wrong states should
575 * be distinguised.
576 * @return string A brief textual description of the current state.
577 */
578 public function get_state_string($showcorrectness) {
f8e28244
RK
579 // Special case when attempt is based on previous one, see MDL-31226.
580 if ($this->get_num_steps() == 1 && $this->get_state() == question_state::$complete) {
581 return get_string('notchanged', 'question');
582 }
dcd03928
TH
583 return $this->behaviour->get_state_string($showcorrectness);
584 }
585
97cdc1de
TH
586 /**
587 * @param bool $showcorrectness Whether right/partial/wrong states should
588 * be distinguised.
589 * @return string a CSS class name for the current state.
590 */
591 public function get_state_class($showcorrectness) {
592 return $this->get_state()->get_state_class($showcorrectness);
593 }
594
dcd03928
TH
595 /**
596 * @return int the timestamp of the most recent step in this question attempt.
597 */
598 public function get_last_action_time() {
599 return $this->get_last_step()->get_timecreated();
600 }
601
602 /**
603 * Get the current fraction of this question attempt. That is, the fraction
604 * of the latest step, or null if this question has not yet been graded.
605 * @return number the current fraction.
606 */
607 public function get_fraction() {
608 return $this->get_last_step()->get_fraction();
609 }
610
611 /** @return bool whether this question attempt has a non-zero maximum mark. */
612 public function has_marks() {
613 // Since grades are stored in the database as NUMBER(12,7).
614 return $this->maxmark >= 0.00000005;
615 }
616
617 /**
618 * @return number the current mark for this question.
619 * {@link get_fraction()} * {@link get_max_mark()}.
620 */
621 public function get_mark() {
622 return $this->fraction_to_mark($this->get_fraction());
623 }
624
625 /**
626 * This is used by the manual grading code, particularly in association with
627 * validation. If there is a mark submitted in the request, then use that,
628 * otherwise use the latest mark for this question.
629 * @return number the current mark for this question.
630 * {@link get_fraction()} * {@link get_max_mark()}.
631 */
632 public function get_current_manual_mark() {
633 $mark = $this->get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
634 if (is_null($mark)) {
635 return $this->get_mark();
636 } else {
637 return $mark;
638 }
639 }
640
641 /**
642 * @param number|null $fraction a fraction.
643 * @return number|null the corresponding mark.
644 */
645 public function fraction_to_mark($fraction) {
646 if (is_null($fraction)) {
647 return null;
648 }
649 return $fraction * $this->maxmark;
650 }
651
652 /** @return number the maximum mark possible for this question attempt. */
653 public function get_max_mark() {
654 return $this->maxmark;
655 }
656
657 /** @return number the maximum mark possible for this question attempt. */
658 public function get_min_fraction() {
659 if (is_null($this->minfraction)) {
660 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
661 }
662 return $this->minfraction;
663 }
664
665 /**
666 * The current mark, formatted to the stated number of decimal places. Uses
667 * {@link format_float()} to format floats according to the current locale.
668 * @param int $dp number of decimal places.
669 * @return string formatted mark.
670 */
671 public function format_mark($dp) {
672 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
673 }
674
675 /**
676 * The current mark, formatted to the stated number of decimal places. Uses
677 * {@link format_float()} to format floats according to the current locale.
678 * @param int $dp number of decimal places.
679 * @return string formatted mark.
680 */
681 public function format_fraction_as_mark($fraction, $dp) {
682 return format_float($this->fraction_to_mark($fraction), $dp);
683 }
684
685 /**
686 * The maximum mark for this question attempt, formatted to the stated number
687 * of decimal places. Uses {@link format_float()} to format floats according
688 * to the current locale.
689 * @param int $dp number of decimal places.
690 * @return string formatted maximum mark.
691 */
692 public function format_max_mark($dp) {
693 return format_float($this->maxmark, $dp);
694 }
695
696 /**
697 * Return the hint that applies to the question in its current state, or null.
698 * @return question_hint|null
699 */
700 public function get_applicable_hint() {
701 return $this->behaviour->get_applicable_hint();
702 }
703
704 /**
705 * Produce a plain-text summary of what the user did during a step.
706 * @param question_attempt_step $step the step in quetsion.
707 * @return string a summary of what was done during that step.
708 */
709 public function summarise_action(question_attempt_step $step) {
710 return $this->behaviour->summarise_action($step);
711 }
712
713 /**
714 * Helper function used by {@link rewrite_pluginfile_urls()} and
715 * {@link rewrite_response_pluginfile_urls()}.
716 * @return array ids that need to go into the file paths.
717 */
718 protected function extra_file_path_components() {
719 return array($this->get_usage_id(), $this->get_slot());
720 }
721
722 /**
723 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
724 * for content belonging to this question.
725 * @param string $text the content to output.
726 * @param string $component the component name (normally 'question' or 'qtype_...')
727 * @param string $filearea the name of the file area.
728 * @param int $itemid the item id.
729 * @return srting the content with the URLs rewritten.
730 */
731 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
732 return question_rewrite_question_urls($text, 'pluginfile.php',
733 $this->question->contextid, $component, $filearea,
734 $this->extra_file_path_components(), $itemid);
735 }
736
737 /**
738 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
739 * for content belonging to responses to this question.
740 *
741 * @param string $text the text to update the URLs in.
742 * @param int $contextid the id of the context the quba belongs to.
743 * @param string $name the variable name the files belong to.
744 * @param question_attempt_step $step the step the response is coming from.
745 * @return srting the content with the URLs rewritten.
746 */
747 public function rewrite_response_pluginfile_urls($text, $contextid, $name,
748 question_attempt_step $step) {
749 return $step->rewrite_response_pluginfile_urls($text, $contextid, $name,
750 $this->extra_file_path_components());
751 }
752
753 /**
754 * Get the {@link core_question_renderer}, in collaboration with appropriate
755 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
756 * HTML to display this question attempt in its current state.
757 * @param question_display_options $options controls how the question is rendered.
758 * @param string|null $number The question number to display.
759 * @return string HTML fragment representing the question.
760 */
761 public function render($options, $number, $page = null) {
762 if (is_null($page)) {
763 global $PAGE;
764 $page = $PAGE;
765 }
766 $qoutput = $page->get_renderer('core', 'question');
767 $qtoutput = $this->question->get_renderer($page);
768 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
769 }
770
771 /**
772 * Generate any bits of HTML that needs to go in the <head> tag when this question
773 * attempt is displayed in the body.
774 * @return string HTML fragment.
775 */
776 public function render_head_html($page = null) {
777 if (is_null($page)) {
778 global $PAGE;
779 $page = $PAGE;
780 }
781 // TODO go via behaviour.
782 return $this->question->get_renderer($page)->head_code($this) .
783 $this->behaviour->get_renderer($page)->head_code($this);
784 }
785
786 /**
787 * Like {@link render_question()} but displays the question at the past step
788 * indicated by $seq, rather than showing the latest step.
789 *
790 * @param int $seq the seq number of the past state to display.
791 * @param question_display_options $options controls how the question is rendered.
792 * @param string|null $number The question number to display. 'i' is a special
793 * value that gets displayed as Information. Null means no number is displayed.
794 * @return string HTML fragment representing the question.
795 */
796 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
797 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
798 return $restrictedqa->render($options, $number);
799 }
800
801 /**
802 * Checks whether the users is allow to be served a particular file.
803 * @param question_display_options $options the options that control display of the question.
804 * @param string $component the name of the component we are serving files for.
805 * @param string $filearea the name of the file area.
806 * @param array $args the remaining bits of the file path.
807 * @param bool $forcedownload whether the user must be forced to download the file.
808 * @return bool true if the user can access this file.
809 */
810 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
811 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
812 }
813
814 /**
815 * Add a step to this question attempt.
816 * @param question_attempt_step $step the new step.
817 */
818 protected function add_step(question_attempt_step $step) {
819 $this->steps[] = $step;
820 end($this->steps);
821 $this->observer->notify_step_added($step, $this, key($this->steps));
822 }
823
0a606a2b
TH
824 /**
825 * Add an auto-saved step to this question attempt. We mark auto-saved steps by
826 * changing saving the step number with a - sign.
827 * @param question_attempt_step $step the new step.
828 */
829 protected function add_autosaved_step(question_attempt_step $step) {
830 $this->steps[] = $step;
831 $this->autosavedstep = $step;
832 end($this->steps);
833 $this->observer->notify_step_added($step, $this, -key($this->steps));
834 }
835
836 /**
837 * Discard any auto-saved data belonging to this question attempt.
838 */
839 public function discard_autosaved_step() {
840 if (!$this->has_autosaved_step()) {
841 return;
842 }
843
844 $autosaved = array_pop($this->steps);
845 $this->autosavedstep = null;
846 $this->observer->notify_step_deleted($autosaved, $this);
847 }
848
1da821bb
TH
849 /**
850 * Use a strategy to pick a variant.
851 * @param question_variant_selection_strategy $variantstrategy a strategy.
852 * @return int the selected variant.
853 */
854 public function select_variant(question_variant_selection_strategy $variantstrategy) {
855 return $variantstrategy->choose_variant($this->get_question()->get_num_variants(),
856 $this->get_question()->get_variants_selection_seed());
857 }
858
dcd03928
TH
859 /**
860 * Start this question attempt.
861 *
862 * You should not call this method directly. Call
863 * {@link question_usage_by_activity::start_question()} instead.
864 *
865 * @param string|question_behaviour $preferredbehaviour the name of the
866 * desired archetypal behaviour, or an actual model instance.
1da821bb
TH
867 * @param int $variant the variant of the question to start. Between 1 and
868 * $this->get_question()->get_num_variants() inclusive.
dcd03928
TH
869 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
870 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
871 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
94815ccf
TH
872 * @param int $existingstepid optional, if this step is going to replace an existing step
873 * (for example, during a regrade) this is the id of the previous step we are replacing.
dcd03928 874 */
1da821bb 875 public function start($preferredbehaviour, $variant, $submitteddata = array(),
94815ccf 876 $timestamp = null, $userid = null, $existingstepid = null) {
1da821bb 877
dcd03928 878 // Initialise the behaviour.
1da821bb 879 $this->variant = $variant;
dcd03928
TH
880 if (is_string($preferredbehaviour)) {
881 $this->behaviour =
882 $this->question->make_behaviour($this, $preferredbehaviour);
883 } else {
884 $class = get_class($preferredbehaviour);
885 $this->behaviour = new $class($this, $preferredbehaviour);
886 }
887
888 // Record the minimum fraction.
889 $this->minfraction = $this->behaviour->get_min_fraction();
890
891 // Initialise the first step.
94815ccf 892 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid, $existingstepid);
dcd03928 893 if ($submitteddata) {
f8e28244
RK
894 $firststep->set_state(question_state::$complete);
895 $this->behaviour->apply_attempt_state($firststep);
dcd03928 896 } else {
1da821bb 897 $this->behaviour->init_first_step($firststep, $variant);
dcd03928
TH
898 }
899 $this->add_step($firststep);
900
901 // Record questionline and correct answer.
902 $this->questionsummary = $this->behaviour->get_question_summary();
903 $this->rightanswer = $this->behaviour->get_right_answer_summary();
904 }
905
906 /**
907 * Start this question attempt, starting from the point that the previous
908 * attempt $oldqa had reached.
909 *
910 * You should not call this method directly. Call
911 * {@link question_usage_by_activity::start_question_based_on()} instead.
912 *
913 * @param question_attempt $oldqa a previous attempt at this quetsion that
914 * defines the starting point.
915 */
916 public function start_based_on(question_attempt $oldqa) {
1da821bb 917 $this->start($oldqa->behaviour, $oldqa->get_variant(), $oldqa->get_resume_data());
dcd03928
TH
918 }
919
920 /**
921 * Used by {@link start_based_on()} to get the data needed to start a new
922 * attempt from the point this attempt has go to.
923 * @return array name => value pairs.
924 */
925 protected function get_resume_data() {
afb1b3d0
TH
926 $resumedata = $this->behaviour->get_resume_data();
927 foreach ($resumedata as $name => $value) {
928 if ($value instanceof question_file_loader) {
929 $resumedata[$name] = $value->get_question_file_saver();
930 }
931 }
932 return $resumedata;
dcd03928
TH
933 }
934
935 /**
936 * Get a particular parameter from the current request. A wrapper round
937 * {@link optional_param()}, except that the results is returned without
938 * slashes.
939 * @param string $name the paramter name.
940 * @param int $type one of the standard PARAM_... constants, or one of the
941 * special extra constands defined by this class.
942 * @param array $postdata (optional, only inteded for testing use) take the
943 * data from this array, instead of from $_POST.
944 * @return mixed the requested value.
945 */
946 public function get_submitted_var($name, $type, $postdata = null) {
947 switch ($type) {
948 case self::PARAM_MARK:
61cca0b7 949 // Special case to work around PARAM_FLOAT converting '' to 0.
2c76c894 950 return question_utils::clean_param_mark($this->get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata));
dcd03928
TH
951
952 case self::PARAM_FILES:
953 return $this->process_response_files($name, $name, $postdata);
954
2d2018ab
TH
955 case self::PARAM_RAW_FILES:
956 $var = $this->get_submitted_var($name, PARAM_RAW, $postdata);
dcd03928
TH
957 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
958
959 default:
960 if (is_null($postdata)) {
961 $var = optional_param($name, null, $type);
962 } else if (array_key_exists($name, $postdata)) {
963 $var = clean_param($postdata[$name], $type);
964 } else {
965 $var = null;
966 }
967
968 return $var;
969 }
970 }
971
972 /**
973 * Handle a submitted variable representing uploaded files.
974 * @param string $name the field name.
975 * @param string $draftidname the field name holding the draft file area id.
976 * @param array $postdata (optional, only inteded for testing use) take the
977 * data from this array, instead of from $_POST. At the moment, this
978 * behaves as if there were no files.
979 * @param string $text optional reponse text.
980 * @return question_file_saver that can be used to save the files later.
981 */
982 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
983 if ($postdata) {
afb1b3d0
TH
984 // For simulated posts, get the draft itemid from there.
985 $draftitemid = $this->get_submitted_var($draftidname, PARAM_INT, $postdata);
986 } else {
987 $draftitemid = file_get_submitted_draft_itemid($draftidname);
dcd03928
TH
988 }
989
dcd03928
TH
990 if (!$draftitemid) {
991 return null;
992 }
993
994 return new question_file_saver($draftitemid, 'question', 'response_' .
995 str_replace($this->get_field_prefix(), '', $name), $text);
996 }
997
998 /**
999 * Get any data from the request that matches the list of expected params.
1000 * @param array $expected variable name => PARAM_... constant.
1001 * @param string $extraprefix '-' or ''.
1002 * @return array name => value.
1003 */
1004 protected function get_expected_data($expected, $postdata, $extraprefix) {
1005 $submitteddata = array();
1006 foreach ($expected as $name => $type) {
1007 $value = $this->get_submitted_var(
1008 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
1009 if (!is_null($value)) {
1010 $submitteddata[$extraprefix . $name] = $value;
1011 }
1012 }
1013 return $submitteddata;
1014 }
1015
1016 /**
1017 * Get all the submitted question type data for this question, whithout checking
1018 * that it is valid or cleaning it in any way.
1019 * @return array name => value.
1020 */
df7d175d 1021 public function get_all_submitted_qt_vars($postdata) {
dcd03928
TH
1022 if (is_null($postdata)) {
1023 $postdata = $_POST;
1024 }
1025
03cefcc9 1026 $pattern = '/^' . preg_quote($this->get_field_prefix(), '/') . '[^-:]/';
dcd03928
TH
1027 $prefixlen = strlen($this->get_field_prefix());
1028
1029 $submitteddata = array();
df7d175d 1030 foreach ($postdata as $name => $value) {
dcd03928
TH
1031 if (preg_match($pattern, $name)) {
1032 $submitteddata[substr($name, $prefixlen)] = $value;
1033 }
1034 }
1035
1036 return $submitteddata;
1037 }
1038
1039 /**
1040 * Get all the sumbitted data belonging to this question attempt from the
1041 * current request.
1042 * @param array $postdata (optional, only inteded for testing use) take the
1043 * data from this array, instead of from $_POST.
1044 * @return array name => value pairs that could be passed to {@link process_action()}.
1045 */
1046 public function get_submitted_data($postdata = null) {
1047 $submitteddata = $this->get_expected_data(
1048 $this->behaviour->get_expected_data(), $postdata, '-');
1049
1050 $expected = $this->behaviour->get_expected_qt_data();
1051 if ($expected === self::USE_RAW_DATA) {
1052 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
1053 } else {
1054 $submitteddata += $this->get_expected_data($expected, $postdata, '');
1055 }
1056 return $submitteddata;
1057 }
1058
1059 /**
1060 * Get a set of response data for this question attempt that would get the
da22c012
K
1061 * best possible mark. If it is not possible to compute a correct
1062 * response, this method should return null.
1063 * @return array|null name => value pairs that could be passed to {@link process_action()}.
dcd03928
TH
1064 */
1065 public function get_correct_response() {
1066 $response = $this->question->get_correct_response();
da22c012
K
1067 if (is_null($response)) {
1068 return null;
1069 }
dcd03928
TH
1070 $imvars = $this->behaviour->get_correct_response();
1071 foreach ($imvars as $name => $value) {
1072 $response['-' . $name] = $value;
1073 }
1074 return $response;
1075 }
1076
1077 /**
1078 * Change the quetsion summary. Note, that this is almost never necessary.
1079 * This method was only added to work around a limitation of the Opaque
1080 * protocol, which only sends questionLine at the end of an attempt.
1081 * @param $questionsummary the new summary to set.
1082 */
1083 public function set_question_summary($questionsummary) {
1084 $this->questionsummary = $questionsummary;
1085 $this->observer->notify_attempt_modified($this);
1086 }
1087
1088 /**
1089 * @return string a simple textual summary of the question that was asked.
1090 */
1091 public function get_question_summary() {
1092 return $this->questionsummary;
1093 }
1094
1095 /**
1096 * @return string a simple textual summary of response given.
1097 */
1098 public function get_response_summary() {
1099 return $this->responsesummary;
1100 }
1101
1102 /**
1103 * @return string a simple textual summary of the correct resonse.
1104 */
1105 public function get_right_answer_summary() {
1106 return $this->rightanswer;
1107 }
1108
1109 /**
1110 * Perform the action described by $submitteddata.
1111 * @param array $submitteddata the submitted data the determines the action.
1112 * @param int $timestamp the time to record for the action. (If not given, use now.)
0a606a2b
TH
1113 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1114 * @param int $existingstepid used by the regrade code.
dcd03928 1115 */
94815ccf
TH
1116 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1117 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid, $existingstepid);
0a606a2b 1118 $this->discard_autosaved_step();
dcd03928
TH
1119 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1120 $this->add_step($pendingstep);
1121 if ($pendingstep->response_summary_changed()) {
1122 $this->responsesummary = $pendingstep->get_new_response_summary();
1123 }
1124 }
1125 }
1126
0a606a2b
TH
1127 /**
1128 * Process an autosave.
1129 * @param array $submitteddata the submitted data the determines the action.
1130 * @param int $timestamp the time to record for the action. (If not given, use now.)
1131 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1132 * @return bool whether anything was saved.
1133 */
1134 public function process_autosave($submitteddata, $timestamp = null, $userid = null) {
1135 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1136 if ($this->behaviour->process_autosave($pendingstep) == self::KEEP) {
1137 $this->add_autosaved_step($pendingstep);
1138 return true;
1139 }
1140 return false;
1141 }
1142
dcd03928
TH
1143 /**
1144 * Perform a finish action on this question attempt. This corresponds to an
1145 * external finish action, for example the user pressing Submit all and finish
1146 * in the quiz, rather than using one of the controls that is part of the
1147 * question.
1148 *
1149 * @param int $timestamp the time to record for the action. (If not given, use now.)
1150 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1151 */
1152 public function finish($timestamp = null, $userid = null) {
1153 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1154 }
1155
1156 /**
1157 * Perform a regrade. This replays all the actions from $oldqa into this
1158 * attempt.
1159 * @param question_attempt $oldqa the attempt to regrade.
1160 * @param bool $finished whether the question attempt should be forced to be finished
1161 * after the regrade, or whether it may still be in progress (default false).
1162 */
1163 public function regrade(question_attempt $oldqa, $finished) {
1164 $first = true;
1165 foreach ($oldqa->get_step_iterator() as $step) {
94815ccf 1166 $this->observer->notify_step_deleted($step, $this);
9212fe7a 1167
dcd03928 1168 if ($first) {
9212fe7a 1169 // First step of the attempt.
dcd03928 1170 $first = false;
1da821bb 1171 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
94815ccf 1172 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
9212fe7a
TH
1173
1174 } else if ($step->has_behaviour_var('finish') && count($step->get_submitted_data()) > 1) {
1175 // This case relates to MDL-32062. The upgrade code from 2.0
1176 // generates attempts where the final submit of the question
1177 // data, and the finish action, are in the same step. The system
1178 // cannot cope with that, so convert the single old step into
1179 // two new steps.
1180 $submitteddata = $step->get_submitted_data();
1181 unset($submitteddata['-finish']);
1182 $this->process_action($submitteddata,
1183 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1184 $this->finish($step->get_timecreated(), $step->get_user_id());
1185
dcd03928 1186 } else {
9212fe7a 1187 // This is the normal case. Replay the next step of the attempt.
dcd03928 1188 $this->process_action($step->get_submitted_data(),
94815ccf 1189 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
dcd03928
TH
1190 }
1191 }
9212fe7a 1192
dcd03928
TH
1193 if ($finished) {
1194 $this->finish();
1195 }
1196 }
1197
1198 /**
1199 * Perform a manual grading action on this attempt.
53b8e256
TH
1200 * @param string $comment the comment being added.
1201 * @param float $mark the new mark. If null, then only a comment is added.
1202 * @param int $commentformat the FORMAT_... for $comment. Must be given.
dcd03928
TH
1203 * @param int $timestamp the time to record for the action. (If not given, use now.)
1204 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
dcd03928 1205 */
53b8e256 1206 public function manual_grade($comment, $mark, $commentformat = null, $timestamp = null, $userid = null) {
dcd03928 1207 $submitteddata = array('-comment' => $comment);
53b8e256
TH
1208 if (is_null($commentformat)) {
1209 debugging('You should pass $commentformat to manual_grade.', DEBUG_DEVELOPER);
1210 $commentformat = FORMAT_HTML;
1211 }
1212 $submitteddata['-commentformat'] = $commentformat;
dcd03928
TH
1213 if (!is_null($mark)) {
1214 $submitteddata['-mark'] = $mark;
1215 $submitteddata['-maxmark'] = $this->maxmark;
1216 }
1217 $this->process_action($submitteddata, $timestamp, $userid);
1218 }
1219
1220 /** @return bool Whether this question attempt has had a manual comment added. */
1221 public function has_manual_comment() {
1222 foreach ($this->steps as $step) {
1223 if ($step->has_behaviour_var('comment')) {
1224 return true;
1225 }
1226 }
1227 return false;
1228 }
1229
1230 /**
1231 * @return array(string, int) the most recent manual comment that was added
1232 * to this question, and the FORMAT_... it is.
1233 */
1234 public function get_manual_comment() {
1235 foreach ($this->get_reverse_step_iterator() as $step) {
1236 if ($step->has_behaviour_var('comment')) {
1237 return array($step->get_behaviour_var('comment'),
1238 $step->get_behaviour_var('commentformat'));
1239 }
1240 }
1241 return array(null, null);
1242 }
1243
1244 /**
d50b05e6
JP
1245 * Break down a student response by sub part and classification.
1246 * See also {@link question_type::get_possible_responses()}
1247 * Used for response analysis.
1248 *
1249 * @return question_possible_response[] where keys are subpartid.
dcd03928
TH
1250 */
1251 public function classify_response() {
1252 return $this->behaviour->classify_response();
1253 }
1254
1255 /**
1256 * Create a question_attempt_step from records loaded from the database.
1257 *
1258 * For internal use only.
1259 *
35d5f1c2 1260 * @param Iterator $records Raw records loaded from the database.
dcd03928 1261 * @param int $questionattemptid The id of the question_attempt to extract.
94815ccf 1262 * @return question_attempt The newly constructed question_attempt.
dcd03928 1263 */
35d5f1c2 1264 public static function load_from_records($records, $questionattemptid,
dcd03928 1265 question_usage_observer $observer, $preferredbehaviour) {
35d5f1c2 1266 $record = $records->current();
dcd03928 1267 while ($record->questionattemptid != $questionattemptid) {
35d5f1c2
TH
1268 $record = $records->next();
1269 if (!$records->valid()) {
dcd03928
TH
1270 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
1271 }
35d5f1c2 1272 $record = $records->current();
dcd03928
TH
1273 }
1274
1275 try {
1276 $question = question_bank::load_question($record->questionid);
1277 } catch (Exception $e) {
1278 // The question must have been deleted somehow. Create a missing
1279 // question to use in its place.
1280 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1281 $record->questionid, $record->maxmark + 0);
1282 }
1283
1284 $qa = new question_attempt($question, $record->questionusageid,
1285 null, $record->maxmark + 0);
1286 $qa->set_database_id($record->questionattemptid);
94815ccf 1287 $qa->set_slot($record->slot);
1da821bb 1288 $qa->variant = $record->variant + 0;
dcd03928
TH
1289 $qa->minfraction = $record->minfraction + 0;
1290 $qa->set_flagged($record->flagged);
1291 $qa->questionsummary = $record->questionsummary;
1292 $qa->rightanswer = $record->rightanswer;
1293 $qa->responsesummary = $record->responsesummary;
1294 $qa->timemodified = $record->timemodified;
1295
1296 $qa->behaviour = question_engine::make_behaviour(
1297 $record->behaviour, $qa, $preferredbehaviour);
0a606a2b 1298 $qa->observer = $observer;
dcd03928 1299
dd7aa583
TH
1300 // If attemptstepid is null (which should not happen, but has happened
1301 // due to corrupt data, see MDL-34251) then the current pointer in $records
1302 // will not be advanced in the while loop below, and we get stuck in an
1303 // infinite loop, since this method is supposed to always consume at
1304 // least one record. Therefore, in this case, advance the record here.
1305 if (is_null($record->attemptstepid)) {
1306 $records->next();
1307 }
1308
dcd03928 1309 $i = 0;
0a606a2b
TH
1310 $autosavedstep = null;
1311 $autosavedsequencenumber = null;
dcd03928 1312 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
0a606a2b 1313 $sequencenumber = $record->sequencenumber;
dc1ee5cb 1314 $nextstep = question_attempt_step::load_from_records($records, $record->attemptstepid, $qa->get_question()->get_type_name());
0a606a2b
TH
1315
1316 if ($sequencenumber < 0) {
1317 if (!$autosavedstep) {
1318 $autosavedstep = $nextstep;
1319 $autosavedsequencenumber = -$sequencenumber;
1320 } else {
1321 // Old redundant data. Mark it for deletion.
1322 $qa->observer->notify_step_deleted($nextstep, $qa);
1323 }
1324 } else {
1325 $qa->steps[$i] = $nextstep;
1326 if ($i == 0) {
1327 $question->apply_attempt_state($qa->steps[0]);
1328 }
1329 $i++;
dcd03928 1330 }
0a606a2b 1331
35d5f1c2
TH
1332 if ($records->valid()) {
1333 $record = $records->current();
1334 } else {
1335 $record = false;
1336 }
dcd03928
TH
1337 }
1338
0a606a2b
TH
1339 if ($autosavedstep) {
1340 if ($autosavedsequencenumber >= $i) {
1341 $qa->autosavedstep = $autosavedstep;
1342 $qa->steps[$i] = $qa->autosavedstep;
1343 } else {
1344 $qa->observer->notify_step_deleted($autosavedstep, $qa);
1345 }
1346 }
dcd03928
TH
1347
1348 return $qa;
1349 }
1350}
1351
1352
1353/**
1354 * This subclass of question_attempt pretends that only part of the step history
1355 * exists. It is used for rendering the question in past states.
1356 *
1357 * All methods that try to modify the question_attempt throw exceptions.
1358 *
1359 * @copyright 2010 The Open University
1360 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1361 */
1362class question_attempt_with_restricted_history extends question_attempt {
1363 /**
1364 * @var question_attempt the underlying question_attempt.
1365 */
1366 protected $baseqa;
1367
1368 /**
1369 * Create a question_attempt_with_restricted_history
1370 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1371 * @param int $lastseq the index of the last step to include.
1372 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1373 * annoyting that this needs to be passed, but unavoidable for now.
1374 */
1375 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
f123d67f
TH
1376 $this->baseqa = $baseqa->get_full_qa();
1377
1378 if ($lastseq < 0 || $lastseq >= $this->baseqa->get_num_steps()) {
1379 throw new coding_exception('$lastseq out of range', $lastseq);
dcd03928
TH
1380 }
1381
f123d67f 1382 $this->steps = array_slice($this->baseqa->steps, 0, $lastseq + 1);
dcd03928
TH
1383 $this->observer = new question_usage_null_observer();
1384
1385 // This should be a straight copy of all the remaining fields.
f123d67f
TH
1386 $this->id = $this->baseqa->id;
1387 $this->usageid = $this->baseqa->usageid;
1388 $this->slot = $this->baseqa->slot;
1389 $this->question = $this->baseqa->question;
1390 $this->maxmark = $this->baseqa->maxmark;
1391 $this->minfraction = $this->baseqa->minfraction;
1392 $this->questionsummary = $this->baseqa->questionsummary;
1393 $this->responsesummary = $this->baseqa->responsesummary;
1394 $this->rightanswer = $this->baseqa->rightanswer;
1395 $this->flagged = $this->baseqa->flagged;
dcd03928
TH
1396
1397 // Except behaviour, where we need to create a new one.
1398 $this->behaviour = question_engine::make_behaviour(
f123d67f
TH
1399 $this->baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1400 }
1401
1402 public function get_full_qa() {
1403 return $this->baseqa;
dcd03928
TH
1404 }
1405
1406 public function get_full_step_iterator() {
1407 return $this->baseqa->get_step_iterator();
1408 }
1409
1410 protected function add_step(question_attempt_step $step) {
1411 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1412 }
072db71c 1413 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1414 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1415 }
072db71c 1416 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1417 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1418 }
1419
1420 public function set_database_id($id) {
1421 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1422 }
1423 public function set_flagged($flagged) {
1424 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1425 }
94815ccf 1426 public function set_slot($slot) {
dcd03928
TH
1427 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1428 }
1429 public function set_question_summary($questionsummary) {
1430 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1431 }
1432 public function set_usage_id($usageid) {
1433 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1434 }
1435}
1436
1437
1438/**
1439 * A class abstracting access to the {@link question_attempt::$states} array.
1440 *
1441 * This is actively linked to question_attempt. If you add an new step
1442 * mid-iteration, then it will be included.
1443 *
1444 * @copyright 2009 The Open University
1445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1446 */
1447class question_attempt_step_iterator implements Iterator, ArrayAccess {
1448 /** @var question_attempt the question_attempt being iterated over. */
1449 protected $qa;
1450 /** @var integer records the current position in the iteration. */
1451 protected $i;
1452
1453 /**
1454 * Do not call this constructor directly.
1455 * Use {@link question_attempt::get_step_iterator()}.
1456 * @param question_attempt $qa the attempt to iterate over.
1457 */
1458 public function __construct(question_attempt $qa) {
1459 $this->qa = $qa;
1460 $this->rewind();
1461 }
1462
1463 /** @return question_attempt_step */
1464 public function current() {
1465 return $this->offsetGet($this->i);
1466 }
1467 /** @return int */
1468 public function key() {
1469 return $this->i;
1470 }
1471 public function next() {
1472 ++$this->i;
1473 }
1474 public function rewind() {
1475 $this->i = 0;
1476 }
1477 /** @return bool */
1478 public function valid() {
1479 return $this->offsetExists($this->i);
1480 }
1481
1482 /** @return bool */
1483 public function offsetExists($i) {
1484 return $i >= 0 && $i < $this->qa->get_num_steps();
1485 }
1486 /** @return question_attempt_step */
1487 public function offsetGet($i) {
1488 return $this->qa->get_step($i);
1489 }
1490 public function offsetSet($offset, $value) {
1491 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1492 }
1493 public function offsetUnset($offset) {
1494 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1495 }
1496}
1497
1498
1499/**
1500 * A variant of {@link question_attempt_step_iterator} that iterates through the
1501 * steps in reverse order.
1502 *
1503 * @copyright 2009 The Open University
1504 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1505 */
1506class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1507 public function next() {
1508 --$this->i;
1509 }
1510
1511 public function rewind() {
1512 $this->i = $this->qa->get_num_steps() - 1;
1513 }
1514}