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