Merge branch 'MDL-32746-master' of git://github.com/FMCorz/moodle
[moodle.git] / question / engine / questionusage.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 usage 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 * This class keeps track of a group of questions that are being attempted,
32 * and which state, and so on, each one is currently in.
33 *
34 * A quiz attempt or a lesson attempt could use an instance of this class to
35 * keep track of all the questions in the attempt and process student submissions.
36 * It is basically a collection of {@question_attempt} objects.
37 *
38 * The questions being attempted as part of this usage are identified by an integer
39 * that is passed into many of the methods as $slot. ($question->id is not
40 * used so that the same question can be used more than once in an attempt.)
41 *
42 * Normally, calling code should be able to do everything it needs to be calling
43 * methods of this class. You should not normally need to get individual
44 * {@question_attempt} objects and play around with their inner workind, in code
45 * that it outside the quetsion engine.
46 *
47 * Instances of this class correspond to rows in the question_usages table.
48 *
49 * @copyright 2009 The Open University
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 */
52class question_usage_by_activity {
53 /**
54 * @var integer|string the id for this usage. If this usage was loaded from
55 * the database, then this is the database id. Otherwise a unique random
56 * string is used.
57 */
58 protected $id = null;
59
60 /**
61 * @var string name of an archetypal behaviour, that should be used
62 * by questions in this usage if possible.
63 */
64 protected $preferredbehaviour = null;
65
4c16e191 66 /** @var context the context this usage belongs to. */
dcd03928
TH
67 protected $context;
68
69 /** @var string plugin name of the plugin this usage belongs to. */
70 protected $owningcomponent;
71
72 /** @var array {@link question_attempt}s that make up this usage. */
73 protected $questionattempts = array();
74
75 /** @var question_usage_observer that tracks changes to this usage. */
76 protected $observer;
77
78 /**
79 * Create a new instance. Normally, calling code should use
80 * {@link question_engine::make_questions_usage_by_activity()} or
81 * {@link question_engine::load_questions_usage_by_activity()} rather than
82 * calling this constructor directly.
83 *
84 * @param string $component the plugin creating this attempt. For example mod_quiz.
85 * @param object $context the context this usage belongs to.
86 */
87 public function __construct($component, $context) {
88 $this->owningcomponent = $component;
89 $this->context = $context;
90 $this->observer = new question_usage_null_observer();
91 }
92
93 /**
94 * @param string $behaviour the name of an archetypal behaviour, that should
95 * be used by questions in this usage if possible.
96 */
97 public function set_preferred_behaviour($behaviour) {
98 $this->preferredbehaviour = $behaviour;
99 $this->observer->notify_modified();
100 }
101
102 /** @return string the name of the preferred behaviour. */
103 public function get_preferred_behaviour() {
104 return $this->preferredbehaviour;
105 }
106
4c16e191 107 /** @return context the context this usage belongs to. */
dcd03928
TH
108 public function get_owning_context() {
109 return $this->context;
110 }
111
112 /** @return string the name of the plugin that owns this attempt. */
113 public function get_owning_component() {
114 return $this->owningcomponent;
115 }
116
117 /** @return int|string If this usage came from the database, then the id
118 * from the question_usages table is returned. Otherwise a random string is
119 * returned. */
120 public function get_id() {
121 if (is_null($this->id)) {
122 $this->id = random_string(10);
123 }
124 return $this->id;
125 }
126
dcd03928
TH
127 /**
128 * For internal use only. Used by {@link question_engine_data_mapper} to set
129 * the id when a usage is saved to the database.
130 * @param int $id the newly determined id for this usage.
131 */
132 public function set_id_from_database($id) {
133 $this->id = $id;
134 foreach ($this->questionattempts as $qa) {
135 $qa->set_usage_id($id);
136 }
137 }
138
94815ccf
TH
139 /** @return question_usage_observer that is tracking changes made to this usage. */
140 public function get_observer() {
141 return $this->observer;
142 }
143
144 /**
145 * You should almost certainly not call this method from your code. It is for
146 * internal use only.
147 * @param question_usage_observer that should be used to tracking changes made to this usage.
148 */
149 public function set_observer($observer) {
150 $this->observer = $observer;
151 foreach ($this->questionattempts as $qa) {
152 $qa->set_observer($observer);
153 }
154 }
155
dcd03928
TH
156 /**
157 * Add another question to this usage.
158 *
159 * The added question is not started until you call {@link start_question()}
160 * on it.
161 *
162 * @param question_definition $question the question to add.
163 * @param number $maxmark the maximum this question will be marked out of in
164 * this attempt (optional). If not given, $question->defaultmark is used.
165 * @return int the number used to identify this question within this usage.
166 */
167 public function add_question(question_definition $question, $maxmark = null) {
168 $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark);
169 if (count($this->questionattempts) == 0) {
170 $this->questionattempts[1] = $qa;
171 } else {
172 $this->questionattempts[] = $qa;
173 }
b9832f2b
TH
174 end($this->questionattempts); // Ready to get the last key on the next line.
175 $qa->set_slot(key($this->questionattempts));
dcd03928
TH
176 $this->observer->notify_attempt_added($qa);
177 return $qa->get_slot();
178 }
179
180 /**
181 * Get the question_definition for a question in this attempt.
182 * @param int $slot the number used to identify this question within this usage.
183 * @return question_definition the requested question object.
184 */
185 public function get_question($slot) {
186 return $this->get_question_attempt($slot)->get_question();
187 }
188
189 /** @return array all the identifying numbers of all the questions in this usage. */
190 public function get_slots() {
191 return array_keys($this->questionattempts);
192 }
193
194 /** @return int the identifying number of the first question that was added to this usage. */
195 public function get_first_question_number() {
196 reset($this->questionattempts);
197 return key($this->questionattempts);
198 }
199
200 /** @return int the number of questions that are currently in this usage. */
201 public function question_count() {
202 return count($this->questionattempts);
203 }
204
205 /**
206 * Note the part of the {@link question_usage_by_activity} comment that explains
207 * that {@link question_attempt} objects should be considered part of the inner
208 * workings of the question engine, and should not, if possible, be accessed directly.
209 *
210 * @return question_attempt_iterator for iterating over all the questions being
211 * attempted. as part of this usage.
212 */
213 public function get_attempt_iterator() {
214 return new question_attempt_iterator($this);
215 }
216
217 /**
218 * Check whether $number actually corresponds to a question attempt that is
219 * part of this usage. Throws an exception if not.
220 *
221 * @param int $slot a number allegedly identifying a question within this usage.
222 */
223 protected function check_slot($slot) {
224 if (!array_key_exists($slot, $this->questionattempts)) {
9c197f44
TH
225 throw new coding_exception('There is no question_attempt number ' . $slot .
226 ' in this attempt.');
dcd03928
TH
227 }
228 }
229
230 /**
231 * Note the part of the {@link question_usage_by_activity} comment that explains
232 * that {@link question_attempt} objects should be considered part of the inner
233 * workings of the question engine, and should not, if possible, be accessed directly.
234 *
235 * @param int $slot the number used to identify this question within this usage.
236 * @return question_attempt the corresponding {@link question_attempt} object.
237 */
238 public function get_question_attempt($slot) {
239 $this->check_slot($slot);
240 return $this->questionattempts[$slot];
241 }
242
243 /**
244 * Get the current state of the attempt at a question.
245 * @param int $slot the number used to identify this question within this usage.
246 * @return question_state.
247 */
248 public function get_question_state($slot) {
249 return $this->get_question_attempt($slot)->get_state();
250 }
251
252 /**
253 * @param int $slot the number used to identify this question within this usage.
254 * @param bool $showcorrectness Whether right/partial/wrong states should
255 * be distinguised.
256 * @return string A brief textual description of the current state.
257 */
258 public function get_question_state_string($slot, $showcorrectness) {
259 return $this->get_question_attempt($slot)->get_state_string($showcorrectness);
260 }
261
97cdc1de
TH
262 /**
263 * @param int $slot the number used to identify this question within this usage.
264 * @param bool $showcorrectness Whether right/partial/wrong states should
265 * be distinguised.
266 * @return string a CSS class name for the current state.
267 */
268 public function get_question_state_class($slot, $showcorrectness) {
269 return $this->get_question_attempt($slot)->get_state_class($showcorrectness);
270 }
271
dcd03928
TH
272 /**
273 * Get the time of the most recent action performed on a question.
274 * @param int $slot the number used to identify this question within this usage.
275 * @return int timestamp.
276 */
277 public function get_question_action_time($slot) {
278 return $this->get_question_attempt($slot)->get_last_action_time();
279 }
280
281 /**
282 * Get the current fraction awarded for the attempt at a question.
283 * @param int $slot the number used to identify this question within this usage.
284 * @return number|null The current fraction for this question, or null if one has
285 * not been assigned yet.
286 */
287 public function get_question_fraction($slot) {
288 return $this->get_question_attempt($slot)->get_fraction();
289 }
290
291 /**
292 * Get the current mark awarded for the attempt at a question.
293 * @param int $slot the number used to identify this question within this usage.
294 * @return number|null The current mark for this question, or null if one has
295 * not been assigned yet.
296 */
297 public function get_question_mark($slot) {
298 return $this->get_question_attempt($slot)->get_mark();
299 }
300
301 /**
302 * Get the maximum mark possible for the attempt at a question.
303 * @param int $slot the number used to identify this question within this usage.
304 * @return number the available marks for this question.
305 */
306 public function get_question_max_mark($slot) {
307 return $this->get_question_attempt($slot)->get_max_mark();
308 }
309
310 /**
311 * Get the current mark awarded for the attempt at a question.
312 * @param int $slot the number used to identify this question within this usage.
313 * @return number|null The current mark for this question, or null if one has
314 * not been assigned yet.
315 */
316 public function get_total_mark() {
317 $mark = 0;
318 foreach ($this->questionattempts as $qa) {
319 if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
320 return null;
321 }
322 $mark += $qa->get_mark();
323 }
324 return $mark;
325 }
326
327 /**
328 * @return string a simple textual summary of the question that was asked.
329 */
330 public function get_question_summary($slot) {
331 return $this->get_question_attempt($slot)->get_question_summary();
332 }
333
334 /**
335 * @return string a simple textual summary of response given.
336 */
337 public function get_response_summary($slot) {
338 return $this->get_question_attempt($slot)->get_response_summary();
339 }
340
341 /**
342 * @return string a simple textual summary of the correct resonse.
343 */
344 public function get_right_answer_summary($slot) {
345 return $this->get_question_attempt($slot)->get_right_answer_summary();
346 }
347
348 /**
349 * Get the {@link core_question_renderer}, in collaboration with appropriate
350 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
351 * HTML to display this question.
352 * @param int $slot the number used to identify this question within this usage.
353 * @param question_display_options $options controls how the question is rendered.
354 * @param string|null $number The question number to display. 'i' is a special
355 * value that gets displayed as Information. Null means no number is displayed.
356 * @return string HTML fragment representing the question.
357 */
358 public function render_question($slot, $options, $number = null) {
359 $options->context = $this->context;
360 return $this->get_question_attempt($slot)->render($options, $number);
361 }
362
363 /**
364 * Generate any bits of HTML that needs to go in the <head> tag when this question
365 * is displayed in the body.
366 * @param int $slot the number used to identify this question within this usage.
367 * @return string HTML fragment.
368 */
369 public function render_question_head_html($slot) {
92701024 370 //$options->context = $this->context;
dcd03928
TH
371 return $this->get_question_attempt($slot)->render_head_html();
372 }
373
374 /**
375 * Like {@link render_question()} but displays the question at the past step
376 * indicated by $seq, rather than showing the latest step.
377 *
378 * @param int $slot the number used to identify this question within this usage.
379 * @param int $seq the seq number of the past state to display.
380 * @param question_display_options $options controls how the question is rendered.
381 * @param string|null $number The question number to display. 'i' is a special
382 * value that gets displayed as Information. Null means no number is displayed.
383 * @return string HTML fragment representing the question.
384 */
385 public function render_question_at_step($slot, $seq, $options, $number = null) {
386 $options->context = $this->context;
9c197f44
TH
387 return $this->get_question_attempt($slot)->render_at_step(
388 $seq, $options, $number, $this->preferredbehaviour);
dcd03928
TH
389 }
390
391 /**
392 * Checks whether the users is allow to be served a particular file.
393 * @param int $slot the number used to identify this question within this usage.
394 * @param question_display_options $options the options that control display of the question.
395 * @param string $component the name of the component we are serving files for.
396 * @param string $filearea the name of the file area.
397 * @param array $args the remaining bits of the file path.
398 * @param bool $forcedownload whether the user must be forced to download the file.
399 * @return bool true if the user can access this file.
400 */
9c197f44
TH
401 public function check_file_access($slot, $options, $component, $filearea,
402 $args, $forcedownload) {
403 return $this->get_question_attempt($slot)->check_file_access(
404 $options, $component, $filearea, $args, $forcedownload);
dcd03928
TH
405 }
406
407 /**
408 * Replace a particular question_attempt with a different one.
409 *
410 * For internal use only. Used when reloading the state of a question from the
411 * database.
412 *
413 * @param array $records Raw records loaded from the database.
414 * @param int $questionattemptid The id of the question_attempt to extract.
415 * @return question_attempt The newly constructed question_attempt_step.
416 */
417 public function replace_loaded_question_attempt_info($slot, $qa) {
418 $this->check_slot($slot);
419 $this->questionattempts[$slot] = $qa;
420 }
421
422 /**
423 * You should probably not use this method in code outside the question engine.
424 * The main reason for exposing it was for the benefit of unit tests.
425 * @param int $slot the number used to identify this question within this usage.
426 * @return string return the prefix that is pre-pended to field names in the HTML
427 * that is output.
428 */
429 public function get_field_prefix($slot) {
430 return $this->get_question_attempt($slot)->get_field_prefix();
431 }
432
1da821bb
TH
433 /**
434 * Get the number of variants available for the question in this slot.
435 * @param int $slot the number used to identify this question within this usage.
436 * @return int the number of variants available.
437 */
438 public function get_num_variants($slot) {
439 return $this->get_question_attempt($slot)->get_question()->get_num_variants();
440 }
441
442 /**
443 * Get the variant of the question being used in a given slot.
444 * @param int $slot the number used to identify this question within this usage.
445 * @return int the variant of this question that is being used.
446 */
447 public function get_variant($slot) {
448 return $this->get_question_attempt($slot)->get_variant();
449 }
450
dcd03928
TH
451 /**
452 * Start the attempt at a question that has been added to this usage.
453 * @param int $slot the number used to identify this question within this usage.
1da821bb
TH
454 * @param int $variant which variant of the question to use. Must be between
455 * 1 and ->get_num_variants($slot) inclusive. If not give, a variant is
456 * chosen at random.
dcd03928 457 */
1da821bb
TH
458 public function start_question($slot, $variant = null) {
459 if (is_null($variant)) {
460 $variant = rand(1, $this->get_num_variants($slot));
461 }
462
dcd03928 463 $qa = $this->get_question_attempt($slot);
1da821bb 464 $qa->start($this->preferredbehaviour, $variant);
dcd03928
TH
465 $this->observer->notify_attempt_modified($qa);
466 }
467
468 /**
469 * Start the attempt at all questions that has been added to this usage.
1da821bb 470 * @param question_variant_selection_strategy how to pick which variant of each question to use.
e35ba43c
TH
471 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
472 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
dcd03928 473 */
1da821bb
TH
474 public function start_all_questions(question_variant_selection_strategy $variantstrategy = null,
475 $timestamp = null, $userid = null) {
476 if (is_null($variantstrategy)) {
477 $variantstrategy = new question_variant_random_strategy();
478 }
479
dcd03928 480 foreach ($this->questionattempts as $qa) {
1da821bb 481 $qa->start($this->preferredbehaviour, $qa->select_variant($variantstrategy));
dcd03928
TH
482 $this->observer->notify_attempt_modified($qa);
483 }
484 }
485
486 /**
487 * Start the attempt at a question, starting from the point where the previous
488 * question_attempt $oldqa had reached. This is used by the quiz 'Each attempt
489 * builds on last' mode.
490 * @param int $slot the number used to identify this question within this usage.
491 * @param question_attempt $oldqa a previous attempt at this quetsion that
492 * defines the starting point.
493 */
494 public function start_question_based_on($slot, question_attempt $oldqa) {
495 $qa = $this->get_question_attempt($slot);
496 $qa->start_based_on($oldqa);
497 $this->observer->notify_attempt_modified($qa);
498 }
499
500 /**
501 * Process all the question actions in the current request.
502 *
503 * If there is a parameter slots included in the post data, then only
504 * those question numbers will be processed, otherwise all questions in this
505 * useage will be.
506 *
507 * This function also does {@link update_question_flags()}.
508 *
509 * @param int $timestamp optional, use this timestamp as 'now'.
510 * @param array $postdata optional, only intended for testing. Use this data
511 * instead of the data from $_POST.
512 */
513 public function process_all_actions($timestamp = null, $postdata = null) {
0a606a2b
TH
514 foreach ($this->get_slots_in_request($postdata) as $slot) {
515 if (!$this->validate_sequence_number($slot, $postdata)) {
516 continue;
517 }
518 $submitteddata = $this->extract_responses($slot, $postdata);
519 $this->process_action($slot, $submitteddata, $timestamp);
520 }
521 $this->update_question_flags($postdata);
522 }
523
524 /**
525 * Process all the question autosave data in the current request.
526 *
527 * If there is a parameter slots included in the post data, then only
528 * those question numbers will be processed, otherwise all questions in this
529 * useage will be.
530 *
531 * This function also does {@link update_question_flags()}.
532 *
533 * @param int $timestamp optional, use this timestamp as 'now'.
534 * @param array $postdata optional, only intended for testing. Use this data
535 * instead of the data from $_POST.
536 */
537 public function process_all_autosaves($timestamp = null, $postdata = null) {
538 foreach ($this->get_slots_in_request($postdata) as $slot) {
539 if (!$this->is_autosave_required($slot, $postdata)) {
540 continue;
541 }
542 $submitteddata = $this->extract_responses($slot, $postdata);
543 $this->process_autosave($slot, $submitteddata, $timestamp);
544 }
545 $this->update_question_flags($postdata);
546 }
547
548 /**
549 * Get the list of slot numbers that should be processed as part of processing
550 * the current request.
551 * @param array $postdata optional, only intended for testing. Use this data
552 * instead of the data from $_POST.
553 * @return array of slot numbers.
554 */
555 protected function get_slots_in_request($postdata = null) {
556 // Note: we must not use "question_attempt::get_submitted_var()" because there is no attempt instance!!!
caee6e6c
PS
557 if (is_null($postdata)) {
558 $slots = optional_param('slots', null, PARAM_SEQUENCE);
559 } else if (array_key_exists('slots', $postdata)) {
560 $slots = clean_param($postdata['slots'], PARAM_SEQUENCE);
561 } else {
562 $slots = null;
563 }
dcd03928
TH
564 if (is_null($slots)) {
565 $slots = $this->get_slots();
566 } else if (!$slots) {
567 $slots = array();
568 } else {
569 $slots = explode(',', $slots);
570 }
0a606a2b 571 return $slots;
dcd03928
TH
572 }
573
574 /**
575 * Get the submitted data from the current request that belongs to this
576 * particular question.
577 *
578 * @param int $slot the number used to identify this question within this usage.
579 * @param $postdata optional, only intended for testing. Use this data
580 * instead of the data from $_POST.
581 * @return array submitted data specific to this question.
582 */
583 public function extract_responses($slot, $postdata = null) {
584 return $this->get_question_attempt($slot)->get_submitted_data($postdata);
585 }
586
587 /**
588 * Process a specific action on a specific question.
589 * @param int $slot the number used to identify this question within this usage.
590 * @param $submitteddata the submitted data that constitutes the action.
591 */
592 public function process_action($slot, $submitteddata, $timestamp = null) {
593 $qa = $this->get_question_attempt($slot);
594 $qa->process_action($submitteddata, $timestamp);
595 $this->observer->notify_attempt_modified($qa);
596 }
597
0a606a2b
TH
598 /**
599 * Process an autosave action on a specific question.
600 * @param int $slot the number used to identify this question within this usage.
601 * @param $submitteddata the submitted data that constitutes the action.
602 */
603 public function process_autosave($slot, $submitteddata, $timestamp = null) {
604 $qa = $this->get_question_attempt($slot);
605 if ($qa->process_autosave($submitteddata, $timestamp)) {
606 $this->observer->notify_attempt_modified($qa);
607 }
608 }
609
dcd03928
TH
610 /**
611 * Check that the sequence number, that detects weird things like the student
612 * clicking back, is OK. If the sequence check variable is not present, returns
613 * false. If the check variable is present and correct, returns true. If the
614 * variable is present and wrong, throws an exception.
615 * @param int $slot the number used to identify this question within this usage.
616 * @param array $submitteddata the submitted data that constitutes the action.
617 * @return bool true if the check variable is present and correct. False if it
618 * is missing. (Throws an exception if the check fails.)
619 */
620 public function validate_sequence_number($slot, $postdata = null) {
621 $qa = $this->get_question_attempt($slot);
622 $sequencecheck = $qa->get_submitted_var(
623 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
624 if (is_null($sequencecheck)) {
625 return false;
c7fbfe46 626 } else if ($sequencecheck != $qa->get_sequence_check_count()) {
dcd03928
TH
627 throw new question_out_of_sequence_exception($this->id, $slot, $postdata);
628 } else {
629 return true;
630 }
631 }
d122fe32
TH
632
633 /**
634 * Check, based on the sequence number, whether this auto-save is still required.
635 * @param int $slot the number used to identify this question within this usage.
636 * @param array $submitteddata the submitted data that constitutes the action.
637 * @return bool true if the check variable is present and correct, otherwise false.
638 */
639 public function is_autosave_required($slot, $postdata = null) {
640 $qa = $this->get_question_attempt($slot);
641 $sequencecheck = $qa->get_submitted_var(
642 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
643 if (is_null($sequencecheck)) {
644 return false;
c7fbfe46 645 } else if ($sequencecheck != $qa->get_sequence_check_count()) {
d122fe32
TH
646 return false;
647 } else {
648 return true;
649 }
650 }
651
dcd03928
TH
652 /**
653 * Update the flagged state for all question_attempts in this usage, if their
654 * flagged state was changed in the request.
655 *
656 * @param $postdata optional, only intended for testing. Use this data
657 * instead of the data from $_POST.
658 */
659 public function update_question_flags($postdata = null) {
660 foreach ($this->questionattempts as $qa) {
661 $flagged = $qa->get_submitted_var(
662 $qa->get_flag_field_name(), PARAM_BOOL, $postdata);
663 if (!is_null($flagged) && $flagged != $qa->is_flagged()) {
664 $qa->set_flagged($flagged);
665 }
666 }
667 }
668
669 /**
670 * Get the correct response to a particular question. Passing the results of
671 * this method to {@link process_action()} will probably result in full marks.
da22c012 672 * If it is not possible to compute a correct response, this method should return null.
dcd03928
TH
673 * @param int $slot the number used to identify this question within this usage.
674 * @return array that constitutes a correct response to this question.
675 */
676 public function get_correct_response($slot) {
677 return $this->get_question_attempt($slot)->get_correct_response();
678 }
679
680 /**
681 * Finish the active phase of an attempt at a question.
682 *
683 * This is an external act of finishing the attempt. Think, for example, of
684 * the 'Submit all and finish' button in the quiz. Some behaviours,
685 * (for example, immediatefeedback) give a way of finishing the active phase
686 * of a question attempt as part of a {@link process_action()} call.
687 *
688 * After the active phase is over, the only changes possible are things like
689 * manual grading, or changing the flag state.
690 *
691 * @param int $slot the number used to identify this question within this usage.
692 */
693 public function finish_question($slot, $timestamp = null) {
694 $qa = $this->get_question_attempt($slot);
695 $qa->finish($timestamp);
696 $this->observer->notify_attempt_modified($qa);
697 }
698
699 /**
700 * Finish the active phase of an attempt at a question. See {@link finish_question()}
701 * for a fuller description of what 'finish' means.
702 */
703 public function finish_all_questions($timestamp = null) {
704 foreach ($this->questionattempts as $qa) {
705 $qa->finish($timestamp);
706 $this->observer->notify_attempt_modified($qa);
707 }
708 }
709
710 /**
711 * Perform a manual grading action on a question attempt.
712 * @param int $slot the number used to identify this question within this usage.
713 * @param string $comment the comment being added to the question attempt.
714 * @param number $mark the mark that is being assigned. Can be null to just
715 * add a comment.
770e4a46 716 * @param int $commentformat one of the FORMAT_... constants. The format of $comment.
dcd03928 717 */
53b8e256 718 public function manual_grade($slot, $comment, $mark, $commentformat = null) {
dcd03928 719 $qa = $this->get_question_attempt($slot);
53b8e256 720 $qa->manual_grade($comment, $mark, $commentformat);
dcd03928
TH
721 $this->observer->notify_attempt_modified($qa);
722 }
723
724 /**
725 * Regrade a question in this usage. This replays the sequence of submitted
726 * actions to recompute the outcomes.
727 * @param int $slot the number used to identify this question within this usage.
728 * @param bool $finished whether the question attempt should be forced to be finished
729 * after the regrade, or whether it may still be in progress (default false).
730 * @param number $newmaxmark (optional) if given, will change the max mark while regrading.
731 */
732 public function regrade_question($slot, $finished = false, $newmaxmark = null) {
733 $oldqa = $this->get_question_attempt($slot);
734 if (is_null($newmaxmark)) {
735 $newmaxmark = $oldqa->get_max_mark();
736 }
737
dcd03928
TH
738 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(),
739 $this->observer, $newmaxmark);
740 $newqa->set_database_id($oldqa->get_database_id());
94815ccf 741 $newqa->set_slot($oldqa->get_slot());
dcd03928
TH
742 $newqa->regrade($oldqa, $finished);
743
744 $this->questionattempts[$slot] = $newqa;
745 $this->observer->notify_attempt_modified($newqa);
746 }
747
748 /**
749 * Regrade all the questions in this usage (without changing their max mark).
750 * @param bool $finished whether each question should be forced to be finished
751 * after the regrade, or whether it may still be in progress (default false).
752 */
753 public function regrade_all_questions($finished = false) {
754 foreach ($this->questionattempts as $slot => $notused) {
755 $this->regrade_question($slot, $finished);
756 }
757 }
758
759 /**
760 * Create a question_usage_by_activity from records loaded from the database.
761 *
762 * For internal use only.
763 *
35d5f1c2 764 * @param Iterator $records Raw records loaded from the database.
dcd03928 765 * @param int $questionattemptid The id of the question_attempt to extract.
94815ccf 766 * @return question_usage_by_activity The newly constructed usage.
dcd03928 767 */
35d5f1c2
TH
768 public static function load_from_records($records, $qubaid) {
769 $record = $records->current();
dcd03928 770 while ($record->qubaid != $qubaid) {
35d5f1c2
TH
771 $records->next();
772 if (!$records->valid()) {
dcd03928
TH
773 throw new coding_exception("Question usage $qubaid not found in the database.");
774 }
35d5f1c2 775 $record = $records->current();
dcd03928
TH
776 }
777
778 $quba = new question_usage_by_activity($record->component,
2cdd5d85 779 context::instance_by_id($record->contextid, IGNORE_MISSING));
dcd03928
TH
780 $quba->set_id_from_database($record->qubaid);
781 $quba->set_preferred_behaviour($record->preferredbehaviour);
782
783 $quba->observer = new question_engine_unit_of_work($quba);
784
dd7aa583
TH
785 // If slot is null then the current pointer in $records will not be
786 // advanced in the while loop below, and we get stuck in an infinite loop,
787 // since this method is supposed to always consume at least one record.
788 // Therefore, in this case, advance the record here.
789 if (is_null($record->slot)) {
790 $records->next();
791 }
792
dcd03928
TH
793 while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
794 $quba->questionattempts[$record->slot] =
795 question_attempt::load_from_records($records,
796 $record->questionattemptid, $quba->observer,
797 $quba->get_preferred_behaviour());
35d5f1c2
TH
798 if ($records->valid()) {
799 $record = $records->current();
800 } else {
801 $record = false;
802 }
dcd03928
TH
803 }
804
805 return $quba;
806 }
807}
808
809
810/**
811 * A class abstracting access to the
812 * {@link question_usage_by_activity::$questionattempts} array.
813 *
814 * This class snapshots the list of {@link question_attempts} to iterate over
815 * when it is created. If a question is added to the usage mid-iteration, it
816 * will now show up.
817 *
818 * To create an instance of this class, use
819 * {@link question_usage_by_activity::get_attempt_iterator()}
820 *
821 * @copyright 2009 The Open University
822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
823 */
824class question_attempt_iterator implements Iterator, ArrayAccess {
825 /** @var question_usage_by_activity that we are iterating over. */
826 protected $quba;
827 /** @var array of question numbers. */
828 protected $slots;
829
830 /**
9c197f44
TH
831 * To create an instance of this class, use
832 * {@link question_usage_by_activity::get_attempt_iterator()}.
dcd03928
TH
833 * @param $quba the usage to iterate over.
834 */
835 public function __construct(question_usage_by_activity $quba) {
836 $this->quba = $quba;
837 $this->slots = $quba->get_slots();
838 $this->rewind();
839 }
840
841 /** @return question_attempt_step */
842 public function current() {
843 return $this->offsetGet(current($this->slots));
844 }
845 /** @return int */
846 public function key() {
847 return current($this->slots);
848 }
849 public function next() {
850 next($this->slots);
851 }
852 public function rewind() {
853 reset($this->slots);
854 }
855 /** @return bool */
856 public function valid() {
857 return current($this->slots) !== false;
858 }
859
860 /** @return bool */
861 public function offsetExists($slot) {
862 return in_array($slot, $this->slots);
863 }
864 /** @return question_attempt_step */
865 public function offsetGet($slot) {
866 return $this->quba->get_question_attempt($slot);
867 }
868 public function offsetSet($slot, $value) {
9c197f44
TH
869 throw new coding_exception('You are only allowed read-only access to ' .
870 'question_attempt::states through a question_attempt_step_iterator. Cannot set.');
dcd03928
TH
871 }
872 public function offsetUnset($slot) {
9c197f44
TH
873 throw new coding_exception('You are only allowed read-only access to ' .
874 'question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
dcd03928
TH
875 }
876}
877
878
879/**
880 * Interface for things that want to be notified of signficant changes to a
881 * {@link question_usage_by_activity}.
882 *
883 * A question behaviour controls the flow of actions a student can
884 * take as they work through a question, and later, as a teacher manually grades it.
885 *
886 * @copyright 2009 The Open University
887 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
888 */
889interface question_usage_observer {
890 /** Called when a field of the question_usage_by_activity is changed. */
891 public function notify_modified();
892
893 /**
894 * Called when the fields of a question attempt in this usage are modified.
895 * @param question_attempt $qa the newly added question attempt.
896 */
897 public function notify_attempt_modified(question_attempt $qa);
898
899 /**
900 * Called when a new question attempt is added to this usage.
901 * @param question_attempt $qa the newly added question attempt.
902 */
903 public function notify_attempt_added(question_attempt $qa);
904
905 /**
94815ccf
TH
906 * Called when a new step is added to a question attempt in this usage.
907 * @param question_attempt_step $step the new step.
908 * @param question_attempt $qa the usage it is being added to.
909 * @param int $seq the sequence number of the new step.
dcd03928 910 */
94815ccf 911 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq);
dcd03928
TH
912
913 /**
94815ccf
TH
914 * Called when a new step is updated in a question attempt in this usage.
915 * @param question_attempt_step $step the step that was updated.
916 * @param question_attempt $qa the usage it is being added to.
917 * @param int $seq the sequence number of the new step.
dcd03928 918 */
94815ccf
TH
919 public function notify_step_modified(question_attempt_step $step, question_attempt $qa, $seq);
920
921 /**
922 * Called when a new step is updated in a question attempt in this usage.
923 * @param question_attempt_step $step the step to delete.
924 * @param question_attempt $qa the usage it is being added to.
925 */
926 public function notify_step_deleted(question_attempt_step $step, question_attempt $qa);
927
dcd03928
TH
928}
929
930
931/**
932 * Null implmentation of the {@link question_usage_watcher} interface.
933 * Does nothing.
934 *
935 * @copyright 2009 The Open University
936 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
937 */
938class question_usage_null_observer implements question_usage_observer {
939 public function notify_modified() {
940 }
941 public function notify_attempt_modified(question_attempt $qa) {
942 }
943 public function notify_attempt_added(question_attempt $qa) {
944 }
dcd03928
TH
945 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
946 }
94815ccf
TH
947 public function notify_step_modified(question_attempt_step $step, question_attempt $qa, $seq) {
948 }
949 public function notify_step_deleted(question_attempt_step $step, question_attempt $qa) {
950 }
dcd03928 951}