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