on-demand release 2.1beta
[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
97cdc1de
TH
520 /**
521 * @param bool $showcorrectness Whether right/partial/wrong states should
522 * be distinguised.
523 * @return string a CSS class name for the current state.
524 */
525 public function get_state_class($showcorrectness) {
526 return $this->get_state()->get_state_class($showcorrectness);
527 }
528
dcd03928
TH
529 /**
530 * @return int the timestamp of the most recent step in this question attempt.
531 */
532 public function get_last_action_time() {
533 return $this->get_last_step()->get_timecreated();
534 }
535
536 /**
537 * Get the current fraction of this question attempt. That is, the fraction
538 * of the latest step, or null if this question has not yet been graded.
539 * @return number the current fraction.
540 */
541 public function get_fraction() {
542 return $this->get_last_step()->get_fraction();
543 }
544
545 /** @return bool whether this question attempt has a non-zero maximum mark. */
546 public function has_marks() {
547 // Since grades are stored in the database as NUMBER(12,7).
548 return $this->maxmark >= 0.00000005;
549 }
550
551 /**
552 * @return number the current mark for this question.
553 * {@link get_fraction()} * {@link get_max_mark()}.
554 */
555 public function get_mark() {
556 return $this->fraction_to_mark($this->get_fraction());
557 }
558
559 /**
560 * This is used by the manual grading code, particularly in association with
561 * validation. If there is a mark submitted in the request, then use that,
562 * otherwise use the latest mark for this question.
563 * @return number the current mark for this question.
564 * {@link get_fraction()} * {@link get_max_mark()}.
565 */
566 public function get_current_manual_mark() {
567 $mark = $this->get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
568 if (is_null($mark)) {
569 return $this->get_mark();
570 } else {
571 return $mark;
572 }
573 }
574
575 /**
576 * @param number|null $fraction a fraction.
577 * @return number|null the corresponding mark.
578 */
579 public function fraction_to_mark($fraction) {
580 if (is_null($fraction)) {
581 return null;
582 }
583 return $fraction * $this->maxmark;
584 }
585
586 /** @return number the maximum mark possible for this question attempt. */
587 public function get_max_mark() {
588 return $this->maxmark;
589 }
590
591 /** @return number the maximum mark possible for this question attempt. */
592 public function get_min_fraction() {
593 if (is_null($this->minfraction)) {
594 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
595 }
596 return $this->minfraction;
597 }
598
599 /**
600 * The current mark, formatted to the stated number of decimal places. Uses
601 * {@link format_float()} to format floats according to the current locale.
602 * @param int $dp number of decimal places.
603 * @return string formatted mark.
604 */
605 public function format_mark($dp) {
606 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
607 }
608
609 /**
610 * The current mark, formatted to the stated number of decimal places. Uses
611 * {@link format_float()} to format floats according to the current locale.
612 * @param int $dp number of decimal places.
613 * @return string formatted mark.
614 */
615 public function format_fraction_as_mark($fraction, $dp) {
616 return format_float($this->fraction_to_mark($fraction), $dp);
617 }
618
619 /**
620 * The maximum mark for this question attempt, formatted to the stated number
621 * of decimal places. Uses {@link format_float()} to format floats according
622 * to the current locale.
623 * @param int $dp number of decimal places.
624 * @return string formatted maximum mark.
625 */
626 public function format_max_mark($dp) {
627 return format_float($this->maxmark, $dp);
628 }
629
630 /**
631 * Return the hint that applies to the question in its current state, or null.
632 * @return question_hint|null
633 */
634 public function get_applicable_hint() {
635 return $this->behaviour->get_applicable_hint();
636 }
637
638 /**
639 * Produce a plain-text summary of what the user did during a step.
640 * @param question_attempt_step $step the step in quetsion.
641 * @return string a summary of what was done during that step.
642 */
643 public function summarise_action(question_attempt_step $step) {
644 return $this->behaviour->summarise_action($step);
645 }
646
647 /**
648 * Helper function used by {@link rewrite_pluginfile_urls()} and
649 * {@link rewrite_response_pluginfile_urls()}.
650 * @return array ids that need to go into the file paths.
651 */
652 protected function extra_file_path_components() {
653 return array($this->get_usage_id(), $this->get_slot());
654 }
655
656 /**
657 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
658 * for content belonging to this question.
659 * @param string $text the content to output.
660 * @param string $component the component name (normally 'question' or 'qtype_...')
661 * @param string $filearea the name of the file area.
662 * @param int $itemid the item id.
663 * @return srting the content with the URLs rewritten.
664 */
665 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
666 return question_rewrite_question_urls($text, 'pluginfile.php',
667 $this->question->contextid, $component, $filearea,
668 $this->extra_file_path_components(), $itemid);
669 }
670
671 /**
672 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
673 * for content belonging to responses to this question.
674 *
675 * @param string $text the text to update the URLs in.
676 * @param int $contextid the id of the context the quba belongs to.
677 * @param string $name the variable name the files belong to.
678 * @param question_attempt_step $step the step the response is coming from.
679 * @return srting the content with the URLs rewritten.
680 */
681 public function rewrite_response_pluginfile_urls($text, $contextid, $name,
682 question_attempt_step $step) {
683 return $step->rewrite_response_pluginfile_urls($text, $contextid, $name,
684 $this->extra_file_path_components());
685 }
686
687 /**
688 * Get the {@link core_question_renderer}, in collaboration with appropriate
689 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
690 * HTML to display this question attempt in its current state.
691 * @param question_display_options $options controls how the question is rendered.
692 * @param string|null $number The question number to display.
693 * @return string HTML fragment representing the question.
694 */
695 public function render($options, $number, $page = null) {
696 if (is_null($page)) {
697 global $PAGE;
698 $page = $PAGE;
699 }
700 $qoutput = $page->get_renderer('core', 'question');
701 $qtoutput = $this->question->get_renderer($page);
702 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
703 }
704
705 /**
706 * Generate any bits of HTML that needs to go in the <head> tag when this question
707 * attempt is displayed in the body.
708 * @return string HTML fragment.
709 */
710 public function render_head_html($page = null) {
711 if (is_null($page)) {
712 global $PAGE;
713 $page = $PAGE;
714 }
715 // TODO go via behaviour.
716 return $this->question->get_renderer($page)->head_code($this) .
717 $this->behaviour->get_renderer($page)->head_code($this);
718 }
719
720 /**
721 * Like {@link render_question()} but displays the question at the past step
722 * indicated by $seq, rather than showing the latest step.
723 *
724 * @param int $seq the seq number of the past state to display.
725 * @param question_display_options $options controls how the question is rendered.
726 * @param string|null $number The question number to display. 'i' is a special
727 * value that gets displayed as Information. Null means no number is displayed.
728 * @return string HTML fragment representing the question.
729 */
730 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
731 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
732 return $restrictedqa->render($options, $number);
733 }
734
735 /**
736 * Checks whether the users is allow to be served a particular file.
737 * @param question_display_options $options the options that control display of the question.
738 * @param string $component the name of the component we are serving files for.
739 * @param string $filearea the name of the file area.
740 * @param array $args the remaining bits of the file path.
741 * @param bool $forcedownload whether the user must be forced to download the file.
742 * @return bool true if the user can access this file.
743 */
744 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
745 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
746 }
747
748 /**
749 * Add a step to this question attempt.
750 * @param question_attempt_step $step the new step.
751 */
752 protected function add_step(question_attempt_step $step) {
753 $this->steps[] = $step;
754 end($this->steps);
755 $this->observer->notify_step_added($step, $this, key($this->steps));
756 }
757
1da821bb
TH
758 /**
759 * Use a strategy to pick a variant.
760 * @param question_variant_selection_strategy $variantstrategy a strategy.
761 * @return int the selected variant.
762 */
763 public function select_variant(question_variant_selection_strategy $variantstrategy) {
764 return $variantstrategy->choose_variant($this->get_question()->get_num_variants(),
765 $this->get_question()->get_variants_selection_seed());
766 }
767
dcd03928
TH
768 /**
769 * Start this question attempt.
770 *
771 * You should not call this method directly. Call
772 * {@link question_usage_by_activity::start_question()} instead.
773 *
774 * @param string|question_behaviour $preferredbehaviour the name of the
775 * desired archetypal behaviour, or an actual model instance.
1da821bb
TH
776 * @param int $variant the variant of the question to start. Between 1 and
777 * $this->get_question()->get_num_variants() inclusive.
dcd03928
TH
778 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
779 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
780 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
781 */
1da821bb
TH
782 public function start($preferredbehaviour, $variant, $submitteddata = array(),
783 $timestamp = null, $userid = null) {
784
dcd03928 785 // Initialise the behaviour.
1da821bb 786 $this->variant = $variant;
dcd03928
TH
787 if (is_string($preferredbehaviour)) {
788 $this->behaviour =
789 $this->question->make_behaviour($this, $preferredbehaviour);
790 } else {
791 $class = get_class($preferredbehaviour);
792 $this->behaviour = new $class($this, $preferredbehaviour);
793 }
794
795 // Record the minimum fraction.
796 $this->minfraction = $this->behaviour->get_min_fraction();
797
798 // Initialise the first step.
799 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid);
800 $firststep->set_state(question_state::$todo);
801 if ($submitteddata) {
802 $this->question->apply_attempt_state($firststep);
803 } else {
1da821bb 804 $this->behaviour->init_first_step($firststep, $variant);
dcd03928
TH
805 }
806 $this->add_step($firststep);
807
808 // Record questionline and correct answer.
809 $this->questionsummary = $this->behaviour->get_question_summary();
810 $this->rightanswer = $this->behaviour->get_right_answer_summary();
811 }
812
813 /**
814 * Start this question attempt, starting from the point that the previous
815 * attempt $oldqa had reached.
816 *
817 * You should not call this method directly. Call
818 * {@link question_usage_by_activity::start_question_based_on()} instead.
819 *
820 * @param question_attempt $oldqa a previous attempt at this quetsion that
821 * defines the starting point.
822 */
823 public function start_based_on(question_attempt $oldqa) {
1da821bb 824 $this->start($oldqa->behaviour, $oldqa->get_variant(), $oldqa->get_resume_data());
dcd03928
TH
825 }
826
827 /**
828 * Used by {@link start_based_on()} to get the data needed to start a new
829 * attempt from the point this attempt has go to.
830 * @return array name => value pairs.
831 */
832 protected function get_resume_data() {
833 return $this->behaviour->get_resume_data();
834 }
835
836 /**
837 * Get a particular parameter from the current request. A wrapper round
838 * {@link optional_param()}, except that the results is returned without
839 * slashes.
840 * @param string $name the paramter name.
841 * @param int $type one of the standard PARAM_... constants, or one of the
842 * special extra constands defined by this class.
843 * @param array $postdata (optional, only inteded for testing use) take the
844 * data from this array, instead of from $_POST.
845 * @return mixed the requested value.
846 */
847 public function get_submitted_var($name, $type, $postdata = null) {
848 switch ($type) {
849 case self::PARAM_MARK:
850 // Special case to work around PARAM_NUMBER converting '' to 0.
851 $mark = $this->get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata);
852 if ($mark === '') {
853 return $mark;
854 } else {
855 return $this->get_submitted_var($name, PARAM_NUMBER, $postdata);
856 }
857
858 case self::PARAM_FILES:
859 return $this->process_response_files($name, $name, $postdata);
860
861 case self::PARAM_CLEANHTML_FILES:
862 $var = $this->get_submitted_var($name, PARAM_CLEANHTML, $postdata);
863 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
864
865 default:
866 if (is_null($postdata)) {
867 $var = optional_param($name, null, $type);
868 } else if (array_key_exists($name, $postdata)) {
869 $var = clean_param($postdata[$name], $type);
870 } else {
871 $var = null;
872 }
873
874 return $var;
875 }
876 }
877
878 /**
879 * Handle a submitted variable representing uploaded files.
880 * @param string $name the field name.
881 * @param string $draftidname the field name holding the draft file area id.
882 * @param array $postdata (optional, only inteded for testing use) take the
883 * data from this array, instead of from $_POST. At the moment, this
884 * behaves as if there were no files.
885 * @param string $text optional reponse text.
886 * @return question_file_saver that can be used to save the files later.
887 */
888 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
889 if ($postdata) {
890 // There can be no files with test data (at the moment).
891 return null;
892 }
893
894 $draftitemid = file_get_submitted_draft_itemid($draftidname);
895 if (!$draftitemid) {
896 return null;
897 }
898
899 return new question_file_saver($draftitemid, 'question', 'response_' .
900 str_replace($this->get_field_prefix(), '', $name), $text);
901 }
902
903 /**
904 * Get any data from the request that matches the list of expected params.
905 * @param array $expected variable name => PARAM_... constant.
906 * @param string $extraprefix '-' or ''.
907 * @return array name => value.
908 */
909 protected function get_expected_data($expected, $postdata, $extraprefix) {
910 $submitteddata = array();
911 foreach ($expected as $name => $type) {
912 $value = $this->get_submitted_var(
913 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
914 if (!is_null($value)) {
915 $submitteddata[$extraprefix . $name] = $value;
916 }
917 }
918 return $submitteddata;
919 }
920
921 /**
922 * Get all the submitted question type data for this question, whithout checking
923 * that it is valid or cleaning it in any way.
924 * @return array name => value.
925 */
926 protected function get_all_submitted_qt_vars($postdata) {
927 if (is_null($postdata)) {
928 $postdata = $_POST;
929 }
930
931 $pattern = '/^' . preg_quote($this->get_field_prefix()) . '[^-:]/';
932 $prefixlen = strlen($this->get_field_prefix());
933
934 $submitteddata = array();
935 foreach ($_POST as $name => $value) {
936 if (preg_match($pattern, $name)) {
937 $submitteddata[substr($name, $prefixlen)] = $value;
938 }
939 }
940
941 return $submitteddata;
942 }
943
944 /**
945 * Get all the sumbitted data belonging to this question attempt from the
946 * current request.
947 * @param array $postdata (optional, only inteded for testing use) take the
948 * data from this array, instead of from $_POST.
949 * @return array name => value pairs that could be passed to {@link process_action()}.
950 */
951 public function get_submitted_data($postdata = null) {
952 $submitteddata = $this->get_expected_data(
953 $this->behaviour->get_expected_data(), $postdata, '-');
954
955 $expected = $this->behaviour->get_expected_qt_data();
956 if ($expected === self::USE_RAW_DATA) {
957 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
958 } else {
959 $submitteddata += $this->get_expected_data($expected, $postdata, '');
960 }
961 return $submitteddata;
962 }
963
964 /**
965 * Get a set of response data for this question attempt that would get the
966 * best possible mark.
967 * @return array name => value pairs that could be passed to {@link process_action()}.
968 */
969 public function get_correct_response() {
970 $response = $this->question->get_correct_response();
971 $imvars = $this->behaviour->get_correct_response();
972 foreach ($imvars as $name => $value) {
973 $response['-' . $name] = $value;
974 }
975 return $response;
976 }
977
978 /**
979 * Change the quetsion summary. Note, that this is almost never necessary.
980 * This method was only added to work around a limitation of the Opaque
981 * protocol, which only sends questionLine at the end of an attempt.
982 * @param $questionsummary the new summary to set.
983 */
984 public function set_question_summary($questionsummary) {
985 $this->questionsummary = $questionsummary;
986 $this->observer->notify_attempt_modified($this);
987 }
988
989 /**
990 * @return string a simple textual summary of the question that was asked.
991 */
992 public function get_question_summary() {
993 return $this->questionsummary;
994 }
995
996 /**
997 * @return string a simple textual summary of response given.
998 */
999 public function get_response_summary() {
1000 return $this->responsesummary;
1001 }
1002
1003 /**
1004 * @return string a simple textual summary of the correct resonse.
1005 */
1006 public function get_right_answer_summary() {
1007 return $this->rightanswer;
1008 }
1009
1010 /**
1011 * Perform the action described by $submitteddata.
1012 * @param array $submitteddata the submitted data the determines the action.
1013 * @param int $timestamp the time to record for the action. (If not given, use now.)
1014 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1015 */
1016 public function process_action($submitteddata, $timestamp = null, $userid = null) {
1017 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1018 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1019 $this->add_step($pendingstep);
1020 if ($pendingstep->response_summary_changed()) {
1021 $this->responsesummary = $pendingstep->get_new_response_summary();
1022 }
1023 }
1024 }
1025
1026 /**
1027 * Perform a finish action on this question attempt. This corresponds to an
1028 * external finish action, for example the user pressing Submit all and finish
1029 * in the quiz, rather than using one of the controls that is part of the
1030 * question.
1031 *
1032 * @param int $timestamp the time to record for the action. (If not given, use now.)
1033 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1034 */
1035 public function finish($timestamp = null, $userid = null) {
1036 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1037 }
1038
1039 /**
1040 * Perform a regrade. This replays all the actions from $oldqa into this
1041 * attempt.
1042 * @param question_attempt $oldqa the attempt to regrade.
1043 * @param bool $finished whether the question attempt should be forced to be finished
1044 * after the regrade, or whether it may still be in progress (default false).
1045 */
1046 public function regrade(question_attempt $oldqa, $finished) {
1047 $first = true;
1048 foreach ($oldqa->get_step_iterator() as $step) {
1049 if ($first) {
1050 $first = false;
1da821bb 1051 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
dcd03928
TH
1052 $step->get_timecreated(), $step->get_user_id());
1053 } else {
1054 $this->process_action($step->get_submitted_data(),
1055 $step->get_timecreated(), $step->get_user_id());
1056 }
1057 }
1058 if ($finished) {
1059 $this->finish();
1060 }
1061 }
1062
1063 /**
1064 * Perform a manual grading action on this attempt.
1065 * @param $comment the comment being added.
1066 * @param $mark the new mark. (Optional, if not given, then only a comment is added.)
1067 * @param int $timestamp the time to record for the action. (If not given, use now.)
1068 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1069 * @return unknown_type
1070 */
1071 public function manual_grade($comment, $mark, $timestamp = null, $userid = null) {
1072 $submitteddata = array('-comment' => $comment);
1073 if (!is_null($mark)) {
1074 $submitteddata['-mark'] = $mark;
1075 $submitteddata['-maxmark'] = $this->maxmark;
1076 }
1077 $this->process_action($submitteddata, $timestamp, $userid);
1078 }
1079
1080 /** @return bool Whether this question attempt has had a manual comment added. */
1081 public function has_manual_comment() {
1082 foreach ($this->steps as $step) {
1083 if ($step->has_behaviour_var('comment')) {
1084 return true;
1085 }
1086 }
1087 return false;
1088 }
1089
1090 /**
1091 * @return array(string, int) the most recent manual comment that was added
1092 * to this question, and the FORMAT_... it is.
1093 */
1094 public function get_manual_comment() {
1095 foreach ($this->get_reverse_step_iterator() as $step) {
1096 if ($step->has_behaviour_var('comment')) {
1097 return array($step->get_behaviour_var('comment'),
1098 $step->get_behaviour_var('commentformat'));
1099 }
1100 }
1101 return array(null, null);
1102 }
1103
1104 /**
1105 * @return array subpartid => object with fields
1106 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
1107 * ->response the actual response the student gave to this part, as a string.
1108 * ->fraction the credit awarded for this subpart, may be null.
1109 * returns an empty array if no analysis is possible.
1110 */
1111 public function classify_response() {
1112 return $this->behaviour->classify_response();
1113 }
1114
1115 /**
1116 * Create a question_attempt_step from records loaded from the database.
1117 *
1118 * For internal use only.
1119 *
1120 * @param array $records Raw records loaded from the database.
1121 * @param int $questionattemptid The id of the question_attempt to extract.
1122 * @return question_attempt The newly constructed question_attempt_step.
1123 */
1124 public static function load_from_records(&$records, $questionattemptid,
1125 question_usage_observer $observer, $preferredbehaviour) {
1126 $record = current($records);
1127 while ($record->questionattemptid != $questionattemptid) {
1128 $record = next($records);
1129 if (!$record) {
1130 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
1131 }
1132 }
1133
1134 try {
1135 $question = question_bank::load_question($record->questionid);
1136 } catch (Exception $e) {
1137 // The question must have been deleted somehow. Create a missing
1138 // question to use in its place.
1139 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1140 $record->questionid, $record->maxmark + 0);
1141 }
1142
1143 $qa = new question_attempt($question, $record->questionusageid,
1144 null, $record->maxmark + 0);
1145 $qa->set_database_id($record->questionattemptid);
1146 $qa->set_number_in_usage($record->slot);
1da821bb 1147 $qa->variant = $record->variant + 0;
dcd03928
TH
1148 $qa->minfraction = $record->minfraction + 0;
1149 $qa->set_flagged($record->flagged);
1150 $qa->questionsummary = $record->questionsummary;
1151 $qa->rightanswer = $record->rightanswer;
1152 $qa->responsesummary = $record->responsesummary;
1153 $qa->timemodified = $record->timemodified;
1154
1155 $qa->behaviour = question_engine::make_behaviour(
1156 $record->behaviour, $qa, $preferredbehaviour);
1157
1158 $i = 0;
1159 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
1160 $qa->steps[$i] = question_attempt_step::load_from_records($records, $record->attemptstepid);
1161 if ($i == 0) {
1162 $question->apply_attempt_state($qa->steps[0]);
1163 }
1164 $i++;
1165 $record = current($records);
1166 }
1167
1168 $qa->observer = $observer;
1169
1170 return $qa;
1171 }
1172}
1173
1174
1175/**
1176 * This subclass of question_attempt pretends that only part of the step history
1177 * exists. It is used for rendering the question in past states.
1178 *
1179 * All methods that try to modify the question_attempt throw exceptions.
1180 *
1181 * @copyright 2010 The Open University
1182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1183 */
1184class question_attempt_with_restricted_history extends question_attempt {
1185 /**
1186 * @var question_attempt the underlying question_attempt.
1187 */
1188 protected $baseqa;
1189
1190 /**
1191 * Create a question_attempt_with_restricted_history
1192 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1193 * @param int $lastseq the index of the last step to include.
1194 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1195 * annoyting that this needs to be passed, but unavoidable for now.
1196 */
1197 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
1198 if ($lastseq < 0 || $lastseq >= $baseqa->get_num_steps()) {
1199 throw new coding_exception('$seq out of range', $seq);
1200 }
1201
1202 $this->baseqa = $baseqa;
1203 $this->steps = array_slice($baseqa->steps, 0, $lastseq + 1);
1204 $this->observer = new question_usage_null_observer();
1205
1206 // This should be a straight copy of all the remaining fields.
1207 $this->id = $baseqa->id;
1208 $this->usageid = $baseqa->usageid;
1209 $this->slot = $baseqa->slot;
1210 $this->question = $baseqa->question;
1211 $this->maxmark = $baseqa->maxmark;
1212 $this->minfraction = $baseqa->minfraction;
1213 $this->questionsummary = $baseqa->questionsummary;
1214 $this->responsesummary = $baseqa->responsesummary;
1215 $this->rightanswer = $baseqa->rightanswer;
1216 $this->flagged = $baseqa->flagged;
1217
1218 // Except behaviour, where we need to create a new one.
1219 $this->behaviour = question_engine::make_behaviour(
1220 $baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1221 }
1222
1223 public function get_full_step_iterator() {
1224 return $this->baseqa->get_step_iterator();
1225 }
1226
1227 protected function add_step(question_attempt_step $step) {
1228 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1229 }
1230 public function process_action($submitteddata, $timestamp = null, $userid = null) {
1231 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1232 }
1da821bb 1233 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null) {
dcd03928
TH
1234 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1235 }
1236
1237 public function set_database_id($id) {
1238 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1239 }
1240 public function set_flagged($flagged) {
1241 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1242 }
1243 public function set_number_in_usage($slot) {
1244 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1245 }
1246 public function set_question_summary($questionsummary) {
1247 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1248 }
1249 public function set_usage_id($usageid) {
1250 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1251 }
1252}
1253
1254
1255/**
1256 * A class abstracting access to the {@link question_attempt::$states} array.
1257 *
1258 * This is actively linked to question_attempt. If you add an new step
1259 * mid-iteration, then it will be included.
1260 *
1261 * @copyright 2009 The Open University
1262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1263 */
1264class question_attempt_step_iterator implements Iterator, ArrayAccess {
1265 /** @var question_attempt the question_attempt being iterated over. */
1266 protected $qa;
1267 /** @var integer records the current position in the iteration. */
1268 protected $i;
1269
1270 /**
1271 * Do not call this constructor directly.
1272 * Use {@link question_attempt::get_step_iterator()}.
1273 * @param question_attempt $qa the attempt to iterate over.
1274 */
1275 public function __construct(question_attempt $qa) {
1276 $this->qa = $qa;
1277 $this->rewind();
1278 }
1279
1280 /** @return question_attempt_step */
1281 public function current() {
1282 return $this->offsetGet($this->i);
1283 }
1284 /** @return int */
1285 public function key() {
1286 return $this->i;
1287 }
1288 public function next() {
1289 ++$this->i;
1290 }
1291 public function rewind() {
1292 $this->i = 0;
1293 }
1294 /** @return bool */
1295 public function valid() {
1296 return $this->offsetExists($this->i);
1297 }
1298
1299 /** @return bool */
1300 public function offsetExists($i) {
1301 return $i >= 0 && $i < $this->qa->get_num_steps();
1302 }
1303 /** @return question_attempt_step */
1304 public function offsetGet($i) {
1305 return $this->qa->get_step($i);
1306 }
1307 public function offsetSet($offset, $value) {
1308 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1309 }
1310 public function offsetUnset($offset) {
1311 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1312 }
1313}
1314
1315
1316/**
1317 * A variant of {@link question_attempt_step_iterator} that iterates through the
1318 * steps in reverse order.
1319 *
1320 * @copyright 2009 The Open University
1321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1322 */
1323class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1324 public function next() {
1325 --$this->i;
1326 }
1327
1328 public function rewind() {
1329 $this->i = $this->qa->get_num_steps() - 1;
1330 }
1331}