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 // Special case when attempt is based on previous one, see MDL-31226.
580 if ($this->get_num_steps() == 1 && $this->get_state() == question_state::$complete) {
581 return get_string('notchanged', 'question');
583 return $this->behaviour->get_state_string($showcorrectness);
587 * @param bool $showcorrectness Whether right/partial/wrong states should
589 * @return string a CSS class name for the current state.
591 public function get_state_class($showcorrectness) {
592 return $this->get_state()->get_state_class($showcorrectness);
596 * @return int the timestamp of the most recent step in this question attempt.
598 public function get_last_action_time() {
599 return $this->get_last_step()->get_timecreated();
603 * Get the current fraction of this question attempt. That is, the fraction
604 * of the latest step, or null if this question has not yet been graded.
605 * @return number the current fraction.
607 public function get_fraction() {
608 return $this->get_last_step()->get_fraction();
611 /** @return bool whether this question attempt has a non-zero maximum mark. */
612 public function has_marks() {
613 // Since grades are stored in the database as NUMBER(12,7).
614 return $this->maxmark >= 0.00000005;
618 * @return number the current mark for this question.
619 * {@link get_fraction()} * {@link get_max_mark()}.
621 public function get_mark() {
622 return $this->fraction_to_mark($this->get_fraction());
626 * This is used by the manual grading code, particularly in association with
627 * validation. If there is a mark submitted in the request, then use that,
628 * otherwise use the latest mark for this question.
629 * @return number the current mark for this question.
630 * {@link get_fraction()} * {@link get_max_mark()}.
632 public function get_current_manual_mark() {
633 $mark = $this->get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
634 if (is_null($mark)) {
635 return $this->get_mark();
642 * @param number|null $fraction a fraction.
643 * @return number|null the corresponding mark.
645 public function fraction_to_mark($fraction) {
646 if (is_null($fraction)) {
649 return $fraction * $this->maxmark;
652 /** @return number the maximum mark possible for this question attempt. */
653 public function get_max_mark() {
654 return $this->maxmark;
657 /** @return number the maximum mark possible for this question attempt. */
658 public function get_min_fraction() {
659 if (is_null($this->minfraction)) {
660 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
662 return $this->minfraction;
666 * The current mark, formatted to the stated number of decimal places. Uses
667 * {@link format_float()} to format floats according to the current locale.
668 * @param int $dp number of decimal places.
669 * @return string formatted mark.
671 public function format_mark($dp) {
672 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
676 * The current mark, formatted to the stated number of decimal places. Uses
677 * {@link format_float()} to format floats according to the current locale.
678 * @param int $dp number of decimal places.
679 * @return string formatted mark.
681 public function format_fraction_as_mark($fraction, $dp) {
682 return format_float($this->fraction_to_mark($fraction), $dp);
686 * The maximum mark for this question attempt, formatted to the stated number
687 * of decimal places. Uses {@link format_float()} to format floats according
688 * to the current locale.
689 * @param int $dp number of decimal places.
690 * @return string formatted maximum mark.
692 public function format_max_mark($dp) {
693 return format_float($this->maxmark, $dp);
697 * Return the hint that applies to the question in its current state, or null.
698 * @return question_hint|null
700 public function get_applicable_hint() {
701 return $this->behaviour->get_applicable_hint();
705 * Produce a plain-text summary of what the user did during a step.
706 * @param question_attempt_step $step the step in quetsion.
707 * @return string a summary of what was done during that step.
709 public function summarise_action(question_attempt_step $step) {
710 return $this->behaviour->summarise_action($step);
714 * Helper function used by {@link rewrite_pluginfile_urls()} and
715 * {@link rewrite_response_pluginfile_urls()}.
716 * @return array ids that need to go into the file paths.
718 protected function extra_file_path_components() {
719 return array($this->get_usage_id(), $this->get_slot());
723 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
724 * for content belonging to this question.
725 * @param string $text the content to output.
726 * @param string $component the component name (normally 'question' or 'qtype_...')
727 * @param string $filearea the name of the file area.
728 * @param int $itemid the item id.
729 * @return srting the content with the URLs rewritten.
731 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
732 return question_rewrite_question_urls($text, 'pluginfile.php',
733 $this->question->contextid, $component, $filearea,
734 $this->extra_file_path_components(), $itemid);
738 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
739 * for content belonging to responses to this question.
741 * @param string $text the text to update the URLs in.
742 * @param int $contextid the id of the context the quba belongs to.
743 * @param string $name the variable name the files belong to.
744 * @param question_attempt_step $step the step the response is coming from.
745 * @return srting the content with the URLs rewritten.
747 public function rewrite_response_pluginfile_urls($text, $contextid, $name,
748 question_attempt_step $step) {
749 return $step->rewrite_response_pluginfile_urls($text, $contextid, $name,
750 $this->extra_file_path_components());
754 * Get the {@link core_question_renderer}, in collaboration with appropriate
755 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
756 * HTML to display this question attempt in its current state.
757 * @param question_display_options $options controls how the question is rendered.
758 * @param string|null $number The question number to display.
759 * @return string HTML fragment representing the question.
761 public function render($options, $number, $page = null) {
762 if (is_null($page)) {
766 $qoutput = $page->get_renderer('core', 'question');
767 $qtoutput = $this->question->get_renderer($page);
768 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
772 * Generate any bits of HTML that needs to go in the <head> tag when this question
773 * attempt is displayed in the body.
774 * @return string HTML fragment.
776 public function render_head_html($page = null) {
777 if (is_null($page)) {
781 // TODO go via behaviour.
782 return $this->question->get_renderer($page)->head_code($this) .
783 $this->behaviour->get_renderer($page)->head_code($this);
787 * Like {@link render_question()} but displays the question at the past step
788 * indicated by $seq, rather than showing the latest step.
790 * @param int $seq the seq number of the past state to display.
791 * @param question_display_options $options controls how the question is rendered.
792 * @param string|null $number The question number to display. 'i' is a special
793 * value that gets displayed as Information. Null means no number is displayed.
794 * @return string HTML fragment representing the question.
796 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
797 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
798 return $restrictedqa->render($options, $number);
802 * Checks whether the users is allow to be served a particular file.
803 * @param question_display_options $options the options that control display of the question.
804 * @param string $component the name of the component we are serving files for.
805 * @param string $filearea the name of the file area.
806 * @param array $args the remaining bits of the file path.
807 * @param bool $forcedownload whether the user must be forced to download the file.
808 * @return bool true if the user can access this file.
810 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
811 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
815 * Add a step to this question attempt.
816 * @param question_attempt_step $step the new step.
818 protected function add_step(question_attempt_step $step) {
819 $this->steps[] = $step;
821 $this->observer->notify_step_added($step, $this, key($this->steps));
825 * Add an auto-saved step to this question attempt. We mark auto-saved steps by
826 * changing saving the step number with a - sign.
827 * @param question_attempt_step $step the new step.
829 protected function add_autosaved_step(question_attempt_step $step) {
830 $this->steps[] = $step;
831 $this->autosavedstep = $step;
833 $this->observer->notify_step_added($step, $this, -key($this->steps));
837 * Discard any auto-saved data belonging to this question attempt.
839 public function discard_autosaved_step() {
840 if (!$this->has_autosaved_step()) {
844 $autosaved = array_pop($this->steps);
845 $this->autosavedstep = null;
846 $this->observer->notify_step_deleted($autosaved, $this);
850 * Use a strategy to pick a variant.
851 * @param question_variant_selection_strategy $variantstrategy a strategy.
852 * @return int the selected variant.
854 public function select_variant(question_variant_selection_strategy $variantstrategy) {
855 return $variantstrategy->choose_variant($this->get_question()->get_num_variants(),
856 $this->get_question()->get_variants_selection_seed());
860 * Start this question attempt.
862 * You should not call this method directly. Call
863 * {@link question_usage_by_activity::start_question()} instead.
865 * @param string|question_behaviour $preferredbehaviour the name of the
866 * desired archetypal behaviour, or an actual model instance.
867 * @param int $variant the variant of the question to start. Between 1 and
868 * $this->get_question()->get_num_variants() inclusive.
869 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
870 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
871 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
872 * @param int $existingstepid optional, if this step is going to replace an existing step
873 * (for example, during a regrade) this is the id of the previous step we are replacing.
875 public function start($preferredbehaviour, $variant, $submitteddata = array(),
876 $timestamp = null, $userid = null, $existingstepid = null) {
878 // Initialise the behaviour.
879 $this->variant = $variant;
880 if (is_string($preferredbehaviour)) {
882 $this->question->make_behaviour($this, $preferredbehaviour);
884 $class = get_class($preferredbehaviour);
885 $this->behaviour = new $class($this, $preferredbehaviour);
888 // Record the minimum fraction.
889 $this->minfraction = $this->behaviour->get_min_fraction();
891 // Initialise the first step.
892 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid, $existingstepid);
893 if ($submitteddata) {
894 $firststep->set_state(question_state::$complete);
895 $this->behaviour->apply_attempt_state($firststep);
897 $this->behaviour->init_first_step($firststep, $variant);
899 $this->add_step($firststep);
901 // Record questionline and correct answer.
902 $this->questionsummary = $this->behaviour->get_question_summary();
903 $this->rightanswer = $this->behaviour->get_right_answer_summary();
907 * Start this question attempt, starting from the point that the previous
908 * attempt $oldqa had reached.
910 * You should not call this method directly. Call
911 * {@link question_usage_by_activity::start_question_based_on()} instead.
913 * @param question_attempt $oldqa a previous attempt at this quetsion that
914 * defines the starting point.
916 public function start_based_on(question_attempt $oldqa) {
917 $this->start($oldqa->behaviour, $oldqa->get_variant(), $oldqa->get_resume_data());
921 * Used by {@link start_based_on()} to get the data needed to start a new
922 * attempt from the point this attempt has go to.
923 * @return array name => value pairs.
925 protected function get_resume_data() {
926 return $this->behaviour->get_resume_data();
930 * Get a particular parameter from the current request. A wrapper round
931 * {@link optional_param()}, except that the results is returned without
933 * @param string $name the paramter name.
934 * @param int $type one of the standard PARAM_... constants, or one of the
935 * special extra constands defined by this class.
936 * @param array $postdata (optional, only inteded for testing use) take the
937 * data from this array, instead of from $_POST.
938 * @return mixed the requested value.
940 public function get_submitted_var($name, $type, $postdata = null) {
942 case self::PARAM_MARK:
943 // Special case to work around PARAM_FLOAT converting '' to 0.
944 return question_utils::clean_param_mark($this->get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata));
946 case self::PARAM_FILES:
947 return $this->process_response_files($name, $name, $postdata);
949 case self::PARAM_RAW_FILES:
950 $var = $this->get_submitted_var($name, PARAM_RAW, $postdata);
951 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
954 if (is_null($postdata)) {
955 $var = optional_param($name, null, $type);
956 } else if (array_key_exists($name, $postdata)) {
957 $var = clean_param($postdata[$name], $type);
967 * Handle a submitted variable representing uploaded files.
968 * @param string $name the field name.
969 * @param string $draftidname the field name holding the draft file area id.
970 * @param array $postdata (optional, only inteded for testing use) take the
971 * data from this array, instead of from $_POST. At the moment, this
972 * behaves as if there were no files.
973 * @param string $text optional reponse text.
974 * @return question_file_saver that can be used to save the files later.
976 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
978 // There can be no files with test data (at the moment).
982 $draftitemid = file_get_submitted_draft_itemid($draftidname);
987 return new question_file_saver($draftitemid, 'question', 'response_' .
988 str_replace($this->get_field_prefix(), '', $name), $text);
992 * Get any data from the request that matches the list of expected params.
993 * @param array $expected variable name => PARAM_... constant.
994 * @param string $extraprefix '-' or ''.
995 * @return array name => value.
997 protected function get_expected_data($expected, $postdata, $extraprefix) {
998 $submitteddata = array();
999 foreach ($expected as $name => $type) {
1000 $value = $this->get_submitted_var(
1001 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
1002 if (!is_null($value)) {
1003 $submitteddata[$extraprefix . $name] = $value;
1006 return $submitteddata;
1010 * Get all the submitted question type data for this question, whithout checking
1011 * that it is valid or cleaning it in any way.
1012 * @return array name => value.
1014 protected function get_all_submitted_qt_vars($postdata) {
1015 if (is_null($postdata)) {
1019 $pattern = '/^' . preg_quote($this->get_field_prefix(), '/') . '[^-:]/';
1020 $prefixlen = strlen($this->get_field_prefix());
1022 $submitteddata = array();
1023 foreach ($_POST as $name => $value) {
1024 if (preg_match($pattern, $name)) {
1025 $submitteddata[substr($name, $prefixlen)] = $value;
1029 return $submitteddata;
1033 * Get all the sumbitted data belonging to this question attempt from the
1035 * @param array $postdata (optional, only inteded for testing use) take the
1036 * data from this array, instead of from $_POST.
1037 * @return array name => value pairs that could be passed to {@link process_action()}.
1039 public function get_submitted_data($postdata = null) {
1040 $submitteddata = $this->get_expected_data(
1041 $this->behaviour->get_expected_data(), $postdata, '-');
1043 $expected = $this->behaviour->get_expected_qt_data();
1044 if ($expected === self::USE_RAW_DATA) {
1045 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
1047 $submitteddata += $this->get_expected_data($expected, $postdata, '');
1049 return $submitteddata;
1053 * Get a set of response data for this question attempt that would get the
1054 * best possible mark. If it is not possible to compute a correct
1055 * response, this method should return null.
1056 * @return array|null name => value pairs that could be passed to {@link process_action()}.
1058 public function get_correct_response() {
1059 $response = $this->question->get_correct_response();
1060 if (is_null($response)) {
1063 $imvars = $this->behaviour->get_correct_response();
1064 foreach ($imvars as $name => $value) {
1065 $response['-' . $name] = $value;
1071 * Change the quetsion summary. Note, that this is almost never necessary.
1072 * This method was only added to work around a limitation of the Opaque
1073 * protocol, which only sends questionLine at the end of an attempt.
1074 * @param $questionsummary the new summary to set.
1076 public function set_question_summary($questionsummary) {
1077 $this->questionsummary = $questionsummary;
1078 $this->observer->notify_attempt_modified($this);
1082 * @return string a simple textual summary of the question that was asked.
1084 public function get_question_summary() {
1085 return $this->questionsummary;
1089 * @return string a simple textual summary of response given.
1091 public function get_response_summary() {
1092 return $this->responsesummary;
1096 * @return string a simple textual summary of the correct resonse.
1098 public function get_right_answer_summary() {
1099 return $this->rightanswer;
1103 * Perform the action described by $submitteddata.
1104 * @param array $submitteddata the submitted data the determines the action.
1105 * @param int $timestamp the time to record for the action. (If not given, use now.)
1106 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1107 * @param int $existingstepid used by the regrade code.
1109 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1110 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid, $existingstepid);
1111 $this->discard_autosaved_step();
1112 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1113 $this->add_step($pendingstep);
1114 if ($pendingstep->response_summary_changed()) {
1115 $this->responsesummary = $pendingstep->get_new_response_summary();
1121 * Process an autosave.
1122 * @param array $submitteddata the submitted data the determines the action.
1123 * @param int $timestamp the time to record for the action. (If not given, use now.)
1124 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1125 * @return bool whether anything was saved.
1127 public function process_autosave($submitteddata, $timestamp = null, $userid = null) {
1128 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1129 if ($this->behaviour->process_autosave($pendingstep) == self::KEEP) {
1130 $this->add_autosaved_step($pendingstep);
1137 * Perform a finish action on this question attempt. This corresponds to an
1138 * external finish action, for example the user pressing Submit all and finish
1139 * in the quiz, rather than using one of the controls that is part of the
1142 * @param int $timestamp the time to record for the action. (If not given, use now.)
1143 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1145 public function finish($timestamp = null, $userid = null) {
1146 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1150 * Perform a regrade. This replays all the actions from $oldqa into this
1152 * @param question_attempt $oldqa the attempt to regrade.
1153 * @param bool $finished whether the question attempt should be forced to be finished
1154 * after the regrade, or whether it may still be in progress (default false).
1156 public function regrade(question_attempt $oldqa, $finished) {
1158 foreach ($oldqa->get_step_iterator() as $step) {
1159 $this->observer->notify_step_deleted($step, $this);
1162 // First step of the attempt.
1164 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
1165 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1167 } else if ($step->has_behaviour_var('finish') && count($step->get_submitted_data()) > 1) {
1168 // This case relates to MDL-32062. The upgrade code from 2.0
1169 // generates attempts where the final submit of the question
1170 // data, and the finish action, are in the same step. The system
1171 // cannot cope with that, so convert the single old step into
1173 $submitteddata = $step->get_submitted_data();
1174 unset($submitteddata['-finish']);
1175 $this->process_action($submitteddata,
1176 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1177 $this->finish($step->get_timecreated(), $step->get_user_id());
1180 // This is the normal case. Replay the next step of the attempt.
1181 $this->process_action($step->get_submitted_data(),
1182 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1192 * Perform a manual grading action on this attempt.
1193 * @param string $comment the comment being added.
1194 * @param float $mark the new mark. If null, then only a comment is added.
1195 * @param int $commentformat the FORMAT_... for $comment. Must be given.
1196 * @param int $timestamp the time to record for the action. (If not given, use now.)
1197 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1199 public function manual_grade($comment, $mark, $commentformat = null, $timestamp = null, $userid = null) {
1200 $submitteddata = array('-comment' => $comment);
1201 if (is_null($commentformat)) {
1202 debugging('You should pass $commentformat to manual_grade.', DEBUG_DEVELOPER);
1203 $commentformat = FORMAT_HTML;
1205 $submitteddata['-commentformat'] = $commentformat;
1206 if (!is_null($mark)) {
1207 $submitteddata['-mark'] = $mark;
1208 $submitteddata['-maxmark'] = $this->maxmark;
1210 $this->process_action($submitteddata, $timestamp, $userid);
1213 /** @return bool Whether this question attempt has had a manual comment added. */
1214 public function has_manual_comment() {
1215 foreach ($this->steps as $step) {
1216 if ($step->has_behaviour_var('comment')) {
1224 * @return array(string, int) the most recent manual comment that was added
1225 * to this question, and the FORMAT_... it is.
1227 public function get_manual_comment() {
1228 foreach ($this->get_reverse_step_iterator() as $step) {
1229 if ($step->has_behaviour_var('comment')) {
1230 return array($step->get_behaviour_var('comment'),
1231 $step->get_behaviour_var('commentformat'));
1234 return array(null, null);
1238 * @return array subpartid => object with fields
1239 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
1240 * ->response the actual response the student gave to this part, as a string.
1241 * ->fraction the credit awarded for this subpart, may be null.
1242 * returns an empty array if no analysis is possible.
1244 public function classify_response() {
1245 return $this->behaviour->classify_response();
1249 * Create a question_attempt_step from records loaded from the database.
1251 * For internal use only.
1253 * @param Iterator $records Raw records loaded from the database.
1254 * @param int $questionattemptid The id of the question_attempt to extract.
1255 * @return question_attempt The newly constructed question_attempt.
1257 public static function load_from_records($records, $questionattemptid,
1258 question_usage_observer $observer, $preferredbehaviour) {
1259 $record = $records->current();
1260 while ($record->questionattemptid != $questionattemptid) {
1261 $record = $records->next();
1262 if (!$records->valid()) {
1263 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
1265 $record = $records->current();
1269 $question = question_bank::load_question($record->questionid);
1270 } catch (Exception $e) {
1271 // The question must have been deleted somehow. Create a missing
1272 // question to use in its place.
1273 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1274 $record->questionid, $record->maxmark + 0);
1277 $qa = new question_attempt($question, $record->questionusageid,
1278 null, $record->maxmark + 0);
1279 $qa->set_database_id($record->questionattemptid);
1280 $qa->set_slot($record->slot);
1281 $qa->variant = $record->variant + 0;
1282 $qa->minfraction = $record->minfraction + 0;
1283 $qa->set_flagged($record->flagged);
1284 $qa->questionsummary = $record->questionsummary;
1285 $qa->rightanswer = $record->rightanswer;
1286 $qa->responsesummary = $record->responsesummary;
1287 $qa->timemodified = $record->timemodified;
1289 $qa->behaviour = question_engine::make_behaviour(
1290 $record->behaviour, $qa, $preferredbehaviour);
1291 $qa->observer = $observer;
1293 // If attemptstepid is null (which should not happen, but has happened
1294 // due to corrupt data, see MDL-34251) then the current pointer in $records
1295 // will not be advanced in the while loop below, and we get stuck in an
1296 // infinite loop, since this method is supposed to always consume at
1297 // least one record. Therefore, in this case, advance the record here.
1298 if (is_null($record->attemptstepid)) {
1303 $autosavedstep = null;
1304 $autosavedsequencenumber = null;
1305 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
1306 $sequencenumber = $record->sequencenumber;
1307 $nextstep = question_attempt_step::load_from_records($records, $record->attemptstepid, $qa->get_question()->get_type_name());
1309 if ($sequencenumber < 0) {
1310 if (!$autosavedstep) {
1311 $autosavedstep = $nextstep;
1312 $autosavedsequencenumber = -$sequencenumber;
1314 // Old redundant data. Mark it for deletion.
1315 $qa->observer->notify_step_deleted($nextstep, $qa);
1318 $qa->steps[$i] = $nextstep;
1320 $question->apply_attempt_state($qa->steps[0]);
1325 if ($records->valid()) {
1326 $record = $records->current();
1332 if ($autosavedstep) {
1333 if ($autosavedsequencenumber >= $i) {
1334 $qa->autosavedstep = $autosavedstep;
1335 $qa->steps[$i] = $qa->autosavedstep;
1337 $qa->observer->notify_step_deleted($autosavedstep, $qa);
1347 * This subclass of question_attempt pretends that only part of the step history
1348 * exists. It is used for rendering the question in past states.
1350 * All methods that try to modify the question_attempt throw exceptions.
1352 * @copyright 2010 The Open University
1353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1355 class question_attempt_with_restricted_history extends question_attempt {
1357 * @var question_attempt the underlying question_attempt.
1362 * Create a question_attempt_with_restricted_history
1363 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1364 * @param int $lastseq the index of the last step to include.
1365 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1366 * annoyting that this needs to be passed, but unavoidable for now.
1368 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
1369 $this->baseqa = $baseqa->get_full_qa();
1371 if ($lastseq < 0 || $lastseq >= $this->baseqa->get_num_steps()) {
1372 throw new coding_exception('$lastseq out of range', $lastseq);
1375 $this->steps = array_slice($this->baseqa->steps, 0, $lastseq + 1);
1376 $this->observer = new question_usage_null_observer();
1378 // This should be a straight copy of all the remaining fields.
1379 $this->id = $this->baseqa->id;
1380 $this->usageid = $this->baseqa->usageid;
1381 $this->slot = $this->baseqa->slot;
1382 $this->question = $this->baseqa->question;
1383 $this->maxmark = $this->baseqa->maxmark;
1384 $this->minfraction = $this->baseqa->minfraction;
1385 $this->questionsummary = $this->baseqa->questionsummary;
1386 $this->responsesummary = $this->baseqa->responsesummary;
1387 $this->rightanswer = $this->baseqa->rightanswer;
1388 $this->flagged = $this->baseqa->flagged;
1390 // Except behaviour, where we need to create a new one.
1391 $this->behaviour = question_engine::make_behaviour(
1392 $this->baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1395 public function get_full_qa() {
1396 return $this->baseqa;
1399 public function get_full_step_iterator() {
1400 return $this->baseqa->get_step_iterator();
1403 protected function add_step(question_attempt_step $step) {
1404 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1406 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1407 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1409 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null, $existingstepid = null) {
1410 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1413 public function set_database_id($id) {
1414 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1416 public function set_flagged($flagged) {
1417 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1419 public function set_slot($slot) {
1420 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1422 public function set_question_summary($questionsummary) {
1423 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1425 public function set_usage_id($usageid) {
1426 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1432 * A class abstracting access to the {@link question_attempt::$states} array.
1434 * This is actively linked to question_attempt. If you add an new step
1435 * mid-iteration, then it will be included.
1437 * @copyright 2009 The Open University
1438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1440 class question_attempt_step_iterator implements Iterator, ArrayAccess {
1441 /** @var question_attempt the question_attempt being iterated over. */
1443 /** @var integer records the current position in the iteration. */
1447 * Do not call this constructor directly.
1448 * Use {@link question_attempt::get_step_iterator()}.
1449 * @param question_attempt $qa the attempt to iterate over.
1451 public function __construct(question_attempt $qa) {
1456 /** @return question_attempt_step */
1457 public function current() {
1458 return $this->offsetGet($this->i);
1461 public function key() {
1464 public function next() {
1467 public function rewind() {
1471 public function valid() {
1472 return $this->offsetExists($this->i);
1476 public function offsetExists($i) {
1477 return $i >= 0 && $i < $this->qa->get_num_steps();
1479 /** @return question_attempt_step */
1480 public function offsetGet($i) {
1481 return $this->qa->get_step($i);
1483 public function offsetSet($offset, $value) {
1484 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1486 public function offsetUnset($offset) {
1487 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1493 * A variant of {@link question_attempt_step_iterator} that iterates through the
1494 * steps in reverse order.
1496 * @copyright 2009 The Open University
1497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1499 class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1500 public function next() {
1504 public function rewind() {
1505 $this->i = $this->qa->get_num_steps() - 1;