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