MDL-31226: quiz: Fix message for attempts built on previous.
[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() {
926 return $this->behaviour->get_resume_data();
927 }
928
929 /**
930 * Get a particular parameter from the current request. A wrapper round
931 * {@link optional_param()}, except that the results is returned without
932 * slashes.
933 * @param string $name the paramter name.
934 * @param int $type one of the standard PARAM_... constants, or one of the
935 * special extra constands defined by this class.
936 * @param array $postdata (optional, only inteded for testing use) take the
937 * data from this array, instead of from $_POST.
938 * @return mixed the requested value.
939 */
940 public function get_submitted_var($name, $type, $postdata = null) {
941 switch ($type) {
942 case self::PARAM_MARK:
61cca0b7 943 // Special case to work around PARAM_FLOAT converting '' to 0.
2c76c894 944 return question_utils::clean_param_mark($this->get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata));
dcd03928
TH
945
946 case self::PARAM_FILES:
947 return $this->process_response_files($name, $name, $postdata);
948
2d2018ab
TH
949 case self::PARAM_RAW_FILES:
950 $var = $this->get_submitted_var($name, PARAM_RAW, $postdata);
dcd03928
TH
951 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
952
953 default:
954 if (is_null($postdata)) {
955 $var = optional_param($name, null, $type);
956 } else if (array_key_exists($name, $postdata)) {
957 $var = clean_param($postdata[$name], $type);
958 } else {
959 $var = null;
960 }
961
962 return $var;
963 }
964 }
965
966 /**
967 * Handle a submitted variable representing uploaded files.
968 * @param string $name the field name.
969 * @param string $draftidname the field name holding the draft file area id.
970 * @param array $postdata (optional, only inteded for testing use) take the
971 * data from this array, instead of from $_POST. At the moment, this
972 * behaves as if there were no files.
973 * @param string $text optional reponse text.
974 * @return question_file_saver that can be used to save the files later.
975 */
976 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
977 if ($postdata) {
978 // There can be no files with test data (at the moment).
979 return null;
980 }
981
982 $draftitemid = file_get_submitted_draft_itemid($draftidname);
983 if (!$draftitemid) {
984 return null;
985 }
986
987 return new question_file_saver($draftitemid, 'question', 'response_' .
988 str_replace($this->get_field_prefix(), '', $name), $text);
989 }
990
991 /**
992 * Get any data from the request that matches the list of expected params.
993 * @param array $expected variable name => PARAM_... constant.
994 * @param string $extraprefix '-' or ''.
995 * @return array name => value.
996 */
997 protected function get_expected_data($expected, $postdata, $extraprefix) {
998 $submitteddata = array();
999 foreach ($expected as $name => $type) {
1000 $value = $this->get_submitted_var(
1001 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
1002 if (!is_null($value)) {
1003 $submitteddata[$extraprefix . $name] = $value;
1004 }
1005 }
1006 return $submitteddata;
1007 }
1008
1009 /**
1010 * Get all the submitted question type data for this question, whithout checking
1011 * that it is valid or cleaning it in any way.
1012 * @return array name => value.
1013 */
1014 protected function get_all_submitted_qt_vars($postdata) {
1015 if (is_null($postdata)) {
1016 $postdata = $_POST;
1017 }
1018
03cefcc9 1019 $pattern = '/^' . preg_quote($this->get_field_prefix(), '/') . '[^-:]/';
dcd03928
TH
1020 $prefixlen = strlen($this->get_field_prefix());
1021
1022 $submitteddata = array();
1023 foreach ($_POST as $name => $value) {
1024 if (preg_match($pattern, $name)) {
1025 $submitteddata[substr($name, $prefixlen)] = $value;
1026 }
1027 }
1028
1029 return $submitteddata;
1030 }
1031
1032 /**
1033 * Get all the sumbitted data belonging to this question attempt from the
1034 * current request.
1035 * @param array $postdata (optional, only inteded for testing use) take the
1036 * data from this array, instead of from $_POST.
1037 * @return array name => value pairs that could be passed to {@link process_action()}.
1038 */
1039 public function get_submitted_data($postdata = null) {
1040 $submitteddata = $this->get_expected_data(
1041 $this->behaviour->get_expected_data(), $postdata, '-');
1042
1043 $expected = $this->behaviour->get_expected_qt_data();
1044 if ($expected === self::USE_RAW_DATA) {
1045 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
1046 } else {
1047 $submitteddata += $this->get_expected_data($expected, $postdata, '');
1048 }
1049 return $submitteddata;
1050 }
1051
1052 /**
1053 * Get a set of response data for this question attempt that would get the
da22c012
K
1054 * best possible mark. If it is not possible to compute a correct
1055 * response, this method should return null.
1056 * @return array|null name => value pairs that could be passed to {@link process_action()}.
dcd03928
TH
1057 */
1058 public function get_correct_response() {
1059 $response = $this->question->get_correct_response();
da22c012
K
1060 if (is_null($response)) {
1061 return null;
1062 }
dcd03928
TH
1063 $imvars = $this->behaviour->get_correct_response();
1064 foreach ($imvars as $name => $value) {
1065 $response['-' . $name] = $value;
1066 }
1067 return $response;
1068 }
1069
1070 /**
1071 * Change the quetsion summary. Note, that this is almost never necessary.
1072 * This method was only added to work around a limitation of the Opaque
1073 * protocol, which only sends questionLine at the end of an attempt.
1074 * @param $questionsummary the new summary to set.
1075 */
1076 public function set_question_summary($questionsummary) {
1077 $this->questionsummary = $questionsummary;
1078 $this->observer->notify_attempt_modified($this);
1079 }
1080
1081 /**
1082 * @return string a simple textual summary of the question that was asked.
1083 */
1084 public function get_question_summary() {
1085 return $this->questionsummary;
1086 }
1087
1088 /**
1089 * @return string a simple textual summary of response given.
1090 */
1091 public function get_response_summary() {
1092 return $this->responsesummary;
1093 }
1094
1095 /**
1096 * @return string a simple textual summary of the correct resonse.
1097 */
1098 public function get_right_answer_summary() {
1099 return $this->rightanswer;
1100 }
1101
1102 /**
1103 * Perform the action described by $submitteddata.
1104 * @param array $submitteddata the submitted data the determines the action.
1105 * @param int $timestamp the time to record for the action. (If not given, use now.)
0a606a2b
TH
1106 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1107 * @param int $existingstepid used by the regrade code.
dcd03928 1108 */
94815ccf
TH
1109 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1110 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid, $existingstepid);
0a606a2b 1111 $this->discard_autosaved_step();
dcd03928
TH
1112 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1113 $this->add_step($pendingstep);
1114 if ($pendingstep->response_summary_changed()) {
1115 $this->responsesummary = $pendingstep->get_new_response_summary();
1116 }
1117 }
1118 }
1119
0a606a2b
TH
1120 /**
1121 * Process an autosave.
1122 * @param array $submitteddata the submitted data the determines the action.
1123 * @param int $timestamp the time to record for the action. (If not given, use now.)
1124 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1125 * @return bool whether anything was saved.
1126 */
1127 public function process_autosave($submitteddata, $timestamp = null, $userid = null) {
1128 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1129 if ($this->behaviour->process_autosave($pendingstep) == self::KEEP) {
1130 $this->add_autosaved_step($pendingstep);
1131 return true;
1132 }
1133 return false;
1134 }
1135
dcd03928
TH
1136 /**
1137 * Perform a finish action on this question attempt. This corresponds to an
1138 * external finish action, for example the user pressing Submit all and finish
1139 * in the quiz, rather than using one of the controls that is part of the
1140 * question.
1141 *
1142 * @param int $timestamp the time to record for the action. (If not given, use now.)
1143 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1144 */
1145 public function finish($timestamp = null, $userid = null) {
1146 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1147 }
1148
1149 /**
1150 * Perform a regrade. This replays all the actions from $oldqa into this
1151 * attempt.
1152 * @param question_attempt $oldqa the attempt to regrade.
1153 * @param bool $finished whether the question attempt should be forced to be finished
1154 * after the regrade, or whether it may still be in progress (default false).
1155 */
1156 public function regrade(question_attempt $oldqa, $finished) {
1157 $first = true;
1158 foreach ($oldqa->get_step_iterator() as $step) {
94815ccf 1159 $this->observer->notify_step_deleted($step, $this);
9212fe7a 1160
dcd03928 1161 if ($first) {
9212fe7a 1162 // First step of the attempt.
dcd03928 1163 $first = false;
1da821bb 1164 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
94815ccf 1165 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
9212fe7a
TH
1166
1167 } else if ($step->has_behaviour_var('finish') && count($step->get_submitted_data()) > 1) {
1168 // This case relates to MDL-32062. The upgrade code from 2.0
1169 // generates attempts where the final submit of the question
1170 // data, and the finish action, are in the same step. The system
1171 // cannot cope with that, so convert the single old step into
1172 // two new steps.
1173 $submitteddata = $step->get_submitted_data();
1174 unset($submitteddata['-finish']);
1175 $this->process_action($submitteddata,
1176 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1177 $this->finish($step->get_timecreated(), $step->get_user_id());
1178
dcd03928 1179 } else {
9212fe7a 1180 // This is the normal case. Replay the next step of the attempt.
dcd03928 1181 $this->process_action($step->get_submitted_data(),
94815ccf 1182 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
dcd03928
TH
1183 }
1184 }
9212fe7a 1185
dcd03928
TH
1186 if ($finished) {
1187 $this->finish();
1188 }
1189 }
1190
1191 /**
1192 * Perform a manual grading action on this attempt.
53b8e256
TH
1193 * @param string $comment the comment being added.
1194 * @param float $mark the new mark. If null, then only a comment is added.
1195 * @param int $commentformat the FORMAT_... for $comment. Must be given.
dcd03928
TH
1196 * @param int $timestamp the time to record for the action. (If not given, use now.)
1197 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
dcd03928 1198 */
53b8e256 1199 public function manual_grade($comment, $mark, $commentformat = null, $timestamp = null, $userid = null) {
dcd03928 1200 $submitteddata = array('-comment' => $comment);
53b8e256
TH
1201 if (is_null($commentformat)) {
1202 debugging('You should pass $commentformat to manual_grade.', DEBUG_DEVELOPER);
1203 $commentformat = FORMAT_HTML;
1204 }
1205 $submitteddata['-commentformat'] = $commentformat;
dcd03928
TH
1206 if (!is_null($mark)) {
1207 $submitteddata['-mark'] = $mark;
1208 $submitteddata['-maxmark'] = $this->maxmark;
1209 }
1210 $this->process_action($submitteddata, $timestamp, $userid);
1211 }
1212
1213 /** @return bool Whether this question attempt has had a manual comment added. */
1214 public function has_manual_comment() {
1215 foreach ($this->steps as $step) {
1216 if ($step->has_behaviour_var('comment')) {
1217 return true;
1218 }
1219 }
1220 return false;
1221 }
1222
1223 /**
1224 * @return array(string, int) the most recent manual comment that was added
1225 * to this question, and the FORMAT_... it is.
1226 */
1227 public function get_manual_comment() {
1228 foreach ($this->get_reverse_step_iterator() as $step) {
1229 if ($step->has_behaviour_var('comment')) {
1230 return array($step->get_behaviour_var('comment'),
1231 $step->get_behaviour_var('commentformat'));
1232 }
1233 }
1234 return array(null, null);
1235 }
1236
1237 /**
1238 * @return array subpartid => object with fields
1239 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
1240 * ->response the actual response the student gave to this part, as a string.
1241 * ->fraction the credit awarded for this subpart, may be null.
1242 * returns an empty array if no analysis is possible.
1243 */
1244 public function classify_response() {
1245 return $this->behaviour->classify_response();
1246 }
1247
1248 /**
1249 * Create a question_attempt_step from records loaded from the database.
1250 *
1251 * For internal use only.
1252 *
35d5f1c2 1253 * @param Iterator $records Raw records loaded from the database.
dcd03928 1254 * @param int $questionattemptid The id of the question_attempt to extract.
94815ccf 1255 * @return question_attempt The newly constructed question_attempt.
dcd03928 1256 */
35d5f1c2 1257 public static function load_from_records($records, $questionattemptid,
dcd03928 1258 question_usage_observer $observer, $preferredbehaviour) {
35d5f1c2 1259 $record = $records->current();
dcd03928 1260 while ($record->questionattemptid != $questionattemptid) {
35d5f1c2
TH
1261 $record = $records->next();
1262 if (!$records->valid()) {
dcd03928
TH
1263 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
1264 }
35d5f1c2 1265 $record = $records->current();
dcd03928
TH
1266 }
1267
1268 try {
1269 $question = question_bank::load_question($record->questionid);
1270 } catch (Exception $e) {
1271 // The question must have been deleted somehow. Create a missing
1272 // question to use in its place.
1273 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1274 $record->questionid, $record->maxmark + 0);
1275 }
1276
1277 $qa = new question_attempt($question, $record->questionusageid,
1278 null, $record->maxmark + 0);
1279 $qa->set_database_id($record->questionattemptid);
94815ccf 1280 $qa->set_slot($record->slot);
1da821bb 1281 $qa->variant = $record->variant + 0;
dcd03928
TH
1282 $qa->minfraction = $record->minfraction + 0;
1283 $qa->set_flagged($record->flagged);
1284 $qa->questionsummary = $record->questionsummary;
1285 $qa->rightanswer = $record->rightanswer;
1286 $qa->responsesummary = $record->responsesummary;
1287 $qa->timemodified = $record->timemodified;
1288
1289 $qa->behaviour = question_engine::make_behaviour(
1290 $record->behaviour, $qa, $preferredbehaviour);
0a606a2b 1291 $qa->observer = $observer;
dcd03928 1292
dd7aa583
TH
1293 // If attemptstepid is null (which should not happen, but has happened
1294 // due to corrupt data, see MDL-34251) then the current pointer in $records
1295 // will not be advanced in the while loop below, and we get stuck in an
1296 // infinite loop, since this method is supposed to always consume at
1297 // least one record. Therefore, in this case, advance the record here.
1298 if (is_null($record->attemptstepid)) {
1299 $records->next();
1300 }
1301
dcd03928 1302 $i = 0;
0a606a2b
TH
1303 $autosavedstep = null;
1304 $autosavedsequencenumber = null;
dcd03928 1305 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
0a606a2b 1306 $sequencenumber = $record->sequencenumber;
dc1ee5cb 1307 $nextstep = question_attempt_step::load_from_records($records, $record->attemptstepid, $qa->get_question()->get_type_name());
0a606a2b
TH
1308
1309 if ($sequencenumber < 0) {
1310 if (!$autosavedstep) {
1311 $autosavedstep = $nextstep;
1312 $autosavedsequencenumber = -$sequencenumber;
1313 } else {
1314 // Old redundant data. Mark it for deletion.
1315 $qa->observer->notify_step_deleted($nextstep, $qa);
1316 }
1317 } else {
1318 $qa->steps[$i] = $nextstep;
1319 if ($i == 0) {
1320 $question->apply_attempt_state($qa->steps[0]);
1321 }
1322 $i++;
dcd03928 1323 }
0a606a2b 1324
35d5f1c2
TH
1325 if ($records->valid()) {
1326 $record = $records->current();
1327 } else {
1328 $record = false;
1329 }
dcd03928
TH
1330 }
1331
0a606a2b
TH
1332 if ($autosavedstep) {
1333 if ($autosavedsequencenumber >= $i) {
1334 $qa->autosavedstep = $autosavedstep;
1335 $qa->steps[$i] = $qa->autosavedstep;
1336 } else {
1337 $qa->observer->notify_step_deleted($autosavedstep, $qa);
1338 }
1339 }
dcd03928
TH
1340
1341 return $qa;
1342 }
1343}
1344
1345
1346/**
1347 * This subclass of question_attempt pretends that only part of the step history
1348 * exists. It is used for rendering the question in past states.
1349 *
1350 * All methods that try to modify the question_attempt throw exceptions.
1351 *
1352 * @copyright 2010 The Open University
1353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1354 */
1355class question_attempt_with_restricted_history extends question_attempt {
1356 /**
1357 * @var question_attempt the underlying question_attempt.
1358 */
1359 protected $baseqa;
1360
1361 /**
1362 * Create a question_attempt_with_restricted_history
1363 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1364 * @param int $lastseq the index of the last step to include.
1365 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1366 * annoyting that this needs to be passed, but unavoidable for now.
1367 */
1368 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
f123d67f
TH
1369 $this->baseqa = $baseqa->get_full_qa();
1370
1371 if ($lastseq < 0 || $lastseq >= $this->baseqa->get_num_steps()) {
1372 throw new coding_exception('$lastseq out of range', $lastseq);
dcd03928
TH
1373 }
1374
f123d67f 1375 $this->steps = array_slice($this->baseqa->steps, 0, $lastseq + 1);
dcd03928
TH
1376 $this->observer = new question_usage_null_observer();
1377
1378 // This should be a straight copy of all the remaining fields.
f123d67f
TH
1379 $this->id = $this->baseqa->id;
1380 $this->usageid = $this->baseqa->usageid;
1381 $this->slot = $this->baseqa->slot;
1382 $this->question = $this->baseqa->question;
1383 $this->maxmark = $this->baseqa->maxmark;
1384 $this->minfraction = $this->baseqa->minfraction;
1385 $this->questionsummary = $this->baseqa->questionsummary;
1386 $this->responsesummary = $this->baseqa->responsesummary;
1387 $this->rightanswer = $this->baseqa->rightanswer;
1388 $this->flagged = $this->baseqa->flagged;
dcd03928
TH
1389
1390 // Except behaviour, where we need to create a new one.
1391 $this->behaviour = question_engine::make_behaviour(
f123d67f
TH
1392 $this->baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1393 }
1394
1395 public function get_full_qa() {
1396 return $this->baseqa;
dcd03928
TH
1397 }
1398
1399 public function get_full_step_iterator() {
1400 return $this->baseqa->get_step_iterator();
1401 }
1402
1403 protected function add_step(question_attempt_step $step) {
1404 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1405 }
072db71c 1406 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1407 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1408 }
072db71c 1409 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1410 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1411 }
1412
1413 public function set_database_id($id) {
1414 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1415 }
1416 public function set_flagged($flagged) {
1417 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1418 }
94815ccf 1419 public function set_slot($slot) {
dcd03928
TH
1420 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1421 }
1422 public function set_question_summary($questionsummary) {
1423 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1424 }
1425 public function set_usage_id($usageid) {
1426 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1427 }
1428}
1429
1430
1431/**
1432 * A class abstracting access to the {@link question_attempt::$states} array.
1433 *
1434 * This is actively linked to question_attempt. If you add an new step
1435 * mid-iteration, then it will be included.
1436 *
1437 * @copyright 2009 The Open University
1438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1439 */
1440class question_attempt_step_iterator implements Iterator, ArrayAccess {
1441 /** @var question_attempt the question_attempt being iterated over. */
1442 protected $qa;
1443 /** @var integer records the current position in the iteration. */
1444 protected $i;
1445
1446 /**
1447 * Do not call this constructor directly.
1448 * Use {@link question_attempt::get_step_iterator()}.
1449 * @param question_attempt $qa the attempt to iterate over.
1450 */
1451 public function __construct(question_attempt $qa) {
1452 $this->qa = $qa;
1453 $this->rewind();
1454 }
1455
1456 /** @return question_attempt_step */
1457 public function current() {
1458 return $this->offsetGet($this->i);
1459 }
1460 /** @return int */
1461 public function key() {
1462 return $this->i;
1463 }
1464 public function next() {
1465 ++$this->i;
1466 }
1467 public function rewind() {
1468 $this->i = 0;
1469 }
1470 /** @return bool */
1471 public function valid() {
1472 return $this->offsetExists($this->i);
1473 }
1474
1475 /** @return bool */
1476 public function offsetExists($i) {
1477 return $i >= 0 && $i < $this->qa->get_num_steps();
1478 }
1479 /** @return question_attempt_step */
1480 public function offsetGet($i) {
1481 return $this->qa->get_step($i);
1482 }
1483 public function offsetSet($offset, $value) {
1484 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1485 }
1486 public function offsetUnset($offset) {
1487 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1488 }
1489}
1490
1491
1492/**
1493 * A variant of {@link question_attempt_step_iterator} that iterates through the
1494 * steps in reverse order.
1495 *
1496 * @copyright 2009 The Open University
1497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1498 */
1499class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1500 public function next() {
1501 --$this->i;
1502 }
1503
1504 public function rewind() {
1505 $this->i = $this->qa->get_num_steps() - 1;
1506 }
1507}