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