MDL-40992 qbehaviour: new type method, can Qs can finish naturally
[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);
c2f2e7f0
JP
169 $qa->set_slot($this->next_slot_number());
170 $this->questionattempts[$this->next_slot_number()] = $qa;
dcd03928
TH
171 $this->observer->notify_attempt_added($qa);
172 return $qa->get_slot();
173 }
174
c2f2e7f0
JP
175 /**
176 * The slot number that will be allotted to the next question added.
177 */
178 public function next_slot_number() {
179 return count($this->questionattempts) + 1;
180 }
181
dcd03928
TH
182 /**
183 * Get the question_definition for a question in this attempt.
184 * @param int $slot the number used to identify this question within this usage.
185 * @return question_definition the requested question object.
186 */
187 public function get_question($slot) {
188 return $this->get_question_attempt($slot)->get_question();
189 }
190
191 /** @return array all the identifying numbers of all the questions in this usage. */
192 public function get_slots() {
193 return array_keys($this->questionattempts);
194 }
195
196 /** @return int the identifying number of the first question that was added to this usage. */
197 public function get_first_question_number() {
198 reset($this->questionattempts);
199 return key($this->questionattempts);
200 }
201
202 /** @return int the number of questions that are currently in this usage. */
203 public function question_count() {
204 return count($this->questionattempts);
205 }
206
207 /**
208 * Note the part of the {@link question_usage_by_activity} comment that explains
209 * that {@link question_attempt} objects should be considered part of the inner
210 * workings of the question engine, and should not, if possible, be accessed directly.
211 *
212 * @return question_attempt_iterator for iterating over all the questions being
213 * attempted. as part of this usage.
214 */
215 public function get_attempt_iterator() {
216 return new question_attempt_iterator($this);
217 }
218
219 /**
220 * Check whether $number actually corresponds to a question attempt that is
221 * part of this usage. Throws an exception if not.
222 *
223 * @param int $slot a number allegedly identifying a question within this usage.
224 */
225 protected function check_slot($slot) {
226 if (!array_key_exists($slot, $this->questionattempts)) {
9c197f44
TH
227 throw new coding_exception('There is no question_attempt number ' . $slot .
228 ' in this attempt.');
dcd03928
TH
229 }
230 }
231
232 /**
233 * Note the part of the {@link question_usage_by_activity} comment that explains
234 * that {@link question_attempt} objects should be considered part of the inner
235 * workings of the question engine, and should not, if possible, be accessed directly.
236 *
237 * @param int $slot the number used to identify this question within this usage.
238 * @return question_attempt the corresponding {@link question_attempt} object.
239 */
240 public function get_question_attempt($slot) {
241 $this->check_slot($slot);
242 return $this->questionattempts[$slot];
243 }
244
245 /**
246 * Get the current state of the attempt at a question.
247 * @param int $slot the number used to identify this question within this usage.
248 * @return question_state.
249 */
250 public function get_question_state($slot) {
251 return $this->get_question_attempt($slot)->get_state();
252 }
253
254 /**
255 * @param int $slot the number used to identify this question within this usage.
256 * @param bool $showcorrectness Whether right/partial/wrong states should
257 * be distinguised.
258 * @return string A brief textual description of the current state.
259 */
260 public function get_question_state_string($slot, $showcorrectness) {
261 return $this->get_question_attempt($slot)->get_state_string($showcorrectness);
262 }
263
97cdc1de
TH
264 /**
265 * @param int $slot the number used to identify this question within this usage.
266 * @param bool $showcorrectness Whether right/partial/wrong states should
267 * be distinguised.
268 * @return string a CSS class name for the current state.
269 */
270 public function get_question_state_class($slot, $showcorrectness) {
271 return $this->get_question_attempt($slot)->get_state_class($showcorrectness);
272 }
273
fd7a8af5
TH
274 /**
275 * Whether this attempt at a given question could be completed just by the
276 * student interacting with the question, before {@link finish_question()} is called.
277 *
278 * @param int $slot the number used to identify this question within this usage.
279 * @return boolean whether the attempt at the given question can finish naturally.
280 */
281 public function can_question_finish_during_attempt($slot) {
282 return $this->get_question_attempt($slot)->can_finish_during_attempt();
283 }
284
dcd03928
TH
285 /**
286 * Get the time of the most recent action performed on a question.
287 * @param int $slot the number used to identify this question within this usage.
288 * @return int timestamp.
289 */
290 public function get_question_action_time($slot) {
291 return $this->get_question_attempt($slot)->get_last_action_time();
292 }
293
294 /**
295 * Get the current fraction awarded for the attempt at a question.
296 * @param int $slot the number used to identify this question within this usage.
297 * @return number|null The current fraction for this question, or null if one has
298 * not been assigned yet.
299 */
300 public function get_question_fraction($slot) {
301 return $this->get_question_attempt($slot)->get_fraction();
302 }
303
304 /**
305 * Get the current mark awarded for the attempt at a question.
306 * @param int $slot the number used to identify this question within this usage.
307 * @return number|null The current mark for this question, or null if one has
308 * not been assigned yet.
309 */
310 public function get_question_mark($slot) {
311 return $this->get_question_attempt($slot)->get_mark();
312 }
313
314 /**
315 * Get the maximum mark possible for the attempt at a question.
316 * @param int $slot the number used to identify this question within this usage.
317 * @return number the available marks for this question.
318 */
319 public function get_question_max_mark($slot) {
320 return $this->get_question_attempt($slot)->get_max_mark();
321 }
322
323 /**
a7b4c964
TH
324 * Get the total mark for all questions in this usage.
325 * @return number The sum of marks of all the question_attempts in this usage.
dcd03928
TH
326 */
327 public function get_total_mark() {
328 $mark = 0;
329 foreach ($this->questionattempts as $qa) {
330 if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
331 return null;
332 }
333 $mark += $qa->get_mark();
334 }
335 return $mark;
336 }
337
474aa125
TH
338 /**
339 * Get summary information about this usage.
340 *
341 * Some behaviours may be able to provide interesting summary information
342 * about the attempt as a whole, and this method provides access to that data.
343 * To see how this works, try setting a quiz to one of the CBM behaviours,
344 * and then look at the extra information displayed at the top of the quiz
345 * review page once you have sumitted an attempt.
346 *
347 * In the return value, the array keys are identifiers of the form
348 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary.
349 * The values are arrays with two items, title and content. Each of these
350 * will be either a string, or a renderable.
351 *
474aa125
TH
352 * @return array as described above.
353 */
354 public function get_summary_information(question_display_options $options) {
355 return question_engine::get_behaviour_type($this->preferredbehaviour)
356 ->summarise_usage($this, $options);
357 }
358
dcd03928
TH
359 /**
360 * @return string a simple textual summary of the question that was asked.
361 */
362 public function get_question_summary($slot) {
363 return $this->get_question_attempt($slot)->get_question_summary();
364 }
365
366 /**
367 * @return string a simple textual summary of response given.
368 */
369 public function get_response_summary($slot) {
370 return $this->get_question_attempt($slot)->get_response_summary();
371 }
372
373 /**
374 * @return string a simple textual summary of the correct resonse.
375 */
376 public function get_right_answer_summary($slot) {
377 return $this->get_question_attempt($slot)->get_right_answer_summary();
378 }
379
380 /**
381 * Get the {@link core_question_renderer}, in collaboration with appropriate
382 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
383 * HTML to display this question.
384 * @param int $slot the number used to identify this question within this usage.
385 * @param question_display_options $options controls how the question is rendered.
386 * @param string|null $number The question number to display. 'i' is a special
387 * value that gets displayed as Information. Null means no number is displayed.
388 * @return string HTML fragment representing the question.
389 */
390 public function render_question($slot, $options, $number = null) {
391 $options->context = $this->context;
392 return $this->get_question_attempt($slot)->render($options, $number);
393 }
394
395 /**
396 * Generate any bits of HTML that needs to go in the <head> tag when this question
397 * is displayed in the body.
398 * @param int $slot the number used to identify this question within this usage.
399 * @return string HTML fragment.
400 */
401 public function render_question_head_html($slot) {
92701024 402 //$options->context = $this->context;
dcd03928
TH
403 return $this->get_question_attempt($slot)->render_head_html();
404 }
405
406 /**
407 * Like {@link render_question()} but displays the question at the past step
408 * indicated by $seq, rather than showing the latest step.
409 *
410 * @param int $slot the number used to identify this question within this usage.
411 * @param int $seq the seq number of the past state to display.
412 * @param question_display_options $options controls how the question is rendered.
413 * @param string|null $number The question number to display. 'i' is a special
414 * value that gets displayed as Information. Null means no number is displayed.
415 * @return string HTML fragment representing the question.
416 */
417 public function render_question_at_step($slot, $seq, $options, $number = null) {
418 $options->context = $this->context;
9c197f44
TH
419 return $this->get_question_attempt($slot)->render_at_step(
420 $seq, $options, $number, $this->preferredbehaviour);
dcd03928
TH
421 }
422
423 /**
424 * Checks whether the users is allow to be served a particular file.
425 * @param int $slot the number used to identify this question within this usage.
426 * @param question_display_options $options the options that control display of the question.
427 * @param string $component the name of the component we are serving files for.
428 * @param string $filearea the name of the file area.
429 * @param array $args the remaining bits of the file path.
430 * @param bool $forcedownload whether the user must be forced to download the file.
431 * @return bool true if the user can access this file.
432 */
9c197f44
TH
433 public function check_file_access($slot, $options, $component, $filearea,
434 $args, $forcedownload) {
435 return $this->get_question_attempt($slot)->check_file_access(
436 $options, $component, $filearea, $args, $forcedownload);
dcd03928
TH
437 }
438
439 /**
440 * Replace a particular question_attempt with a different one.
441 *
442 * For internal use only. Used when reloading the state of a question from the
443 * database.
444 *
445 * @param array $records Raw records loaded from the database.
446 * @param int $questionattemptid The id of the question_attempt to extract.
447 * @return question_attempt The newly constructed question_attempt_step.
448 */
449 public function replace_loaded_question_attempt_info($slot, $qa) {
450 $this->check_slot($slot);
451 $this->questionattempts[$slot] = $qa;
452 }
453
454 /**
455 * You should probably not use this method in code outside the question engine.
456 * The main reason for exposing it was for the benefit of unit tests.
457 * @param int $slot the number used to identify this question within this usage.
458 * @return string return the prefix that is pre-pended to field names in the HTML
459 * that is output.
460 */
461 public function get_field_prefix($slot) {
462 return $this->get_question_attempt($slot)->get_field_prefix();
463 }
464
1da821bb
TH
465 /**
466 * Get the number of variants available for the question in this slot.
467 * @param int $slot the number used to identify this question within this usage.
468 * @return int the number of variants available.
469 */
470 public function get_num_variants($slot) {
471 return $this->get_question_attempt($slot)->get_question()->get_num_variants();
472 }
473
474 /**
475 * Get the variant of the question being used in a given slot.
476 * @param int $slot the number used to identify this question within this usage.
477 * @return int the variant of this question that is being used.
478 */
479 public function get_variant($slot) {
480 return $this->get_question_attempt($slot)->get_variant();
481 }
482
dcd03928
TH
483 /**
484 * Start the attempt at a question that has been added to this usage.
485 * @param int $slot the number used to identify this question within this usage.
1da821bb
TH
486 * @param int $variant which variant of the question to use. Must be between
487 * 1 and ->get_num_variants($slot) inclusive. If not give, a variant is
488 * chosen at random.
bb93fc24 489 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
dcd03928 490 */
bb93fc24 491 public function start_question($slot, $variant = null, $timenow = null) {
1da821bb
TH
492 if (is_null($variant)) {
493 $variant = rand(1, $this->get_num_variants($slot));
494 }
495
dcd03928 496 $qa = $this->get_question_attempt($slot);
bb93fc24 497 $qa->start($this->preferredbehaviour, $variant, array(), $timenow);
dcd03928
TH
498 $this->observer->notify_attempt_modified($qa);
499 }
500
501 /**
502 * Start the attempt at all questions that has been added to this usage.
1da821bb 503 * @param question_variant_selection_strategy how to pick which variant of each question to use.
e35ba43c
TH
504 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
505 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
dcd03928 506 */
1da821bb
TH
507 public function start_all_questions(question_variant_selection_strategy $variantstrategy = null,
508 $timestamp = null, $userid = null) {
509 if (is_null($variantstrategy)) {
510 $variantstrategy = new question_variant_random_strategy();
511 }
512
dcd03928 513 foreach ($this->questionattempts as $qa) {
1da821bb 514 $qa->start($this->preferredbehaviour, $qa->select_variant($variantstrategy));
dcd03928
TH
515 $this->observer->notify_attempt_modified($qa);
516 }
517 }
518
519 /**
520 * Start the attempt at a question, starting from the point where the previous
521 * question_attempt $oldqa had reached. This is used by the quiz 'Each attempt
522 * builds on last' mode.
523 * @param int $slot the number used to identify this question within this usage.
524 * @param question_attempt $oldqa a previous attempt at this quetsion that
525 * defines the starting point.
526 */
527 public function start_question_based_on($slot, question_attempt $oldqa) {
528 $qa = $this->get_question_attempt($slot);
529 $qa->start_based_on($oldqa);
530 $this->observer->notify_attempt_modified($qa);
531 }
532
533 /**
534 * Process all the question actions in the current request.
535 *
536 * If there is a parameter slots included in the post data, then only
537 * those question numbers will be processed, otherwise all questions in this
538 * useage will be.
539 *
540 * This function also does {@link update_question_flags()}.
541 *
542 * @param int $timestamp optional, use this timestamp as 'now'.
543 * @param array $postdata optional, only intended for testing. Use this data
544 * instead of the data from $_POST.
545 */
546 public function process_all_actions($timestamp = null, $postdata = null) {
0a606a2b
TH
547 foreach ($this->get_slots_in_request($postdata) as $slot) {
548 if (!$this->validate_sequence_number($slot, $postdata)) {
549 continue;
550 }
551 $submitteddata = $this->extract_responses($slot, $postdata);
552 $this->process_action($slot, $submitteddata, $timestamp);
553 }
554 $this->update_question_flags($postdata);
555 }
556
557 /**
558 * Process all the question autosave data in the current request.
559 *
560 * If there is a parameter slots included in the post data, then only
561 * those question numbers will be processed, otherwise all questions in this
562 * useage will be.
563 *
564 * This function also does {@link update_question_flags()}.
565 *
566 * @param int $timestamp optional, use this timestamp as 'now'.
567 * @param array $postdata optional, only intended for testing. Use this data
568 * instead of the data from $_POST.
569 */
570 public function process_all_autosaves($timestamp = null, $postdata = null) {
571 foreach ($this->get_slots_in_request($postdata) as $slot) {
572 if (!$this->is_autosave_required($slot, $postdata)) {
573 continue;
574 }
575 $submitteddata = $this->extract_responses($slot, $postdata);
576 $this->process_autosave($slot, $submitteddata, $timestamp);
577 }
578 $this->update_question_flags($postdata);
579 }
580
581 /**
582 * Get the list of slot numbers that should be processed as part of processing
583 * the current request.
584 * @param array $postdata optional, only intended for testing. Use this data
585 * instead of the data from $_POST.
586 * @return array of slot numbers.
587 */
588 protected function get_slots_in_request($postdata = null) {
589 // Note: we must not use "question_attempt::get_submitted_var()" because there is no attempt instance!!!
caee6e6c
PS
590 if (is_null($postdata)) {
591 $slots = optional_param('slots', null, PARAM_SEQUENCE);
592 } else if (array_key_exists('slots', $postdata)) {
593 $slots = clean_param($postdata['slots'], PARAM_SEQUENCE);
594 } else {
595 $slots = null;
596 }
dcd03928
TH
597 if (is_null($slots)) {
598 $slots = $this->get_slots();
599 } else if (!$slots) {
600 $slots = array();
601 } else {
602 $slots = explode(',', $slots);
603 }
0a606a2b 604 return $slots;
dcd03928
TH
605 }
606
607 /**
608 * Get the submitted data from the current request that belongs to this
609 * particular question.
610 *
611 * @param int $slot the number used to identify this question within this usage.
612 * @param $postdata optional, only intended for testing. Use this data
613 * instead of the data from $_POST.
614 * @return array submitted data specific to this question.
615 */
616 public function extract_responses($slot, $postdata = null) {
617 return $this->get_question_attempt($slot)->get_submitted_data($postdata);
618 }
619
388f0473
JP
620 /**
621 * Transform an array of response data for slots to an array of post data as you would get from quiz attempt form.
622 *
623 * @param $simulatedresponses array keys are slot nos => contains arrays representing student
624 * responses which will be passed to question_definition::prepare_simulated_post_data method
625 * and then have the appropriate prefix added.
626 * @return array simulated post data
627 */
628 public function prepare_simulated_post_data($simulatedresponses) {
629 $simulatedpostdata = array();
630 $simulatedpostdata['slots'] = implode(',', array_keys($simulatedresponses));
631 foreach ($simulatedresponses as $slot => $responsedata) {
764f6153
JP
632 $slotresponse = array();
633
634 // Behaviour vars should not be processed by question type, just add prefix.
635 $behaviourvars = $this->get_question_attempt($slot)->get_behaviour()->get_expected_data();
99caa248
JP
636 foreach (array_keys($responsedata) as $responsedatakey) {
637 if ($responsedatakey{0} === '-') {
638 $behaviourvarname = substr($responsedatakey, 1);
639 if (isset($behaviourvars[$behaviourvarname])) {
640 // Expected behaviour var found.
641 if ($responsedata[$responsedatakey]) {
642 // Only set the behaviour var if the column value from the cvs file is non zero.
643 // The behaviours only look at whether the var is set or not they don't look at the value.
644 $slotresponse[$responsedatakey] = $responsedata[$responsedatakey];
645 }
646 }
647 // Remove both expected and unexpected vars from data passed to question type.
648 unset($responsedata[$responsedatakey]);
764f6153
JP
649 }
650 }
651
652 $slotresponse += $this->get_question($slot)->prepare_simulated_post_data($responsedata);
99caa248 653 $slotresponse[':sequencecheck'] = $this->get_question_attempt($slot)->get_sequence_check_count();
764f6153
JP
654
655 // Add this slot's prefix to slot data.
656 $prefix = $this->get_field_prefix($slot);
388f0473
JP
657 foreach ($slotresponse as $key => $value) {
658 $simulatedpostdata[$prefix.$key] = $value;
659 }
660 }
661 return $simulatedpostdata;
662 }
663
dcd03928
TH
664 /**
665 * Process a specific action on a specific question.
666 * @param int $slot the number used to identify this question within this usage.
667 * @param $submitteddata the submitted data that constitutes the action.
668 */
669 public function process_action($slot, $submitteddata, $timestamp = null) {
670 $qa = $this->get_question_attempt($slot);
671 $qa->process_action($submitteddata, $timestamp);
672 $this->observer->notify_attempt_modified($qa);
673 }
674
0a606a2b
TH
675 /**
676 * Process an autosave action on a specific question.
677 * @param int $slot the number used to identify this question within this usage.
678 * @param $submitteddata the submitted data that constitutes the action.
679 */
680 public function process_autosave($slot, $submitteddata, $timestamp = null) {
681 $qa = $this->get_question_attempt($slot);
682 if ($qa->process_autosave($submitteddata, $timestamp)) {
683 $this->observer->notify_attempt_modified($qa);
684 }
685 }
686
dcd03928
TH
687 /**
688 * Check that the sequence number, that detects weird things like the student
689 * clicking back, is OK. If the sequence check variable is not present, returns
690 * false. If the check variable is present and correct, returns true. If the
691 * variable is present and wrong, throws an exception.
692 * @param int $slot the number used to identify this question within this usage.
693 * @param array $submitteddata the submitted data that constitutes the action.
694 * @return bool true if the check variable is present and correct. False if it
695 * is missing. (Throws an exception if the check fails.)
696 */
697 public function validate_sequence_number($slot, $postdata = null) {
698 $qa = $this->get_question_attempt($slot);
699 $sequencecheck = $qa->get_submitted_var(
700 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
701 if (is_null($sequencecheck)) {
702 return false;
c7fbfe46 703 } else if ($sequencecheck != $qa->get_sequence_check_count()) {
dcd03928
TH
704 throw new question_out_of_sequence_exception($this->id, $slot, $postdata);
705 } else {
706 return true;
707 }
708 }
d122fe32
TH
709
710 /**
711 * Check, based on the sequence number, whether this auto-save is still required.
712 * @param int $slot the number used to identify this question within this usage.
713 * @param array $submitteddata the submitted data that constitutes the action.
714 * @return bool true if the check variable is present and correct, otherwise false.
715 */
716 public function is_autosave_required($slot, $postdata = null) {
717 $qa = $this->get_question_attempt($slot);
718 $sequencecheck = $qa->get_submitted_var(
719 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
720 if (is_null($sequencecheck)) {
721 return false;
c7fbfe46 722 } else if ($sequencecheck != $qa->get_sequence_check_count()) {
d122fe32
TH
723 return false;
724 } else {
725 return true;
726 }
727 }
728
dcd03928
TH
729 /**
730 * Update the flagged state for all question_attempts in this usage, if their
731 * flagged state was changed in the request.
732 *
733 * @param $postdata optional, only intended for testing. Use this data
734 * instead of the data from $_POST.
735 */
736 public function update_question_flags($postdata = null) {
737 foreach ($this->questionattempts as $qa) {
738 $flagged = $qa->get_submitted_var(
739 $qa->get_flag_field_name(), PARAM_BOOL, $postdata);
740 if (!is_null($flagged) && $flagged != $qa->is_flagged()) {
741 $qa->set_flagged($flagged);
742 }
743 }
744 }
745
746 /**
747 * Get the correct response to a particular question. Passing the results of
748 * this method to {@link process_action()} will probably result in full marks.
da22c012 749 * If it is not possible to compute a correct response, this method should return null.
dcd03928
TH
750 * @param int $slot the number used to identify this question within this usage.
751 * @return array that constitutes a correct response to this question.
752 */
753 public function get_correct_response($slot) {
754 return $this->get_question_attempt($slot)->get_correct_response();
755 }
756
757 /**
758 * Finish the active phase of an attempt at a question.
759 *
760 * This is an external act of finishing the attempt. Think, for example, of
761 * the 'Submit all and finish' button in the quiz. Some behaviours,
762 * (for example, immediatefeedback) give a way of finishing the active phase
763 * of a question attempt as part of a {@link process_action()} call.
764 *
765 * After the active phase is over, the only changes possible are things like
766 * manual grading, or changing the flag state.
767 *
768 * @param int $slot the number used to identify this question within this usage.
769 */
770 public function finish_question($slot, $timestamp = null) {
771 $qa = $this->get_question_attempt($slot);
772 $qa->finish($timestamp);
773 $this->observer->notify_attempt_modified($qa);
774 }
775
776 /**
777 * Finish the active phase of an attempt at a question. See {@link finish_question()}
778 * for a fuller description of what 'finish' means.
779 */
780 public function finish_all_questions($timestamp = null) {
781 foreach ($this->questionattempts as $qa) {
782 $qa->finish($timestamp);
783 $this->observer->notify_attempt_modified($qa);
784 }
785 }
786
787 /**
788 * Perform a manual grading action on a question attempt.
789 * @param int $slot the number used to identify this question within this usage.
790 * @param string $comment the comment being added to the question attempt.
791 * @param number $mark the mark that is being assigned. Can be null to just
792 * add a comment.
770e4a46 793 * @param int $commentformat one of the FORMAT_... constants. The format of $comment.
dcd03928 794 */
53b8e256 795 public function manual_grade($slot, $comment, $mark, $commentformat = null) {
dcd03928 796 $qa = $this->get_question_attempt($slot);
53b8e256 797 $qa->manual_grade($comment, $mark, $commentformat);
dcd03928
TH
798 $this->observer->notify_attempt_modified($qa);
799 }
800
801 /**
802 * Regrade a question in this usage. This replays the sequence of submitted
803 * actions to recompute the outcomes.
804 * @param int $slot the number used to identify this question within this usage.
805 * @param bool $finished whether the question attempt should be forced to be finished
806 * after the regrade, or whether it may still be in progress (default false).
807 * @param number $newmaxmark (optional) if given, will change the max mark while regrading.
808 */
809 public function regrade_question($slot, $finished = false, $newmaxmark = null) {
810 $oldqa = $this->get_question_attempt($slot);
811 if (is_null($newmaxmark)) {
812 $newmaxmark = $oldqa->get_max_mark();
813 }
814
dcd03928
TH
815 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(),
816 $this->observer, $newmaxmark);
817 $newqa->set_database_id($oldqa->get_database_id());
94815ccf 818 $newqa->set_slot($oldqa->get_slot());
dcd03928
TH
819 $newqa->regrade($oldqa, $finished);
820
821 $this->questionattempts[$slot] = $newqa;
822 $this->observer->notify_attempt_modified($newqa);
823 }
824
1700bd4d
K
825 /**
826 * Replace a question in this usage.
827 * @param int $slot the number used to identify this question within this usage.*
828 */
829 public function replace_question($slot) {
830 global $OUTPUT;
831 $oldqa = $this->get_question_attempt($slot);
832 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(), $this->observer);
833 $newqa->set_database_id($oldqa->get_database_id());
834 $newqa->set_slot($oldqa->get_slot());
835 $this->questionattempts[$slot] = $newqa;
836 $this->observer->notify_attempt_deleted($oldqa);
837 $this->observer->notify_attempt_added($newqa);
838 $this->start_question($slot);
839 }
840
dcd03928
TH
841 /**
842 * Regrade all the questions in this usage (without changing their max mark).
843 * @param bool $finished whether each question should be forced to be finished
844 * after the regrade, or whether it may still be in progress (default false).
845 */
846 public function regrade_all_questions($finished = false) {
847 foreach ($this->questionattempts as $slot => $notused) {
848 $this->regrade_question($slot, $finished);
849 }
850 }
851
852 /**
853 * Create a question_usage_by_activity from records loaded from the database.
854 *
855 * For internal use only.
856 *
35d5f1c2 857 * @param Iterator $records Raw records loaded from the database.
dcd03928 858 * @param int $questionattemptid The id of the question_attempt to extract.
94815ccf 859 * @return question_usage_by_activity The newly constructed usage.
dcd03928 860 */
35d5f1c2
TH
861 public static function load_from_records($records, $qubaid) {
862 $record = $records->current();
dcd03928 863 while ($record->qubaid != $qubaid) {
35d5f1c2
TH
864 $records->next();
865 if (!$records->valid()) {
f4fe3968 866 throw new coding_exception("Question usage {$qubaid} not found in the database.");
dcd03928 867 }
35d5f1c2 868 $record = $records->current();
dcd03928
TH
869 }
870
871 $quba = new question_usage_by_activity($record->component,
2cdd5d85 872 context::instance_by_id($record->contextid, IGNORE_MISSING));
dcd03928
TH
873 $quba->set_id_from_database($record->qubaid);
874 $quba->set_preferred_behaviour($record->preferredbehaviour);
875
876 $quba->observer = new question_engine_unit_of_work($quba);
877
dd7aa583
TH
878 // If slot is null then the current pointer in $records will not be
879 // advanced in the while loop below, and we get stuck in an infinite loop,
880 // since this method is supposed to always consume at least one record.
881 // Therefore, in this case, advance the record here.
882 if (is_null($record->slot)) {
883 $records->next();
884 }
885
dcd03928
TH
886 while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
887 $quba->questionattempts[$record->slot] =
888 question_attempt::load_from_records($records,
889 $record->questionattemptid, $quba->observer,
890 $quba->get_preferred_behaviour());
35d5f1c2
TH
891 if ($records->valid()) {
892 $record = $records->current();
893 } else {
894 $record = false;
895 }
dcd03928
TH
896 }
897
898 return $quba;
899 }
900}
901
902
903/**
904 * A class abstracting access to the
905 * {@link question_usage_by_activity::$questionattempts} array.
906 *
907 * This class snapshots the list of {@link question_attempts} to iterate over
908 * when it is created. If a question is added to the usage mid-iteration, it
909 * will now show up.
910 *
911 * To create an instance of this class, use
912 * {@link question_usage_by_activity::get_attempt_iterator()}
913 *
914 * @copyright 2009 The Open University
915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
916 */
917class question_attempt_iterator implements Iterator, ArrayAccess {
918 /** @var question_usage_by_activity that we are iterating over. */
919 protected $quba;
920 /** @var array of question numbers. */
921 protected $slots;
922
923 /**
9c197f44
TH
924 * To create an instance of this class, use
925 * {@link question_usage_by_activity::get_attempt_iterator()}.
dcd03928
TH
926 * @param $quba the usage to iterate over.
927 */
928 public function __construct(question_usage_by_activity $quba) {
929 $this->quba = $quba;
930 $this->slots = $quba->get_slots();
931 $this->rewind();
932 }
933
934 /** @return question_attempt_step */
935 public function current() {
936 return $this->offsetGet(current($this->slots));
937 }
938 /** @return int */
939 public function key() {
940 return current($this->slots);
941 }
942 public function next() {
943 next($this->slots);
944 }
945 public function rewind() {
946 reset($this->slots);
947 }
948 /** @return bool */
949 public function valid() {
950 return current($this->slots) !== false;
951 }
952
953 /** @return bool */
954 public function offsetExists($slot) {
955 return in_array($slot, $this->slots);
956 }
957 /** @return question_attempt_step */
958 public function offsetGet($slot) {
959 return $this->quba->get_question_attempt($slot);
960 }
961 public function offsetSet($slot, $value) {
9c197f44
TH
962 throw new coding_exception('You are only allowed read-only access to ' .
963 'question_attempt::states through a question_attempt_step_iterator. Cannot set.');
dcd03928
TH
964 }
965 public function offsetUnset($slot) {
9c197f44
TH
966 throw new coding_exception('You are only allowed read-only access to ' .
967 'question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
dcd03928
TH
968 }
969}
970
971
972/**
973 * Interface for things that want to be notified of signficant changes to a
974 * {@link question_usage_by_activity}.
975 *
976 * A question behaviour controls the flow of actions a student can
977 * take as they work through a question, and later, as a teacher manually grades it.
978 *
979 * @copyright 2009 The Open University
980 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
981 */
982interface question_usage_observer {
983 /** Called when a field of the question_usage_by_activity is changed. */
984 public function notify_modified();
985
986 /**
987 * Called when the fields of a question attempt in this usage are modified.
988 * @param question_attempt $qa the newly added question attempt.
989 */
990 public function notify_attempt_modified(question_attempt $qa);
991
992 /**
993 * Called when a new question attempt is added to this usage.
994 * @param question_attempt $qa the newly added question attempt.
995 */
996 public function notify_attempt_added(question_attempt $qa);
997
1700bd4d
K
998 /**
999 * Called when the fields of a question attempt in this usage are deleted.
1000 * @param question_attempt $qa
1001 */
1002 public function notify_attempt_deleted(question_attempt $qa);
1003
dcd03928 1004 /**
94815ccf
TH
1005 * Called when a new step is added to a question attempt in this usage.
1006 * @param question_attempt_step $step the new step.
1007 * @param question_attempt $qa the usage it is being added to.
1008 * @param int $seq the sequence number of the new step.
dcd03928 1009 */
94815ccf 1010 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq);
dcd03928
TH
1011
1012 /**
94815ccf
TH
1013 * Called when a new step is updated in a question attempt in this usage.
1014 * @param question_attempt_step $step the step that was updated.
1015 * @param question_attempt $qa the usage it is being added to.
1016 * @param int $seq the sequence number of the new step.
dcd03928 1017 */
94815ccf
TH
1018 public function notify_step_modified(question_attempt_step $step, question_attempt $qa, $seq);
1019
1020 /**
1021 * Called when a new step is updated in a question attempt in this usage.
1022 * @param question_attempt_step $step the step to delete.
1023 * @param question_attempt $qa the usage it is being added to.
1024 */
1025 public function notify_step_deleted(question_attempt_step $step, question_attempt $qa);
1026
dcd03928
TH
1027}
1028
1029
1030/**
1031 * Null implmentation of the {@link question_usage_watcher} interface.
1032 * Does nothing.
1033 *
1034 * @copyright 2009 The Open University
1035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1036 */
1037class question_usage_null_observer implements question_usage_observer {
1038 public function notify_modified() {
1039 }
1040 public function notify_attempt_modified(question_attempt $qa) {
1041 }
1700bd4d
K
1042 public function notify_attempt_deleted(question_attempt $qa) {
1043 }
dcd03928
TH
1044 public function notify_attempt_added(question_attempt $qa) {
1045 }
dcd03928
TH
1046 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
1047 }
94815ccf
TH
1048 public function notify_step_modified(question_attempt_step $step, question_attempt $qa, $seq) {
1049 }
1050 public function notify_step_deleted(question_attempt_step $step, question_attempt $qa) {
1051 }
dcd03928 1052}