weekly release 2.3dev (blame stronk7 for 0202 mistake)
[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
66 /** @var object the context this usage belongs to. */
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
107 /** @return object the context this usage belongs to. */
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
127 /** @return question_usage_observer that is tracking changes made to this usage. */
128 public function get_observer() {
129 return $this->observer;
130 }
131
132 /**
133 * For internal use only. Used by {@link question_engine_data_mapper} to set
134 * the id when a usage is saved to the database.
135 * @param int $id the newly determined id for this usage.
136 */
137 public function set_id_from_database($id) {
138 $this->id = $id;
139 foreach ($this->questionattempts as $qa) {
140 $qa->set_usage_id($id);
141 }
142 }
143
144 /**
145 * Add another question to this usage.
146 *
147 * The added question is not started until you call {@link start_question()}
148 * on it.
149 *
150 * @param question_definition $question the question to add.
151 * @param number $maxmark the maximum this question will be marked out of in
152 * this attempt (optional). If not given, $question->defaultmark is used.
153 * @return int the number used to identify this question within this usage.
154 */
155 public function add_question(question_definition $question, $maxmark = null) {
156 $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark);
157 if (count($this->questionattempts) == 0) {
158 $this->questionattempts[1] = $qa;
159 } else {
160 $this->questionattempts[] = $qa;
161 }
162 $qa->set_number_in_usage(end(array_keys($this->questionattempts)));
163 $this->observer->notify_attempt_added($qa);
164 return $qa->get_slot();
165 }
166
167 /**
168 * Get the question_definition for a question in this attempt.
169 * @param int $slot the number used to identify this question within this usage.
170 * @return question_definition the requested question object.
171 */
172 public function get_question($slot) {
173 return $this->get_question_attempt($slot)->get_question();
174 }
175
176 /** @return array all the identifying numbers of all the questions in this usage. */
177 public function get_slots() {
178 return array_keys($this->questionattempts);
179 }
180
181 /** @return int the identifying number of the first question that was added to this usage. */
182 public function get_first_question_number() {
183 reset($this->questionattempts);
184 return key($this->questionattempts);
185 }
186
187 /** @return int the number of questions that are currently in this usage. */
188 public function question_count() {
189 return count($this->questionattempts);
190 }
191
192 /**
193 * Note the part of the {@link question_usage_by_activity} comment that explains
194 * that {@link question_attempt} objects should be considered part of the inner
195 * workings of the question engine, and should not, if possible, be accessed directly.
196 *
197 * @return question_attempt_iterator for iterating over all the questions being
198 * attempted. as part of this usage.
199 */
200 public function get_attempt_iterator() {
201 return new question_attempt_iterator($this);
202 }
203
204 /**
205 * Check whether $number actually corresponds to a question attempt that is
206 * part of this usage. Throws an exception if not.
207 *
208 * @param int $slot a number allegedly identifying a question within this usage.
209 */
210 protected function check_slot($slot) {
211 if (!array_key_exists($slot, $this->questionattempts)) {
9c197f44
TH
212 throw new coding_exception('There is no question_attempt number ' . $slot .
213 ' in this attempt.');
dcd03928
TH
214 }
215 }
216
217 /**
218 * Note the part of the {@link question_usage_by_activity} comment that explains
219 * that {@link question_attempt} objects should be considered part of the inner
220 * workings of the question engine, and should not, if possible, be accessed directly.
221 *
222 * @param int $slot the number used to identify this question within this usage.
223 * @return question_attempt the corresponding {@link question_attempt} object.
224 */
225 public function get_question_attempt($slot) {
226 $this->check_slot($slot);
227 return $this->questionattempts[$slot];
228 }
229
230 /**
231 * Get the current state of the attempt at a question.
232 * @param int $slot the number used to identify this question within this usage.
233 * @return question_state.
234 */
235 public function get_question_state($slot) {
236 return $this->get_question_attempt($slot)->get_state();
237 }
238
239 /**
240 * @param int $slot the number used to identify this question within this usage.
241 * @param bool $showcorrectness Whether right/partial/wrong states should
242 * be distinguised.
243 * @return string A brief textual description of the current state.
244 */
245 public function get_question_state_string($slot, $showcorrectness) {
246 return $this->get_question_attempt($slot)->get_state_string($showcorrectness);
247 }
248
97cdc1de
TH
249 /**
250 * @param int $slot the number used to identify this question within this usage.
251 * @param bool $showcorrectness Whether right/partial/wrong states should
252 * be distinguised.
253 * @return string a CSS class name for the current state.
254 */
255 public function get_question_state_class($slot, $showcorrectness) {
256 return $this->get_question_attempt($slot)->get_state_class($showcorrectness);
257 }
258
dcd03928
TH
259 /**
260 * Get the time of the most recent action performed on a question.
261 * @param int $slot the number used to identify this question within this usage.
262 * @return int timestamp.
263 */
264 public function get_question_action_time($slot) {
265 return $this->get_question_attempt($slot)->get_last_action_time();
266 }
267
268 /**
269 * Get the current fraction awarded for the attempt at a question.
270 * @param int $slot the number used to identify this question within this usage.
271 * @return number|null The current fraction for this question, or null if one has
272 * not been assigned yet.
273 */
274 public function get_question_fraction($slot) {
275 return $this->get_question_attempt($slot)->get_fraction();
276 }
277
278 /**
279 * Get the current mark awarded for the attempt at a question.
280 * @param int $slot the number used to identify this question within this usage.
281 * @return number|null The current mark for this question, or null if one has
282 * not been assigned yet.
283 */
284 public function get_question_mark($slot) {
285 return $this->get_question_attempt($slot)->get_mark();
286 }
287
288 /**
289 * Get the maximum mark possible for the attempt at a question.
290 * @param int $slot the number used to identify this question within this usage.
291 * @return number the available marks for this question.
292 */
293 public function get_question_max_mark($slot) {
294 return $this->get_question_attempt($slot)->get_max_mark();
295 }
296
297 /**
298 * Get the current mark awarded for the attempt at a question.
299 * @param int $slot the number used to identify this question within this usage.
300 * @return number|null The current mark for this question, or null if one has
301 * not been assigned yet.
302 */
303 public function get_total_mark() {
304 $mark = 0;
305 foreach ($this->questionattempts as $qa) {
306 if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
307 return null;
308 }
309 $mark += $qa->get_mark();
310 }
311 return $mark;
312 }
313
314 /**
315 * @return string a simple textual summary of the question that was asked.
316 */
317 public function get_question_summary($slot) {
318 return $this->get_question_attempt($slot)->get_question_summary();
319 }
320
321 /**
322 * @return string a simple textual summary of response given.
323 */
324 public function get_response_summary($slot) {
325 return $this->get_question_attempt($slot)->get_response_summary();
326 }
327
328 /**
329 * @return string a simple textual summary of the correct resonse.
330 */
331 public function get_right_answer_summary($slot) {
332 return $this->get_question_attempt($slot)->get_right_answer_summary();
333 }
334
335 /**
336 * Get the {@link core_question_renderer}, in collaboration with appropriate
337 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
338 * HTML to display this question.
339 * @param int $slot the number used to identify this question within this usage.
340 * @param question_display_options $options controls how the question is rendered.
341 * @param string|null $number The question number to display. 'i' is a special
342 * value that gets displayed as Information. Null means no number is displayed.
343 * @return string HTML fragment representing the question.
344 */
345 public function render_question($slot, $options, $number = null) {
346 $options->context = $this->context;
347 return $this->get_question_attempt($slot)->render($options, $number);
348 }
349
350 /**
351 * Generate any bits of HTML that needs to go in the <head> tag when this question
352 * is displayed in the body.
353 * @param int $slot the number used to identify this question within this usage.
354 * @return string HTML fragment.
355 */
356 public function render_question_head_html($slot) {
92701024 357 //$options->context = $this->context;
dcd03928
TH
358 return $this->get_question_attempt($slot)->render_head_html();
359 }
360
361 /**
362 * Like {@link render_question()} but displays the question at the past step
363 * indicated by $seq, rather than showing the latest step.
364 *
365 * @param int $slot the number used to identify this question within this usage.
366 * @param int $seq the seq number of the past state to display.
367 * @param question_display_options $options controls how the question is rendered.
368 * @param string|null $number The question number to display. 'i' is a special
369 * value that gets displayed as Information. Null means no number is displayed.
370 * @return string HTML fragment representing the question.
371 */
372 public function render_question_at_step($slot, $seq, $options, $number = null) {
373 $options->context = $this->context;
9c197f44
TH
374 return $this->get_question_attempt($slot)->render_at_step(
375 $seq, $options, $number, $this->preferredbehaviour);
dcd03928
TH
376 }
377
378 /**
379 * Checks whether the users is allow to be served a particular file.
380 * @param int $slot the number used to identify this question within this usage.
381 * @param question_display_options $options the options that control display of the question.
382 * @param string $component the name of the component we are serving files for.
383 * @param string $filearea the name of the file area.
384 * @param array $args the remaining bits of the file path.
385 * @param bool $forcedownload whether the user must be forced to download the file.
386 * @return bool true if the user can access this file.
387 */
9c197f44
TH
388 public function check_file_access($slot, $options, $component, $filearea,
389 $args, $forcedownload) {
390 return $this->get_question_attempt($slot)->check_file_access(
391 $options, $component, $filearea, $args, $forcedownload);
dcd03928
TH
392 }
393
394 /**
395 * Replace a particular question_attempt with a different one.
396 *
397 * For internal use only. Used when reloading the state of a question from the
398 * database.
399 *
400 * @param array $records Raw records loaded from the database.
401 * @param int $questionattemptid The id of the question_attempt to extract.
402 * @return question_attempt The newly constructed question_attempt_step.
403 */
404 public function replace_loaded_question_attempt_info($slot, $qa) {
405 $this->check_slot($slot);
406 $this->questionattempts[$slot] = $qa;
407 }
408
409 /**
410 * You should probably not use this method in code outside the question engine.
411 * The main reason for exposing it was for the benefit of unit tests.
412 * @param int $slot the number used to identify this question within this usage.
413 * @return string return the prefix that is pre-pended to field names in the HTML
414 * that is output.
415 */
416 public function get_field_prefix($slot) {
417 return $this->get_question_attempt($slot)->get_field_prefix();
418 }
419
1da821bb
TH
420 /**
421 * Get the number of variants available for the question in this slot.
422 * @param int $slot the number used to identify this question within this usage.
423 * @return int the number of variants available.
424 */
425 public function get_num_variants($slot) {
426 return $this->get_question_attempt($slot)->get_question()->get_num_variants();
427 }
428
429 /**
430 * Get the variant of the question being used in a given slot.
431 * @param int $slot the number used to identify this question within this usage.
432 * @return int the variant of this question that is being used.
433 */
434 public function get_variant($slot) {
435 return $this->get_question_attempt($slot)->get_variant();
436 }
437
dcd03928
TH
438 /**
439 * Start the attempt at a question that has been added to this usage.
440 * @param int $slot the number used to identify this question within this usage.
1da821bb
TH
441 * @param int $variant which variant of the question to use. Must be between
442 * 1 and ->get_num_variants($slot) inclusive. If not give, a variant is
443 * chosen at random.
dcd03928 444 */
1da821bb
TH
445 public function start_question($slot, $variant = null) {
446 if (is_null($variant)) {
447 $variant = rand(1, $this->get_num_variants($slot));
448 }
449
dcd03928 450 $qa = $this->get_question_attempt($slot);
1da821bb 451 $qa->start($this->preferredbehaviour, $variant);
dcd03928
TH
452 $this->observer->notify_attempt_modified($qa);
453 }
454
455 /**
456 * Start the attempt at all questions that has been added to this usage.
1da821bb 457 * @param question_variant_selection_strategy how to pick which variant of each question to use.
e35ba43c
TH
458 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
459 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
dcd03928 460 */
1da821bb
TH
461 public function start_all_questions(question_variant_selection_strategy $variantstrategy = null,
462 $timestamp = null, $userid = null) {
463 if (is_null($variantstrategy)) {
464 $variantstrategy = new question_variant_random_strategy();
465 }
466
dcd03928 467 foreach ($this->questionattempts as $qa) {
1da821bb 468 $qa->start($this->preferredbehaviour, $qa->select_variant($variantstrategy));
dcd03928
TH
469 $this->observer->notify_attempt_modified($qa);
470 }
471 }
472
473 /**
474 * Start the attempt at a question, starting from the point where the previous
475 * question_attempt $oldqa had reached. This is used by the quiz 'Each attempt
476 * builds on last' mode.
477 * @param int $slot the number used to identify this question within this usage.
478 * @param question_attempt $oldqa a previous attempt at this quetsion that
479 * defines the starting point.
480 */
481 public function start_question_based_on($slot, question_attempt $oldqa) {
482 $qa = $this->get_question_attempt($slot);
483 $qa->start_based_on($oldqa);
484 $this->observer->notify_attempt_modified($qa);
485 }
486
487 /**
488 * Process all the question actions in the current request.
489 *
490 * If there is a parameter slots included in the post data, then only
491 * those question numbers will be processed, otherwise all questions in this
492 * useage will be.
493 *
494 * This function also does {@link update_question_flags()}.
495 *
496 * @param int $timestamp optional, use this timestamp as 'now'.
497 * @param array $postdata optional, only intended for testing. Use this data
498 * instead of the data from $_POST.
499 */
500 public function process_all_actions($timestamp = null, $postdata = null) {
501 $slots = question_attempt::get_submitted_var('slots', PARAM_SEQUENCE, $postdata);
502 if (is_null($slots)) {
503 $slots = $this->get_slots();
504 } else if (!$slots) {
505 $slots = array();
506 } else {
507 $slots = explode(',', $slots);
508 }
509 foreach ($slots as $slot) {
510 if (!$this->validate_sequence_number($slot, $postdata)) {
511 continue;
512 }
513 $submitteddata = $this->extract_responses($slot, $postdata);
514 $this->process_action($slot, $submitteddata, $timestamp);
515 }
516 $this->update_question_flags($postdata);
517 }
518
519 /**
520 * Get the submitted data from the current request that belongs to this
521 * particular question.
522 *
523 * @param int $slot the number used to identify this question within this usage.
524 * @param $postdata optional, only intended for testing. Use this data
525 * instead of the data from $_POST.
526 * @return array submitted data specific to this question.
527 */
528 public function extract_responses($slot, $postdata = null) {
529 return $this->get_question_attempt($slot)->get_submitted_data($postdata);
530 }
531
532 /**
533 * Process a specific action on a specific question.
534 * @param int $slot the number used to identify this question within this usage.
535 * @param $submitteddata the submitted data that constitutes the action.
536 */
537 public function process_action($slot, $submitteddata, $timestamp = null) {
538 $qa = $this->get_question_attempt($slot);
539 $qa->process_action($submitteddata, $timestamp);
540 $this->observer->notify_attempt_modified($qa);
541 }
542
543 /**
544 * Check that the sequence number, that detects weird things like the student
545 * clicking back, is OK. If the sequence check variable is not present, returns
546 * false. If the check variable is present and correct, returns true. If the
547 * variable is present and wrong, throws an exception.
548 * @param int $slot the number used to identify this question within this usage.
549 * @param array $submitteddata the submitted data that constitutes the action.
550 * @return bool true if the check variable is present and correct. False if it
551 * is missing. (Throws an exception if the check fails.)
552 */
553 public function validate_sequence_number($slot, $postdata = null) {
554 $qa = $this->get_question_attempt($slot);
555 $sequencecheck = $qa->get_submitted_var(
556 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
557 if (is_null($sequencecheck)) {
558 return false;
559 } else if ($sequencecheck != $qa->get_num_steps()) {
560 throw new question_out_of_sequence_exception($this->id, $slot, $postdata);
561 } else {
562 return true;
563 }
564 }
565 /**
566 * Update the flagged state for all question_attempts in this usage, if their
567 * flagged state was changed in the request.
568 *
569 * @param $postdata optional, only intended for testing. Use this data
570 * instead of the data from $_POST.
571 */
572 public function update_question_flags($postdata = null) {
573 foreach ($this->questionattempts as $qa) {
574 $flagged = $qa->get_submitted_var(
575 $qa->get_flag_field_name(), PARAM_BOOL, $postdata);
576 if (!is_null($flagged) && $flagged != $qa->is_flagged()) {
577 $qa->set_flagged($flagged);
578 }
579 }
580 }
581
582 /**
583 * Get the correct response to a particular question. Passing the results of
584 * this method to {@link process_action()} will probably result in full marks.
da22c012 585 * If it is not possible to compute a correct response, this method should return null.
dcd03928
TH
586 * @param int $slot the number used to identify this question within this usage.
587 * @return array that constitutes a correct response to this question.
588 */
589 public function get_correct_response($slot) {
590 return $this->get_question_attempt($slot)->get_correct_response();
591 }
592
593 /**
594 * Finish the active phase of an attempt at a question.
595 *
596 * This is an external act of finishing the attempt. Think, for example, of
597 * the 'Submit all and finish' button in the quiz. Some behaviours,
598 * (for example, immediatefeedback) give a way of finishing the active phase
599 * of a question attempt as part of a {@link process_action()} call.
600 *
601 * After the active phase is over, the only changes possible are things like
602 * manual grading, or changing the flag state.
603 *
604 * @param int $slot the number used to identify this question within this usage.
605 */
606 public function finish_question($slot, $timestamp = null) {
607 $qa = $this->get_question_attempt($slot);
608 $qa->finish($timestamp);
609 $this->observer->notify_attempt_modified($qa);
610 }
611
612 /**
613 * Finish the active phase of an attempt at a question. See {@link finish_question()}
614 * for a fuller description of what 'finish' means.
615 */
616 public function finish_all_questions($timestamp = null) {
617 foreach ($this->questionattempts as $qa) {
618 $qa->finish($timestamp);
619 $this->observer->notify_attempt_modified($qa);
620 }
621 }
622
623 /**
624 * Perform a manual grading action on a question attempt.
625 * @param int $slot the number used to identify this question within this usage.
626 * @param string $comment the comment being added to the question attempt.
627 * @param number $mark the mark that is being assigned. Can be null to just
628 * add a comment.
629 */
630 public function manual_grade($slot, $comment, $mark) {
631 $qa = $this->get_question_attempt($slot);
632 $qa->manual_grade($comment, $mark);
633 $this->observer->notify_attempt_modified($qa);
634 }
635
636 /**
637 * Regrade a question in this usage. This replays the sequence of submitted
638 * actions to recompute the outcomes.
639 * @param int $slot the number used to identify this question within this usage.
640 * @param bool $finished whether the question attempt should be forced to be finished
641 * after the regrade, or whether it may still be in progress (default false).
642 * @param number $newmaxmark (optional) if given, will change the max mark while regrading.
643 */
644 public function regrade_question($slot, $finished = false, $newmaxmark = null) {
645 $oldqa = $this->get_question_attempt($slot);
646 if (is_null($newmaxmark)) {
647 $newmaxmark = $oldqa->get_max_mark();
648 }
649
650 $this->observer->notify_delete_attempt_steps($oldqa);
651
652 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(),
653 $this->observer, $newmaxmark);
654 $newqa->set_database_id($oldqa->get_database_id());
655 $newqa->regrade($oldqa, $finished);
656
657 $this->questionattempts[$slot] = $newqa;
658 $this->observer->notify_attempt_modified($newqa);
659 }
660
661 /**
662 * Regrade all the questions in this usage (without changing their max mark).
663 * @param bool $finished whether each question should be forced to be finished
664 * after the regrade, or whether it may still be in progress (default false).
665 */
666 public function regrade_all_questions($finished = false) {
667 foreach ($this->questionattempts as $slot => $notused) {
668 $this->regrade_question($slot, $finished);
669 }
670 }
671
672 /**
673 * Create a question_usage_by_activity from records loaded from the database.
674 *
675 * For internal use only.
676 *
35d5f1c2 677 * @param Iterator $records Raw records loaded from the database.
dcd03928
TH
678 * @param int $questionattemptid The id of the question_attempt to extract.
679 * @return question_attempt The newly constructed question_attempt_step.
680 */
35d5f1c2
TH
681 public static function load_from_records($records, $qubaid) {
682 $record = $records->current();
dcd03928 683 while ($record->qubaid != $qubaid) {
35d5f1c2
TH
684 $records->next();
685 if (!$records->valid()) {
dcd03928
TH
686 throw new coding_exception("Question usage $qubaid not found in the database.");
687 }
35d5f1c2 688 $record = $records->current();
dcd03928
TH
689 }
690
691 $quba = new question_usage_by_activity($record->component,
692 get_context_instance_by_id($record->contextid));
693 $quba->set_id_from_database($record->qubaid);
694 $quba->set_preferred_behaviour($record->preferredbehaviour);
695
696 $quba->observer = new question_engine_unit_of_work($quba);
697
698 while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
699 $quba->questionattempts[$record->slot] =
700 question_attempt::load_from_records($records,
701 $record->questionattemptid, $quba->observer,
702 $quba->get_preferred_behaviour());
35d5f1c2
TH
703 if ($records->valid()) {
704 $record = $records->current();
705 } else {
706 $record = false;
707 }
dcd03928
TH
708 }
709
710 return $quba;
711 }
712}
713
714
715/**
716 * A class abstracting access to the
717 * {@link question_usage_by_activity::$questionattempts} array.
718 *
719 * This class snapshots the list of {@link question_attempts} to iterate over
720 * when it is created. If a question is added to the usage mid-iteration, it
721 * will now show up.
722 *
723 * To create an instance of this class, use
724 * {@link question_usage_by_activity::get_attempt_iterator()}
725 *
726 * @copyright 2009 The Open University
727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
728 */
729class question_attempt_iterator implements Iterator, ArrayAccess {
730 /** @var question_usage_by_activity that we are iterating over. */
731 protected $quba;
732 /** @var array of question numbers. */
733 protected $slots;
734
735 /**
9c197f44
TH
736 * To create an instance of this class, use
737 * {@link question_usage_by_activity::get_attempt_iterator()}.
dcd03928
TH
738 * @param $quba the usage to iterate over.
739 */
740 public function __construct(question_usage_by_activity $quba) {
741 $this->quba = $quba;
742 $this->slots = $quba->get_slots();
743 $this->rewind();
744 }
745
746 /** @return question_attempt_step */
747 public function current() {
748 return $this->offsetGet(current($this->slots));
749 }
750 /** @return int */
751 public function key() {
752 return current($this->slots);
753 }
754 public function next() {
755 next($this->slots);
756 }
757 public function rewind() {
758 reset($this->slots);
759 }
760 /** @return bool */
761 public function valid() {
762 return current($this->slots) !== false;
763 }
764
765 /** @return bool */
766 public function offsetExists($slot) {
767 return in_array($slot, $this->slots);
768 }
769 /** @return question_attempt_step */
770 public function offsetGet($slot) {
771 return $this->quba->get_question_attempt($slot);
772 }
773 public function offsetSet($slot, $value) {
9c197f44
TH
774 throw new coding_exception('You are only allowed read-only access to ' .
775 'question_attempt::states through a question_attempt_step_iterator. Cannot set.');
dcd03928
TH
776 }
777 public function offsetUnset($slot) {
9c197f44
TH
778 throw new coding_exception('You are only allowed read-only access to ' .
779 'question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
dcd03928
TH
780 }
781}
782
783
784/**
785 * Interface for things that want to be notified of signficant changes to a
786 * {@link question_usage_by_activity}.
787 *
788 * A question behaviour controls the flow of actions a student can
789 * take as they work through a question, and later, as a teacher manually grades it.
790 *
791 * @copyright 2009 The Open University
792 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
793 */
794interface question_usage_observer {
795 /** Called when a field of the question_usage_by_activity is changed. */
796 public function notify_modified();
797
798 /**
799 * Called when the fields of a question attempt in this usage are modified.
800 * @param question_attempt $qa the newly added question attempt.
801 */
802 public function notify_attempt_modified(question_attempt $qa);
803
804 /**
805 * Called when a new question attempt is added to this usage.
806 * @param question_attempt $qa the newly added question attempt.
807 */
808 public function notify_attempt_added(question_attempt $qa);
809
810 /**
811 * Called we want to delete the old step records for an attempt, prior to
812 * inserting newones. This is used by regrading.
813 * @param question_attempt $qa the question attempt to delete the steps for.
814 */
815 public function notify_delete_attempt_steps(question_attempt $qa);
816
817 /**
818 * Called when a new step is added to a question attempt in this usage.
819 * @param $step the new step.
820 * @param $qa the usage it is being added to.
821 * @param $seq the sequence number of the new step.
822 */
823 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq);
824}
825
826
827/**
828 * Null implmentation of the {@link question_usage_watcher} interface.
829 * Does nothing.
830 *
831 * @copyright 2009 The Open University
832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
833 */
834class question_usage_null_observer implements question_usage_observer {
835 public function notify_modified() {
836 }
837 public function notify_attempt_modified(question_attempt $qa) {
838 }
839 public function notify_attempt_added(question_attempt $qa) {
840 }
841 public function notify_delete_attempt_steps(question_attempt $qa) {
842 }
843 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
844 }
845}