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