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