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