2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * This file defines the question attempt class, and a few related classes.
21 * @subpackage questionengine
22 * @copyright 2009 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
31 * Tracks an attempt at one particular question in a {@link question_usage_by_activity}.
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.
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.
41 * @copyright 2009 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class question_attempt {
46 * @var string this is a magic value that question types can return from
47 * {@link question_definition::get_expected_data()}.
49 const USE_RAW_DATA = 'use raw data';
52 * @var string special value used by manual grading because {@link PARAM_FLOAT}
55 const PARAM_MARK = 'parammark';
58 * @var string special value to indicate a response variable that is uploaded
61 const PARAM_FILES = 'paramfiles';
64 * @var string special value to indicate a response variable that is uploaded
67 const PARAM_RAW_FILES = 'paramrawfiles';
69 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
72 /** @var integer|string the id of the question_usage_by_activity we belong to. */
75 /** @var integer the number used to identify this question_attempt within the usage. */
76 protected $slot = null;
79 * @var question_behaviour the behaviour controlling this attempt.
80 * null until {@link start()} is called.
82 protected $behaviour = null;
84 /** @var question_definition the question this is an attempt at. */
87 /** @var int which variant of the question to use. */
90 /** @var number the maximum mark that can be scored at this question. */
94 * @var number the minimum fraction that can be scored at this question, so
95 * the minimum mark is $this->minfraction * $this->maxmark.
97 protected $minfraction = null;
100 * @var string plain text summary of the variant of the question the
101 * student saw. Intended for reporting purposes.
103 protected $questionsummary = null;
106 * @var string plain text summary of the response the student gave.
107 * Intended for reporting purposes.
109 protected $responsesummary = null;
112 * @var string plain text summary of the correct response to this question
113 * variant the student saw. The format should be similar to responsesummary.
114 * Intended for reporting purposes.
116 protected $rightanswer = null;
118 /** @var array of {@link question_attempt_step}s. The steps in this attempt. */
119 protected $steps = array();
122 * @var question_attempt_step if, when we loaded the step from the DB, there was
123 * an autosaved step, we save a pointer to it here. (It is also added to the $steps array.)
125 protected $autosavedstep = null;
127 /** @var boolean whether the user has flagged this attempt within the usage. */
128 protected $flagged = false;
130 /** @var question_usage_observer tracks changes to the useage this attempt is part of.*/
134 * Constants used by the intereaction models to indicate whether the current
135 * pending step should be kept or discarded.
138 const DISCARD = false;
142 * Create a new {@link question_attempt}. Normally you should create question_attempts
143 * indirectly, by calling {@link question_usage_by_activity::add_question()}.
145 * @param question_definition $question the question this is an attempt at.
146 * @param int|string $usageid The id of the
147 * {@link question_usage_by_activity} we belong to. Used by {@link get_field_prefix()}.
148 * @param question_usage_observer $observer tracks changes to the useage this
149 * attempt is part of. (Optional, a {@link question_usage_null_observer} is
150 * used if one is not passed.
151 * @param number $maxmark the maximum grade for this question_attempt. If not
152 * passed, $question->defaultmark is used.
154 public function __construct(question_definition $question, $usageid,
155 question_usage_observer $observer = null, $maxmark = null) {
156 $this->question = $question;
157 $this->usageid = $usageid;
158 if (is_null($observer)) {
159 $observer = new question_usage_null_observer();
161 $this->observer = $observer;
162 if (!is_null($maxmark)) {
163 $this->maxmark = $maxmark;
165 $this->maxmark = $question->defaultmark;
170 * This method exists so that {@link question_attempt_with_restricted_history}
171 * can override it. You should not normally need to call it.
172 * @return question_attempt return ourself.
174 public function get_full_qa() {
178 /** @return question_definition the question this is an attempt at. */
179 public function get_question() {
180 return $this->question;
184 * Get the variant of the question being used in a given slot.
185 * @return int the variant number.
187 public function get_variant() {
188 return $this->variant;
192 * Set the number used to identify this question_attempt within the usage.
193 * For internal use only.
196 public function set_slot($slot) {
200 /** @return int the number used to identify this question_attempt within the usage. */
201 public function get_slot() {
206 * @return int the id of row for this question_attempt, if it is stored in the
207 * database. null if not.
209 public function get_database_id() {
214 * For internal use only. Set the id of the corresponding database row.
215 * @param int $id the id of row for this question_attempt, if it is
216 * stored in the database.
218 public function set_database_id($id) {
223 * You should almost certainly not call this method from your code. It is for
225 * @param question_usage_observer that should be used to tracking changes made to this qa.
227 public function set_observer($observer) {
228 $this->observer = $observer;
231 /** @return int|string the id of the {@link question_usage_by_activity} we belong to. */
232 public function get_usage_id() {
233 return $this->usageid;
237 * Set the id of the {@link question_usage_by_activity} we belong to.
238 * For internal use only.
239 * @param int|string the new id.
241 public function set_usage_id($usageid) {
242 $this->usageid = $usageid;
245 /** @return string the name of the behaviour that is controlling this attempt. */
246 public function get_behaviour_name() {
247 return $this->behaviour->get_name();
251 * For internal use only.
252 * @return question_behaviour the behaviour that is controlling this attempt.
254 public function get_behaviour() {
255 return $this->behaviour;
259 * Set the flagged state of this question.
260 * @param bool $flagged the new state.
262 public function set_flagged($flagged) {
263 $this->flagged = $flagged;
264 $this->observer->notify_attempt_modified($this);
267 /** @return bool whether this question is currently flagged. */
268 public function is_flagged() {
269 return $this->flagged;
273 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
274 * name) to use for the field that indicates whether this question is flagged.
276 * @return string The field name to use.
278 public function get_flag_field_name() {
279 return $this->get_control_field_name('flagged');
283 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
284 * name) to use for a question_type variable belonging to this question_attempt.
286 * See the comment on {@link question_attempt_step} for an explanation of
287 * question type and behaviour variables.
289 * @param $varname The short form of the variable name.
290 * @return string The field name to use.
292 public function get_qt_field_name($varname) {
293 return $this->get_field_prefix() . $varname;
297 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
298 * name) to use for a question_type variable belonging to this question_attempt.
300 * See the comment on {@link question_attempt_step} for an explanation of
301 * question type and behaviour variables.
303 * @param $varname The short form of the variable name.
304 * @return string The field name to use.
306 public function get_behaviour_field_name($varname) {
307 return $this->get_field_prefix() . '-' . $varname;
311 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
312 * name) to use for a control variables belonging to this question_attempt.
314 * Examples are :sequencecheck and :flagged
316 * @param $varname The short form of the variable name.
317 * @return string The field name to use.
319 public function get_control_field_name($varname) {
320 return $this->get_field_prefix() . ':' . $varname;
324 * Get the prefix added to variable names to give field names for this
327 * You should not use this method directly. This is an implementation detail
328 * anyway, but if you must access it, use {@link question_usage_by_activity::get_field_prefix()}.
330 * @param $varname The short form of the variable name.
331 * @return string The field name to use.
333 public function get_field_prefix() {
334 return 'q' . $this->usageid . ':' . $this->slot . '_';
338 * Get one of the steps in this attempt.
339 * For internal/test code use only.
340 * @param int $i the step number.
341 * @return question_attempt_step
343 public function get_step($i) {
344 if ($i < 0 || $i >= count($this->steps)) {
345 throw new coding_exception('Index out of bounds in question_attempt::get_step.');
347 return $this->steps[$i];
351 * Get the number of real steps in this attempt.
352 * This is put as a hidden field in the HTML, so that when we receive some
353 * data to process, then we can check that it came from the question
354 * in the state we are now it.
355 * @return int a number that summarises the current state of this question attempt.
357 public function get_sequence_check_count() {
358 $numrealsteps = $this->get_num_steps();
359 if ($this->has_autosaved_step()) {
362 return $numrealsteps;
366 * Get the number of steps in this attempt.
367 * For internal/test code use only.
368 * @return int the number of steps we currently have.
370 public function get_num_steps() {
371 return count($this->steps);
375 * Return the latest step in this question_attempt.
376 * For internal/test code use only.
377 * @return question_attempt_step
379 public function get_last_step() {
380 if (count($this->steps) == 0) {
381 return new question_null_step();
383 return end($this->steps);
387 * @return boolean whether this question_attempt has autosaved data from
388 * some time in the past.
390 public function has_autosaved_step() {
391 return !is_null($this->autosavedstep);
395 * @return question_attempt_step_iterator for iterating over the steps in
396 * this attempt, in order.
398 public function get_step_iterator() {
399 return new question_attempt_step_iterator($this);
403 * The same as {@link get_step_iterator()}. However, for a
404 * {@link question_attempt_with_restricted_history} this returns the full
405 * list of steps, while {@link get_step_iterator()} returns only the
407 * @return question_attempt_step_iterator for iterating over the steps in
408 * this attempt, in order.
410 public function get_full_step_iterator() {
411 return $this->get_step_iterator();
415 * @return question_attempt_reverse_step_iterator for iterating over the steps in
416 * this attempt, in reverse order.
418 public function get_reverse_step_iterator() {
419 return new question_attempt_reverse_step_iterator($this);
423 * Get the qt data from the latest step that has any qt data. Return $default
424 * array if it is no step has qt data.
426 * @param string $name the name of the variable to get.
427 * @param mixed default the value to return no step has qt data.
428 * (Optional, defaults to an empty array.)
429 * @return array|mixed the data, or $default if there is not any.
431 public function get_last_qt_data($default = array()) {
432 foreach ($this->get_reverse_step_iterator() as $step) {
433 $response = $step->get_qt_data();
434 if (!empty($response)) {
442 * Get the last step with a particular question type varialbe set.
443 * @param string $name the name of the variable to get.
444 * @return question_attempt_step the last step, or a step with no variables
445 * if there was not a real step.
447 public function get_last_step_with_qt_var($name) {
448 foreach ($this->get_reverse_step_iterator() as $step) {
449 if ($step->has_qt_var($name)) {
453 return new question_attempt_step_read_only();
457 * Get the last step with a particular behaviour variable set.
458 * @param string $name the name of the variable to get.
459 * @return question_attempt_step the last step, or a step with no variables
460 * if there was not a real step.
462 public function get_last_step_with_behaviour_var($name) {
463 foreach ($this->get_reverse_step_iterator() as $step) {
464 if ($step->has_behaviour_var($name)) {
468 return new question_attempt_step_read_only();
472 * Get the latest value of a particular question type variable. That is, get
473 * the value from the latest step that has it set. Return null if it is not
476 * @param string $name the name of the variable to get.
477 * @param mixed default the value to return in the variable has never been set.
478 * (Optional, defaults to null.)
479 * @return mixed string value, or $default if it has never been set.
481 public function get_last_qt_var($name, $default = null) {
482 $step = $this->get_last_step_with_qt_var($name);
483 if ($step->has_qt_var($name)) {
484 return $step->get_qt_var($name);
491 * Get the latest set of files for a particular question type variable of
492 * type question_attempt::PARAM_FILES.
494 * @param string $name the name of the associated variable.
495 * @return array of {@link stored_files}.
497 public function get_last_qt_files($name, $contextid) {
498 foreach ($this->get_reverse_step_iterator() as $step) {
499 if ($step->has_qt_var($name)) {
500 return $step->get_qt_files($name, $contextid);
507 * Get the URL of a file that belongs to a response variable of this
509 * @param stored_file $file the file to link to.
510 * @return string the URL of that file.
512 public function get_response_file_url(stored_file $file) {
513 return file_encode_url(new moodle_url('/pluginfile.php'), '/' . implode('/', array(
514 $file->get_contextid(),
515 $file->get_component(),
516 $file->get_filearea(),
519 $file->get_itemid())) .
520 $file->get_filepath() . $file->get_filename(), true);
524 * Prepare a draft file are for the files belonging the a response variable
525 * of this question attempt. The draft area is populated with the files from
526 * the most recent step having files.
528 * @param string $name the variable name the files belong to.
529 * @param int $contextid the id of the context the quba belongs to.
530 * @return int the draft itemid.
532 public function prepare_response_files_draft_itemid($name, $contextid) {
533 foreach ($this->get_reverse_step_iterator() as $step) {
534 if ($step->has_qt_var($name)) {
535 return $step->prepare_response_files_draft_itemid($name, $contextid);
540 $draftid = 0; // Will be filled in by file_prepare_draft_area.
541 file_prepare_draft_area($draftid, $contextid, 'question', 'response_' . $name, null);
546 * Get the latest value of a particular behaviour variable. That is,
547 * get the value from the latest step that has it set. Return null if it is
548 * not set in any step.
550 * @param string $name the name of the variable to get.
551 * @param mixed default the value to return in the variable has never been set.
552 * (Optional, defaults to null.)
553 * @return mixed string value, or $default if it has never been set.
555 public function get_last_behaviour_var($name, $default = null) {
556 foreach ($this->get_reverse_step_iterator() as $step) {
557 if ($step->has_behaviour_var($name)) {
558 return $step->get_behaviour_var($name);
565 * Get the current state of this question attempt. That is, the state of the
567 * @return question_state
569 public function get_state() {
570 return $this->get_last_step()->get_state();
574 * @param bool $showcorrectness Whether right/partial/wrong states should
576 * @return string A brief textual description of the current state.
578 public function get_state_string($showcorrectness) {
579 return $this->behaviour->get_state_string($showcorrectness);
583 * @param bool $showcorrectness Whether right/partial/wrong states should
585 * @return string a CSS class name for the current state.
587 public function get_state_class($showcorrectness) {
588 return $this->get_state()->get_state_class($showcorrectness);
592 * @return int the timestamp of the most recent step in this question attempt.
594 public function get_last_action_time() {
595 return $this->get_last_step()->get_timecreated();
599 * Get the current fraction of this question attempt. That is, the fraction
600 * of the latest step, or null if this question has not yet been graded.
601 * @return number the current fraction.
603 public function get_fraction() {
604 return $this->get_last_step()->get_fraction();
607 /** @return bool whether this question attempt has a non-zero maximum mark. */
608 public function has_marks() {
609 // Since grades are stored in the database as NUMBER(12,7).
610 return $this->maxmark >= 0.00000005;
614 * @return number the current mark for this question.
615 * {@link get_fraction()} * {@link get_max_mark()}.
617 public function get_mark() {
618 return $this->fraction_to_mark($this->get_fraction());
622 * This is used by the manual grading code, particularly in association with
623 * validation. If there is a mark submitted in the request, then use that,
624 * otherwise use the latest mark for this question.
625 * @return number the current mark for this question.
626 * {@link get_fraction()} * {@link get_max_mark()}.
628 public function get_current_manual_mark() {
629 $mark = $this->get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
630 if (is_null($mark)) {
631 return $this->get_mark();
638 * @param number|null $fraction a fraction.
639 * @return number|null the corresponding mark.
641 public function fraction_to_mark($fraction) {
642 if (is_null($fraction)) {
645 return $fraction * $this->maxmark;
648 /** @return number the maximum mark possible for this question attempt. */
649 public function get_max_mark() {
650 return $this->maxmark;
653 /** @return number the maximum mark possible for this question attempt. */
654 public function get_min_fraction() {
655 if (is_null($this->minfraction)) {
656 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
658 return $this->minfraction;
662 * The current mark, formatted to the stated number of decimal places. Uses
663 * {@link format_float()} to format floats according to the current locale.
664 * @param int $dp number of decimal places.
665 * @return string formatted mark.
667 public function format_mark($dp) {
668 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
672 * The current mark, formatted to the stated number of decimal places. Uses
673 * {@link format_float()} to format floats according to the current locale.
674 * @param int $dp number of decimal places.
675 * @return string formatted mark.
677 public function format_fraction_as_mark($fraction, $dp) {
678 return format_float($this->fraction_to_mark($fraction), $dp);
682 * The maximum mark for this question attempt, formatted to the stated number
683 * of decimal places. Uses {@link format_float()} to format floats according
684 * to the current locale.
685 * @param int $dp number of decimal places.
686 * @return string formatted maximum mark.
688 public function format_max_mark($dp) {
689 return format_float($this->maxmark, $dp);
693 * Return the hint that applies to the question in its current state, or null.
694 * @return question_hint|null
696 public function get_applicable_hint() {
697 return $this->behaviour->get_applicable_hint();
701 * Produce a plain-text summary of what the user did during a step.
702 * @param question_attempt_step $step the step in quetsion.
703 * @return string a summary of what was done during that step.
705 public function summarise_action(question_attempt_step $step) {
706 return $this->behaviour->summarise_action($step);
710 * Helper function used by {@link rewrite_pluginfile_urls()} and
711 * {@link rewrite_response_pluginfile_urls()}.
712 * @return array ids that need to go into the file paths.
714 protected function extra_file_path_components() {
715 return array($this->get_usage_id(), $this->get_slot());
719 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
720 * for content belonging to this question.
721 * @param string $text the content to output.
722 * @param string $component the component name (normally 'question' or 'qtype_...')
723 * @param string $filearea the name of the file area.
724 * @param int $itemid the item id.
725 * @return srting the content with the URLs rewritten.
727 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
728 return question_rewrite_question_urls($text, 'pluginfile.php',
729 $this->question->contextid, $component, $filearea,
730 $this->extra_file_path_components(), $itemid);
734 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
735 * for content belonging to responses to this question.
737 * @param string $text the text to update the URLs in.
738 * @param int $contextid the id of the context the quba belongs to.
739 * @param string $name the variable name the files belong to.
740 * @param question_attempt_step $step the step the response is coming from.
741 * @return srting the content with the URLs rewritten.
743 public function rewrite_response_pluginfile_urls($text, $contextid, $name,
744 question_attempt_step $step) {
745 return $step->rewrite_response_pluginfile_urls($text, $contextid, $name,
746 $this->extra_file_path_components());
750 * Get the {@link core_question_renderer}, in collaboration with appropriate
751 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
752 * HTML to display this question attempt in its current state.
753 * @param question_display_options $options controls how the question is rendered.
754 * @param string|null $number The question number to display.
755 * @return string HTML fragment representing the question.
757 public function render($options, $number, $page = null) {
758 if (is_null($page)) {
762 $qoutput = $page->get_renderer('core', 'question');
763 $qtoutput = $this->question->get_renderer($page);
764 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
768 * Generate any bits of HTML that needs to go in the <head> tag when this question
769 * attempt is displayed in the body.
770 * @return string HTML fragment.
772 public function render_head_html($page = null) {
773 if (is_null($page)) {
777 // TODO go via behaviour.
778 return $this->question->get_renderer($page)->head_code($this) .
779 $this->behaviour->get_renderer($page)->head_code($this);
783 * Like {@link render_question()} but displays the question at the past step
784 * indicated by $seq, rather than showing the latest step.
786 * @param int $seq the seq number of the past state to display.
787 * @param question_display_options $options controls how the question is rendered.
788 * @param string|null $number The question number to display. 'i' is a special
789 * value that gets displayed as Information. Null means no number is displayed.
790 * @return string HTML fragment representing the question.
792 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
793 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
794 return $restrictedqa->render($options, $number);
798 * Checks whether the users is allow to be served a particular file.
799 * @param question_display_options $options the options that control display of the question.
800 * @param string $component the name of the component we are serving files for.
801 * @param string $filearea the name of the file area.
802 * @param array $args the remaining bits of the file path.
803 * @param bool $forcedownload whether the user must be forced to download the file.
804 * @return bool true if the user can access this file.
806 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
807 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
811 * Add a step to this question attempt.
812 * @param question_attempt_step $step the new step.
814 protected function add_step(question_attempt_step $step) {
815 $this->steps[] = $step;
817 $this->observer->notify_step_added($step, $this, key($this->steps));
821 * Add an auto-saved step to this question attempt. We mark auto-saved steps by
822 * changing saving the step number with a - sign.
823 * @param question_attempt_step $step the new step.
825 protected function add_autosaved_step(question_attempt_step $step) {
826 $this->steps[] = $step;
827 $this->autosavedstep = $step;
829 $this->observer->notify_step_added($step, $this, -key($this->steps));
833 * Discard any auto-saved data belonging to this question attempt.
835 public function discard_autosaved_step() {
836 if (!$this->has_autosaved_step()) {
840 $autosaved = array_pop($this->steps);
841 $this->autosavedstep = null;
842 $this->observer->notify_step_deleted($autosaved, $this);
846 * Use a strategy to pick a variant.
847 * @param question_variant_selection_strategy $variantstrategy a strategy.
848 * @return int the selected variant.
850 public function select_variant(question_variant_selection_strategy $variantstrategy) {
851 return $variantstrategy->choose_variant($this->get_question()->get_num_variants(),
852 $this->get_question()->get_variants_selection_seed());
856 * Start this question attempt.
858 * You should not call this method directly. Call
859 * {@link question_usage_by_activity::start_question()} instead.
861 * @param string|question_behaviour $preferredbehaviour the name of the
862 * desired archetypal behaviour, or an actual model instance.
863 * @param int $variant the variant of the question to start. Between 1 and
864 * $this->get_question()->get_num_variants() inclusive.
865 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
866 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
867 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
868 * @param int $existingstepid optional, if this step is going to replace an existing step
869 * (for example, during a regrade) this is the id of the previous step we are replacing.
871 public function start($preferredbehaviour, $variant, $submitteddata = array(),
872 $timestamp = null, $userid = null, $existingstepid = null) {
874 // Initialise the behaviour.
875 $this->variant = $variant;
876 if (is_string($preferredbehaviour)) {
878 $this->question->make_behaviour($this, $preferredbehaviour);
880 $class = get_class($preferredbehaviour);
881 $this->behaviour = new $class($this, $preferredbehaviour);
884 // Record the minimum fraction.
885 $this->minfraction = $this->behaviour->get_min_fraction();
887 // Initialise the first step.
888 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid, $existingstepid);
889 $firststep->set_state(question_state::$todo);
890 if ($submitteddata) {
891 $this->question->apply_attempt_state($firststep);
893 $this->behaviour->init_first_step($firststep, $variant);
895 $this->add_step($firststep);
897 // Record questionline and correct answer.
898 $this->questionsummary = $this->behaviour->get_question_summary();
899 $this->rightanswer = $this->behaviour->get_right_answer_summary();
903 * Start this question attempt, starting from the point that the previous
904 * attempt $oldqa had reached.
906 * You should not call this method directly. Call
907 * {@link question_usage_by_activity::start_question_based_on()} instead.
909 * @param question_attempt $oldqa a previous attempt at this quetsion that
910 * defines the starting point.
912 public function start_based_on(question_attempt $oldqa) {
913 $this->start($oldqa->behaviour, $oldqa->get_variant(), $oldqa->get_resume_data());
917 * Used by {@link start_based_on()} to get the data needed to start a new
918 * attempt from the point this attempt has go to.
919 * @return array name => value pairs.
921 protected function get_resume_data() {
922 return $this->behaviour->get_resume_data();
926 * Get a particular parameter from the current request. A wrapper round
927 * {@link optional_param()}, except that the results is returned without
929 * @param string $name the paramter name.
930 * @param int $type one of the standard PARAM_... constants, or one of the
931 * special extra constands defined by this class.
932 * @param array $postdata (optional, only inteded for testing use) take the
933 * data from this array, instead of from $_POST.
934 * @return mixed the requested value.
936 public function get_submitted_var($name, $type, $postdata = null) {
938 case self::PARAM_MARK:
939 // Special case to work around PARAM_FLOAT converting '' to 0.
940 return question_utils::clean_param_mark($this->get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata));
942 case self::PARAM_FILES:
943 return $this->process_response_files($name, $name, $postdata);
945 case self::PARAM_RAW_FILES:
946 $var = $this->get_submitted_var($name, PARAM_RAW, $postdata);
947 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
950 if (is_null($postdata)) {
951 $var = optional_param($name, null, $type);
952 } else if (array_key_exists($name, $postdata)) {
953 $var = clean_param($postdata[$name], $type);
963 * Handle a submitted variable representing uploaded files.
964 * @param string $name the field name.
965 * @param string $draftidname the field name holding the draft file area id.
966 * @param array $postdata (optional, only inteded for testing use) take the
967 * data from this array, instead of from $_POST. At the moment, this
968 * behaves as if there were no files.
969 * @param string $text optional reponse text.
970 * @return question_file_saver that can be used to save the files later.
972 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
974 // There can be no files with test data (at the moment).
978 $draftitemid = file_get_submitted_draft_itemid($draftidname);
983 return new question_file_saver($draftitemid, 'question', 'response_' .
984 str_replace($this->get_field_prefix(), '', $name), $text);
988 * Get any data from the request that matches the list of expected params.
989 * @param array $expected variable name => PARAM_... constant.
990 * @param string $extraprefix '-' or ''.
991 * @return array name => value.
993 protected function get_expected_data($expected, $postdata, $extraprefix) {
994 $submitteddata = array();
995 foreach ($expected as $name => $type) {
996 $value = $this->get_submitted_var(
997 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
998 if (!is_null($value)) {
999 $submitteddata[$extraprefix . $name] = $value;
1002 return $submitteddata;
1006 * Get all the submitted question type data for this question, whithout checking
1007 * that it is valid or cleaning it in any way.
1008 * @return array name => value.
1010 protected function get_all_submitted_qt_vars($postdata) {
1011 if (is_null($postdata)) {
1015 $pattern = '/^' . preg_quote($this->get_field_prefix(), '/') . '[^-:]/';
1016 $prefixlen = strlen($this->get_field_prefix());
1018 $submitteddata = array();
1019 foreach ($_POST as $name => $value) {
1020 if (preg_match($pattern, $name)) {
1021 $submitteddata[substr($name, $prefixlen)] = $value;
1025 return $submitteddata;
1029 * Get all the sumbitted data belonging to this question attempt from the
1031 * @param array $postdata (optional, only inteded for testing use) take the
1032 * data from this array, instead of from $_POST.
1033 * @return array name => value pairs that could be passed to {@link process_action()}.
1035 public function get_submitted_data($postdata = null) {
1036 $submitteddata = $this->get_expected_data(
1037 $this->behaviour->get_expected_data(), $postdata, '-');
1039 $expected = $this->behaviour->get_expected_qt_data();
1040 if ($expected === self::USE_RAW_DATA) {
1041 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
1043 $submitteddata += $this->get_expected_data($expected, $postdata, '');
1045 return $submitteddata;
1049 * Get a set of response data for this question attempt that would get the
1050 * best possible mark. If it is not possible to compute a correct
1051 * response, this method should return null.
1052 * @return array|null name => value pairs that could be passed to {@link process_action()}.
1054 public function get_correct_response() {
1055 $response = $this->question->get_correct_response();
1056 if (is_null($response)) {
1059 $imvars = $this->behaviour->get_correct_response();
1060 foreach ($imvars as $name => $value) {
1061 $response['-' . $name] = $value;
1067 * Change the quetsion summary. Note, that this is almost never necessary.
1068 * This method was only added to work around a limitation of the Opaque
1069 * protocol, which only sends questionLine at the end of an attempt.
1070 * @param $questionsummary the new summary to set.
1072 public function set_question_summary($questionsummary) {
1073 $this->questionsummary = $questionsummary;
1074 $this->observer->notify_attempt_modified($this);
1078 * @return string a simple textual summary of the question that was asked.
1080 public function get_question_summary() {
1081 return $this->questionsummary;
1085 * @return string a simple textual summary of response given.
1087 public function get_response_summary() {
1088 return $this->responsesummary;
1092 * @return string a simple textual summary of the correct resonse.
1094 public function get_right_answer_summary() {
1095 return $this->rightanswer;
1099 * Perform the action described by $submitteddata.
1100 * @param array $submitteddata the submitted data the determines the action.
1101 * @param int $timestamp the time to record for the action. (If not given, use now.)
1102 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1103 * @param int $existingstepid used by the regrade code.
1105 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1106 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid, $existingstepid);
1107 $this->discard_autosaved_step();
1108 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1109 $this->add_step($pendingstep);
1110 if ($pendingstep->response_summary_changed()) {
1111 $this->responsesummary = $pendingstep->get_new_response_summary();
1117 * Process an autosave.
1118 * @param array $submitteddata the submitted data the determines the action.
1119 * @param int $timestamp the time to record for the action. (If not given, use now.)
1120 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1121 * @return bool whether anything was saved.
1123 public function process_autosave($submitteddata, $timestamp = null, $userid = null) {
1124 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1125 if ($this->behaviour->process_autosave($pendingstep) == self::KEEP) {
1126 $this->add_autosaved_step($pendingstep);
1133 * Perform a finish action on this question attempt. This corresponds to an
1134 * external finish action, for example the user pressing Submit all and finish
1135 * in the quiz, rather than using one of the controls that is part of the
1138 * @param int $timestamp the time to record for the action. (If not given, use now.)
1139 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1141 public function finish($timestamp = null, $userid = null) {
1142 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1146 * Perform a regrade. This replays all the actions from $oldqa into this
1148 * @param question_attempt $oldqa the attempt to regrade.
1149 * @param bool $finished whether the question attempt should be forced to be finished
1150 * after the regrade, or whether it may still be in progress (default false).
1152 public function regrade(question_attempt $oldqa, $finished) {
1154 foreach ($oldqa->get_step_iterator() as $step) {
1155 $this->observer->notify_step_deleted($step, $this);
1158 // First step of the attempt.
1160 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
1161 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1163 } else if ($step->has_behaviour_var('finish') && count($step->get_submitted_data()) > 1) {
1164 // This case relates to MDL-32062. The upgrade code from 2.0
1165 // generates attempts where the final submit of the question
1166 // data, and the finish action, are in the same step. The system
1167 // cannot cope with that, so convert the single old step into
1169 $submitteddata = $step->get_submitted_data();
1170 unset($submitteddata['-finish']);
1171 $this->process_action($submitteddata,
1172 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1173 $this->finish($step->get_timecreated(), $step->get_user_id());
1176 // This is the normal case. Replay the next step of the attempt.
1177 $this->process_action($step->get_submitted_data(),
1178 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1188 * Perform a manual grading action on this attempt.
1189 * @param string $comment the comment being added.
1190 * @param float $mark the new mark. If null, then only a comment is added.
1191 * @param int $commentformat the FORMAT_... for $comment. Must be given.
1192 * @param int $timestamp the time to record for the action. (If not given, use now.)
1193 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1195 public function manual_grade($comment, $mark, $commentformat = null, $timestamp = null, $userid = null) {
1196 $submitteddata = array('-comment' => $comment);
1197 if (is_null($commentformat)) {
1198 debugging('You should pass $commentformat to manual_grade.', DEBUG_DEVELOPER);
1199 $commentformat = FORMAT_HTML;
1201 $submitteddata['-commentformat'] = $commentformat;
1202 if (!is_null($mark)) {
1203 $submitteddata['-mark'] = $mark;
1204 $submitteddata['-maxmark'] = $this->maxmark;
1206 $this->process_action($submitteddata, $timestamp, $userid);
1209 /** @return bool Whether this question attempt has had a manual comment added. */
1210 public function has_manual_comment() {
1211 foreach ($this->steps as $step) {
1212 if ($step->has_behaviour_var('comment')) {
1220 * @return array(string, int) the most recent manual comment that was added
1221 * to this question, and the FORMAT_... it is.
1223 public function get_manual_comment() {
1224 foreach ($this->get_reverse_step_iterator() as $step) {
1225 if ($step->has_behaviour_var('comment')) {
1226 return array($step->get_behaviour_var('comment'),
1227 $step->get_behaviour_var('commentformat'));
1230 return array(null, null);
1234 * @return array subpartid => object with fields
1235 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
1236 * ->response the actual response the student gave to this part, as a string.
1237 * ->fraction the credit awarded for this subpart, may be null.
1238 * returns an empty array if no analysis is possible.
1240 public function classify_response() {
1241 return $this->behaviour->classify_response();
1245 * Create a question_attempt_step from records loaded from the database.
1247 * For internal use only.
1249 * @param Iterator $records Raw records loaded from the database.
1250 * @param int $questionattemptid The id of the question_attempt to extract.
1251 * @return question_attempt The newly constructed question_attempt.
1253 public static function load_from_records($records, $questionattemptid,
1254 question_usage_observer $observer, $preferredbehaviour) {
1255 $record = $records->current();
1256 while ($record->questionattemptid != $questionattemptid) {
1257 $record = $records->next();
1258 if (!$records->valid()) {
1259 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
1261 $record = $records->current();
1265 $question = question_bank::load_question($record->questionid);
1266 } catch (Exception $e) {
1267 // The question must have been deleted somehow. Create a missing
1268 // question to use in its place.
1269 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1270 $record->questionid, $record->maxmark + 0);
1273 $qa = new question_attempt($question, $record->questionusageid,
1274 null, $record->maxmark + 0);
1275 $qa->set_database_id($record->questionattemptid);
1276 $qa->set_slot($record->slot);
1277 $qa->variant = $record->variant + 0;
1278 $qa->minfraction = $record->minfraction + 0;
1279 $qa->set_flagged($record->flagged);
1280 $qa->questionsummary = $record->questionsummary;
1281 $qa->rightanswer = $record->rightanswer;
1282 $qa->responsesummary = $record->responsesummary;
1283 $qa->timemodified = $record->timemodified;
1285 $qa->behaviour = question_engine::make_behaviour(
1286 $record->behaviour, $qa, $preferredbehaviour);
1287 $qa->observer = $observer;
1289 // If attemptstepid is null (which should not happen, but has happened
1290 // due to corrupt data, see MDL-34251) then the current pointer in $records
1291 // will not be advanced in the while loop below, and we get stuck in an
1292 // infinite loop, since this method is supposed to always consume at
1293 // least one record. Therefore, in this case, advance the record here.
1294 if (is_null($record->attemptstepid)) {
1299 $autosavedstep = null;
1300 $autosavedsequencenumber = null;
1301 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
1302 $sequencenumber = $record->sequencenumber;
1303 $nextstep = question_attempt_step::load_from_records($records, $record->attemptstepid, $qa->get_question()->get_type_name());
1305 if ($sequencenumber < 0) {
1306 if (!$autosavedstep) {
1307 $autosavedstep = $nextstep;
1308 $autosavedsequencenumber = -$sequencenumber;
1310 // Old redundant data. Mark it for deletion.
1311 $qa->observer->notify_step_deleted($nextstep, $qa);
1314 $qa->steps[$i] = $nextstep;
1316 $question->apply_attempt_state($qa->steps[0]);
1321 if ($records->valid()) {
1322 $record = $records->current();
1328 if ($autosavedstep) {
1329 if ($autosavedsequencenumber >= $i) {
1330 $qa->autosavedstep = $autosavedstep;
1331 $qa->steps[$i] = $qa->autosavedstep;
1333 $qa->observer->notify_step_deleted($autosavedstep, $qa);
1343 * This subclass of question_attempt pretends that only part of the step history
1344 * exists. It is used for rendering the question in past states.
1346 * All methods that try to modify the question_attempt throw exceptions.
1348 * @copyright 2010 The Open University
1349 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1351 class question_attempt_with_restricted_history extends question_attempt {
1353 * @var question_attempt the underlying question_attempt.
1358 * Create a question_attempt_with_restricted_history
1359 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1360 * @param int $lastseq the index of the last step to include.
1361 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1362 * annoyting that this needs to be passed, but unavoidable for now.
1364 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
1365 $this->baseqa = $baseqa->get_full_qa();
1367 if ($lastseq < 0 || $lastseq >= $this->baseqa->get_num_steps()) {
1368 throw new coding_exception('$lastseq out of range', $lastseq);
1371 $this->steps = array_slice($this->baseqa->steps, 0, $lastseq + 1);
1372 $this->observer = new question_usage_null_observer();
1374 // This should be a straight copy of all the remaining fields.
1375 $this->id = $this->baseqa->id;
1376 $this->usageid = $this->baseqa->usageid;
1377 $this->slot = $this->baseqa->slot;
1378 $this->question = $this->baseqa->question;
1379 $this->maxmark = $this->baseqa->maxmark;
1380 $this->minfraction = $this->baseqa->minfraction;
1381 $this->questionsummary = $this->baseqa->questionsummary;
1382 $this->responsesummary = $this->baseqa->responsesummary;
1383 $this->rightanswer = $this->baseqa->rightanswer;
1384 $this->flagged = $this->baseqa->flagged;
1386 // Except behaviour, where we need to create a new one.
1387 $this->behaviour = question_engine::make_behaviour(
1388 $this->baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1391 public function get_full_qa() {
1392 return $this->baseqa;
1395 public function get_full_step_iterator() {
1396 return $this->baseqa->get_step_iterator();
1399 protected function add_step(question_attempt_step $step) {
1400 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1402 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1403 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1405 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null, $existingstepid = null) {
1406 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1409 public function set_database_id($id) {
1410 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1412 public function set_flagged($flagged) {
1413 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1415 public function set_slot($slot) {
1416 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1418 public function set_question_summary($questionsummary) {
1419 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1421 public function set_usage_id($usageid) {
1422 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1428 * A class abstracting access to the {@link question_attempt::$states} array.
1430 * This is actively linked to question_attempt. If you add an new step
1431 * mid-iteration, then it will be included.
1433 * @copyright 2009 The Open University
1434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1436 class question_attempt_step_iterator implements Iterator, ArrayAccess {
1437 /** @var question_attempt the question_attempt being iterated over. */
1439 /** @var integer records the current position in the iteration. */
1443 * Do not call this constructor directly.
1444 * Use {@link question_attempt::get_step_iterator()}.
1445 * @param question_attempt $qa the attempt to iterate over.
1447 public function __construct(question_attempt $qa) {
1452 /** @return question_attempt_step */
1453 public function current() {
1454 return $this->offsetGet($this->i);
1457 public function key() {
1460 public function next() {
1463 public function rewind() {
1467 public function valid() {
1468 return $this->offsetExists($this->i);
1472 public function offsetExists($i) {
1473 return $i >= 0 && $i < $this->qa->get_num_steps();
1475 /** @return question_attempt_step */
1476 public function offsetGet($i) {
1477 return $this->qa->get_step($i);
1479 public function offsetSet($offset, $value) {
1480 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1482 public function offsetUnset($offset) {
1483 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1489 * A variant of {@link question_attempt_step_iterator} that iterates through the
1490 * steps in reverse order.
1492 * @copyright 2009 The Open University
1493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1495 class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1496 public function next() {
1500 public function rewind() {
1501 $this->i = $this->qa->get_num_steps() - 1;