weekly release 3.7dev
[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 /**
b2694c02
TH
52 * @var string Should not longer be used.
53 * @deprecated since Moodle 3.0
dcd03928 54 */
b2694c02 55 const PARAM_MARK = PARAM_RAW_TRIMMED;
dcd03928
TH
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 */
2d2018ab 67 const PARAM_RAW_FILES = 'paramrawfiles';
dcd03928 68
99caa248
JP
69 /**
70 * @var string means first try at a question during an attempt by a user.
71 */
72 const FIRST_TRY = 'firsttry';
73
74 /**
75 * @var string means last try at a question during an attempt by a user.
76 */
77 const LAST_TRY = 'lasttry';
78
79 /**
80 * @var string means all tries at a question during an attempt by a user.
81 */
82 const ALL_TRIES = 'alltries';
83
dcd03928
TH
84 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
85 protected $id = null;
86
87 /** @var integer|string the id of the question_usage_by_activity we belong to. */
88 protected $usageid;
89
90 /** @var integer the number used to identify this question_attempt within the usage. */
91 protected $slot = null;
92
93 /**
94 * @var question_behaviour the behaviour controlling this attempt.
95 * null until {@link start()} is called.
96 */
97 protected $behaviour = null;
98
99 /** @var question_definition the question this is an attempt at. */
100 protected $question;
101
1da821bb
TH
102 /** @var int which variant of the question to use. */
103 protected $variant;
104
4e3d8293
TH
105 /**
106 * @var float the maximum mark that can be scored at this question.
107 * Actually, this is only really a nominal maximum. It might be better thought
108 * of as the question weight.
109 */
dcd03928
TH
110 protected $maxmark;
111
112 /**
4e3d8293 113 * @var float the minimum fraction that can be scored at this question, so
dcd03928
TH
114 * the minimum mark is $this->minfraction * $this->maxmark.
115 */
116 protected $minfraction = null;
117
4e3d8293
TH
118 /**
119 * @var float the maximum fraction that can be scored at this question, so
120 * the maximum mark is $this->maxfraction * $this->maxmark.
121 */
122 protected $maxfraction = null;
123
dcd03928
TH
124 /**
125 * @var string plain text summary of the variant of the question the
126 * student saw. Intended for reporting purposes.
127 */
128 protected $questionsummary = null;
129
130 /**
131 * @var string plain text summary of the response the student gave.
132 * Intended for reporting purposes.
133 */
134 protected $responsesummary = null;
135
136 /**
137 * @var string plain text summary of the correct response to this question
138 * variant the student saw. The format should be similar to responsesummary.
139 * Intended for reporting purposes.
140 */
141 protected $rightanswer = null;
142
143 /** @var array of {@link question_attempt_step}s. The steps in this attempt. */
144 protected $steps = array();
145
0a606a2b
TH
146 /**
147 * @var question_attempt_step if, when we loaded the step from the DB, there was
148 * an autosaved step, we save a pointer to it here. (It is also added to the $steps array.)
149 */
150 protected $autosavedstep = null;
151
dcd03928
TH
152 /** @var boolean whether the user has flagged this attempt within the usage. */
153 protected $flagged = false;
154
155 /** @var question_usage_observer tracks changes to the useage this attempt is part of.*/
156 protected $observer;
157
158 /**#@+
159 * Constants used by the intereaction models to indicate whether the current
160 * pending step should be kept or discarded.
161 */
162 const KEEP = true;
163 const DISCARD = false;
164 /**#@-*/
165
166 /**
167 * Create a new {@link question_attempt}. Normally you should create question_attempts
168 * indirectly, by calling {@link question_usage_by_activity::add_question()}.
169 *
170 * @param question_definition $question the question this is an attempt at.
171 * @param int|string $usageid The id of the
172 * {@link question_usage_by_activity} we belong to. Used by {@link get_field_prefix()}.
173 * @param question_usage_observer $observer tracks changes to the useage this
174 * attempt is part of. (Optional, a {@link question_usage_null_observer} is
175 * used if one is not passed.
176 * @param number $maxmark the maximum grade for this question_attempt. If not
177 * passed, $question->defaultmark is used.
178 */
179 public function __construct(question_definition $question, $usageid,
180 question_usage_observer $observer = null, $maxmark = null) {
181 $this->question = $question;
182 $this->usageid = $usageid;
183 if (is_null($observer)) {
184 $observer = new question_usage_null_observer();
185 }
186 $this->observer = $observer;
187 if (!is_null($maxmark)) {
188 $this->maxmark = $maxmark;
189 } else {
190 $this->maxmark = $question->defaultmark;
191 }
192 }
193
f123d67f
TH
194 /**
195 * This method exists so that {@link question_attempt_with_restricted_history}
196 * can override it. You should not normally need to call it.
197 * @return question_attempt return ourself.
198 */
199 public function get_full_qa() {
200 return $this;
201 }
202
dcd03928
TH
203 /** @return question_definition the question this is an attempt at. */
204 public function get_question() {
205 return $this->question;
206 }
207
1da821bb
TH
208 /**
209 * Get the variant of the question being used in a given slot.
210 * @return int the variant number.
211 */
212 public function get_variant() {
213 return $this->variant;
214 }
215
dcd03928
TH
216 /**
217 * Set the number used to identify this question_attempt within the usage.
218 * For internal use only.
219 * @param int $slot
220 */
94815ccf 221 public function set_slot($slot) {
dcd03928
TH
222 $this->slot = $slot;
223 }
224
225 /** @return int the number used to identify this question_attempt within the usage. */
226 public function get_slot() {
227 return $this->slot;
228 }
229
230 /**
231 * @return int the id of row for this question_attempt, if it is stored in the
232 * database. null if not.
233 */
234 public function get_database_id() {
235 return $this->id;
236 }
237
238 /**
239 * For internal use only. Set the id of the corresponding database row.
240 * @param int $id the id of row for this question_attempt, if it is
241 * stored in the database.
242 */
243 public function set_database_id($id) {
244 $this->id = $id;
245 }
246
94815ccf
TH
247 /**
248 * You should almost certainly not call this method from your code. It is for
249 * internal use only.
250 * @param question_usage_observer that should be used to tracking changes made to this qa.
251 */
252 public function set_observer($observer) {
253 $this->observer = $observer;
254 }
255
dcd03928
TH
256 /** @return int|string the id of the {@link question_usage_by_activity} we belong to. */
257 public function get_usage_id() {
258 return $this->usageid;
259 }
260
261 /**
262 * Set the id of the {@link question_usage_by_activity} we belong to.
263 * For internal use only.
264 * @param int|string the new id.
265 */
266 public function set_usage_id($usageid) {
267 $this->usageid = $usageid;
268 }
269
270 /** @return string the name of the behaviour that is controlling this attempt. */
271 public function get_behaviour_name() {
272 return $this->behaviour->get_name();
273 }
274
275 /**
276 * For internal use only.
277 * @return question_behaviour the behaviour that is controlling this attempt.
278 */
279 public function get_behaviour() {
280 return $this->behaviour;
281 }
282
283 /**
284 * Set the flagged state of this question.
285 * @param bool $flagged the new state.
286 */
287 public function set_flagged($flagged) {
288 $this->flagged = $flagged;
289 $this->observer->notify_attempt_modified($this);
290 }
291
292 /** @return bool whether this question is currently flagged. */
293 public function is_flagged() {
294 return $this->flagged;
295 }
296
297 /**
298 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
299 * name) to use for the field that indicates whether this question is flagged.
300 *
301 * @return string The field name to use.
302 */
303 public function get_flag_field_name() {
304 return $this->get_control_field_name('flagged');
305 }
306
307 /**
308 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
309 * name) to use for a question_type variable belonging to this question_attempt.
310 *
311 * See the comment on {@link question_attempt_step} for an explanation of
312 * question type and behaviour variables.
313 *
314 * @param $varname The short form of the variable name.
315 * @return string The field name to use.
316 */
317 public function get_qt_field_name($varname) {
318 return $this->get_field_prefix() . $varname;
319 }
320
321 /**
322 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
323 * name) to use for a question_type variable belonging to this question_attempt.
324 *
325 * See the comment on {@link question_attempt_step} for an explanation of
326 * question type and behaviour variables.
327 *
328 * @param $varname The short form of the variable name.
329 * @return string The field name to use.
330 */
331 public function get_behaviour_field_name($varname) {
332 return $this->get_field_prefix() . '-' . $varname;
333 }
334
335 /**
336 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
337 * name) to use for a control variables belonging to this question_attempt.
338 *
339 * Examples are :sequencecheck and :flagged
340 *
341 * @param $varname The short form of the variable name.
342 * @return string The field name to use.
343 */
344 public function get_control_field_name($varname) {
345 return $this->get_field_prefix() . ':' . $varname;
346 }
347
348 /**
349 * Get the prefix added to variable names to give field names for this
350 * question attempt.
351 *
352 * You should not use this method directly. This is an implementation detail
353 * anyway, but if you must access it, use {@link question_usage_by_activity::get_field_prefix()}.
354 *
355 * @param $varname The short form of the variable name.
356 * @return string The field name to use.
357 */
358 public function get_field_prefix() {
359 return 'q' . $this->usageid . ':' . $this->slot . '_';
360 }
361
362 /**
363 * Get one of the steps in this attempt.
99caa248 364 *
f6579bea 365 * @param int $i the step number, which counts from 0.
dcd03928
TH
366 * @return question_attempt_step
367 */
368 public function get_step($i) {
369 if ($i < 0 || $i >= count($this->steps)) {
370 throw new coding_exception('Index out of bounds in question_attempt::get_step.');
371 }
372 return $this->steps[$i];
373 }
374
c7fbfe46
TH
375 /**
376 * Get the number of real steps in this attempt.
377 * This is put as a hidden field in the HTML, so that when we receive some
378 * data to process, then we can check that it came from the question
379 * in the state we are now it.
380 * @return int a number that summarises the current state of this question attempt.
381 */
382 public function get_sequence_check_count() {
383 $numrealsteps = $this->get_num_steps();
384 if ($this->has_autosaved_step()) {
385 $numrealsteps -= 1;
386 }
387 return $numrealsteps;
388 }
389
dcd03928
TH
390 /**
391 * Get the number of steps in this attempt.
392 * For internal/test code use only.
393 * @return int the number of steps we currently have.
394 */
395 public function get_num_steps() {
396 return count($this->steps);
397 }
398
399 /**
400 * Return the latest step in this question_attempt.
401 * For internal/test code use only.
402 * @return question_attempt_step
403 */
404 public function get_last_step() {
405 if (count($this->steps) == 0) {
406 return new question_null_step();
407 }
408 return end($this->steps);
409 }
410
0a606a2b
TH
411 /**
412 * @return boolean whether this question_attempt has autosaved data from
413 * some time in the past.
414 */
415 public function has_autosaved_step() {
416 return !is_null($this->autosavedstep);
417 }
418
dcd03928
TH
419 /**
420 * @return question_attempt_step_iterator for iterating over the steps in
421 * this attempt, in order.
422 */
423 public function get_step_iterator() {
424 return new question_attempt_step_iterator($this);
425 }
426
427 /**
428 * The same as {@link get_step_iterator()}. However, for a
429 * {@link question_attempt_with_restricted_history} this returns the full
430 * list of steps, while {@link get_step_iterator()} returns only the
431 * limited history.
432 * @return question_attempt_step_iterator for iterating over the steps in
433 * this attempt, in order.
434 */
435 public function get_full_step_iterator() {
436 return $this->get_step_iterator();
437 }
438
439 /**
440 * @return question_attempt_reverse_step_iterator for iterating over the steps in
441 * this attempt, in reverse order.
442 */
443 public function get_reverse_step_iterator() {
444 return new question_attempt_reverse_step_iterator($this);
445 }
446
447 /**
448 * Get the qt data from the latest step that has any qt data. Return $default
449 * array if it is no step has qt data.
450 *
451 * @param string $name the name of the variable to get.
452 * @param mixed default the value to return no step has qt data.
453 * (Optional, defaults to an empty array.)
454 * @return array|mixed the data, or $default if there is not any.
455 */
456 public function get_last_qt_data($default = array()) {
457 foreach ($this->get_reverse_step_iterator() as $step) {
458 $response = $step->get_qt_data();
459 if (!empty($response)) {
460 return $response;
461 }
462 }
463 return $default;
464 }
465
466 /**
467 * Get the last step with a particular question type varialbe set.
468 * @param string $name the name of the variable to get.
469 * @return question_attempt_step the last step, or a step with no variables
470 * if there was not a real step.
471 */
472 public function get_last_step_with_qt_var($name) {
473 foreach ($this->get_reverse_step_iterator() as $step) {
474 if ($step->has_qt_var($name)) {
475 return $step;
476 }
cc9fc649
HB
477 }
478 return new question_attempt_step_read_only();
479 }
480
481 /**
482 * Get the last step with a particular behaviour variable set.
483 * @param string $name the name of the variable to get.
484 * @return question_attempt_step the last step, or a step with no variables
485 * if there was not a real step.
486 */
487 public function get_last_step_with_behaviour_var($name) {
488 foreach ($this->get_reverse_step_iterator() as $step) {
489 if ($step->has_behaviour_var($name)) {
490 return $step;
491 }
dcd03928
TH
492 }
493 return new question_attempt_step_read_only();
494 }
495
496 /**
497 * Get the latest value of a particular question type variable. That is, get
498 * the value from the latest step that has it set. Return null if it is not
499 * set in any step.
500 *
501 * @param string $name the name of the variable to get.
502 * @param mixed default the value to return in the variable has never been set.
503 * (Optional, defaults to null.)
504 * @return mixed string value, or $default if it has never been set.
505 */
506 public function get_last_qt_var($name, $default = null) {
507 $step = $this->get_last_step_with_qt_var($name);
508 if ($step->has_qt_var($name)) {
509 return $step->get_qt_var($name);
510 } else {
511 return $default;
512 }
513 }
514
515 /**
516 * Get the latest set of files for a particular question type variable of
517 * type question_attempt::PARAM_FILES.
518 *
519 * @param string $name the name of the associated variable.
520 * @return array of {@link stored_files}.
521 */
522 public function get_last_qt_files($name, $contextid) {
523 foreach ($this->get_reverse_step_iterator() as $step) {
524 if ($step->has_qt_var($name)) {
525 return $step->get_qt_files($name, $contextid);
526 }
527 }
528 return array();
529 }
530
531 /**
532 * Get the URL of a file that belongs to a response variable of this
533 * question_attempt.
534 * @param stored_file $file the file to link to.
535 * @return string the URL of that file.
536 */
537 public function get_response_file_url(stored_file $file) {
538 return file_encode_url(new moodle_url('/pluginfile.php'), '/' . implode('/', array(
539 $file->get_contextid(),
540 $file->get_component(),
541 $file->get_filearea(),
542 $this->usageid,
543 $this->slot,
544 $file->get_itemid())) .
545 $file->get_filepath() . $file->get_filename(), true);
546 }
547
548 /**
549 * Prepare a draft file are for the files belonging the a response variable
550 * of this question attempt. The draft area is populated with the files from
551 * the most recent step having files.
552 *
553 * @param string $name the variable name the files belong to.
554 * @param int $contextid the id of the context the quba belongs to.
555 * @return int the draft itemid.
556 */
557 public function prepare_response_files_draft_itemid($name, $contextid) {
558 foreach ($this->get_reverse_step_iterator() as $step) {
559 if ($step->has_qt_var($name)) {
560 return $step->prepare_response_files_draft_itemid($name, $contextid);
561 }
562 }
563
564 // No files yet.
565 $draftid = 0; // Will be filled in by file_prepare_draft_area.
566 file_prepare_draft_area($draftid, $contextid, 'question', 'response_' . $name, null);
567 return $draftid;
568 }
569
570 /**
571 * Get the latest value of a particular behaviour variable. That is,
572 * get the value from the latest step that has it set. Return null if it is
573 * not set in any step.
574 *
575 * @param string $name the name of the variable to get.
576 * @param mixed default the value to return in the variable has never been set.
577 * (Optional, defaults to null.)
578 * @return mixed string value, or $default if it has never been set.
579 */
580 public function get_last_behaviour_var($name, $default = null) {
581 foreach ($this->get_reverse_step_iterator() as $step) {
582 if ($step->has_behaviour_var($name)) {
583 return $step->get_behaviour_var($name);
584 }
585 }
586 return $default;
587 }
588
589 /**
590 * Get the current state of this question attempt. That is, the state of the
591 * latest step.
592 * @return question_state
593 */
594 public function get_state() {
595 return $this->get_last_step()->get_state();
596 }
597
598 /**
599 * @param bool $showcorrectness Whether right/partial/wrong states should
600 * be distinguised.
601 * @return string A brief textual description of the current state.
602 */
603 public function get_state_string($showcorrectness) {
f8e28244
RK
604 // Special case when attempt is based on previous one, see MDL-31226.
605 if ($this->get_num_steps() == 1 && $this->get_state() == question_state::$complete) {
606 return get_string('notchanged', 'question');
607 }
dcd03928
TH
608 return $this->behaviour->get_state_string($showcorrectness);
609 }
610
97cdc1de
TH
611 /**
612 * @param bool $showcorrectness Whether right/partial/wrong states should
613 * be distinguised.
614 * @return string a CSS class name for the current state.
615 */
616 public function get_state_class($showcorrectness) {
617 return $this->get_state()->get_state_class($showcorrectness);
618 }
619
dcd03928
TH
620 /**
621 * @return int the timestamp of the most recent step in this question attempt.
622 */
623 public function get_last_action_time() {
624 return $this->get_last_step()->get_timecreated();
625 }
626
627 /**
628 * Get the current fraction of this question attempt. That is, the fraction
629 * of the latest step, or null if this question has not yet been graded.
630 * @return number the current fraction.
631 */
632 public function get_fraction() {
633 return $this->get_last_step()->get_fraction();
634 }
635
636 /** @return bool whether this question attempt has a non-zero maximum mark. */
637 public function has_marks() {
638 // Since grades are stored in the database as NUMBER(12,7).
639 return $this->maxmark >= 0.00000005;
640 }
641
642 /**
643 * @return number the current mark for this question.
644 * {@link get_fraction()} * {@link get_max_mark()}.
645 */
646 public function get_mark() {
647 return $this->fraction_to_mark($this->get_fraction());
648 }
649
650 /**
651 * This is used by the manual grading code, particularly in association with
808b6883
TH
652 * validation. It gets the current manual mark for a question, in exactly the string
653 * form that the teacher entered it, if possible. This may come from the current
654 * POST request, if there is one, otherwise from the database.
655 *
656 * @return string the current manual mark for this question, in the format the teacher typed,
657 * if possible.
dcd03928
TH
658 */
659 public function get_current_manual_mark() {
808b6883 660 // Is there a current value in the current POST data? If so, use that.
b2694c02 661 $mark = $this->get_submitted_var($this->get_behaviour_field_name('mark'), PARAM_RAW_TRIMMED);
808b6883 662 if ($mark !== null) {
dcd03928
TH
663 return $mark;
664 }
808b6883
TH
665
666 // Otherwise, use the stored value.
667 // If the question max mark has not changed, use the stored value that was input.
668 $storedmaxmark = $this->get_last_behaviour_var('maxmark');
669 if ($storedmaxmark !== null && ($storedmaxmark - $this->get_max_mark()) < 0.0000005) {
670 return $this->get_last_behaviour_var('mark');
671 }
672
673 // The max mark for this question has changed so we must re-scale the current mark.
674 return format_float($this->get_mark(), 7, true, true);
dcd03928
TH
675 }
676
677 /**
678 * @param number|null $fraction a fraction.
679 * @return number|null the corresponding mark.
680 */
681 public function fraction_to_mark($fraction) {
682 if (is_null($fraction)) {
683 return null;
684 }
685 return $fraction * $this->maxmark;
686 }
687
4e3d8293
TH
688 /**
689 * @return float the maximum mark possible for this question attempt.
690 * In fact, this is not strictly the maximum, becuase get_max_fraction may
691 * return a number greater than 1. It might be better to think of this as a
692 * question weight.
693 */
dcd03928
TH
694 public function get_max_mark() {
695 return $this->maxmark;
696 }
697
4e3d8293 698 /** @return float the maximum mark possible for this question attempt. */
dcd03928
TH
699 public function get_min_fraction() {
700 if (is_null($this->minfraction)) {
4e3d8293 701 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet known.');
dcd03928
TH
702 }
703 return $this->minfraction;
704 }
705
4e3d8293
TH
706 /** @return float the maximum mark possible for this question attempt. */
707 public function get_max_fraction() {
708 if (is_null($this->maxfraction)) {
709 throw new coding_exception('This question_attempt has not been started yet, the max fraction is not yet known.');
710 }
711 return $this->maxfraction;
712 }
713
dcd03928
TH
714 /**
715 * The current mark, formatted to the stated number of decimal places. Uses
716 * {@link format_float()} to format floats according to the current locale.
717 * @param int $dp number of decimal places.
718 * @return string formatted mark.
719 */
720 public function format_mark($dp) {
721 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
722 }
723
724 /**
725 * The current mark, formatted to the stated number of decimal places. Uses
726 * {@link format_float()} to format floats according to the current locale.
727 * @param int $dp number of decimal places.
728 * @return string formatted mark.
729 */
730 public function format_fraction_as_mark($fraction, $dp) {
731 return format_float($this->fraction_to_mark($fraction), $dp);
732 }
733
734 /**
735 * The maximum mark for this question attempt, formatted to the stated number
736 * of decimal places. Uses {@link format_float()} to format floats according
737 * to the current locale.
738 * @param int $dp number of decimal places.
739 * @return string formatted maximum mark.
740 */
741 public function format_max_mark($dp) {
742 return format_float($this->maxmark, $dp);
743 }
744
745 /**
746 * Return the hint that applies to the question in its current state, or null.
747 * @return question_hint|null
748 */
749 public function get_applicable_hint() {
750 return $this->behaviour->get_applicable_hint();
751 }
752
753 /**
754 * Produce a plain-text summary of what the user did during a step.
755 * @param question_attempt_step $step the step in quetsion.
756 * @return string a summary of what was done during that step.
757 */
758 public function summarise_action(question_attempt_step $step) {
759 return $this->behaviour->summarise_action($step);
760 }
761
f6579bea
TH
762 /**
763 * Return one of the bits of metadata for a this question attempt.
764 * @param string $name the name of the metadata variable to return.
765 * @return string the value of that metadata variable.
766 */
767 public function get_metadata($name) {
768 return $this->get_step(0)->get_metadata_var($name);
769 }
770
771 /**
772 * Set some metadata for this question attempt.
773 * @param string $name the name of the metadata variable to return.
774 * @param string $value the value to set that metadata variable to.
775 */
776 public function set_metadata($name, $value) {
777 $firststep = $this->get_step(0);
778 if (!$firststep->has_metadata_var($name)) {
779 $this->observer->notify_metadata_added($this, $name);
780 } else if ($value !== $firststep->get_metadata_var($name)) {
781 $this->observer->notify_metadata_modified($this, $name);
782 }
783 $firststep->set_metadata_var($name, $value);
784 }
785
dcd03928
TH
786 /**
787 * Helper function used by {@link rewrite_pluginfile_urls()} and
788 * {@link rewrite_response_pluginfile_urls()}.
789 * @return array ids that need to go into the file paths.
790 */
791 protected function extra_file_path_components() {
792 return array($this->get_usage_id(), $this->get_slot());
793 }
794
795 /**
796 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
797 * for content belonging to this question.
798 * @param string $text the content to output.
799 * @param string $component the component name (normally 'question' or 'qtype_...')
800 * @param string $filearea the name of the file area.
801 * @param int $itemid the item id.
802 * @return srting the content with the URLs rewritten.
803 */
804 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
805 return question_rewrite_question_urls($text, 'pluginfile.php',
806 $this->question->contextid, $component, $filearea,
807 $this->extra_file_path_components(), $itemid);
808 }
809
810 /**
811 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
812 * for content belonging to responses to this question.
813 *
814 * @param string $text the text to update the URLs in.
815 * @param int $contextid the id of the context the quba belongs to.
816 * @param string $name the variable name the files belong to.
817 * @param question_attempt_step $step the step the response is coming from.
818 * @return srting the content with the URLs rewritten.
819 */
820 public function rewrite_response_pluginfile_urls($text, $contextid, $name,
821 question_attempt_step $step) {
822 return $step->rewrite_response_pluginfile_urls($text, $contextid, $name,
823 $this->extra_file_path_components());
824 }
825
826 /**
827 * Get the {@link core_question_renderer}, in collaboration with appropriate
828 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
829 * HTML to display this question attempt in its current state.
830 * @param question_display_options $options controls how the question is rendered.
831 * @param string|null $number The question number to display.
832 * @return string HTML fragment representing the question.
833 */
834 public function render($options, $number, $page = null) {
835 if (is_null($page)) {
836 global $PAGE;
837 $page = $PAGE;
838 }
839 $qoutput = $page->get_renderer('core', 'question');
840 $qtoutput = $this->question->get_renderer($page);
841 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
842 }
843
844 /**
845 * Generate any bits of HTML that needs to go in the <head> tag when this question
846 * attempt is displayed in the body.
847 * @return string HTML fragment.
848 */
849 public function render_head_html($page = null) {
850 if (is_null($page)) {
851 global $PAGE;
852 $page = $PAGE;
853 }
854 // TODO go via behaviour.
855 return $this->question->get_renderer($page)->head_code($this) .
856 $this->behaviour->get_renderer($page)->head_code($this);
857 }
858
859 /**
860 * Like {@link render_question()} but displays the question at the past step
861 * indicated by $seq, rather than showing the latest step.
862 *
863 * @param int $seq the seq number of the past state to display.
864 * @param question_display_options $options controls how the question is rendered.
865 * @param string|null $number The question number to display. 'i' is a special
866 * value that gets displayed as Information. Null means no number is displayed.
867 * @return string HTML fragment representing the question.
868 */
869 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
870 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
871 return $restrictedqa->render($options, $number);
872 }
873
874 /**
875 * Checks whether the users is allow to be served a particular file.
876 * @param question_display_options $options the options that control display of the question.
877 * @param string $component the name of the component we are serving files for.
878 * @param string $filearea the name of the file area.
879 * @param array $args the remaining bits of the file path.
880 * @param bool $forcedownload whether the user must be forced to download the file.
881 * @return bool true if the user can access this file.
882 */
883 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
884 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
885 }
886
887 /**
888 * Add a step to this question attempt.
889 * @param question_attempt_step $step the new step.
890 */
891 protected function add_step(question_attempt_step $step) {
892 $this->steps[] = $step;
893 end($this->steps);
894 $this->observer->notify_step_added($step, $this, key($this->steps));
895 }
896
0a606a2b
TH
897 /**
898 * Add an auto-saved step to this question attempt. We mark auto-saved steps by
899 * changing saving the step number with a - sign.
900 * @param question_attempt_step $step the new step.
901 */
902 protected function add_autosaved_step(question_attempt_step $step) {
903 $this->steps[] = $step;
904 $this->autosavedstep = $step;
905 end($this->steps);
906 $this->observer->notify_step_added($step, $this, -key($this->steps));
907 }
908
909 /**
910 * Discard any auto-saved data belonging to this question attempt.
911 */
912 public function discard_autosaved_step() {
913 if (!$this->has_autosaved_step()) {
914 return;
915 }
916
917 $autosaved = array_pop($this->steps);
918 $this->autosavedstep = null;
919 $this->observer->notify_step_deleted($autosaved, $this);
920 }
921
3d96b494
TH
922 /**
923 * If there is an autosaved step, convert it into a real save, so that it
924 * is preserved.
925 */
926 protected function convert_autosaved_step_to_real_step() {
927 if ($this->autosavedstep === null) {
928 return;
929 }
930
931 $laststep = end($this->steps);
932 if ($laststep !== $this->autosavedstep) {
933 throw new coding_exception('Cannot convert autosaved step to real step, since other steps have been added.');
934 }
935
936 $this->observer->notify_step_modified($this->autosavedstep, $this, key($this->steps));
937 $this->autosavedstep = null;
938 }
939
1da821bb
TH
940 /**
941 * Use a strategy to pick a variant.
942 * @param question_variant_selection_strategy $variantstrategy a strategy.
943 * @return int the selected variant.
944 */
945 public function select_variant(question_variant_selection_strategy $variantstrategy) {
946 return $variantstrategy->choose_variant($this->get_question()->get_num_variants(),
947 $this->get_question()->get_variants_selection_seed());
948 }
949
dcd03928
TH
950 /**
951 * Start this question attempt.
952 *
953 * You should not call this method directly. Call
954 * {@link question_usage_by_activity::start_question()} instead.
955 *
956 * @param string|question_behaviour $preferredbehaviour the name of the
957 * desired archetypal behaviour, or an actual model instance.
1da821bb
TH
958 * @param int $variant the variant of the question to start. Between 1 and
959 * $this->get_question()->get_num_variants() inclusive.
dcd03928
TH
960 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
961 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
962 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
94815ccf
TH
963 * @param int $existingstepid optional, if this step is going to replace an existing step
964 * (for example, during a regrade) this is the id of the previous step we are replacing.
dcd03928 965 */
1da821bb 966 public function start($preferredbehaviour, $variant, $submitteddata = array(),
94815ccf 967 $timestamp = null, $userid = null, $existingstepid = null) {
1da821bb 968
f6579bea
TH
969 if ($this->get_num_steps() > 0) {
970 throw new coding_exception('Cannot start a question that is already started.');
971 }
972
dcd03928 973 // Initialise the behaviour.
1da821bb 974 $this->variant = $variant;
dcd03928
TH
975 if (is_string($preferredbehaviour)) {
976 $this->behaviour =
977 $this->question->make_behaviour($this, $preferredbehaviour);
978 } else {
979 $class = get_class($preferredbehaviour);
980 $this->behaviour = new $class($this, $preferredbehaviour);
981 }
982
4e3d8293 983 // Record the minimum and maximum fractions.
dcd03928 984 $this->minfraction = $this->behaviour->get_min_fraction();
4e3d8293 985 $this->maxfraction = $this->behaviour->get_max_fraction();
dcd03928
TH
986
987 // Initialise the first step.
94815ccf 988 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid, $existingstepid);
dcd03928 989 if ($submitteddata) {
f8e28244
RK
990 $firststep->set_state(question_state::$complete);
991 $this->behaviour->apply_attempt_state($firststep);
dcd03928 992 } else {
1da821bb 993 $this->behaviour->init_first_step($firststep, $variant);
dcd03928
TH
994 }
995 $this->add_step($firststep);
996
997 // Record questionline and correct answer.
998 $this->questionsummary = $this->behaviour->get_question_summary();
999 $this->rightanswer = $this->behaviour->get_right_answer_summary();
1000 }
1001
1002 /**
1003 * Start this question attempt, starting from the point that the previous
1004 * attempt $oldqa had reached.
1005 *
1006 * You should not call this method directly. Call
1007 * {@link question_usage_by_activity::start_question_based_on()} instead.
1008 *
1009 * @param question_attempt $oldqa a previous attempt at this quetsion that
1010 * defines the starting point.
1011 */
1012 public function start_based_on(question_attempt $oldqa) {
1da821bb 1013 $this->start($oldqa->behaviour, $oldqa->get_variant(), $oldqa->get_resume_data());
dcd03928
TH
1014 }
1015
1016 /**
1017 * Used by {@link start_based_on()} to get the data needed to start a new
1018 * attempt from the point this attempt has go to.
1019 * @return array name => value pairs.
1020 */
1021 protected function get_resume_data() {
afb1b3d0
TH
1022 $resumedata = $this->behaviour->get_resume_data();
1023 foreach ($resumedata as $name => $value) {
1024 if ($value instanceof question_file_loader) {
1025 $resumedata[$name] = $value->get_question_file_saver();
1026 }
1027 }
1028 return $resumedata;
dcd03928
TH
1029 }
1030
1031 /**
1032 * Get a particular parameter from the current request. A wrapper round
1033 * {@link optional_param()}, except that the results is returned without
1034 * slashes.
1035 * @param string $name the paramter name.
1036 * @param int $type one of the standard PARAM_... constants, or one of the
1037 * special extra constands defined by this class.
1038 * @param array $postdata (optional, only inteded for testing use) take the
1039 * data from this array, instead of from $_POST.
1040 * @return mixed the requested value.
1041 */
1042 public function get_submitted_var($name, $type, $postdata = null) {
1043 switch ($type) {
dcd03928
TH
1044
1045 case self::PARAM_FILES:
1046 return $this->process_response_files($name, $name, $postdata);
1047
2d2018ab
TH
1048 case self::PARAM_RAW_FILES:
1049 $var = $this->get_submitted_var($name, PARAM_RAW, $postdata);
dcd03928
TH
1050 return $this->process_response_files($name, $name . ':itemid', $postdata, $var);
1051
1052 default:
1053 if (is_null($postdata)) {
1054 $var = optional_param($name, null, $type);
1055 } else if (array_key_exists($name, $postdata)) {
1056 $var = clean_param($postdata[$name], $type);
1057 } else {
1058 $var = null;
1059 }
1060
1061 return $var;
1062 }
1063 }
1064
b2694c02
TH
1065 /**
1066 * Validate the manual mark for a question.
1067 * @param unknown $currentmark the user input (e.g. '1,0', '1,0' or 'invalid'.
1068 * @return string any errors with the value, or '' if it is OK.
1069 */
1070 public function validate_manual_mark($currentmark) {
1071 if ($currentmark === null || $currentmark === '') {
1072 return '';
1073 }
52b08f5f 1074
b2694c02
TH
1075 $mark = question_utils::clean_param_mark($currentmark);
1076 if ($mark === null) {
1077 return get_string('manualgradeinvalidformat', 'question');
52b08f5f 1078 }
b2694c02 1079
52b08f5f 1080 $maxmark = $this->get_max_mark();
b2694c02
TH
1081 if ($mark > $maxmark * $this->get_max_fraction() || $mark < $maxmark * $this->get_min_fraction()) {
1082 return get_string('manualgradeoutofrange', 'question');
52b08f5f
NM
1083 }
1084
1085 return '';
52b08f5f
NM
1086 }
1087
dcd03928
TH
1088 /**
1089 * Handle a submitted variable representing uploaded files.
1090 * @param string $name the field name.
1091 * @param string $draftidname the field name holding the draft file area id.
1092 * @param array $postdata (optional, only inteded for testing use) take the
1093 * data from this array, instead of from $_POST. At the moment, this
1094 * behaves as if there were no files.
1095 * @param string $text optional reponse text.
1096 * @return question_file_saver that can be used to save the files later.
1097 */
1098 protected function process_response_files($name, $draftidname, $postdata = null, $text = null) {
1099 if ($postdata) {
afb1b3d0
TH
1100 // For simulated posts, get the draft itemid from there.
1101 $draftitemid = $this->get_submitted_var($draftidname, PARAM_INT, $postdata);
1102 } else {
1103 $draftitemid = file_get_submitted_draft_itemid($draftidname);
dcd03928
TH
1104 }
1105
dcd03928
TH
1106 if (!$draftitemid) {
1107 return null;
1108 }
1109
18e1450b
AH
1110 $filearea = str_replace($this->get_field_prefix(), '', $name);
1111 $filearea = str_replace('-', 'bf_', $filearea);
1112 $filearea = 'response_' . $filearea;
1113 return new question_file_saver($draftitemid, 'question', $filearea, $text);
dcd03928
TH
1114 }
1115
1116 /**
1117 * Get any data from the request that matches the list of expected params.
1118 * @param array $expected variable name => PARAM_... constant.
1119 * @param string $extraprefix '-' or ''.
1120 * @return array name => value.
1121 */
1122 protected function get_expected_data($expected, $postdata, $extraprefix) {
1123 $submitteddata = array();
1124 foreach ($expected as $name => $type) {
1125 $value = $this->get_submitted_var(
1126 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
1127 if (!is_null($value)) {
1128 $submitteddata[$extraprefix . $name] = $value;
1129 }
1130 }
1131 return $submitteddata;
1132 }
1133
1134 /**
1135 * Get all the submitted question type data for this question, whithout checking
1136 * that it is valid or cleaning it in any way.
1137 * @return array name => value.
1138 */
df7d175d 1139 public function get_all_submitted_qt_vars($postdata) {
dcd03928
TH
1140 if (is_null($postdata)) {
1141 $postdata = $_POST;
1142 }
1143
03cefcc9 1144 $pattern = '/^' . preg_quote($this->get_field_prefix(), '/') . '[^-:]/';
dcd03928
TH
1145 $prefixlen = strlen($this->get_field_prefix());
1146
1147 $submitteddata = array();
df7d175d 1148 foreach ($postdata as $name => $value) {
dcd03928
TH
1149 if (preg_match($pattern, $name)) {
1150 $submitteddata[substr($name, $prefixlen)] = $value;
1151 }
1152 }
1153
1154 return $submitteddata;
1155 }
1156
1157 /**
1158 * Get all the sumbitted data belonging to this question attempt from the
1159 * current request.
1160 * @param array $postdata (optional, only inteded for testing use) take the
1161 * data from this array, instead of from $_POST.
1162 * @return array name => value pairs that could be passed to {@link process_action()}.
1163 */
1164 public function get_submitted_data($postdata = null) {
1165 $submitteddata = $this->get_expected_data(
1166 $this->behaviour->get_expected_data(), $postdata, '-');
1167
1168 $expected = $this->behaviour->get_expected_qt_data();
18e1450b
AH
1169 $this->check_qt_var_name_restrictions($expected);
1170
dcd03928
TH
1171 if ($expected === self::USE_RAW_DATA) {
1172 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
1173 } else {
1174 $submitteddata += $this->get_expected_data($expected, $postdata, '');
1175 }
1176 return $submitteddata;
1177 }
1178
18e1450b
AH
1179 /**
1180 * Ensure that no reserved prefixes are being used by installed
1181 * question types.
1182 * @param array $expected An array of question type variables
1183 */
1184 protected function check_qt_var_name_restrictions($expected) {
1185 global $CFG;
1186
802ff4c9 1187 if ($CFG->debugdeveloper && $expected !== self::USE_RAW_DATA) {
18e1450b
AH
1188 foreach ($expected as $key => $value) {
1189 if (strpos($key, 'bf_') !== false) {
1190 debugging('The bf_ prefix is reserved and cannot be used by question types', DEBUG_DEVELOPER);
1191 }
1192 }
1193 }
1194 }
1195
dcd03928
TH
1196 /**
1197 * Get a set of response data for this question attempt that would get the
da22c012
K
1198 * best possible mark. If it is not possible to compute a correct
1199 * response, this method should return null.
1200 * @return array|null name => value pairs that could be passed to {@link process_action()}.
dcd03928
TH
1201 */
1202 public function get_correct_response() {
1203 $response = $this->question->get_correct_response();
da22c012
K
1204 if (is_null($response)) {
1205 return null;
1206 }
dcd03928
TH
1207 $imvars = $this->behaviour->get_correct_response();
1208 foreach ($imvars as $name => $value) {
1209 $response['-' . $name] = $value;
1210 }
1211 return $response;
1212 }
1213
1214 /**
1215 * Change the quetsion summary. Note, that this is almost never necessary.
1216 * This method was only added to work around a limitation of the Opaque
1217 * protocol, which only sends questionLine at the end of an attempt.
1218 * @param $questionsummary the new summary to set.
1219 */
1220 public function set_question_summary($questionsummary) {
1221 $this->questionsummary = $questionsummary;
1222 $this->observer->notify_attempt_modified($this);
1223 }
1224
1225 /**
1226 * @return string a simple textual summary of the question that was asked.
1227 */
1228 public function get_question_summary() {
1229 return $this->questionsummary;
1230 }
1231
1232 /**
1233 * @return string a simple textual summary of response given.
1234 */
1235 public function get_response_summary() {
1236 return $this->responsesummary;
1237 }
1238
1239 /**
1240 * @return string a simple textual summary of the correct resonse.
1241 */
1242 public function get_right_answer_summary() {
1243 return $this->rightanswer;
1244 }
1245
fd7a8af5
TH
1246 /**
1247 * Whether this attempt at this question could be completed just by the
1248 * student interacting with the question, before {@link finish()} is called.
1249 *
1250 * @return boolean whether this attempt can finish naturally.
1251 */
1252 public function can_finish_during_attempt() {
1253 return $this->behaviour->can_finish_during_attempt();
1254 }
1255
dcd03928
TH
1256 /**
1257 * Perform the action described by $submitteddata.
1258 * @param array $submitteddata the submitted data the determines the action.
1259 * @param int $timestamp the time to record for the action. (If not given, use now.)
0a606a2b
TH
1260 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1261 * @param int $existingstepid used by the regrade code.
dcd03928 1262 */
94815ccf
TH
1263 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
1264 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid, $existingstepid);
0a606a2b 1265 $this->discard_autosaved_step();
dcd03928
TH
1266 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
1267 $this->add_step($pendingstep);
1268 if ($pendingstep->response_summary_changed()) {
1269 $this->responsesummary = $pendingstep->get_new_response_summary();
1270 }
a8de8667
TH
1271 if ($pendingstep->variant_number_changed()) {
1272 $this->variant = $pendingstep->get_new_variant_number();
1273 }
dcd03928
TH
1274 }
1275 }
1276
0a606a2b
TH
1277 /**
1278 * Process an autosave.
1279 * @param array $submitteddata the submitted data the determines the action.
1280 * @param int $timestamp the time to record for the action. (If not given, use now.)
1281 * @param int $userid the user to attribute the action to. (If not given, use the current user.)
1282 * @return bool whether anything was saved.
1283 */
1284 public function process_autosave($submitteddata, $timestamp = null, $userid = null) {
1285 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
1286 if ($this->behaviour->process_autosave($pendingstep) == self::KEEP) {
1287 $this->add_autosaved_step($pendingstep);
1288 return true;
1289 }
1290 return false;
1291 }
1292
dcd03928
TH
1293 /**
1294 * Perform a finish action on this question attempt. This corresponds to an
1295 * external finish action, for example the user pressing Submit all and finish
1296 * in the quiz, rather than using one of the controls that is part of the
1297 * question.
1298 *
1299 * @param int $timestamp the time to record for the action. (If not given, use now.)
1300 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
1301 */
1302 public function finish($timestamp = null, $userid = null) {
3d96b494 1303 $this->convert_autosaved_step_to_real_step();
dcd03928
TH
1304 $this->process_action(array('-finish' => 1), $timestamp, $userid);
1305 }
1306
1307 /**
1308 * Perform a regrade. This replays all the actions from $oldqa into this
1309 * attempt.
1310 * @param question_attempt $oldqa the attempt to regrade.
1311 * @param bool $finished whether the question attempt should be forced to be finished
1312 * after the regrade, or whether it may still be in progress (default false).
1313 */
1314 public function regrade(question_attempt $oldqa, $finished) {
1315 $first = true;
1316 foreach ($oldqa->get_step_iterator() as $step) {
94815ccf 1317 $this->observer->notify_step_deleted($step, $this);
9212fe7a 1318
dcd03928 1319 if ($first) {
9212fe7a 1320 // First step of the attempt.
dcd03928 1321 $first = false;
1da821bb 1322 $this->start($oldqa->behaviour, $oldqa->get_variant(), $step->get_all_data(),
94815ccf 1323 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
9212fe7a
TH
1324
1325 } else if ($step->has_behaviour_var('finish') && count($step->get_submitted_data()) > 1) {
1326 // This case relates to MDL-32062. The upgrade code from 2.0
1327 // generates attempts where the final submit of the question
1328 // data, and the finish action, are in the same step. The system
1329 // cannot cope with that, so convert the single old step into
1330 // two new steps.
1331 $submitteddata = $step->get_submitted_data();
1332 unset($submitteddata['-finish']);
1333 $this->process_action($submitteddata,
1334 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
1335 $this->finish($step->get_timecreated(), $step->get_user_id());
1336
dcd03928 1337 } else {
9212fe7a 1338 // This is the normal case. Replay the next step of the attempt.
dcd03928 1339 $this->process_action($step->get_submitted_data(),
94815ccf 1340 $step->get_timecreated(), $step->get_user_id(), $step->get_id());
dcd03928
TH
1341 }
1342 }
9212fe7a 1343
dcd03928
TH
1344 if ($finished) {
1345 $this->finish();
1346 }
2d708a73
TH
1347
1348 $this->set_flagged($oldqa->is_flagged());
dcd03928
TH
1349 }
1350
f6579bea
TH
1351 /**
1352 * Change the max mark for this question_attempt.
1353 * @param float $maxmark the new max mark.
1354 */
1355 public function set_max_mark($maxmark) {
1356 $this->maxmark = $maxmark;
1357 $this->observer->notify_attempt_modified($this);
1358 }
1359
dcd03928
TH
1360 /**
1361 * Perform a manual grading action on this attempt.
53b8e256
TH
1362 * @param string $comment the comment being added.
1363 * @param float $mark the new mark. If null, then only a comment is added.
1364 * @param int $commentformat the FORMAT_... for $comment. Must be given.
dcd03928
TH
1365 * @param int $timestamp the time to record for the action. (If not given, use now.)
1366 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
dcd03928 1367 */
53b8e256 1368 public function manual_grade($comment, $mark, $commentformat = null, $timestamp = null, $userid = null) {
dcd03928 1369 $submitteddata = array('-comment' => $comment);
53b8e256
TH
1370 if (is_null($commentformat)) {
1371 debugging('You should pass $commentformat to manual_grade.', DEBUG_DEVELOPER);
1372 $commentformat = FORMAT_HTML;
1373 }
1374 $submitteddata['-commentformat'] = $commentformat;
dcd03928
TH
1375 if (!is_null($mark)) {
1376 $submitteddata['-mark'] = $mark;
1377 $submitteddata['-maxmark'] = $this->maxmark;
1378 }
1379 $this->process_action($submitteddata, $timestamp, $userid);
1380 }
1381
1382 /** @return bool Whether this question attempt has had a manual comment added. */
1383 public function has_manual_comment() {
1384 foreach ($this->steps as $step) {
1385 if ($step->has_behaviour_var('comment')) {
1386 return true;
1387 }
1388 }
1389 return false;
1390 }
1391
1392 /**
1393 * @return array(string, int) the most recent manual comment that was added
f3d9872a 1394 * to this question, the FORMAT_... it is and the step itself.
dcd03928
TH
1395 */
1396 public function get_manual_comment() {
1397 foreach ($this->get_reverse_step_iterator() as $step) {
1398 if ($step->has_behaviour_var('comment')) {
1399 return array($step->get_behaviour_var('comment'),
f3d9872a
AH
1400 $step->get_behaviour_var('commentformat'),
1401 $step);
dcd03928
TH
1402 }
1403 }
f3d9872a 1404 return array(null, null, null);
dcd03928
TH
1405 }
1406
1eb470fc
TH
1407 /**
1408 * This is used by the manual grading code, particularly in association with
1409 * validation. If there is a comment submitted in the request, then use that,
1410 * otherwise use the latest comment for this question.
1411 * @return number the current mark for this question.
1412 * {@link get_fraction()} * {@link get_max_mark()}.
1413 */
1414 public function get_current_manual_comment() {
1415 $comment = $this->get_submitted_var($this->get_behaviour_field_name('comment'), PARAM_RAW);
1416 if (is_null($comment)) {
1417 return $this->get_manual_comment();
1418 } else {
1419 $commentformat = $this->get_submitted_var(
1420 $this->get_behaviour_field_name('commentformat'), PARAM_INT);
1421 if ($commentformat === null) {
1422 $commentformat = FORMAT_HTML;
1423 }
f3d9872a 1424 return array($comment, $commentformat, null);
1eb470fc
TH
1425 }
1426 }
1427
dcd03928 1428 /**
038014c4 1429 * Break down a student response by sub part and classification. See also {@link question::classify_response}.
d50b05e6
JP
1430 * Used for response analysis.
1431 *
038014c4
JP
1432 * @param string $whichtries which tries to analyse for response analysis. Will be one of
1433 * question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
1434 * Defaults to question_attempt::LAST_TRY.
1435 * @return (question_classified_response|array)[] If $whichtries is question_attempt::FIRST_TRY or LAST_TRY index is subpartid
1436 * and values are question_classified_response instances.
1437 * If $whichtries is question_attempt::ALL_TRIES then first key is submitted response no
1438 * and the second key is subpartid.
dcd03928 1439 */
038014c4
JP
1440 public function classify_response($whichtries = self::LAST_TRY) {
1441 return $this->behaviour->classify_response($whichtries);
dcd03928
TH
1442 }
1443
1444 /**
1445 * Create a question_attempt_step from records loaded from the database.
1446 *
1447 * For internal use only.
1448 *
35d5f1c2 1449 * @param Iterator $records Raw records loaded from the database.
dcd03928 1450 * @param int $questionattemptid The id of the question_attempt to extract.
94815ccf 1451 * @return question_attempt The newly constructed question_attempt.
dcd03928 1452 */
35d5f1c2 1453 public static function load_from_records($records, $questionattemptid,
dcd03928 1454 question_usage_observer $observer, $preferredbehaviour) {
35d5f1c2 1455 $record = $records->current();
dcd03928 1456 while ($record->questionattemptid != $questionattemptid) {
35d5f1c2
TH
1457 $record = $records->next();
1458 if (!$records->valid()) {
f4fe3968 1459 throw new coding_exception("Question attempt {$questionattemptid} not found in the database.");
dcd03928 1460 }
35d5f1c2 1461 $record = $records->current();
dcd03928
TH
1462 }
1463
1464 try {
1465 $question = question_bank::load_question($record->questionid);
1466 } catch (Exception $e) {
1467 // The question must have been deleted somehow. Create a missing
1468 // question to use in its place.
1469 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
1470 $record->questionid, $record->maxmark + 0);
1471 }
1472
1473 $qa = new question_attempt($question, $record->questionusageid,
1474 null, $record->maxmark + 0);
1475 $qa->set_database_id($record->questionattemptid);
94815ccf 1476 $qa->set_slot($record->slot);
1da821bb 1477 $qa->variant = $record->variant + 0;
dcd03928 1478 $qa->minfraction = $record->minfraction + 0;
4e3d8293 1479 $qa->maxfraction = $record->maxfraction + 0;
dcd03928
TH
1480 $qa->set_flagged($record->flagged);
1481 $qa->questionsummary = $record->questionsummary;
1482 $qa->rightanswer = $record->rightanswer;
1483 $qa->responsesummary = $record->responsesummary;
1484 $qa->timemodified = $record->timemodified;
1485
1486 $qa->behaviour = question_engine::make_behaviour(
1487 $record->behaviour, $qa, $preferredbehaviour);
0a606a2b 1488 $qa->observer = $observer;
dcd03928 1489
dd7aa583
TH
1490 // If attemptstepid is null (which should not happen, but has happened
1491 // due to corrupt data, see MDL-34251) then the current pointer in $records
1492 // will not be advanced in the while loop below, and we get stuck in an
1493 // infinite loop, since this method is supposed to always consume at
1494 // least one record. Therefore, in this case, advance the record here.
1495 if (is_null($record->attemptstepid)) {
1496 $records->next();
1497 }
1498
dcd03928 1499 $i = 0;
0a606a2b
TH
1500 $autosavedstep = null;
1501 $autosavedsequencenumber = null;
dcd03928 1502 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
0a606a2b 1503 $sequencenumber = $record->sequencenumber;
dc1ee5cb 1504 $nextstep = question_attempt_step::load_from_records($records, $record->attemptstepid, $qa->get_question()->get_type_name());
0a606a2b
TH
1505
1506 if ($sequencenumber < 0) {
1507 if (!$autosavedstep) {
1508 $autosavedstep = $nextstep;
1509 $autosavedsequencenumber = -$sequencenumber;
1510 } else {
1511 // Old redundant data. Mark it for deletion.
1512 $qa->observer->notify_step_deleted($nextstep, $qa);
1513 }
1514 } else {
1515 $qa->steps[$i] = $nextstep;
1516 if ($i == 0) {
1517 $question->apply_attempt_state($qa->steps[0]);
1518 }
1519 $i++;
dcd03928 1520 }
0a606a2b 1521
35d5f1c2
TH
1522 if ($records->valid()) {
1523 $record = $records->current();
1524 } else {
1525 $record = false;
1526 }
dcd03928
TH
1527 }
1528
0a606a2b
TH
1529 if ($autosavedstep) {
1530 if ($autosavedsequencenumber >= $i) {
1531 $qa->autosavedstep = $autosavedstep;
1532 $qa->steps[$i] = $qa->autosavedstep;
1533 } else {
1534 $qa->observer->notify_step_deleted($autosavedstep, $qa);
1535 }
1536 }
dcd03928
TH
1537
1538 return $qa;
1539 }
99caa248
JP
1540
1541 /**
1542 * Allow access to steps with responses submitted by students for grading in a question attempt.
1543 *
1544 * @return question_attempt_steps_with_submitted_response_iterator to access all steps with submitted data for questions that
1545 * allow multiple submissions that count towards grade, per attempt.
1546 */
1547 public function get_steps_with_submitted_response_iterator() {
1548 return new question_attempt_steps_with_submitted_response_iterator($this);
1549 }
dcd03928
TH
1550}
1551
1552
1553/**
1554 * This subclass of question_attempt pretends that only part of the step history
1555 * exists. It is used for rendering the question in past states.
1556 *
1557 * All methods that try to modify the question_attempt throw exceptions.
1558 *
1559 * @copyright 2010 The Open University
1560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1561 */
1562class question_attempt_with_restricted_history extends question_attempt {
1563 /**
1564 * @var question_attempt the underlying question_attempt.
1565 */
1566 protected $baseqa;
1567
1568 /**
1569 * Create a question_attempt_with_restricted_history
1570 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
1571 * @param int $lastseq the index of the last step to include.
1572 * @param string $preferredbehaviour the preferred behaviour. It is slightly
1573 * annoyting that this needs to be passed, but unavoidable for now.
1574 */
1575 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
f123d67f
TH
1576 $this->baseqa = $baseqa->get_full_qa();
1577
1578 if ($lastseq < 0 || $lastseq >= $this->baseqa->get_num_steps()) {
1579 throw new coding_exception('$lastseq out of range', $lastseq);
dcd03928
TH
1580 }
1581
f123d67f 1582 $this->steps = array_slice($this->baseqa->steps, 0, $lastseq + 1);
dcd03928
TH
1583 $this->observer = new question_usage_null_observer();
1584
1585 // This should be a straight copy of all the remaining fields.
f123d67f
TH
1586 $this->id = $this->baseqa->id;
1587 $this->usageid = $this->baseqa->usageid;
1588 $this->slot = $this->baseqa->slot;
1589 $this->question = $this->baseqa->question;
1590 $this->maxmark = $this->baseqa->maxmark;
1591 $this->minfraction = $this->baseqa->minfraction;
4e3d8293 1592 $this->maxfraction = $this->baseqa->maxfraction;
f123d67f
TH
1593 $this->questionsummary = $this->baseqa->questionsummary;
1594 $this->responsesummary = $this->baseqa->responsesummary;
1595 $this->rightanswer = $this->baseqa->rightanswer;
1596 $this->flagged = $this->baseqa->flagged;
dcd03928
TH
1597
1598 // Except behaviour, where we need to create a new one.
1599 $this->behaviour = question_engine::make_behaviour(
f123d67f
TH
1600 $this->baseqa->get_behaviour_name(), $this, $preferredbehaviour);
1601 }
1602
1603 public function get_full_qa() {
1604 return $this->baseqa;
dcd03928
TH
1605 }
1606
1607 public function get_full_step_iterator() {
1608 return $this->baseqa->get_step_iterator();
1609 }
1610
1611 protected function add_step(question_attempt_step $step) {
1612 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1613 }
072db71c 1614 public function process_action($submitteddata, $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1615 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1616 }
072db71c 1617 public function start($preferredbehaviour, $variant, $submitteddata = array(), $timestamp = null, $userid = null, $existingstepid = null) {
dcd03928
TH
1618 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1619 }
1620
1621 public function set_database_id($id) {
1622 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1623 }
1624 public function set_flagged($flagged) {
1625 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1626 }
94815ccf 1627 public function set_slot($slot) {
dcd03928
TH
1628 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1629 }
1630 public function set_question_summary($questionsummary) {
1631 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1632 }
1633 public function set_usage_id($usageid) {
1634 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
1635 }
1636}
1637
1638
1639/**
1640 * A class abstracting access to the {@link question_attempt::$states} array.
1641 *
1642 * This is actively linked to question_attempt. If you add an new step
1643 * mid-iteration, then it will be included.
1644 *
1645 * @copyright 2009 The Open University
1646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1647 */
1648class question_attempt_step_iterator implements Iterator, ArrayAccess {
1649 /** @var question_attempt the question_attempt being iterated over. */
1650 protected $qa;
1651 /** @var integer records the current position in the iteration. */
1652 protected $i;
1653
1654 /**
1655 * Do not call this constructor directly.
1656 * Use {@link question_attempt::get_step_iterator()}.
1657 * @param question_attempt $qa the attempt to iterate over.
1658 */
1659 public function __construct(question_attempt $qa) {
1660 $this->qa = $qa;
1661 $this->rewind();
1662 }
1663
1664 /** @return question_attempt_step */
1665 public function current() {
1666 return $this->offsetGet($this->i);
1667 }
1668 /** @return int */
1669 public function key() {
1670 return $this->i;
1671 }
1672 public function next() {
1673 ++$this->i;
1674 }
1675 public function rewind() {
1676 $this->i = 0;
1677 }
1678 /** @return bool */
1679 public function valid() {
1680 return $this->offsetExists($this->i);
1681 }
1682
1683 /** @return bool */
1684 public function offsetExists($i) {
1685 return $i >= 0 && $i < $this->qa->get_num_steps();
1686 }
1687 /** @return question_attempt_step */
1688 public function offsetGet($i) {
1689 return $this->qa->get_step($i);
1690 }
1691 public function offsetSet($offset, $value) {
1692 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
1693 }
1694 public function offsetUnset($offset) {
1695 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
1696 }
1697}
1698
1699
1700/**
1701 * A variant of {@link question_attempt_step_iterator} that iterates through the
1702 * steps in reverse order.
1703 *
1704 * @copyright 2009 The Open University
1705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1706 */
1707class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
1708 public function next() {
1709 --$this->i;
1710 }
1711
1712 public function rewind() {
1713 $this->i = $this->qa->get_num_steps() - 1;
1714 }
1715}
99caa248
JP
1716
1717/**
1718 * A variant of {@link question_attempt_step_iterator} that iterates through the
1719 * steps with submitted tries.
1720 *
1721 * @copyright 2014 The Open University
1722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1723 */
1724class question_attempt_steps_with_submitted_response_iterator extends question_attempt_step_iterator implements Countable {
1725
1726 /** @var question_attempt the question_attempt being iterated over. */
1727 protected $qa;
1728
1729 /** @var integer records the current position in the iteration. */
1730 protected $submittedresponseno;
1731
1732 /**
1733 * Index is the submitted response number and value is the step no.
1734 *
1735 * @var int[]
1736 */
1737 protected $stepswithsubmittedresponses;
1738
1739 /**
1740 * Do not call this constructor directly.
1741 * Use {@link question_attempt::get_submission_step_iterator()}.
1742 * @param question_attempt $qa the attempt to iterate over.
1743 */
1744 public function __construct(question_attempt $qa) {
1745 $this->qa = $qa;
1746 $this->find_steps_with_submitted_response();
1747 $this->rewind();
1748 }
1749
1750 /**
1751 * Find the step nos in which a student has submitted a response. Including any step with a response that is saved before
1752 * the question attempt finishes.
1753 *
1754 * Called from constructor, should not be called from elsewhere.
1755 *
1756 */
1757 protected function find_steps_with_submitted_response() {
1758 $stepnos = array();
1759 $lastsavedstep = null;
1760 foreach ($this->qa->get_step_iterator() as $stepno => $step) {
1761 if ($this->qa->get_behaviour()->step_has_a_submitted_response($step)) {
1762 $stepnos[] = $stepno;
1763 $lastsavedstep = null;
1764 } else {
1765 $qtdata = $step->get_qt_data();
1766 if (count($qtdata)) {
1767 $lastsavedstep = $stepno;
1768 }
1769 }
1770 }
1771
1772 if (!is_null($lastsavedstep)) {
1773 $stepnos[] = $lastsavedstep;
1774 }
1775 if (empty($stepnos)) {
1776 $this->stepswithsubmittedresponses = array();
1777 } else {
1778 // Re-index array so index starts with 1.
1779 $this->stepswithsubmittedresponses = array_combine(range(1, count($stepnos)), $stepnos);
1780 }
1781 }
1782
1783 /** @return question_attempt_step */
1784 public function current() {
1785 return $this->offsetGet($this->submittedresponseno);
1786 }
1787 /** @return int */
1788 public function key() {
1789 return $this->submittedresponseno;
1790 }
1791 public function next() {
1792 ++$this->submittedresponseno;
1793 }
1794 public function rewind() {
1795 $this->submittedresponseno = 1;
1796 }
1797 /** @return bool */
1798 public function valid() {
038014c4 1799 return $this->submittedresponseno >= 1 && $this->submittedresponseno <= count($this->stepswithsubmittedresponses);
99caa248
JP
1800 }
1801
1802 /**
1803 * @param int $submittedresponseno
1804 * @return bool
1805 */
1806 public function offsetExists($submittedresponseno) {
1807 return $submittedresponseno >= 1;
1808 }
1809
1810 /**
1811 * @param int $submittedresponseno
1812 * @return question_attempt_step
1813 */
1814 public function offsetGet($submittedresponseno) {
1815 if ($submittedresponseno > count($this->stepswithsubmittedresponses)) {
1816 return null;
1817 } else {
1818 return $this->qa->get_step($this->step_no_for_try($submittedresponseno));
1819 }
1820 }
1821
1822 /**
1823 * @return int the count of steps with tries.
1824 */
1825 public function count() {
1826 return count($this->stepswithsubmittedresponses);
1827 }
1828
1829 /**
1830 * @param int $submittedresponseno
1831 * @throws coding_exception
1832 * @return int|null the step number or null if there is no such submitted response.
1833 */
1834 public function step_no_for_try($submittedresponseno) {
1835 if (isset($this->stepswithsubmittedresponses[$submittedresponseno])) {
1836 return $this->stepswithsubmittedresponses[$submittedresponseno];
1837 } else if ($submittedresponseno > count($this->stepswithsubmittedresponses)) {
1838 return null;
1839 } else {
1840 throw new coding_exception('Try number not found. It should be 1 or more.');
1841 }
1842 }
1843
1844 public function offsetSet($offset, $value) {
1845 throw new coding_exception('You are only allowed read-only access to question_attempt::states '.
1846 'through a question_attempt_step_iterator. Cannot set.');
1847 }
1848 public function offsetUnset($offset) {
1849 throw new coding_exception('You are only allowed read-only access to question_attempt::states '.
1850 'through a question_attempt_step_iterator. Cannot unset.');
1851 }
1852
1853}