-
Notifications
You must be signed in to change notification settings - Fork 0
/
question.php
390 lines (360 loc) · 15.9 KB
/
question.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
// This file is part of the QuestionPy Moodle plugin - https://questionpy.org
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* QuestionPy question definition class.
*
* @package qtype_questionpy
* @copyright 2022 Martin Gauk, TU Berlin, innoCampus - www.questionpy.org
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use qtype_questionpy\api\api;
use qtype_questionpy\api\attempt_ui;
use qtype_questionpy\api\scoring_code;
use qtype_questionpy\constants;
use qtype_questionpy\question_ui_metadata_extractor;
use qtype_questionpy\utils;
/**
* Represents a QuestionPy question.
*
* @copyright 2022 Martin Gauk, TU Berlin, innoCampus - www.questionpy.org
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_questionpy_question extends question_graded_automatically_with_countback {
// Properties which do not change between attempts.
/** @var api */
private api $api;
/** @var string */
public string $packagehash;
/** @var string */
public string $questionstate;
/** @var stored_file|null */
private ?stored_file $packagefile;
// Properties which do change between attempts (i.e. are modified by start_attempt and apply_attempt_state).
/** @var string */
public string $attemptstate;
/** @var string|null */
public ?string $scoringstate;
/** @var attempt_ui */
public attempt_ui $ui;
/** @var question_ui_metadata_extractor $metadata */
public question_ui_metadata_extractor $metadata;
/** @var qbehaviour_questionpy|null $behaviour */
public ?qbehaviour_questionpy $behaviour = null;
/**
* Initialize a new question. Called from {@see qtype_questionpy::make_question_instance()}.
*
* @param string $packagehash
* @param string $questionstate
* @param stored_file|null $packagefile
* @param api $api
*/
public function __construct(string $packagehash, string $questionstate, ?stored_file $packagefile, api $api) {
parent::__construct();
$this->api = $api;
$this->packagehash = $packagehash;
$this->questionstate = $questionstate;
$this->packagefile = $packagefile;
}
/**
* Updates the ui property and metadata extractor.
*
* @param attempt_ui $ui
*/
private function update_ui(attempt_ui $ui): void {
$this->ui = $ui;
$this->metadata = new question_ui_metadata_extractor($this->ui->formulation);
}
/**
* Start a new attempt at this question, storing any information that will
* be needed later in the step.
*
* This is where the question can do any initialisation required on a
* per-attempt basis. For example, this is where the multiple choice
* question type randomly shuffles the choices (if that option is set).
*
* Any information about how the question has been set up for this attempt
* should be stored in the $step, by calling $step->set_qt_var(...).
*
* @param question_attempt_step $step The first step of the {@see question_attempt}
* being started. Can be used to store state.
* @param int $variant which variant of this question to start. Will be between
* 1 and {@see get_num_variants()} inclusive.
* @throws Throwable
*/
public function start_attempt(question_attempt_step $step, $variant): void {
global $PAGE;
try {
$attempt = $this->api->package($this->packagehash, $this->packagefile)->start_attempt($this->questionstate, $variant);
$this->attemptstate = $attempt->attemptstate;
$step->set_qt_var(constants::QT_VAR_ATTEMPT_STATE, $attempt->attemptstate);
$this->scoringstate = null;
$this->update_ui($attempt->ui);
} catch (Throwable $t) {
// Trigger error event.
$qa = $this->get_behaviour()->get_qa();
$params = [
'context' => $PAGE->context,
'relateduserid' => $step->get_user_id(),
'other' => [
'questionid' => $this->id,
'attemptusageid' => $qa->get_usage_id(),
'attemptslot' => $qa->get_slot(),
'errormessage' => $t->getMessage(),
],
];
$event = \qtype_questionpy\event\starting_attempt_failed::create($params);
$event->trigger();
debugging($event->get_description());
throw $t;
}
}
/**
* When an in-progress {@see question_attempt} is re-loaded from the
* database, this method is called so that the question can re-initialise
* its internal state as needed by this attempt.
*
* For example, the multiple choice question type needs to set the order
* of the choices to the order that was set up when start_attempt was called
* originally. All the information required to do this should be in the
* $step object, which is the first step of the question_attempt being loaded.
*
* @param question_attempt_step $step The first step of the {@see question_attempt}
* being loaded.
* @throws coding_exception
* @throws moodle_exception
*/
public function apply_attempt_state(question_attempt_step $step) {
global $PAGE;
$attemptstate = $step->get_qt_var(constants::QT_VAR_ATTEMPT_STATE);
if (is_null($attemptstate)) {
// There was a request error at start_attempt.
return;
}
$this->attemptstate = $attemptstate;
$this->scoringstate = $this->get_behaviour()->get_qa()->get_last_qt_var(constants::QT_VAR_SCORING_STATE);
$lastqtdata = $this->get_behaviour()->get_qa()->get_last_qt_data(null);
$lastresponse = $lastqtdata === null ? null : utils::filter_for_response($lastqtdata);
/* TODO: This method is also called from question_attempt->regrade and
question_attempt->start_question_based_on, where we shouldn't need to get the UI. */
try {
$attempt = $this->api->package($this->packagehash, $this->packagefile)
->view_attempt(
$this->questionstate,
$this->attemptstate,
$this->scoringstate,
$lastresponse
);
$this->update_ui($attempt->ui);
} catch (Throwable $t) {
// Trigger error event.
$params = [
'context' => $PAGE->context,
'relateduserid' => $step->get_user_id(),
'other' => [
'questionid' => $this->id,
'questionattemptid' => $this->get_behaviour()->get_qa()->get_database_id(),
'errormessage' => $t->getMessage(),
],
];
$event = \qtype_questionpy\event\viewing_attempt_failed::create($params);
$event->trigger();
debugging($event->get_description());
}
}
/**
* Checks that our behaviour has been set, which happens in {@see qbehaviour_questionpy::__construct}.
*
* @throws coding_exception
*/
private function get_behaviour(): qbehaviour_questionpy {
if ($this->behaviour === null) {
throw new coding_exception(
'qtype_questionpy_question->behaviour is not set, does the question use the wrong behaviour?'
);
}
return $this->behaviour;
}
/**
* What data may be included in the form submission when a student submits
* this question in its current state?
*
* This information is used in calls to optional_param. The parameter name
* has {@see question_attempt::get_field_prefix()} automatically prepended.
*
* @return array|string variable name => PARAM_... constant, or, as a special case
* that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
* meaning take all the raw submitted data belonging to this question.
*/
public function get_expected_data(): array|string {
if (!isset($this->metadata)) {
// There was an error -> get all the submitted data.
return question_attempt::USE_RAW_DATA;
}
return $this->metadata->extract()->expecteddata;
}
/**
* What data would need to be submitted to get this question correct.
* If there is more than one correct answer, this method should just
* return one possibility. If it is not possible to compute a correct
* response, this method should return null.
*
* @return array|null parameter name => value.
*/
public function get_correct_response(): ?array {
if (!isset($this->metadata)) {
// There was an error -> we cannot compute the correct response.
return null;
}
return $this->metadata->extract()->correctresponse;
}
/**
* Used by many of the behaviours, to work out whether the student's
* response to the question is complete. That is, whether the question attempt
* should move to the COMPLETE or INCOMPLETE state.
*
* @param array $response responses, as returned by
* {@see question_attempt_step::get_qt_data()}.
* @return bool whether this response is a complete answer to this question.
*/
public function is_complete_response(array $response): bool {
if (!isset($this->metadata)) {
// There was an error -> if no data was provided we want the question state to be set to INCOMPLETE.
return !empty($response);
}
foreach ($this->metadata->extract()->requiredfields as $requiredfield) {
if (!isset($response[$requiredfield]) || $response[$requiredfield] === '') {
return false;
}
}
return true;
}
/**
* Used by many of the behaviours to determine whether the student's
* response has changed. This is normally used to determine that a new set
* of responses can safely be discarded.
*
* @param array $prevresponse the responses previously recorded for this question,
* as returned by {@see question_attempt_step::get_qt_data()}
* @param array $newresponse the new responses, in the same format.
* @return bool whether the two sets of responses are the same - that is
* whether the new set of responses can safely be discarded.
*/
public function is_same_response(array $prevresponse, array $newresponse): bool {
// The response has already been filtered against get_expected_data, we just need to filter out attempt state
// and scoring state before comparing.
return utils::filter_for_response($prevresponse) == utils::filter_for_response($newresponse);
}
/**
* Produce a plain text summary of a response.
*
* @param array $response a response, as might be passed to {@see grade_response()}.
* @return string a plain text summary of that response, that could be used in reports.
*/
public function summarise_response(array $response) {
return '';
}
/**
* In situations where is_gradable_response() returns false, this method
* should generate a description of what the problem is.
*
* @param array $response responses
* @return string the message.
*/
public function get_validation_error(array $response) {
// This method is only called by the renderer of each question type.
// We do not call it in our renderer, so we can just return an empty string.
// The question package is responsible for displaying validation errors using JavaScript.
return '';
}
/**
* Grade a response to the question, returning a fraction between
* get_min_fraction() and get_max_fraction(), and the corresponding {@see question_state}
* right, partial or wrong.
*
* @param array $response responses, as returned by
* {@see question_attempt_step::get_qt_data()}.
* @return array (float, integer) the fraction, and the state.
* @throws coding_exception
* @throws moodle_exception
*/
public function grade_response(array $response): array {
global $PAGE;
try {
$attemptscored = $this->api->package($this->packagehash, $this->packagefile)->score_attempt(
$this->questionstate,
$this->attemptstate,
$this->scoringstate,
$response
);
$this->update_ui($attemptscored->ui);
} catch (Throwable $t) {
// Trigger error event.
$params = [
'context' => $PAGE->context,
// TODO: It would be nice to set a 'relateduserid'.
'other' => [
'questionid' => $this->id,
'errormessage' => $t->getMessage(),
],
];
$event = \qtype_questionpy\event\grading_response_failed::create($params);
$event->trigger();
debugging($event->get_description());
// As the server was not able to score the response, we mark this question with manual scoring.
return [0, question_state::$needsgrading];
}
// Persist scoring state.
$this->scoringstate = $attemptscored->scoringstate;
$this->get_behaviour()->get_pending_step()
->set_qt_var(constants::QT_VAR_SCORING_STATE, $attemptscored->scoringstate);
$newqstate = match ($attemptscored->scoringcode) {
scoring_code::automatically_scored => question_state::graded_state_for_fraction($attemptscored->score),
scoring_code::needs_manual_scoring => question_state::$needsgrading,
scoring_code::response_not_scorable => question_state::$gaveup,
scoring_code::invalid_response => question_state::$invalid,
};
return [$attemptscored->score, $newqstate];
}
/**
* Work out a final grade for this attempt, taking into account all the
* tries the student made.
*
* @param array $responses the response for each try. Each element of this
* array is a response array, as would be passed to {@see grade_response()}.
* There may be between 1 and $totaltries responses.
* @param int $totaltries The maximum number of tries allowed.
* @return numeric the fraction that should be awarded for this
* sequence of response.
* @throws coding_exception
*/
public function compute_final_grade($responses, $totaltries) {
// TODO: This is necessary to support interactive countback.
throw new coding_exception('not implemented');
}
/**
* Wraps the behaviour which would ordinarily have been used in a {@see qbehaviour_questionpy}.
*
* @param question_attempt $qa
* @param string $preferredbehaviour the requested type of behaviour.
* @return question_behaviour
* @throws coding_exception
*/
public function make_behaviour(question_attempt $qa, $preferredbehaviour): question_behaviour {
question_engine::load_behaviour_class('questionpy');
$delegate = parent::make_behaviour($qa, $preferredbehaviour);
return new qbehaviour_questionpy($qa, $preferredbehaviour, $delegate);
}
}