MDL-20636 Cannot really delete questions that were only used in previews #196
[moodle.git] / question / engine / lib.php
CommitLineData
d1b7e03d
TH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This defines the core classes of the Moodle question engine.
20 *
017bc1d9 21 * @package moodlecore
d1b7e03d 22 * @subpackage questionengine
017bc1d9
TH
23 * @copyright 2009 The Open University
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
25 */
26
27
a17b297d
TH
28defined('MOODLE_INTERNAL') || die();
29
d1b7e03d
TH
30require_once(dirname(__FILE__) . '/states.php');
31require_once(dirname(__FILE__) . '/datalib.php');
32require_once(dirname(__FILE__) . '/renderer.php');
33require_once(dirname(__FILE__) . '/bank.php');
34require_once(dirname(__FILE__) . '/../type/questiontype.php');
35require_once(dirname(__FILE__) . '/../type/questionbase.php');
36require_once(dirname(__FILE__) . '/../type/rendererbase.php');
37require_once(dirname(__FILE__) . '/../behaviour/behaviourbase.php');
38require_once(dirname(__FILE__) . '/../behaviour/rendererbase.php');
39require_once($CFG->libdir . '/questionlib.php');
40
41
42/**
43 * This static class provides access to the other question engine classes.
44 *
45 * It provides functions for managing question behaviours), and for
46 * creating, loading, saving and deleting {@link question_usage_by_activity}s,
47 * which is the main class that is used by other code that wants to use questions.
48 *
017bc1d9
TH
49 * @copyright 2009 The Open University
50 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
51 */
52abstract class question_engine {
53 /** @var array behaviour name => 1. Records which behaviours have been loaded. */
54 private static $loadedbehaviours = array();
55
56 /**
57 * Create a new {@link question_usage_by_activity}. The usage is
58 * created in memory. If you want it to persist, you will need to call
59 * {@link save_questions_usage_by_activity()}.
60 *
61 * @param string $component the plugin creating this attempt. For example mod_quiz.
62 * @param object $context the context this usage belongs to.
63 * @return question_usage_by_activity the newly created object.
64 */
65 public static function make_questions_usage_by_activity($component, $context) {
66 return new question_usage_by_activity($component, $context);
67 }
68
69 /**
70 * Load a {@link question_usage_by_activity} from the database, based on its id.
f7970e3c 71 * @param int $qubaid the id of the usage to load.
d1b7e03d
TH
72 * @return question_usage_by_activity loaded from the database.
73 */
74 public static function load_questions_usage_by_activity($qubaid) {
75 $dm = new question_engine_data_mapper();
76 return $dm->load_questions_usage_by_activity($qubaid);
77 }
78
79 /**
80 * Save a {@link question_usage_by_activity} to the database. This works either
81 * if the usage was newly created by {@link make_questions_usage_by_activity()}
82 * or loaded from the database using {@link load_questions_usage_by_activity()}
83 * @param question_usage_by_activity the usage to save.
84 */
85 public static function save_questions_usage_by_activity(question_usage_by_activity $quba) {
86 $dm = new question_engine_data_mapper();
87 $observer = $quba->get_observer();
88 if ($observer instanceof question_engine_unit_of_work) {
89 $observer->save($dm);
90 } else {
91 $dm->insert_questions_usage_by_activity($quba);
92 }
93 }
94
95 /**
96 * Delete a {@link question_usage_by_activity} from the database, based on its id.
f7970e3c 97 * @param int $qubaid the id of the usage to delete.
d1b7e03d
TH
98 */
99 public static function delete_questions_usage_by_activity($qubaid) {
100 global $CFG;
c76145d3 101 self::delete_questions_usage_by_activities('{question_usages}.id = :qubaid', array('qubaid' => $qubaid));
d1b7e03d
TH
102 }
103
104 /**
2daffca5
TH
105 * Delete {@link question_usage_by_activity}s from the database that match
106 * an arbitrary SQL where clause.
107 * @param string $where a where clause. Becuase of MySQL limitations, you
108 * must refer to {question_usages}.id in full like that.
109 * @param array $params values to substitute for placeholders in $where.
d1b7e03d 110 */
c76145d3 111 public static function delete_questions_usage_by_activities($where, $params) {
d1b7e03d 112 $dm = new question_engine_data_mapper();
c76145d3 113 $dm->delete_questions_usage_by_activities($where, $params);
d1b7e03d
TH
114 }
115
116 /**
117 * Change the maxmark for the question_attempt with number in usage $slot
118 * for all the specified question_attempts.
119 * @param qubaid_condition $qubaids Selects which usages are updated.
f7970e3c 120 * @param int $slot the number is usage to affect.
d1b7e03d
TH
121 * @param number $newmaxmark the new max mark to set.
122 */
123 public static function set_max_mark_in_attempts(qubaid_condition $qubaids,
124 $slot, $newmaxmark) {
125 $dm = new question_engine_data_mapper();
126 $dm->set_max_mark_in_attempts($qubaids, $slot, $newmaxmark);
127 }
128
129 /**
130 * @param array $questionids of question ids.
07f88584
TH
131 * @param qubaid_condition $qubaids ids of the usages to consider.
132 * @return boolean whether any of these questions are being used by any of
133 * those usages.
d1b7e03d 134 */
07f88584
TH
135 public static function questions_in_use(array $questionids, qubaid_condition $qubaids = null) {
136 if (is_null($qubaids)) {
137 return false;
138 }
d1b7e03d 139 $dm = new question_engine_data_mapper();
07f88584 140 return $dm->questions_in_use($questionids, $qubaids);
d1b7e03d
TH
141 }
142
143 /**
144 * Create an archetypal behaviour for a particular question attempt.
145 * Used by {@link question_definition::make_behaviour()}.
146 *
147 * @param string $preferredbehaviour the type of model required.
148 * @param question_attempt $qa the question attempt the model will process.
149 * @return question_behaviour an instance of appropriate behaviour class.
150 */
151 public static function make_archetypal_behaviour($preferredbehaviour, question_attempt $qa) {
152 question_engine::load_behaviour_class($preferredbehaviour);
153 $class = 'qbehaviour_' . $preferredbehaviour;
154 if (!constant($class . '::IS_ARCHETYPAL')) {
88f0eb15 155 throw new coding_exception('The requested behaviour is not actually an archetypal one.');
d1b7e03d
TH
156 }
157 return new $class($qa, $preferredbehaviour);
158 }
159
160 /**
161 * @param string $behaviour the name of a behaviour.
162 * @return array of {@link question_display_options} field names, that are
163 * not relevant to this behaviour before a 'finish' action.
164 */
165 public static function get_behaviour_unused_display_options($behaviour) {
166 self::load_behaviour_class($behaviour);
167 $class = 'qbehaviour_' . $behaviour;
168 if (!method_exists($class, 'get_unused_display_options')) {
169 return question_behaviour::get_unused_display_options();
170 }
171 return call_user_func(array($class, 'get_unused_display_options'));
172 }
173
174 /**
175 * Create an behaviour for a particular type. If that type cannot be
176 * found, return an instance of qbehaviour_missing.
177 *
178 * Normally you should use {@link make_archetypal_behaviour()}, or
179 * call the constructor of a particular model class directly. This method
180 * is only intended for use by {@link question_attempt::load_from_records()}.
181 *
182 * @param string $behaviour the type of model to create.
183 * @param question_attempt $qa the question attempt the model will process.
184 * @param string $preferredbehaviour the preferred behaviour for the containing usage.
185 * @return question_behaviour an instance of appropriate behaviour class.
186 */
187 public static function make_behaviour($behaviour, question_attempt $qa, $preferredbehaviour) {
188 try {
189 self::load_behaviour_class($behaviour);
190 } catch (Exception $e) {
191 question_engine::load_behaviour_class('missing');
192 return new qbehaviour_missing($qa, $preferredbehaviour);
193 }
194 $class = 'qbehaviour_' . $behaviour;
195 return new $class($qa, $preferredbehaviour);
196 }
197
198 /**
199 * Load the behaviour class(es) belonging to a particular model. That is,
200 * include_once('/question/behaviour/' . $behaviour . '/behaviour.php'), with a bit
201 * of checking.
202 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
203 */
204 public static function load_behaviour_class($behaviour) {
205 global $CFG;
206 if (isset(self::$loadedbehaviours[$behaviour])) {
207 return;
208 }
209 $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviour.php';
210 if (!is_readable($file)) {
88f0eb15 211 throw new coding_exception('Unknown question behaviour ' . $behaviour);
d1b7e03d
TH
212 }
213 include_once($file);
214 self::$loadedbehaviours[$behaviour] = 1;
215 }
216
217 /**
218 * Return an array where the keys are the internal names of the archetypal
219 * behaviours, and the values are a human-readable name. An
220 * archetypal behaviour is one that is suitable to pass the name of to
221 * {@link question_usage_by_activity::set_preferred_behaviour()}.
222 *
223 * @return array model name => lang string for this behaviour name.
224 */
225 public static function get_archetypal_behaviours() {
226 $archetypes = array();
227 $behaviours = get_list_of_plugins('question/behaviour');
228 foreach ($behaviours as $path) {
229 $behaviour = basename($path);
230 self::load_behaviour_class($behaviour);
231 $plugin = 'qbehaviour_' . $behaviour;
232 if (constant($plugin . '::IS_ARCHETYPAL')) {
233 $archetypes[$behaviour] = self::get_behaviour_name($behaviour);
234 }
235 }
236 asort($archetypes, SORT_LOCALE_STRING);
237 return $archetypes;
238 }
239
240 /**
241 * Return an array where the keys are the internal names of the behaviours
242 * in preferred order and the values are a human-readable name.
243 *
244 * @param array $archetypes, array of behaviours
245 * @param string $questionbehavioursorder, a comma separated list of behaviour names
246 * @param string $questionbehavioursdisabled, a comma separated list of behaviour names
247 * @param string $currentbahaviour, current behaviour name
248 * @return array model name => lang string for this behaviour name.
249 */
250 public static function sort_behaviours($archetypes, $questionbehavioursorder,
251 $questionbehavioursdisabled, $currentbahaviour) {
252 $behaviourorder = array();
253 $behaviourdisabled = array();
254
255 // Get disabled behaviours
256 if ($questionbehavioursdisabled) {
257 $behaviourdisabledtemp = preg_split('/[\s,;]+/', $questionbehavioursdisabled);
258 } else {
259 $behaviourdisabledtemp = array();
260 }
261
262 if ($questionbehavioursorder) {
263 $behaviourordertemp = preg_split('/[\s,;]+/', $questionbehavioursorder);
264 } else {
265 $behaviourordertemp = array();
266 }
267
268 foreach ($behaviourdisabledtemp as $key) {
269 if (array_key_exists($key, $archetypes)) {
270 // Do not disable the current behaviour
271 if ($key != $currentbahaviour) {
272 $behaviourdisabled[$key] = $archetypes[$key];
273 }
274 }
275 }
276
277 // Get behaviours in preferred order
278 foreach ($behaviourordertemp as $key) {
279 if (array_key_exists($key, $archetypes)) {
280 $behaviourorder[$key] = $archetypes[$key];
281 }
282 }
283 // Get the rest of behaviours and sort them alphabetically
284 $leftover = array_diff_key($archetypes, $behaviourdisabled, $behaviourorder);
285 asort($leftover, SORT_LOCALE_STRING);
286
287 // Set up the final order to be displayed
288 $finalorder = $behaviourorder + $leftover;
289 return $finalorder;
290 }
291
292 /**
293 * Return an array where the keys are the internal names of the behaviours
294 * in preferred order and the values are a human-readable name.
295 *
296 * @param string $currentbahaviour
297 * @return array model name => lang string for this behaviour name.
298 */
299 public static function get_behaviour_options($currentbahaviour) {
300 global $CFG;
301 $archetypes = self::get_archetypal_behaviours();
302
303 // If no admin setting return all behavious
c76145d3 304 if (empty($CFG->questionbehavioursdisabled) && empty($CFG->questionbehavioursorder)) {
d1b7e03d
TH
305 return $archetypes;
306 }
307
308 return self::sort_behaviours($archetypes, $CFG->questionbehavioursorder,
309 $CFG->questionbehavioursdisabled, $currentbahaviour);
310 }
311
312 /**
313 * Get the translated name of an behaviour, for display in the UI.
314 * @param string $behaviour the internal name of the model.
315 * @return string name from the current language pack.
316 */
317 public static function get_behaviour_name($behaviour) {
aa9bdbe3 318 return get_string('pluginname', 'qbehaviour_' . $behaviour);
d1b7e03d
TH
319 }
320
321 /**
322 * Returns the valid choices for the number of decimal places for showing
323 * question marks. For use in the user interface.
324 * @return array suitable for passing to {@link choose_from_menu()} or similar.
325 */
326 public static function get_dp_options() {
327 return question_display_options::get_dp_options();
328 }
329
330 public static function initialise_js() {
331 return question_flags::initialise_js();
332 }
333}
334
335
336/**
337 * This class contains all the options that controls how a question is displayed.
338 *
339 * Normally, what will happen is that the calling code will set up some display
340 * options to indicate what sort of question display it wants, and then before the
341 * question is rendered, the behaviour will be given a chance to modify the
342 * display options, so that, for example, A question that is finished will only
343 * be shown read-only, and a question that has not been submitted will not have
344 * any sort of feedback displayed.
345 *
017bc1d9
TH
346 * @copyright 2009 The Open University
347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
348 */
349class question_display_options {
350 /**#@+ @var integer named constants for the values that most of the options take. */
351 const HIDDEN = 0;
352 const VISIBLE = 1;
353 const EDITABLE = 2;
354 /**#@-*/
355
356 /**#@+ @var integer named constants for the {@link $marks} option. */
357 const MAX_ONLY = 1;
358 const MARK_AND_MAX = 2;
359 /**#@-*/
360
361 /**
362 * @var integer maximum value for the {@link $markpd} option. This is
363 * effectively set by the database structure, which uses NUMBER(12,7) columns
364 * for question marks/fractions.
365 */
366 const MAX_DP = 7;
367
368 /**
369 * @var boolean whether the question should be displayed as a read-only review,
370 * or in an active state where you can change the answer.
371 */
372 public $readonly = false;
373
374 /**
375 * @var boolean whether the question type should output hidden form fields
376 * to reset any incorrect parts of the resonse to blank.
377 */
378 public $clearwrong = false;
379
380 /**
381 * Should the student have what they got right and wrong clearly indicated.
382 * This includes the green/red hilighting of the bits of their response,
383 * whether the one-line summary of the current state of the question says
384 * correct/incorrect or just answered.
385 * @var integer {@link question_display_options::HIDDEN} or
386 * {@link question_display_options::VISIBLE}
387 */
388 public $correctness = self::VISIBLE;
389
390 /**
391 * The the mark and/or the maximum available mark for this question be visible?
392 * @var integer {@link question_display_options::HIDDEN},
393 * {@link question_display_options::MAX_ONLY} or {@link question_display_options::MARK_AND_MAX}
394 */
395 public $marks = self::MARK_AND_MAX;
396
397 /** @var number of decimal places to use when formatting marks for output. */
398 public $markdp = 2;
399
400 /**
401 * Should the flag this question UI element be visible, and if so, should the
402 * flag state be changable?
403 * @var integer {@link question_display_options::HIDDEN},
404 * {@link question_display_options::VISIBLE} or {@link question_display_options::EDITABLE}
405 */
406 public $flags = self::VISIBLE;
407
408 /**
409 * Should the specific feedback be visible.
410 * @var integer {@link question_display_options::HIDDEN} or
411 * {@link question_display_options::VISIBLE}
412 */
413 public $feedback = self::VISIBLE;
414
415 /**
416 * For questions with a number of sub-parts (like matching, or
417 * multiple-choice, multiple-reponse) display the number of sub-parts that
418 * were correct.
419 * @var integer {@link question_display_options::HIDDEN} or
420 * {@link question_display_options::VISIBLE}
421 */
422 public $numpartscorrect = self::VISIBLE;
423
424 /**
425 * Should the general feedback be visible?
426 * @var integer {@link question_display_options::HIDDEN} or
427 * {@link question_display_options::VISIBLE}
428 */
429 public $generalfeedback = self::VISIBLE;
430
431 /**
432 * Should the automatically generated display of what the correct answer is
433 * be visible?
434 * @var integer {@link question_display_options::HIDDEN} or
435 * {@link question_display_options::VISIBLE}
436 */
437 public $rightanswer = self::VISIBLE;
438
439 /**
440 * Should the manually added marker's comment be visible. Should the link for
441 * adding/editing the comment be there.
442 * @var integer {@link question_display_options::HIDDEN},
443 * {@link question_display_options::VISIBLE}, or {@link question_display_options::EDITABLE}.
444 * Editable means that form fields are displayed inline.
445 */
446 public $manualcomment = self::VISIBLE;
447
448 /**
449 * Should we show a 'Make comment or override grade' link?
450 * @var string base URL for the edit comment script, which will be shown if
451 * $manualcomment = self::VISIBLE.
452 */
453 public $manualcommentlink = null;
454
455 /**
456 * Used in places like the question history table, to show a link to review
457 * this question in a certain state. If blank, a link is not shown.
458 * @var string base URL for a review question script.
459 */
460 public $questionreviewlink = null;
461
462 /**
463 * Should the history of previous question states table be visible?
464 * @var integer {@link question_display_options::HIDDEN} or
465 * {@link question_display_options::VISIBLE}
466 */
467 public $history = self::HIDDEN;
468
469 /**
470 * Set all the feedback-related fields {@link $feedback}, {@link generalfeedback},
471 * {@link rightanswer} and {@link manualcomment} to
472 * {@link question_display_options::HIDDEN}.
473 */
474 public function hide_all_feedback() {
475 $this->feedback = self::HIDDEN;
476 $this->numpartscorrect = self::HIDDEN;
477 $this->generalfeedback = self::HIDDEN;
478 $this->rightanswer = self::HIDDEN;
479 $this->manualcomment = self::HIDDEN;
480 $this->correctness = self::HIDDEN;
481 }
482
483 /**
484 * Returns the valid choices for the number of decimal places for showing
485 * question marks. For use in the user interface.
486 *
487 * Calling code should probably use {@link question_engine::get_dp_options()}
488 * rather than calling this method directly.
489 *
490 * @return array suitable for passing to {@link choose_from_menu()} or similar.
491 */
492 public static function get_dp_options() {
493 $options = array();
494 for ($i = 0; $i <= self::MAX_DP; $i += 1) {
495 $options[$i] = $i;
496 }
497 return $options;
498 }
499}
500
501
502/**
503 * Contains the logic for handling question flags.
504 *
f7970e3c 505 * @copyright 2010 The Open University
017bc1d9 506 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
507 */
508abstract class question_flags {
509 /**
510 * Get the checksum that validates that a toggle request is valid.
f7970e3c
TH
511 * @param int $qubaid the question usage id.
512 * @param int $questionid the question id.
513 * @param int $sessionid the question_attempt id.
d1b7e03d
TH
514 * @param object $user the user. If null, defaults to $USER.
515 * @return string that needs to be sent to question/toggleflag.php for it to work.
516 */
06f8ed54 517 protected static function get_toggle_checksum($qubaid, $questionid, $qaid, $slot, $user = null) {
d1b7e03d
TH
518 if (is_null($user)) {
519 global $USER;
520 $user = $USER;
521 }
06f8ed54 522 return md5($qubaid . "_" . $user->secret . "_" . $questionid . "_" . $qaid . "_" . $slot);
d1b7e03d
TH
523 }
524
525 /**
526 * Get the postdata that needs to be sent to question/toggleflag.php to change the flag state.
527 * You need to append &newstate=0/1 to this.
528 * @return the post data to send.
529 */
530 public static function get_postdata(question_attempt $qa) {
531 $qaid = $qa->get_database_id();
532 $qubaid = $qa->get_usage_id();
533 $qid = $qa->get_question()->id;
06f8ed54
TH
534 $slot = $qa->get_slot();
535 $checksum = self::get_toggle_checksum($qubaid, $qid, $qaid, $slot);
404da238
TH
536 return "qaid=$qaid&qubaid=$qubaid&qid=$qid&slot=$slot&checksum=$checksum&sesskey=" .
537 sesskey() . '&newstate=';
d1b7e03d
TH
538 }
539
540 /**
541 * If the request seems valid, update the flag state of a question attempt.
542 * Throws exceptions if this is not a valid update request.
f7970e3c
TH
543 * @param int $qubaid the question usage id.
544 * @param int $questionid the question id.
545 * @param int $sessionid the question_attempt id.
d1b7e03d
TH
546 * @param string $checksum checksum, as computed by {@link get_toggle_checksum()}
547 * corresponding to the last three arguments.
f7970e3c 548 * @param bool $newstate the new state of the flag. true = flagged.
d1b7e03d 549 */
06f8ed54 550 public static function update_flag($qubaid, $questionid, $qaid, $slot, $checksum, $newstate) {
d1b7e03d 551 // Check the checksum - it is very hard to know who a question session belongs
f9b0500f 552 // to, so we require that checksum parameter is matches an md5 hash of the
d1b7e03d
TH
553 // three ids and the users username. Since we are only updating a flag, that
554 // probably makes it sufficiently difficult for malicious users to toggle
555 // other users flags.
06f8ed54 556 if ($checksum != question_flags::get_toggle_checksum($qubaid, $questionid, $qaid, $slot)) {
88f0eb15 557 throw new moodle_exception('errorsavingflags', 'question');
d1b7e03d
TH
558 }
559
560 $dm = new question_engine_data_mapper();
06f8ed54 561 $dm->update_question_attempt_flag($qubaid, $questionid, $qaid, $slot, $newstate);
d1b7e03d
TH
562 }
563
564 public static function initialise_js() {
f29aeb5a
TH
565 global $CFG, $PAGE, $OUTPUT;
566 static $done = false;
567 if ($done) {
568 return;
569 }
570 $module = array(
571 'name' => 'core_question_flags',
572 'fullpath' => '/question/flags.js',
573 'requires' => array('base', 'dom', 'event-delegate', 'io-base'),
574 );
575 $actionurl = $CFG->wwwroot . '/question/toggleflag.php';
576 $flagattributes = array(
577 0 => array(
578 'src' => $OUTPUT->pix_url('i/unflagged') . '',
579 'title' => get_string('clicktoflag', 'question'),
580 'alt' => get_string('notflagged', 'question'),
581 ),
582 1 => array(
583 'src' => $OUTPUT->pix_url('i/flagged') . '',
584 'title' => get_string('clicktounflag', 'question'),
585 'alt' => get_string('flagged', 'question'),
586 ),
d1b7e03d 587 );
f29aeb5a
TH
588 $PAGE->requires->js_init_call('M.core_question_flags.init',
589 array($actionurl, $flagattributes), false, $module);
590 $done = true;
d1b7e03d
TH
591 }
592}
593
594
f7970e3c
TH
595/**
596 * Exception thrown when the system detects that a student has done something
597 * out-of-order to a question. This can happen, for example, if they click
5e8a85aa 598 * the browser's back button in a quiz, then try to submit a different response.
f7970e3c
TH
599 *
600 * @copyright 2010 The Open University
601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
602 */
d1b7e03d
TH
603class question_out_of_sequence_exception extends moodle_exception {
604 function __construct($qubaid, $slot, $postdata) {
605 if ($postdata == null) {
606 $postdata = data_submitted();
607 }
608 parent::__construct('submissionoutofsequence', 'question', '', null,
609 "QUBAid: $qubaid, slot: $slot, post data: " . print_r($postdata, true));
610 }
611}
612
613
614/**
615 * This class keeps track of a group of questions that are being attempted,
616 * and which state, and so on, each one is currently in.
617 *
618 * A quiz attempt or a lesson attempt could use an instance of this class to
619 * keep track of all the questions in the attempt and process student submissions.
620 * It is basically a collection of {@question_attempt} objects.
621 *
622 * The questions being attempted as part of this usage are identified by an integer
623 * that is passed into many of the methods as $slot. ($question->id is not
624 * used so that the same question can be used more than once in an attempt.)
625 *
626 * Normally, calling code should be able to do everything it needs to be calling
627 * methods of this class. You should not normally need to get individual
628 * {@question_attempt} objects and play around with their inner workind, in code
629 * that it outside the quetsion engine.
630 *
631 * Instances of this class correspond to rows in the question_usages table.
632 *
017bc1d9
TH
633 * @copyright 2009 The Open University
634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
635 */
636class question_usage_by_activity {
637 /**
638 * @var integer|string the id for this usage. If this usage was loaded from
639 * the database, then this is the database id. Otherwise a unique random
640 * string is used.
641 */
642 protected $id = null;
643
644 /**
645 * @var string name of an archetypal behaviour, that should be used
646 * by questions in this usage if possible.
647 */
648 protected $preferredbehaviour = null;
649
650 /** @var object the context this usage belongs to. */
651 protected $context;
652
653 /** @var string plugin name of the plugin this usage belongs to. */
654 protected $owningcomponent;
655
656 /** @var array {@link question_attempt}s that make up this usage. */
657 protected $questionattempts = array();
658
659 /** @var question_usage_observer that tracks changes to this usage. */
660 protected $observer;
661
662 /**
663 * Create a new instance. Normally, calling code should use
664 * {@link question_engine::make_questions_usage_by_activity()} or
665 * {@link question_engine::load_questions_usage_by_activity()} rather than
666 * calling this constructor directly.
667 *
668 * @param string $component the plugin creating this attempt. For example mod_quiz.
669 * @param object $context the context this usage belongs to.
670 */
671 public function __construct($component, $context) {
672 $this->owningcomponent = $component;
673 $this->context = $context;
674 $this->observer = new question_usage_null_observer();
675 }
676
677 /**
678 * @param string $behaviour the name of an archetypal behaviour, that should
679 * be used by questions in this usage if possible.
680 */
681 public function set_preferred_behaviour($behaviour) {
682 $this->preferredbehaviour = $behaviour;
683 $this->observer->notify_modified();
684 }
685
686 /** @return string the name of the preferred behaviour. */
687 public function get_preferred_behaviour() {
688 return $this->preferredbehaviour;
689 }
690
0ff4bd08 691 /** @return object the context this usage belongs to. */
d1b7e03d
TH
692 public function get_owning_context() {
693 return $this->context;
694 }
695
696 /** @return string the name of the plugin that owns this attempt. */
697 public function get_owning_component() {
698 return $this->owningcomponent;
699 }
700
f7970e3c 701 /** @return int|string If this usage came from the database, then the id
d1b7e03d
TH
702 * from the question_usages table is returned. Otherwise a random string is
703 * returned. */
704 public function get_id() {
705 if (is_null($this->id)) {
706 $this->id = random_string(10);
707 }
708 return $this->id;
709 }
710
711 /** @return question_usage_observer that is tracking changes made to this usage. */
712 public function get_observer() {
713 return $this->observer;
714 }
715
716 /**
717 * For internal use only. Used by {@link question_engine_data_mapper} to set
718 * the id when a usage is saved to the database.
f7970e3c 719 * @param int $id the newly determined id for this usage.
d1b7e03d
TH
720 */
721 public function set_id_from_database($id) {
722 $this->id = $id;
723 foreach ($this->questionattempts as $qa) {
724 $qa->set_usage_id($id);
725 }
726 }
727
728 /**
729 * Add another question to this usage.
730 *
731 * The added question is not started until you call {@link start_question()}
732 * on it.
733 *
734 * @param question_definition $question the question to add.
735 * @param number $maxmark the maximum this question will be marked out of in
736 * this attempt (optional). If not given, $question->defaultmark is used.
f7970e3c 737 * @return int the number used to identify this question within this usage.
d1b7e03d
TH
738 */
739 public function add_question(question_definition $question, $maxmark = null) {
2daffca5 740 $qa = new question_attempt($question, $this->get_id(), $this->observer, $maxmark);
d1b7e03d
TH
741 if (count($this->questionattempts) == 0) {
742 $this->questionattempts[1] = $qa;
743 } else {
744 $this->questionattempts[] = $qa;
745 }
746 $qa->set_number_in_usage(end(array_keys($this->questionattempts)));
747 $this->observer->notify_attempt_added($qa);
748 return $qa->get_slot();
749 }
750
751 /**
752 * Get the question_definition for a question in this attempt.
f7970e3c 753 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
754 * @return question_definition the requested question object.
755 */
756 public function get_question($slot) {
757 return $this->get_question_attempt($slot)->get_question();
758 }
759
760 /** @return array all the identifying numbers of all the questions in this usage. */
a1eb3a44 761 public function get_slots() {
d1b7e03d
TH
762 return array_keys($this->questionattempts);
763 }
764
f7970e3c 765 /** @return int the identifying number of the first question that was added to this usage. */
d1b7e03d
TH
766 public function get_first_question_number() {
767 reset($this->questionattempts);
768 return key($this->questionattempts);
769 }
770
f7970e3c 771 /** @return int the number of questions that are currently in this usage. */
d1b7e03d
TH
772 public function question_count() {
773 return count($this->questionattempts);
774 }
775
776 /**
777 * Note the part of the {@link question_usage_by_activity} comment that explains
778 * that {@link question_attempt} objects should be considered part of the inner
779 * workings of the question engine, and should not, if possible, be accessed directly.
780 *
781 * @return question_attempt_iterator for iterating over all the questions being
782 * attempted. as part of this usage.
783 */
784 public function get_attempt_iterator() {
785 return new question_attempt_iterator($this);
786 }
787
788 /**
789 * Check whether $number actually corresponds to a question attempt that is
790 * part of this usage. Throws an exception if not.
791 *
f7970e3c 792 * @param int $slot a number allegedly identifying a question within this usage.
d1b7e03d
TH
793 */
794 protected function check_slot($slot) {
795 if (!array_key_exists($slot, $this->questionattempts)) {
88f0eb15 796 throw new coding_exception("There is no question_attempt number $slot in this attempt.");
d1b7e03d
TH
797 }
798 }
799
800 /**
801 * Note the part of the {@link question_usage_by_activity} comment that explains
802 * that {@link question_attempt} objects should be considered part of the inner
803 * workings of the question engine, and should not, if possible, be accessed directly.
804 *
f7970e3c 805 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
806 * @return question_attempt the corresponding {@link question_attempt} object.
807 */
808 public function get_question_attempt($slot) {
809 $this->check_slot($slot);
810 return $this->questionattempts[$slot];
811 }
812
813 /**
814 * Get the current state of the attempt at a question.
f7970e3c 815 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
816 * @return question_state.
817 */
818 public function get_question_state($slot) {
819 return $this->get_question_attempt($slot)->get_state();
820 }
821
822 /**
f7970e3c
TH
823 * @param int $slot the number used to identify this question within this usage.
824 * @param bool $showcorrectness Whether right/partial/wrong states should
d1b7e03d
TH
825 * be distinguised.
826 * @return string A brief textual description of the current state.
827 */
828 public function get_question_state_string($slot, $showcorrectness) {
829 return $this->get_question_attempt($slot)->get_state_string($showcorrectness);
830 }
831
832 /**
833 * Get the time of the most recent action performed on a question.
f7970e3c
TH
834 * @param int $slot the number used to identify this question within this usage.
835 * @return int timestamp.
d1b7e03d
TH
836 */
837 public function get_question_action_time($slot) {
838 return $this->get_question_attempt($slot)->get_last_action_time();
839 }
840
841 /**
842 * Get the current fraction awarded for the attempt at a question.
f7970e3c 843 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
844 * @return number|null The current fraction for this question, or null if one has
845 * not been assigned yet.
846 */
847 public function get_question_fraction($slot) {
848 return $this->get_question_attempt($slot)->get_fraction();
849 }
850
851 /**
852 * Get the current mark awarded for the attempt at a question.
f7970e3c 853 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
854 * @return number|null The current mark for this question, or null if one has
855 * not been assigned yet.
856 */
857 public function get_question_mark($slot) {
858 return $this->get_question_attempt($slot)->get_mark();
859 }
860
861 /**
862 * Get the maximum mark possible for the attempt at a question.
f7970e3c 863 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
864 * @return number the available marks for this question.
865 */
866 public function get_question_max_mark($slot) {
867 return $this->get_question_attempt($slot)->get_max_mark();
868 }
869
870 /**
871 * Get the current mark awarded for the attempt at a question.
f7970e3c 872 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
873 * @return number|null The current mark for this question, or null if one has
874 * not been assigned yet.
875 */
876 public function get_total_mark() {
877 $mark = 0;
878 foreach ($this->questionattempts as $qa) {
f86390dc 879 if ($qa->get_max_mark() > 0 && $qa->get_state() == question_state::$needsgrading) {
d1b7e03d
TH
880 return null;
881 }
882 $mark += $qa->get_mark();
883 }
884 return $mark;
885 }
886
887 /**
888 * @return string a simple textual summary of the question that was asked.
889 */
890 public function get_question_summary($slot) {
891 return $this->get_question_attempt($slot)->get_question_summary();
892 }
893
894 /**
895 * @return string a simple textual summary of response given.
896 */
897 public function get_response_summary($slot) {
898 return $this->get_question_attempt($slot)->get_response_summary();
899 }
900
901 /**
902 * @return string a simple textual summary of the correct resonse.
903 */
904 public function get_right_answer_summary($slot) {
905 return $this->get_question_attempt($slot)->get_right_answer_summary();
906 }
907
908 /**
909 * Get the {@link core_question_renderer}, in collaboration with appropriate
910 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
911 * HTML to display this question.
f7970e3c 912 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
913 * @param question_display_options $options controls how the question is rendered.
914 * @param string|null $number The question number to display. 'i' is a special
915 * value that gets displayed as Information. Null means no number is displayed.
916 * @return string HTML fragment representing the question.
917 */
918 public function render_question($slot, $options, $number = null) {
919 return $this->get_question_attempt($slot)->render($options, $number);
920 }
921
922 /**
923 * Generate any bits of HTML that needs to go in the <head> tag when this question
924 * is displayed in the body.
f7970e3c 925 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
926 * @return string HTML fragment.
927 */
928 public function render_question_head_html($slot) {
929 return $this->get_question_attempt($slot)->render_head_html();
930 }
931
932 /**
933 * Like {@link render_question()} but displays the question at the past step
934 * indicated by $seq, rather than showing the latest step.
935 *
f7970e3c
TH
936 * @param int $slot the number used to identify this question within this usage.
937 * @param int $seq the seq number of the past state to display.
d1b7e03d
TH
938 * @param question_display_options $options controls how the question is rendered.
939 * @param string|null $number The question number to display. 'i' is a special
940 * value that gets displayed as Information. Null means no number is displayed.
941 * @return string HTML fragment representing the question.
942 */
943 public function render_question_at_step($slot, $seq, $options, $number = null) {
944 return $this->get_question_attempt($slot)->render_at_step($seq, $options, $number, $this->preferredbehaviour);
945 }
946
7a719748
TH
947 /**
948 * Checks whether the users is allow to be served a particular file.
f7970e3c 949 * @param int $slot the number used to identify this question within this usage.
7a719748
TH
950 * @param question_display_options $options the options that control display of the question.
951 * @param string $component the name of the component we are serving files for.
952 * @param string $filearea the name of the file area.
953 * @param array $args the remaining bits of the file path.
f7970e3c
TH
954 * @param bool $forcedownload whether the user must be forced to download the file.
955 * @return bool true if the user can access this file.
7a719748
TH
956 */
957 public function check_file_access($slot, $options, $component, $filearea, $args, $forcedownload) {
958 return $this->get_question_attempt($slot)->check_file_access($options, $component, $filearea, $args, $forcedownload);
959 }
960
d1b7e03d
TH
961 /**
962 * Replace a particular question_attempt with a different one.
963 *
964 * For internal use only. Used when reloading the state of a question from the
965 * database.
966 *
967 * @param array $records Raw records loaded from the database.
f7970e3c 968 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
969 * @return question_attempt The newly constructed question_attempt_step.
970 */
971 public function replace_loaded_question_attempt_info($slot, $qa) {
972 $this->check_slot($slot);
973 $this->questionattempts[$slot] = $qa;
974 }
975
976 /**
977 * You should probably not use this method in code outside the question engine.
978 * The main reason for exposing it was for the benefit of unit tests.
f7970e3c 979 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
980 * @return string return the prefix that is pre-pended to field names in the HTML
981 * that is output.
982 */
983 public function get_field_prefix($slot) {
984 return $this->get_question_attempt($slot)->get_field_prefix();
985 }
986
987 /**
988 * Start the attempt at a question that has been added to this usage.
f7970e3c 989 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
990 */
991 public function start_question($slot) {
992 $qa = $this->get_question_attempt($slot);
993 $qa->start($this->preferredbehaviour);
994 $this->observer->notify_attempt_modified($qa);
995 }
996
997 /**
998 * Start the attempt at all questions that has been added to this usage.
999 */
1000 public function start_all_questions() {
1001 foreach ($this->questionattempts as $qa) {
1002 $qa->start($this->preferredbehaviour);
1003 $this->observer->notify_attempt_modified($qa);
1004 }
1005 }
1006
1007 /**
1008 * Start the attempt at a question, starting from the point where the previous
1009 * question_attempt $oldqa had reached. This is used by the quiz 'Each attempt
1010 * builds on last' mode.
f7970e3c 1011 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1012 * @param question_attempt $oldqa a previous attempt at this quetsion that
1013 * defines the starting point.
1014 */
1015 public function start_question_based_on($slot, question_attempt $oldqa) {
1016 $qa = $this->get_question_attempt($slot);
1017 $qa->start_based_on($oldqa);
1018 $this->observer->notify_attempt_modified($qa);
1019 }
1020
1021 /**
1022 * Process all the question actions in the current request.
1023 *
1024 * If there is a parameter slots included in the post data, then only
1025 * those question numbers will be processed, otherwise all questions in this
1026 * useage will be.
1027 *
1028 * This function also does {@link update_question_flags()}.
1029 *
f7970e3c 1030 * @param int $timestamp optional, use this timestamp as 'now'.
d1b7e03d
TH
1031 * @param array $postdata optional, only intended for testing. Use this data
1032 * instead of the data from $_POST.
1033 */
1034 public function process_all_actions($timestamp = null, $postdata = null) {
1035 $slots = question_attempt::get_submitted_var('slots', PARAM_SEQUENCE, $postdata);
1036 if (is_null($slots)) {
a1eb3a44 1037 $slots = $this->get_slots();
d1b7e03d
TH
1038 } else if (!$slots) {
1039 $slots = array();
1040 } else {
1041 $slots = explode(',', $slots);
1042 }
1043 foreach ($slots as $slot) {
1044 $this->validate_sequence_number($slot, $postdata);
1045 $submitteddata = $this->extract_responses($slot, $postdata);
1046 $this->process_action($slot, $submitteddata, $timestamp);
1047 }
1048 $this->update_question_flags($postdata);
1049 }
1050
1051 /**
1052 * Get the submitted data from the current request that belongs to this
1053 * particular question.
1054 *
f7970e3c 1055 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1056 * @param $postdata optional, only intended for testing. Use this data
1057 * instead of the data from $_POST.
1058 * @return array submitted data specific to this question.
1059 */
1060 public function extract_responses($slot, $postdata = null) {
1061 return $this->get_question_attempt($slot)->get_submitted_data($postdata);
1062 }
1063
1064 /**
1065 * Process a specific action on a specific question.
f7970e3c 1066 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1067 * @param $submitteddata the submitted data that constitutes the action.
1068 */
1069 public function process_action($slot, $submitteddata, $timestamp = null) {
1070 $qa = $this->get_question_attempt($slot);
1071 $qa->process_action($submitteddata, $timestamp);
1072 $this->observer->notify_attempt_modified($qa);
1073 }
1074
1075 /**
1076 * Check that the sequence number, that detects weird things like the student
1077 * clicking back, is OK.
f7970e3c 1078 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1079 * @param array $submitteddata the submitted data that constitutes the action.
1080 */
1081 public function validate_sequence_number($slot, $postdata = null) {
1082 $qa = $this->get_question_attempt($slot);
1083 $sequencecheck = question_attempt::get_submitted_var(
1084 $qa->get_control_field_name('sequencecheck'), PARAM_INT, $postdata);
1085 if (!is_null($sequencecheck) && $sequencecheck != $qa->get_num_steps()) {
1086 throw new question_out_of_sequence_exception($this->id, $slot, $postdata);
1087 }
1088 }
1089 /**
1090 * Update the flagged state for all question_attempts in this usage, if their
1091 * flagged state was changed in the request.
1092 *
1093 * @param $postdata optional, only intended for testing. Use this data
1094 * instead of the data from $_POST.
1095 */
1096 public function update_question_flags($postdata = null) {
1097 foreach ($this->questionattempts as $qa) {
1098 $flagged = question_attempt::get_submitted_var(
1099 $qa->get_flag_field_name(), PARAM_BOOL, $postdata);
1100 if (!is_null($flagged) && $flagged != $qa->is_flagged()) {
1101 $qa->set_flagged($flagged);
1102 }
1103 }
d1b7e03d
TH
1104 }
1105
1106 /**
1107 * Get the correct response to a particular question. Passing the results of
1108 * this method to {@link process_action()} will probably result in full marks.
f7970e3c 1109 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1110 * @return array that constitutes a correct response to this question.
1111 */
1112 public function get_correct_response($slot) {
1113 return $this->get_question_attempt($slot)->get_correct_response();
1114 }
1115
1116 /**
1117 * Finish the active phase of an attempt at a question.
1118 *
1119 * This is an external act of finishing the attempt. Think, for example, of
1120 * the 'Submit all and finish' button in the quiz. Some behaviours,
1121 * (for example, immediatefeedback) give a way of finishing the active phase
1122 * of a question attempt as part of a {@link process_action()} call.
1123 *
1124 * After the active phase is over, the only changes possible are things like
1125 * manual grading, or changing the flag state.
1126 *
f7970e3c 1127 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1128 */
1129 public function finish_question($slot, $timestamp = null) {
1130 $qa = $this->get_question_attempt($slot);
1131 $qa->finish($timestamp);
1132 $this->observer->notify_attempt_modified($qa);
1133 }
1134
1135 /**
1136 * Finish the active phase of an attempt at a question. See {@link finish_question()}
1137 * for a fuller description of what 'finish' means.
1138 */
1139 public function finish_all_questions($timestamp = null) {
1140 foreach ($this->questionattempts as $qa) {
1141 $qa->finish($timestamp);
1142 $this->observer->notify_attempt_modified($qa);
1143 }
1144 }
1145
1146 /**
1147 * Perform a manual grading action on a question attempt.
f7970e3c 1148 * @param int $slot the number used to identify this question within this usage.
d1b7e03d
TH
1149 * @param string $comment the comment being added to the question attempt.
1150 * @param number $mark the mark that is being assigned. Can be null to just
1151 * add a comment.
1152 */
1153 public function manual_grade($slot, $comment, $mark) {
1154 $qa = $this->get_question_attempt($slot);
1155 $qa->manual_grade($comment, $mark);
1156 $this->observer->notify_attempt_modified($qa);
1157 }
1158
1159 /**
1160 * Regrade a question in this usage. This replays the sequence of submitted
1161 * actions to recompute the outcomes.
f7970e3c
TH
1162 * @param int $slot the number used to identify this question within this usage.
1163 * @param bool $finished whether the question attempt should be forced to be finished
d1b7e03d
TH
1164 * after the regrade, or whether it may still be in progress (default false).
1165 * @param number $newmaxmark (optional) if given, will change the max mark while regrading.
1166 */
1167 public function regrade_question($slot, $finished = false, $newmaxmark = null) {
1168 $oldqa = $this->get_question_attempt($slot);
1169 if (is_null($newmaxmark)) {
1170 $newmaxmark = $oldqa->get_max_mark();
1171 }
1172
1173 $this->observer->notify_delete_attempt_steps($oldqa);
1174
1175 $newqa = new question_attempt($oldqa->get_question(), $oldqa->get_usage_id(),
2daffca5 1176 $this->observer, $newmaxmark);
d1b7e03d
TH
1177 $newqa->set_database_id($oldqa->get_database_id());
1178 $newqa->regrade($oldqa, $finished);
1179
1180 $this->questionattempts[$slot] = $newqa;
1181 $this->observer->notify_attempt_modified($newqa);
1182 }
1183
1184 /**
1185 * Regrade all the questions in this usage (without changing their max mark).
f7970e3c 1186 * @param bool $finished whether each question should be forced to be finished
d1b7e03d
TH
1187 * after the regrade, or whether it may still be in progress (default false).
1188 */
1189 public function regrade_all_questions($finished = false) {
1190 foreach ($this->questionattempts as $slot => $notused) {
1191 $this->regrade_question($slot, $finished);
1192 }
1193 }
1194
1195 /**
1196 * Create a question_usage_by_activity from records loaded from the database.
1197 *
1198 * For internal use only.
1199 *
1200 * @param array $records Raw records loaded from the database.
f7970e3c 1201 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
1202 * @return question_attempt The newly constructed question_attempt_step.
1203 */
1204 public static function load_from_records(&$records, $qubaid) {
1205 $record = current($records);
1206 while ($record->qubaid != $qubaid) {
1207 $record = next($records);
1208 if (!$record) {
88f0eb15 1209 throw new coding_exception("Question usage $qubaid not found in the database.");
d1b7e03d
TH
1210 }
1211 }
1212
1213 $quba = new question_usage_by_activity($record->component,
1214 get_context_instance_by_id($record->contextid));
1215 $quba->set_id_from_database($record->qubaid);
1216 $quba->set_preferred_behaviour($record->preferredbehaviour);
1217
1218 $quba->observer = new question_engine_unit_of_work($quba);
1219
1220 while ($record && $record->qubaid == $qubaid && !is_null($record->slot)) {
1221 $quba->questionattempts[$record->slot] =
1222 question_attempt::load_from_records($records,
1223 $record->questionattemptid, $quba->observer,
1224 $quba->get_preferred_behaviour());
1225 $record = current($records);
1226 }
1227
1228 return $quba;
1229 }
1230}
1231
1232
1233/**
1234 * A class abstracting access to the
1235 * {@link question_usage_by_activity::$questionattempts} array.
1236 *
1237 * This class snapshots the list of {@link question_attempts} to iterate over
1238 * when it is created. If a question is added to the usage mid-iteration, it
1239 * will now show up.
1240 *
1241 * To create an instance of this class, use
1242 * {@link question_usage_by_activity::get_attempt_iterator()}
1243 *
017bc1d9
TH
1244 * @copyright 2009 The Open University
1245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1246 */
1247class question_attempt_iterator implements Iterator, ArrayAccess {
1248 /** @var question_usage_by_activity that we are iterating over. */
1249 protected $quba;
1250 /** @var array of question numbers. */
1251 protected $slots;
1252
1253 /**
1254 * To create an instance of this class, use {@link question_usage_by_activity::get_attempt_iterator()}.
1255 * @param $quba the usage to iterate over.
1256 */
1257 public function __construct(question_usage_by_activity $quba) {
1258 $this->quba = $quba;
a1eb3a44 1259 $this->slots = $quba->get_slots();
d1b7e03d
TH
1260 $this->rewind();
1261 }
1262
1263 /** @return question_attempt_step */
1264 public function current() {
1265 return $this->offsetGet(current($this->slots));
1266 }
f7970e3c 1267 /** @return int */
d1b7e03d
TH
1268 public function key() {
1269 return current($this->slots);
1270 }
1271 public function next() {
1272 next($this->slots);
1273 }
1274 public function rewind() {
1275 reset($this->slots);
1276 }
f7970e3c 1277 /** @return bool */
d1b7e03d
TH
1278 public function valid() {
1279 return current($this->slots) !== false;
1280 }
1281
f7970e3c 1282 /** @return bool */
d1b7e03d
TH
1283 public function offsetExists($slot) {
1284 return in_array($slot, $this->slots);
1285 }
1286 /** @return question_attempt_step */
1287 public function offsetGet($slot) {
1288 return $this->quba->get_question_attempt($slot);
1289 }
1290 public function offsetSet($slot, $value) {
88f0eb15 1291 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
d1b7e03d
TH
1292 }
1293 public function offsetUnset($slot) {
88f0eb15 1294 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
d1b7e03d
TH
1295 }
1296}
1297
1298
1299/**
1300 * Tracks an attempt at one particular question in a {@link question_usage_by_activity}.
1301 *
1302 * Most calling code should need to access objects of this class. They should be
1303 * able to do everything through the usage interface. This class is an internal
1304 * implementation detail of the question engine.
1305 *
1306 * Instances of this class correspond to rows in the question_attempts table, and
1307 * a collection of {@link question_attempt_steps}. Question inteaction models and
1308 * question types do work with question_attempt objects.
1309 *
017bc1d9
TH
1310 * @copyright 2009 The Open University
1311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1312 */
1313class question_attempt {
1314 /**
1315 * @var string this is a magic value that question types can return from
1316 * {@link question_definition::get_expected_data()}.
1317 */
1318 const USE_RAW_DATA = 'use raw data';
1319
1320 /**
1321 * @var string special value used by manual grading because {@link PARAM_NUMBER}
1322 * converts '' to 0.
1323 */
1324 const PARAM_MARK = 'parammark';
1325
1326 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
1327 protected $id = null;
1328
1329 /** @var integer|string the id of the question_usage_by_activity we belong to. */
1330 protected $usageid;
1331
1332 /** @var integer the number used to identify this question_attempt within the usage. */
1333 protected $slot = null;
1334
1335 /**
1336 * @var question_behaviour the behaviour controlling this attempt.
1337 * null until {@link start()} is called.
1338 */
1339 protected $behaviour = null;
1340
1341 /** @var question_definition the question this is an attempt at. */
1342 protected $question;
1343
1344 /** @var number the maximum mark that can be scored at this question. */
1345 protected $maxmark;
1346
1347 /**
1348 * @var number the minimum fraction that can be scored at this question, so
1349 * the minimum mark is $this->minfraction * $this->maxmark.
1350 */
1351 protected $minfraction = null;
1352
1353 /**
1354 * @var string plain text summary of the variant of the question the
1355 * student saw. Intended for reporting purposes.
1356 */
1357 protected $questionsummary = null;
1358
1359 /**
1360 * @var string plain text summary of the response the student gave.
1361 * Intended for reporting purposes.
1362 */
1363 protected $responsesummary = null;
1364
1365 /**
1366 * @var string plain text summary of the correct response to this question
1367 * variant the student saw. The format should be similar to responsesummary.
1368 * Intended for reporting purposes.
1369 */
1370 protected $rightanswer = null;
1371
1372 /** @var array of {@link question_attempt_step}s. The steps in this attempt. */
1373 protected $steps = array();
1374
1375 /** @var boolean whether the user has flagged this attempt within the usage. */
1376 protected $flagged = false;
1377
1378 /** @var question_usage_observer tracks changes to the useage this attempt is part of.*/
1379 protected $observer;
1380
1381 /**#@+
1382 * Constants used by the intereaction models to indicate whether the current
1383 * pending step should be kept or discarded.
1384 */
1385 const KEEP = true;
1386 const DISCARD = false;
1387 /**#@-*/
1388
1389 /**
1390 * Create a new {@link question_attempt}. Normally you should create question_attempts
1391 * indirectly, by calling {@link question_usage_by_activity::add_question()}.
1392 *
1393 * @param question_definition $question the question this is an attempt at.
f7970e3c 1394 * @param int|string $usageid The id of the
d1b7e03d
TH
1395 * {@link question_usage_by_activity} we belong to. Used by {@link get_field_prefix()}.
1396 * @param question_usage_observer $observer tracks changes to the useage this
1397 * attempt is part of. (Optional, a {@link question_usage_null_observer} is
1398 * used if one is not passed.
1399 * @param number $maxmark the maximum grade for this question_attempt. If not
1400 * passed, $question->defaultmark is used.
1401 */
2daffca5 1402 public function __construct(question_definition $question, $usageid,
d1b7e03d
TH
1403 question_usage_observer $observer = null, $maxmark = null) {
1404 $this->question = $question;
1405 $this->usageid = $usageid;
1406 if (is_null($observer)) {
1407 $observer = new question_usage_null_observer();
1408 }
1409 $this->observer = $observer;
1410 if (!is_null($maxmark)) {
1411 $this->maxmark = $maxmark;
1412 } else {
1413 $this->maxmark = $question->defaultmark;
1414 }
1415 }
1416
1417 /** @return question_definition the question this is an attempt at. */
1418 public function get_question() {
1419 return $this->question;
1420 }
1421
1422 /**
1423 * Set the number used to identify this question_attempt within the usage.
1424 * For internal use only.
f7970e3c 1425 * @param int $slot
d1b7e03d
TH
1426 */
1427 public function set_number_in_usage($slot) {
1428 $this->slot = $slot;
1429 }
1430
f7970e3c 1431 /** @return int the number used to identify this question_attempt within the usage. */
d1b7e03d
TH
1432 public function get_slot() {
1433 return $this->slot;
1434 }
1435
1436 /**
f7970e3c 1437 * @return int the id of row for this question_attempt, if it is stored in the
d1b7e03d
TH
1438 * database. null if not.
1439 */
1440 public function get_database_id() {
1441 return $this->id;
1442 }
1443
1444 /**
1445 * For internal use only. Set the id of the corresponding database row.
f7970e3c 1446 * @param int $id the id of row for this question_attempt, if it is
d1b7e03d
TH
1447 * stored in the database.
1448 */
1449 public function set_database_id($id) {
1450 $this->id = $id;
1451 }
1452
f7970e3c 1453 /** @return int|string the id of the {@link question_usage_by_activity} we belong to. */
d1b7e03d
TH
1454 public function get_usage_id() {
1455 return $this->usageid;
1456 }
1457
1458 /**
1459 * Set the id of the {@link question_usage_by_activity} we belong to.
1460 * For internal use only.
f7970e3c 1461 * @param int|string the new id.
d1b7e03d
TH
1462 */
1463 public function set_usage_id($usageid) {
1464 $this->usageid = $usageid;
1465 }
1466
1467 /** @return string the name of the behaviour that is controlling this attempt. */
1468 public function get_behaviour_name() {
1469 return $this->behaviour->get_name();
1470 }
1471
1472 /**
1473 * For internal use only.
1474 * @return question_behaviour the behaviour that is controlling this attempt.
1475 */
1476 public function get_behaviour() {
1477 return $this->behaviour;
1478 }
1479
1480 /**
1481 * Set the flagged state of this question.
f7970e3c 1482 * @param bool $flagged the new state.
d1b7e03d
TH
1483 */
1484 public function set_flagged($flagged) {
1485 $this->flagged = $flagged;
1486 $this->observer->notify_attempt_modified($this);
1487 }
1488
f7970e3c 1489 /** @return bool whether this question is currently flagged. */
d1b7e03d
TH
1490 public function is_flagged() {
1491 return $this->flagged;
1492 }
1493
1494 /**
1495 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1496 * name) to use for the field that indicates whether this question is flagged.
1497 *
1498 * @return string The field name to use.
1499 */
1500 public function get_flag_field_name() {
1501 return $this->get_control_field_name('flagged');
1502 }
1503
1504 /**
1505 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1506 * name) to use for a question_type variable belonging to this question_attempt.
1507 *
1508 * See the comment on {@link question_attempt_step} for an explanation of
1509 * question type and behaviour variables.
1510 *
1511 * @param $varname The short form of the variable name.
1512 * @return string The field name to use.
1513 */
1514 public function get_qt_field_name($varname) {
1515 return $this->get_field_prefix() . $varname;
1516 }
1517
1518 /**
1519 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1520 * name) to use for a question_type variable belonging to this question_attempt.
1521 *
1522 * See the comment on {@link question_attempt_step} for an explanation of
1523 * question type and behaviour variables.
1524 *
1525 * @param $varname The short form of the variable name.
1526 * @return string The field name to use.
1527 */
1528 public function get_behaviour_field_name($varname) {
1529 return $this->get_field_prefix() . '-' . $varname;
1530 }
1531
1532 /**
1533 * Get the name (in the sense a HTML name="" attribute, or a $_POST variable
1534 * name) to use for a control variables belonging to this question_attempt.
1535 *
1536 * Examples are :sequencecheck and :flagged
1537 *
1538 * @param $varname The short form of the variable name.
1539 * @return string The field name to use.
1540 */
1541 public function get_control_field_name($varname) {
1542 return $this->get_field_prefix() . ':' . $varname;
1543 }
1544
1545 /**
1546 * Get the prefix added to variable names to give field names for this
1547 * question attempt.
1548 *
1549 * You should not use this method directly. This is an implementation detail
1550 * anyway, but if you must access it, use {@link question_usage_by_activity::get_field_prefix()}.
1551 *
1552 * @param $varname The short form of the variable name.
1553 * @return string The field name to use.
1554 */
1555 public function get_field_prefix() {
1556 return 'q' . $this->usageid . ':' . $this->slot . '_';
1557 }
1558
1559 /**
1560 * Get one of the steps in this attempt.
1561 * For internal/test code use only.
f7970e3c 1562 * @param int $i the step number.
d1b7e03d
TH
1563 * @return question_attempt_step
1564 */
1565 public function get_step($i) {
1566 if ($i < 0 || $i >= count($this->steps)) {
88f0eb15 1567 throw new coding_exception('Index out of bounds in question_attempt::get_step.');
d1b7e03d
TH
1568 }
1569 return $this->steps[$i];
1570 }
1571
1572 /**
1573 * Get the number of steps in this attempt.
1574 * For internal/test code use only.
f7970e3c 1575 * @return int the number of steps we currently have.
d1b7e03d
TH
1576 */
1577 public function get_num_steps() {
1578 return count($this->steps);
1579 }
1580
1581 /**
1582 * Return the latest step in this question_attempt.
1583 * For internal/test code use only.
1584 * @return question_attempt_step
1585 */
1586 public function get_last_step() {
1587 if (count($this->steps) == 0) {
1588 return new question_null_step();
1589 }
1590 return end($this->steps);
1591 }
1592
1593 /**
1594 * @return question_attempt_step_iterator for iterating over the steps in
1595 * this attempt, in order.
1596 */
1597 public function get_step_iterator() {
1598 return new question_attempt_step_iterator($this);
1599 }
1600
1601 /**
1602 * The same as {@link get_step_iterator()}. However, for a
1603 * {@link question_attempt_with_restricted_history} this returns the full
1604 * list of steps, while {@link get_step_iterator()} returns only the
1605 * limited history.
1606 * @return question_attempt_step_iterator for iterating over the steps in
1607 * this attempt, in order.
1608 */
1609 public function get_full_step_iterator() {
1610 return $this->get_step_iterator();
1611 }
1612
1613 /**
1614 * @return question_attempt_reverse_step_iterator for iterating over the steps in
1615 * this attempt, in reverse order.
1616 */
1617 public function get_reverse_step_iterator() {
1618 return new question_attempt_reverse_step_iterator($this);
1619 }
1620
1621 /**
1622 * Get the qt data from the latest step that has any qt data. Return $default
1623 * array if it is no step has qt data.
1624 *
1625 * @param string $name the name of the variable to get.
1626 * @param mixed default the value to return no step has qt data.
1627 * (Optional, defaults to an empty array.)
1628 * @return array|mixed the data, or $default if there is not any.
1629 */
1630 public function get_last_qt_data($default = array()) {
1631 foreach ($this->get_reverse_step_iterator() as $step) {
1632 $response = $step->get_qt_data();
1633 if (!empty($response)) {
1634 return $response;
1635 }
1636 }
1637 return $default;
1638 }
1639
1640 /**
1641 * Get the latest value of a particular question type variable. That is, get
1642 * the value from the latest step that has it set. Return null if it is not
1643 * set in any step.
1644 *
1645 * @param string $name the name of the variable to get.
1646 * @param mixed default the value to return in the variable has never been set.
1647 * (Optional, defaults to null.)
1648 * @return mixed string value, or $default if it has never been set.
1649 */
1650 public function get_last_qt_var($name, $default = null) {
1651 foreach ($this->get_reverse_step_iterator() as $step) {
1652 if ($step->has_qt_var($name)) {
1653 return $step->get_qt_var($name);
1654 }
1655 }
1656 return $default;
1657 }
1658
1659 /**
1660 * Get the latest value of a particular behaviour variable. That is,
1661 * get the value from the latest step that has it set. Return null if it is
1662 * not set in any step.
1663 *
1664 * @param string $name the name of the variable to get.
1665 * @param mixed default the value to return in the variable has never been set.
1666 * (Optional, defaults to null.)
1667 * @return mixed string value, or $default if it has never been set.
1668 */
1669 public function get_last_behaviour_var($name, $default = null) {
1670 foreach ($this->get_reverse_step_iterator() as $step) {
1671 if ($step->has_behaviour_var($name)) {
1672 return $step->get_behaviour_var($name);
1673 }
1674 }
1675 return $default;
1676 }
1677
1678 /**
1679 * Get the current state of this question attempt. That is, the state of the
1680 * latest step.
1681 * @return question_state
1682 */
1683 public function get_state() {
1684 return $this->get_last_step()->get_state();
1685 }
1686
1687 /**
f7970e3c 1688 * @param bool $showcorrectness Whether right/partial/wrong states should
d1b7e03d
TH
1689 * be distinguised.
1690 * @return string A brief textual description of the current state.
1691 */
1692 public function get_state_string($showcorrectness) {
1693 return $this->behaviour->get_state_string($showcorrectness);
1694 }
1695
1696 /**
f7970e3c 1697 * @return int the timestamp of the most recent step in this question attempt.
d1b7e03d
TH
1698 */
1699 public function get_last_action_time() {
1700 return $this->get_last_step()->get_timecreated();
1701 }
1702
1703 /**
1704 * Get the current fraction of this question attempt. That is, the fraction
1705 * of the latest step, or null if this question has not yet been graded.
1706 * @return number the current fraction.
1707 */
1708 public function get_fraction() {
1709 return $this->get_last_step()->get_fraction();
1710 }
1711
f7970e3c 1712 /** @return bool whether this question attempt has a non-zero maximum mark. */
d1b7e03d
TH
1713 public function has_marks() {
1714 // Since grades are stored in the database as NUMBER(12,7).
1715 return $this->maxmark >= 0.00000005;
1716 }
1717
1718 /**
1719 * @return number the current mark for this question.
1720 * {@link get_fraction()} * {@link get_max_mark()}.
1721 */
1722 public function get_mark() {
1723 return $this->fraction_to_mark($this->get_fraction());
1724 }
1725
1726 /**
1727 * This is used by the manual grading code, particularly in association with
1728 * validation. If there is a mark submitted in the request, then use that,
1729 * otherwise use the latest mark for this question.
1730 * @return number the current mark for this question.
1731 * {@link get_fraction()} * {@link get_max_mark()}.
1732 */
1733 public function get_current_manual_mark() {
1734 $mark = self::get_submitted_var($this->get_behaviour_field_name('mark'), question_attempt::PARAM_MARK);
1735 if (is_null($mark)) {
1736 return $this->get_mark();
1737 } else {
1738 return $mark;
1739 }
1740 }
1741
1742 /**
1743 * @param number|null $fraction a fraction.
1744 * @return number|null the corresponding mark.
1745 */
1746 public function fraction_to_mark($fraction) {
1747 if (is_null($fraction)) {
1748 return null;
1749 }
1750 return $fraction * $this->maxmark;
1751 }
1752
1753 /** @return number the maximum mark possible for this question attempt. */
1754 public function get_max_mark() {
1755 return $this->maxmark;
1756 }
1757
1758 /** @return number the maximum mark possible for this question attempt. */
1759 public function get_min_fraction() {
1760 if (is_null($this->minfraction)) {
88f0eb15 1761 throw new coding_exception('This question_attempt has not been started yet, the min fraction is not yet konwn.');
d1b7e03d
TH
1762 }
1763 return $this->minfraction;
1764 }
1765
1766 /**
1767 * The current mark, formatted to the stated number of decimal places. Uses
1768 * {@link format_float()} to format floats according to the current locale.
f7970e3c 1769 * @param int $dp number of decimal places.
d1b7e03d
TH
1770 * @return string formatted mark.
1771 */
1772 public function format_mark($dp) {
1773 return $this->format_fraction_as_mark($this->get_fraction(), $dp);
1774 }
1775
1776 /**
1777 * The current mark, formatted to the stated number of decimal places. Uses
1778 * {@link format_float()} to format floats according to the current locale.
f7970e3c 1779 * @param int $dp number of decimal places.
d1b7e03d
TH
1780 * @return string formatted mark.
1781 */
1782 public function format_fraction_as_mark($fraction, $dp) {
1783 return format_float($this->fraction_to_mark($fraction), $dp);
1784 }
1785
1786 /**
1787 * The maximum mark for this question attempt, formatted to the stated number
1788 * of decimal places. Uses {@link format_float()} to format floats according
1789 * to the current locale.
f7970e3c 1790 * @param int $dp number of decimal places.
d1b7e03d
TH
1791 * @return string formatted maximum mark.
1792 */
1793 public function format_max_mark($dp) {
1794 return format_float($this->maxmark, $dp);
1795 }
1796
1797 /**
1798 * Return the hint that applies to the question in its current state, or null.
1799 * @return question_hint|null
1800 */
1801 public function get_applicable_hint() {
1802 return $this->behaviour->get_applicable_hint();
1803 }
1804
1805 /**
1806 * Produce a plain-text summary of what the user did during a step.
1807 * @param question_attempt_step $step the step in quetsion.
1808 * @return string a summary of what was done during that step.
1809 */
1810 public function summarise_action(question_attempt_step $step) {
1811 return $this->behaviour->summarise_action($step);
1812 }
1813
7a719748
TH
1814 /**
1815 * Calls {@link question_rewrite_question_urls()} with appropriate parameters
1816 * for content belonging to this question.
1817 * @param string $text the content to output.
1818 * @param string $component the component name (normally 'question' or 'qtype_...')
1819 * @param string $filearea the name of the file area.
f7970e3c 1820 * @param int $itemid the item id.
7a719748
TH
1821 */
1822 public function rewrite_pluginfile_urls($text, $component, $filearea, $itemid) {
2b7da645 1823 return question_rewrite_question_urls($text,
56e82d99 1824 'pluginfile.php', $this->question->contextid, $component, $filearea,
7a719748 1825 array($this->get_usage_id(), $this->get_slot()), $itemid);
2b7da645
TH
1826 }
1827
d1b7e03d
TH
1828 /**
1829 * Get the {@link core_question_renderer}, in collaboration with appropriate
1830 * {@link qbehaviour_renderer} and {@link qtype_renderer} subclasses, to generate the
1831 * HTML to display this question attempt in its current state.
1832 * @param question_display_options $options controls how the question is rendered.
1833 * @param string|null $number The question number to display.
1834 * @return string HTML fragment representing the question.
1835 */
2daffca5
TH
1836 public function render($options, $number, $page = null) {
1837 if (is_null($page)) {
1838 global $PAGE;
1839 $page = $PAGE;
1840 }
1841 $qoutput = $page->get_renderer('core', 'question');
1842 $qtoutput = $this->question->get_renderer($page);
d1b7e03d
TH
1843 return $this->behaviour->render($options, $number, $qoutput, $qtoutput);
1844 }
1845
1846 /**
1847 * Generate any bits of HTML that needs to go in the <head> tag when this question
1848 * attempt is displayed in the body.
1849 * @return string HTML fragment.
1850 */
2daffca5
TH
1851 public function render_head_html($page = null) {
1852 if (is_null($page)) {
1853 global $PAGE;
1854 $page = $PAGE;
1855 }
1856 // TODO go via behaviour.
1857 return $this->question->get_renderer($page)->head_code($this) .
1858 $this->behaviour->get_renderer($page)->head_code($this);
d1b7e03d
TH
1859 }
1860
1861 /**
1862 * Like {@link render_question()} but displays the question at the past step
1863 * indicated by $seq, rather than showing the latest step.
1864 *
f7970e3c 1865 * @param int $seq the seq number of the past state to display.
d1b7e03d
TH
1866 * @param question_display_options $options controls how the question is rendered.
1867 * @param string|null $number The question number to display. 'i' is a special
1868 * value that gets displayed as Information. Null means no number is displayed.
1869 * @return string HTML fragment representing the question.
1870 */
1871 public function render_at_step($seq, $options, $number, $preferredbehaviour) {
1872 $restrictedqa = new question_attempt_with_restricted_history($this, $seq, $preferredbehaviour);
1873 return $restrictedqa->render($options, $number);
1874 }
1875
7a719748
TH
1876 /**
1877 * Checks whether the users is allow to be served a particular file.
1878 * @param question_display_options $options the options that control display of the question.
1879 * @param string $component the name of the component we are serving files for.
1880 * @param string $filearea the name of the file area.
1881 * @param array $args the remaining bits of the file path.
f7970e3c
TH
1882 * @param bool $forcedownload whether the user must be forced to download the file.
1883 * @return bool true if the user can access this file.
7a719748
TH
1884 */
1885 public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
1886 return $this->behaviour->check_file_access($options, $component, $filearea, $args, $forcedownload);
1887 }
1888
d1b7e03d
TH
1889 /**
1890 * Add a step to this question attempt.
1891 * @param question_attempt_step $step the new step.
1892 */
1893 protected function add_step(question_attempt_step $step) {
1894 $this->steps[] = $step;
1895 end($this->steps);
1896 $this->observer->notify_step_added($step, $this, key($this->steps));
1897 }
1898
1899 /**
ef31a283 1900 * Start this question attempt.
d1b7e03d
TH
1901 *
1902 * You should not call this method directly. Call
1903 * {@link question_usage_by_activity::start_question()} instead.
1904 *
1905 * @param string|question_behaviour $preferredbehaviour the name of the
1906 * desired archetypal behaviour, or an actual model instance.
ef31a283
TH
1907 * @param array $submitteddata optional, used when re-starting to keep the same initial state.
1908 * @param int $timestamp optional, the timstamp to record for this action. Defaults to now.
1909 * @param int $userid optional, the user to attribute this action to. Defaults to the current user.
d1b7e03d
TH
1910 */
1911 public function start($preferredbehaviour, $submitteddata = array(), $timestamp = null, $userid = null) {
1912 // Initialise the behaviour.
1913 if (is_string($preferredbehaviour)) {
1914 $this->behaviour =
1915 $this->question->make_behaviour($this, $preferredbehaviour);
1916 } else {
1917 $class = get_class($preferredbehaviour);
1918 $this->behaviour = new $class($this, $preferredbehaviour);
1919 }
1920
1921 // Record the minimum fraction.
1922 $this->minfraction = $this->behaviour->get_min_fraction();
1923
1924 // Initialise the first step.
1925 $firststep = new question_attempt_step($submitteddata, $timestamp, $userid);
1926 $firststep->set_state(question_state::$todo);
ef31a283
TH
1927 if ($submitteddata) {
1928 $this->question->apply_attempt_state($firststep);
1929 } else {
1930 $this->behaviour->init_first_step($firststep);
1931 }
d1b7e03d
TH
1932 $this->add_step($firststep);
1933
1934 // Record questionline and correct answer.
d1b7e03d
TH
1935 $this->questionsummary = $this->behaviour->get_question_summary();
1936 $this->rightanswer = $this->behaviour->get_right_answer_summary();
1937 }
1938
1939 /**
1940 * Start this question attempt, starting from the point that the previous
1941 * attempt $oldqa had reached.
1942 *
1943 * You should not call this method directly. Call
1944 * {@link question_usage_by_activity::start_question_based_on()} instead.
1945 *
1946 * @param question_attempt $oldqa a previous attempt at this quetsion that
1947 * defines the starting point.
1948 */
1949 public function start_based_on(question_attempt $oldqa) {
1950 $this->start($oldqa->behaviour, $oldqa->get_resume_data());
1951 }
1952
1953 /**
1954 * Used by {@link start_based_on()} to get the data needed to start a new
1955 * attempt from the point this attempt has go to.
1956 * @return array name => value pairs.
1957 */
1958 protected function get_resume_data() {
1959 return $this->behaviour->get_resume_data();
1960 }
1961
1962 /**
1963 * Get a particular parameter from the current request. A wrapper round
1964 * {@link optional_param()}, except that the results is returned without
1965 * slashes.
1966 * @param string $name the paramter name.
f7970e3c 1967 * @param int $type one of the PARAM_... constants.
d1b7e03d
TH
1968 * @param array $postdata (optional, only inteded for testing use) take the
1969 * data from this array, instead of from $_POST.
1970 * @return mixed the requested value.
1971 */
1972 public static function get_submitted_var($name, $type, $postdata = null) {
1973 // Special case to work around PARAM_NUMBER converting '' to 0.
1974 if ($type == self::PARAM_MARK) {
1975 $mark = self::get_submitted_var($name, PARAM_RAW_TRIMMED, $postdata);
1976 if ($mark === '') {
1977 return $mark;
1978 } else {
1979 return self::get_submitted_var($name, PARAM_NUMBER, $postdata);
1980 }
1981 }
1982
1983 if (is_null($postdata)) {
1984 $var = optional_param($name, null, $type);
1985 } else if (array_key_exists($name, $postdata)) {
1986 $var = clean_param($postdata[$name], $type);
1987 } else {
1988 $var = null;
1989 }
1990 if (is_string($var)) {
1991 $var = stripslashes($var);
1992 }
1993 return $var;
1994 }
1995
1996 /**
1997 * Get any data from the request that matches the list of expected params.
1998 * @param array $expected variable name => PARAM_... constant.
1999 * @param string $extraprefix '-' or ''.
2000 * @return array name => value.
2001 */
2002 protected function get_expected_data($expected, $postdata, $extraprefix) {
2003 $submitteddata = array();
2004 foreach ($expected as $name => $type) {
2005 $value = self::get_submitted_var(
2006 $this->get_field_prefix() . $extraprefix . $name, $type, $postdata);
2007 if (!is_null($value)) {
2008 $submitteddata[$extraprefix . $name] = $value;
2009 }
2010 }
2011 return $submitteddata;
2012 }
2013
2014 /**
2015 * Get all the submitted question type data for this question, whithout checking
2016 * that it is valid or cleaning it in any way.
2017 * @return array name => value.
2018 */
2019 protected function get_all_submitted_qt_vars($postdata) {
2020 if (is_null($postdata)) {
2021 $postdata = $_POST;
2022 }
2023
2024 $pattern = '/^' . preg_quote($this->get_field_prefix()) . '[^-:]/';
2025 $prefixlen = strlen($this->get_field_prefix());
2026
2027 $submitteddata = array();
2028 foreach ($_POST as $name => $value) {
2029 if (preg_match($pattern, $name)) {
2030 $submitteddata[substr($name, $prefixlen)] = $value;
2031 }
2032 }
2033
2034 return $submitteddata;
2035 }
2036
2037 /**
2038 * Get all the sumbitted data belonging to this question attempt from the
2039 * current request.
2040 * @param array $postdata (optional, only inteded for testing use) take the
2041 * data from this array, instead of from $_POST.
2042 * @return array name => value pairs that could be passed to {@link process_action()}.
2043 */
2044 public function get_submitted_data($postdata = null) {
2045 $submitteddata = $this->get_expected_data(
2046 $this->behaviour->get_expected_data(), $postdata, '-');
2047
2048 $expected = $this->behaviour->get_expected_qt_data();
2049 if ($expected === self::USE_RAW_DATA) {
2050 $submitteddata += $this->get_all_submitted_qt_vars($postdata);
2051 } else {
2052 $submitteddata += $this->get_expected_data($expected, $postdata, '');
2053 }
2054 return $submitteddata;
2055 }
2056
2057 /**
2058 * Get a set of response data for this question attempt that would get the
2059 * best possible mark.
2060 * @return array name => value pairs that could be passed to {@link process_action()}.
2061 */
2062 public function get_correct_response() {
2063 $response = $this->question->get_correct_response();
2064 $imvars = $this->behaviour->get_correct_response();
2065 foreach ($imvars as $name => $value) {
2066 $response['-' . $name] = $value;
2067 }
2068 return $response;
2069 }
2070
2071 /**
2072 * Change the quetsion summary. Note, that this is almost never necessary.
2073 * This method was only added to work around a limitation of the Opaque
2074 * protocol, which only sends questionLine at the end of an attempt.
2075 * @param $questionsummary the new summary to set.
2076 */
2077 public function set_question_summary($questionsummary) {
2078 $this->questionsummary = $questionsummary;
2079 $this->observer->notify_attempt_modified($this);
2080 }
2081
2082 /**
2083 * @return string a simple textual summary of the question that was asked.
2084 */
2085 public function get_question_summary() {
2086 return $this->questionsummary;
2087 }
2088
2089 /**
2090 * @return string a simple textual summary of response given.
2091 */
2092 public function get_response_summary() {
2093 return $this->responsesummary;
2094 }
2095
2096 /**
2097 * @return string a simple textual summary of the correct resonse.
2098 */
2099 public function get_right_answer_summary() {
2100 return $this->rightanswer;
2101 }
2102
2103 /**
2104 * Perform the action described by $submitteddata.
2105 * @param array $submitteddata the submitted data the determines the action.
f7970e3c
TH
2106 * @param int $timestamp the time to record for the action. (If not given, use now.)
2107 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2108 */
2109 public function process_action($submitteddata, $timestamp = null, $userid = null) {
2110 $pendingstep = new question_attempt_pending_step($submitteddata, $timestamp, $userid);
2111 if ($this->behaviour->process_action($pendingstep) == self::KEEP) {
2112 $this->add_step($pendingstep);
2113 if ($pendingstep->response_summary_changed()) {
2114 $this->responsesummary = $pendingstep->get_new_response_summary();
2115 }
2116 }
2117 }
2118
2119 /**
2120 * Perform a finish action on this question attempt. This corresponds to an
2121 * external finish action, for example the user pressing Submit all and finish
2122 * in the quiz, rather than using one of the controls that is part of the
2123 * question.
2124 *
f7970e3c
TH
2125 * @param int $timestamp the time to record for the action. (If not given, use now.)
2126 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2127 */
2128 public function finish($timestamp = null, $userid = null) {
2129 $this->process_action(array('-finish' => 1), $timestamp, $userid);
2130 }
2131
2132 /**
2133 * Perform a regrade. This replays all the actions from $oldqa into this
2134 * attempt.
2135 * @param question_attempt $oldqa the attempt to regrade.
f7970e3c 2136 * @param bool $finished whether the question attempt should be forced to be finished
d1b7e03d
TH
2137 * after the regrade, or whether it may still be in progress (default false).
2138 */
2139 public function regrade(question_attempt $oldqa, $finished) {
2140 $first = true;
2141 foreach ($oldqa->get_step_iterator() as $step) {
2142 if ($first) {
2143 $first = false;
2144 $this->start($oldqa->behaviour, $step->get_all_data(),
2145 $step->get_timecreated(), $step->get_user_id());
2146 } else {
2147 $this->process_action($step->get_submitted_data(),
2148 $step->get_timecreated(), $step->get_user_id());
2149 }
2150 }
2151 if ($finished) {
2152 $this->finish();
2153 }
2154 }
2155
2156 /**
2157 * Perform a manual grading action on this attempt.
2158 * @param $comment the comment being added.
2159 * @param $mark the new mark. (Optional, if not given, then only a comment is added.)
f7970e3c
TH
2160 * @param int $timestamp the time to record for the action. (If not given, use now.)
2161 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2162 * @return unknown_type
2163 */
2164 public function manual_grade($comment, $mark, $timestamp = null, $userid = null) {
2165 $submitteddata = array('-comment' => $comment);
2166 if (!is_null($mark)) {
2167 $submitteddata['-mark'] = $mark;
2168 $submitteddata['-maxmark'] = $this->maxmark;
2169 }
2170 $this->process_action($submitteddata, $timestamp, $userid);
2171 }
2172
f7970e3c 2173 /** @return bool Whether this question attempt has had a manual comment added. */
d1b7e03d
TH
2174 public function has_manual_comment() {
2175 foreach ($this->steps as $step) {
2176 if ($step->has_behaviour_var('comment')) {
2177 return true;
2178 }
2179 }
2180 return false;
2181 }
2182
2183 /**
7a719748
TH
2184 * @return array(string, int) the most recent manual comment that was added
2185 * to this question, and the FORMAT_... it is.
d1b7e03d
TH
2186 */
2187 public function get_manual_comment() {
2188 foreach ($this->get_reverse_step_iterator() as $step) {
2189 if ($step->has_behaviour_var('comment')) {
7a719748
TH
2190 return array($step->get_behaviour_var('comment'),
2191 $step->get_behaviour_var('commentformat'));
d1b7e03d
TH
2192 }
2193 }
7a719748 2194 return array(null, null);
d1b7e03d
TH
2195 }
2196
2197 /**
2198 * @return array subpartid => object with fields
f9b0500f 2199 * ->responseclassid matches one of the values returned from quetion_type::get_possible_responses.
d1b7e03d
TH
2200 * ->response the actual response the student gave to this part, as a string.
2201 * ->fraction the credit awarded for this subpart, may be null.
2202 * returns an empty array if no analysis is possible.
2203 */
2204 public function classify_response() {
2205 return $this->behaviour->classify_response();
2206 }
2207
2208 /**
2209 * Create a question_attempt_step from records loaded from the database.
2210 *
2211 * For internal use only.
2212 *
2213 * @param array $records Raw records loaded from the database.
f7970e3c 2214 * @param int $questionattemptid The id of the question_attempt to extract.
d1b7e03d
TH
2215 * @return question_attempt The newly constructed question_attempt_step.
2216 */
2217 public static function load_from_records(&$records, $questionattemptid,
2218 question_usage_observer $observer, $preferredbehaviour) {
2219 $record = current($records);
2220 while ($record->questionattemptid != $questionattemptid) {
2221 $record = next($records);
2222 if (!$record) {
88f0eb15 2223 throw new coding_exception("Question attempt $questionattemptid not found in the database.");
d1b7e03d
TH
2224 }
2225 }
2226
2227 try {
2228 $question = question_bank::load_question($record->questionid);
2229 } catch (Exception $e) {
2230 // The question must have been deleted somehow. Create a missing
2231 // question to use in its place.
2232 $question = question_bank::get_qtype('missingtype')->make_deleted_instance(
2233 $record->questionid, $record->maxmark + 0);
2234 }
2235
7a719748 2236 $qa = new question_attempt($question, $record->questionusageid,
2daffca5 2237 null, $record->maxmark + 0);
d1b7e03d
TH
2238 $qa->set_database_id($record->questionattemptid);
2239 $qa->set_number_in_usage($record->slot);
2240 $qa->minfraction = $record->minfraction + 0;
2241 $qa->set_flagged($record->flagged);
2242 $qa->questionsummary = $record->questionsummary;
2243 $qa->rightanswer = $record->rightanswer;
2244 $qa->responsesummary = $record->responsesummary;
2245 $qa->timemodified = $record->timemodified;
2246
2247 $qa->behaviour = question_engine::make_behaviour(
2248 $record->behaviour, $qa, $preferredbehaviour);
2249
2250 $i = 0;
2251 while ($record && $record->questionattemptid == $questionattemptid && !is_null($record->attemptstepid)) {
2252 $qa->steps[$i] = question_attempt_step::load_from_records($records, $record->attemptstepid);
2253 if ($i == 0) {
ef31a283 2254 $question->apply_attempt_state($qa->steps[0]);
d1b7e03d
TH
2255 }
2256 $i++;
2257 $record = current($records);
2258 }
2259
2260 $qa->observer = $observer;
2261
2262 return $qa;
2263 }
2264}
2265
2266
2267/**
2268 * This subclass of question_attempt pretends that only part of the step history
2269 * exists. It is used for rendering the question in past states.
2270 *
2271 * All methods that try to modify the question_attempt throw exceptions.
2272 *
f7970e3c 2273 * @copyright 2010 The Open University
017bc1d9 2274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2275 */
2276class question_attempt_with_restricted_history extends question_attempt {
2277 /**
2278 * @var question_attempt the underlying question_attempt.
2279 */
2280 protected $baseqa;
2281
2282 /**
2283 * Create a question_attempt_with_restricted_history
2284 * @param question_attempt $baseqa The question_attempt to make a restricted version of.
f7970e3c 2285 * @param int $lastseq the index of the last step to include.
d1b7e03d
TH
2286 * @param string $preferredbehaviour the preferred behaviour. It is slightly
2287 * annoyting that this needs to be passed, but unavoidable for now.
2288 */
2289 public function __construct(question_attempt $baseqa, $lastseq, $preferredbehaviour) {
2290 if ($lastseq < 0 || $lastseq >= $baseqa->get_num_steps()) {
2291 throw new coding_exception('$seq out of range', $seq);
2292 }
2293
2294 $this->baseqa = $baseqa;
2295 $this->steps = array_slice($baseqa->steps, 0, $lastseq + 1);
2296 $this->observer = new question_usage_null_observer();
2297
2298 // This should be a straight copy of all the remaining fields.
2299 $this->id = $baseqa->id;
2300 $this->usageid = $baseqa->usageid;
2301 $this->slot = $baseqa->slot;
2302 $this->question = $baseqa->question;
2303 $this->maxmark = $baseqa->maxmark;
2304 $this->minfraction = $baseqa->minfraction;
2305 $this->questionsummary = $baseqa->questionsummary;
2306 $this->responsesummary = $baseqa->responsesummary;
2307 $this->rightanswer = $baseqa->rightanswer;
2308 $this->flagged = $baseqa->flagged;
2309
2310 // Except behaviour, where we need to create a new one.
2311 $this->behaviour = question_engine::make_behaviour(
2312 $baseqa->get_behaviour_name(), $this, $preferredbehaviour);
2313 }
2314
2315 public function get_full_step_iterator() {
2316 return $this->baseqa->get_step_iterator();
2317 }
2318
2319 protected function add_step(question_attempt_step $step) {
2320 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2321 }
2322 public function process_action($submitteddata, $timestamp = null, $userid = null) {
2323 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2324 }
2325 public function start($preferredbehaviour, $submitteddata = array(), $timestamp = null, $userid = null) {
2326 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2327 }
2328
2329 public function set_database_id($id) {
2330 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2331 }
2332 public function set_flagged($flagged) {
2333 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2334 }
2335 public function set_number_in_usage($slot) {
2336 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2337 }
2338 public function set_question_summary($questionsummary) {
2339 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2340 }
2341 public function set_usage_id($usageid) {
2342 coding_exception('Cannot modify a question_attempt_with_restricted_history.');
2343 }
2344}
2345
2346
2347/**
2348 * A class abstracting access to the {@link question_attempt::$states} array.
2349 *
2350 * This is actively linked to question_attempt. If you add an new step
2351 * mid-iteration, then it will be included.
2352 *
017bc1d9
TH
2353 * @copyright 2009 The Open University
2354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2355 */
2356class question_attempt_step_iterator implements Iterator, ArrayAccess {
2357 /** @var question_attempt the question_attempt being iterated over. */
2358 protected $qa;
2359 /** @var integer records the current position in the iteration. */
2360 protected $i;
2361
2362 /**
2363 * Do not call this constructor directly.
2364 * Use {@link question_attempt::get_step_iterator()}.
2365 * @param question_attempt $qa the attempt to iterate over.
2366 */
2367 public function __construct(question_attempt $qa) {
2368 $this->qa = $qa;
2369 $this->rewind();
2370 }
2371
2372 /** @return question_attempt_step */
2373 public function current() {
2374 return $this->offsetGet($this->i);
2375 }
f7970e3c 2376 /** @return int */
d1b7e03d
TH
2377 public function key() {
2378 return $this->i;
2379 }
2380 public function next() {
2381 ++$this->i;
2382 }
2383 public function rewind() {
2384 $this->i = 0;
2385 }
f7970e3c 2386 /** @return bool */
d1b7e03d
TH
2387 public function valid() {
2388 return $this->offsetExists($this->i);
2389 }
2390
f7970e3c 2391 /** @return bool */
d1b7e03d
TH
2392 public function offsetExists($i) {
2393 return $i >= 0 && $i < $this->qa->get_num_steps();
2394 }
2395 /** @return question_attempt_step */
2396 public function offsetGet($i) {
2397 return $this->qa->get_step($i);
2398 }
2399 public function offsetSet($offset, $value) {
88f0eb15 2400 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot set.');
d1b7e03d
TH
2401 }
2402 public function offsetUnset($offset) {
88f0eb15 2403 throw new coding_exception('You are only allowed read-only access to question_attempt::states through a question_attempt_step_iterator. Cannot unset.');
d1b7e03d
TH
2404 }
2405}
2406
2407
2408/**
2409 * A variant of {@link question_attempt_step_iterator} that iterates through the
2410 * steps in reverse order.
2411 *
017bc1d9
TH
2412 * @copyright 2009 The Open University
2413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2414 */
2415class question_attempt_reverse_step_iterator extends question_attempt_step_iterator {
2416 public function next() {
2417 --$this->i;
2418 }
2419
2420 public function rewind() {
2421 $this->i = $this->qa->get_num_steps() - 1;
2422 }
2423}
2424
2425
2426/**
2427 * Stores one step in a {@link question_attempt}.
2428 *
2429 * The most important attributes of a step are the state, which is one of the
2430 * {@link question_state} constants, the fraction, which may be null, or a
2431 * number bewteen the attempt's minfraction and 1.0, and the array of submitted
2432 * data, about which more later.
2433 *
2434 * A step also tracks the time it was created, and the user responsible for
2435 * creating it.
2436 *
2437 * The submitted data is basically just an array of name => value pairs, with
2438 * certain conventions about the to divide the variables into four = two times two
2439 * categories.
2440 *
2441 * Variables may either belong to the behaviour, in which case the
2442 * name starts with a '-', or they may belong to the question type in which case
2443 * they name does not start with a '-'.
2444 *
2445 * Second, variables may either be ones that came form the original request, in
2446 * which case the name does not start with an _, or they are cached values that
2447 * were created during processing, in which case the name does start with an _.
2448 *
2449 * That is, each name will start with one of '', '_'. '-' or '-_'. The remainder
2450 * of the name should match the regex [a-z][a-z0-9]*.
2451 *
2452 * These variables can be accessed with {@link get_behaviour_var()} and {@link get_qt_var()},
2453 * - to be clear, ->get_behaviour_var('x') gets the variable with name '-x' -
2454 * and values whose names start with '_' can be set using {@link set_behaviour_var()}
2455 * and {@link set_qt_var()}. There are some other methods like {@link has_behaviour_var()}
2456 * to check wether a varaible with a particular name is set, and {@link get_behaviour_data()}
2457 * to get all the behaviour data as an associative array.
2458 *
017bc1d9
TH
2459 * @copyright 2009 The Open University
2460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2461 */
2462class question_attempt_step {
2463 /** @var integer if this attempts is stored in the question_attempts table, the id of that row. */
2464 private $id = null;
2465
2466 /** @var question_state one of the {@link question_state} constants. The state after this step. */
2467 private $state;
2468
2469 /** @var null|number the fraction (grade on a scale of minfraction .. 1.0) or null. */
2470 private $fraction = null;
2471
2472 /** @var integer the timestamp when this step was created. */
2473 private $timecreated;
2474
2475 /** @var integer the id of the user resonsible for creating this step. */
2476 private $userid;
2477
2478 /** @var array name => value pairs. The submitted data. */
2479 private $data;
2480
2481 /**
2482 * You should not need to call this constructor in your own code. Steps are
2483 * normally created by {@link question_attempt} methods like
2484 * {@link question_attempt::process_action()}.
2485 * @param array $data the submitted data that defines this step.
f7970e3c
TH
2486 * @param int $timestamp the time to record for the action. (If not given, use now.)
2487 * @param int $userid the user to attribute the aciton to. (If not given, use the current user.)
d1b7e03d
TH
2488 */
2489 public function __construct($data = array(), $timecreated = null, $userid = null) {
2490 global $USER;
2491 $this->state = question_state::$unprocessed;
2492 $this->data = $data;
2493 if (is_null($timecreated)) {
2494 $this->timecreated = time();
2495 } else {
2496 $this->timecreated = $timecreated;
2497 }
2498 if (is_null($userid)) {
2499 $this->userid = $USER->id;
2500 } else {
2501 $this->userid = $userid;
2502 }
2503 }
2504
2505 /** @return question_state The state after this step. */
2506 public function get_state() {
2507 return $this->state;
2508 }
2509
2510 /**
2511 * Set the state. Normally only called by behaviours.
2512 * @param question_state $state one of the {@link question_state} constants.
2513 */
2514 public function set_state($state) {
2515 $this->state = $state;
2516 }
2517
2518 /**
2519 * @return null|number the fraction (grade on a scale of minfraction .. 1.0)
2520 * or null if this step has not been marked.
2521 */
2522 public function get_fraction() {
2523 return $this->fraction;
2524 }
2525
2526 /**
2527 * Set the fraction. Normally only called by behaviours.
2528 * @param null|number $fraction the fraction to set.
2529 */
2530 public function set_fraction($fraction) {
2531 $this->fraction = $fraction;
2532 }
2533
f7970e3c 2534 /** @return int the id of the user resonsible for creating this step. */
d1b7e03d
TH
2535 public function get_user_id() {
2536 return $this->userid;
2537 }
2538
f7970e3c 2539 /** @return int the timestamp when this step was created. */
d1b7e03d
TH
2540 public function get_timecreated() {
2541 return $this->timecreated;
2542 }
2543
2544 /**
2545 * @param string $name the name of a question type variable to look for in the submitted data.
f7970e3c 2546 * @return bool whether a variable with this name exists in the question type data.
d1b7e03d
TH
2547 */
2548 public function has_qt_var($name) {
2549 return array_key_exists($name, $this->data);
2550 }
2551
2552 /**
2553 * @param string $name the name of a question type variable to look for in the submitted data.
2554 * @return string the requested variable, or null if the variable is not set.
2555 */
2556 public function get_qt_var($name) {
2557 if (!$this->has_qt_var($name)) {
2558 return null;
2559 }
2560 return $this->data[$name];
2561 }
2562
2563 /**
2564 * Set a cached question type variable.
2565 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
2566 * @param string $value the value to set.
2567 */
2568 public function set_qt_var($name, $value) {
2569 if ($name[0] != '_') {
88f0eb15 2570 throw new coding_exception('Cannot set question type data ' . $name . ' on an attempt step. You can only set variables with names begining with _.');
d1b7e03d
TH
2571 }
2572 $this->data[$name] = $value;
2573 }
2574
2575 /**
2576 * Get all the question type variables.
2577 * @param array name => value pairs.
2578 */
2579 public function get_qt_data() {
2580 $result = array();
2581 foreach ($this->data as $name => $value) {
2582 if ($name[0] != '-' && $name[0] != ':') {
2583 $result[$name] = $value;
2584 }
2585 }
2586 return $result;
2587 }
2588
2589 /**
2590 * @param string $name the name of an behaviour variable to look for in the submitted data.
f7970e3c 2591 * @return bool whether a variable with this name exists in the question type data.
d1b7e03d
TH
2592 */
2593 public function has_behaviour_var($name) {
2594 return array_key_exists('-' . $name, $this->data);
2595 }
2596
2597 /**
2598 * @param string $name the name of an behaviour variable to look for in the submitted data.
2599 * @return string the requested variable, or null if the variable is not set.
2600 */
2601 public function get_behaviour_var($name) {
2602 if (!$this->has_behaviour_var($name)) {
2603 return null;
2604 }
2605 return $this->data['-' . $name];
2606 }
2607
2608 /**
2609 * Set a cached behaviour variable.
2610 * @param string $name the name of the variable to set. Must match _[a-z][a-z0-9]*.
2611 * @param string $value the value to set.
2612 */
2613 public function set_behaviour_var($name, $value) {
2614 if ($name[0] != '_') {
88f0eb15 2615 throw new coding_exception('Cannot set question type data ' . $name . ' on an attempt step. You can only set variables with names begining with _.');
d1b7e03d
TH
2616 }
2617 return $this->data['-' . $name] = $value;
2618 }
2619
2620 /**
2621 * Get all the behaviour variables.
2622 * @param array name => value pairs.
2623 */
2624 public function get_behaviour_data() {
2625 $result = array();
2626 foreach ($this->data as $name => $value) {
2627 if ($name[0] == '-') {
2628 $result[substr($name, 1)] = $value;
2629 }
2630 }
2631 return $result;
2632 }
2633
2634 /**
2635 * Get all the submitted data, but not the cached data. behaviour
2636 * variables have the - at the start of their name. This is only really
2637 * intended for use by {@link question_attempt::regrade()}, it should not
2638 * be considered part of the public API.
2639 * @param array name => value pairs.
2640 */
2641 public function get_submitted_data() {
2642 $result = array();
2643 foreach ($this->data as $name => $value) {
2644 if ($name[0] == '_' || ($name[0] == '-' && $name[1] == '_')) {
2645 continue;
2646 }
2647 $result[$name] = $value;
2648 }
2649 return $result;
2650 }
2651
2652 /**
2653 * Get all the data. behaviour variables have the ! at the start of
2654 * their name. This is only intended for internal use, for example by
2655 * {@link question_engine_data_mapper::insert_question_attempt_step()},
2656 * however, it can ocasionally be useful in test code. It should not be
2657 * considered part of the public API of this class.
2658 * @param array name => value pairs.
2659 */
2660 public function get_all_data() {
2661 return $this->data;
2662 }
2663
2664 /**
2665 * Create a question_attempt_step from records loaded from the database.
2666 * @param array $records Raw records loaded from the database.
f7970e3c 2667 * @param int $stepid The id of the records to extract.
d1b7e03d
TH
2668 * @return question_attempt_step The newly constructed question_attempt_step.
2669 */
2670 public static function load_from_records(&$records, $attemptstepid) {
2671 $currentrec = current($records);
2672 while ($currentrec->attemptstepid != $attemptstepid) {
2673 $currentrec = next($records);
2674 if (!$currentrec) {
88f0eb15 2675 throw new coding_exception("Question attempt step $attemptstepid not found in the database.");
d1b7e03d
TH
2676 }
2677 }
2678
2679 $record = $currentrec;
2680 $data = array();
2681 while ($currentrec && $currentrec->attemptstepid == $attemptstepid) {
2682 if ($currentrec->name) {
2683 $data[$currentrec->name] = $currentrec->value;
2684 }
2685 $currentrec = next($records);
2686 }
2687
2688 $step = new question_attempt_step_read_only($data, $record->timecreated, $record->userid);
2689 $step->state = question_state::get($record->state);
2690 if (!is_null($record->fraction)) {
2691 $step->fraction = $record->fraction + 0;
2692 }
2693 return $step;
2694 }
2695}
2696
2697
2698/**
2699 * A subclass with a bit of additional funcitonality, for pending steps.
2700 *
f7970e3c 2701 * @copyright 2010 The Open University
017bc1d9 2702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2703 */
2704class question_attempt_pending_step extends question_attempt_step {
2705 /** @var string . */
2706 protected $newresponsesummary = null;
2707
2708 /**
2709 * If as a result of processing this step, the response summary for the
2710 * question attempt should changed, you should call this method to set the
2711 * new summary.
2712 * @param string $responsesummary the new response summary.
2713 */
2714 public function set_new_response_summary($responsesummary) {
2715 $this->newresponsesummary = $responsesummary;
2716 }
2717
2718 /** @return string the new response summary, if any. */
2719 public function get_new_response_summary() {
2720 return $this->newresponsesummary;
2721 }
2722
2723 /** @return string whether this step changes the response summary. */
2724 public function response_summary_changed() {
2725 return !is_null($this->newresponsesummary);
2726 }
2727}
2728
2729
2730/**
2731 * A subclass of {@link question_attempt_step} that cannot be modified.
2732 *
017bc1d9
TH
2733 * @copyright 2009 The Open University
2734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2735 */
2736class question_attempt_step_read_only extends question_attempt_step {
2737 public function set_state($state) {
2738 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2739 }
2740 public function set_fraction($fraction) {
2741 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2742 }
2743 public function set_qt_var($name, $value) {
2744 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2745 }
2746 public function set_behaviour_var($name, $value) {
2747 throw new coding_exception('Cannot modify a question_attempt_step_read_only.');
2748 }
2749}
2750
2751
2752/**
2753 * A null {@link question_attempt_step} returned from
2754 * {@link question_attempt::get_last_step()} etc. when a an attempt has just been
2755 * created and there is no acutal step.
2756 *
017bc1d9
TH
2757 * @copyright 2009 The Open University
2758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2759 */
2760class question_null_step {
2761 public function get_state() {
2762 return question_state::$notstarted;
2763 }
2764
2765 public function set_state($state) {
88f0eb15 2766 throw new coding_exception('This question has not been started.');
d1b7e03d
TH
2767 }
2768
2769 public function get_fraction() {
2770 return null;
2771 }
2772}
2773
2774
2775/**
2776 * Interface for things that want to be notified of signficant changes to a
2777 * {@link question_usage_by_activity}.
2778 *
2779 * A question behaviour controls the flow of actions a student can
2780 * take as they work through a question, and later, as a teacher manually grades it.
2781 *
017bc1d9
TH
2782 * @copyright 2009 The Open University
2783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2784 */
2785interface question_usage_observer {
2786 /** Called when a field of the question_usage_by_activity is changed. */
2787 public function notify_modified();
2788
2789 /**
2790 * Called when the fields of a question attempt in this usage are modified.
2791 * @param question_attempt $qa the newly added question attempt.
2792 */
2793 public function notify_attempt_modified(question_attempt $qa);
2794
2795 /**
2796 * Called when a new question attempt is added to this usage.
2797 * @param question_attempt $qa the newly added question attempt.
2798 */
2799 public function notify_attempt_added(question_attempt $qa);
2800
2801 /**
2802 * Called we want to delete the old step records for an attempt, prior to
2803 * inserting newones. This is used by regrading.
2804 * @param question_attempt $qa the question attempt to delete the steps for.
2805 */
2806 public function notify_delete_attempt_steps(question_attempt $qa);
2807
2808 /**
2809 * Called when a new step is added to a question attempt in this usage.
2810 * @param $step the new step.
2811 * @param $qa the usage it is being added to.
2812 * @param $seq the sequence number of the new step.
2813 */
2814 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq);
2815}
2816
2817
2818/**
2819 * Null implmentation of the {@link question_usage_watcher} interface.
2820 * Does nothing.
2821 *
017bc1d9
TH
2822 * @copyright 2009 The Open University
2823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2824 */
2825class question_usage_null_observer implements question_usage_observer {
2826 public function notify_modified() {
2827 }
2828 public function notify_attempt_modified(question_attempt $qa) {
2829 }
2830 public function notify_attempt_added(question_attempt $qa) {
2831 }
2832 public function notify_delete_attempt_steps(question_attempt $qa) {
2833 }
2834 public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
2835 }
2836}
2837
2838
2839/**
2840 * Useful functions for writing question types and behaviours.
2841 *
2842 * @copyright 2010 The Open University
017bc1d9 2843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
2844 */
2845abstract class question_utils {
2846 /**
2847 * Tests to see whether two arrays have the same keys, with the same values
2848 * (as compared by ===) for each key. However, the order of the arrays does
2849 * not have to be the same.
2850 * @param array $array1 the first array.
2851 * @param array $array2 the second array.
f7970e3c 2852 * @return bool whether the two arrays have the same keys with the same
d1b7e03d
TH
2853 * corresponding values.
2854 */
2855 public static function arrays_have_same_keys_and_values(array $array1, array $array2) {
2856 if (count($array1) != count($array2)) {
2857 return false;
2858 }
2859 foreach ($array1 as $key => $value1) {
2860 if (!array_key_exists($key, $array2)) {
2861 return false;
2862 }
2863 if (((string) $value1) !== ((string) $array2[$key])) {
2864 return false;
2865 }
2866 }
2867 return true;
2868 }
2869
2870 /**
2871 * Tests to see whether two arrays have the same value at a particular key.
2872 * This method will return true if:
2873 * 1. Neither array contains the key; or
2874 * 2. Both arrays contain the key, and the corresponding values compare
2875 * identical when cast to strings and compared with ===.
2876 * @param array $array1 the first array.
2877 * @param array $array2 the second array.
2878 * @param string $key an array key.
f7970e3c 2879 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
2880 * one) for a given key.
2881 */
2882 public static function arrays_same_at_key(array $array1, array $array2, $key) {
2883 if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
2884 return ((string) $array1[$key]) === ((string) $array2[$key]);
2885 }
2886 if (!array_key_exists($key, $array1) && !array_key_exists($key, $array2)) {
2887 return true;
2888 }
2889 return false;
2890 }
2891
2892 /**
2893 * Tests to see whether two arrays have the same value at a particular key.
2894 * Missing values are replaced by '', and then the values are cast to
2895 * strings and compared with ===.
2896 * @param array $array1 the first array.
2897 * @param array $array2 the second array.
2898 * @param string $key an array key.
f7970e3c 2899 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
2900 * one) for a given key.
2901 */
2902 public static function arrays_same_at_key_missing_is_blank(
2903 array $array1, array $array2, $key) {
2904 if (array_key_exists($key, $array1)) {
2905 $value1 = $array1[$key];
2906 } else {
2907 $value1 = '';
2908 }
2909 if (array_key_exists($key, $array2)) {
2910 $value2 = $array2[$key];
2911 } else {
2912 $value2 = '';
2913 }
2914 return ((string) $value1) === ((string) $value2);
2915 }
2916
2917 /**
2918 * Tests to see whether two arrays have the same value at a particular key.
2919 * Missing values are replaced by 0, and then the values are cast to
2920 * integers and compared with ===.
2921 * @param array $array1 the first array.
2922 * @param array $array2 the second array.
2923 * @param string $key an array key.
f7970e3c 2924 * @return bool whether the two arrays have the same value (or lack of
d1b7e03d
TH
2925 * one) for a given key.
2926 */
2927 public static function arrays_same_at_key_integer(
2928 array $array1, array $array2, $key) {
2929 if (array_key_exists($key, $array1)) {
2930 $value1 = $array1[$key];
2931 } else {
2932 $value1 = 0;
2933 }
2934 if (array_key_exists($key, $array2)) {
2935 $value2 = $array2[$key];
2936 } else {
2937 $value2 = 0;
2938 }
2939 return ((integer) $value1) === ((integer) $value2);
2940 }
2941
2942 private static $units = array('', 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix');
2943 private static $tens = array('', 'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc');
2944 private static $hundreds = array('', 'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm');
2945 private static $thousands = array('', 'm', 'mm', 'mmm');
2946
2947 /**
2948 * Convert an integer to roman numerals.
f7970e3c 2949 * @param int $number an integer between 1 and 3999 inclusive. Anything else will throw an exception.
d1b7e03d
TH
2950 * @return string the number converted to lower case roman numerals.
2951 */
2952 public static function int_to_roman($number) {
2953 if (!is_integer($number) || $number < 1 || $number > 3999) {
2954 throw new coding_exception('Only integers between 0 and 3999 can be ' .
2955 'converted to roman numerals.', $number);
2956 }
2957
2958 return self::$thousands[$number / 1000 % 10] . self::$hundreds[$number / 100 % 10] .
2959 self::$tens[$number / 10 % 10] . self::$units[$number % 10];
2960 }
2961}