Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * This file defines the class {@link question_definition} and its subclasses.
19
 *
20
 * The type hierarchy is quite complex. Here is a summary:
21
 * - question_definition
22
 *   - question_information_item
23
 *   - question_with_responses implements question_manually_gradable
24
 *     - question_graded_automatically implements question_automatically_gradable
25
 *       - question_graded_automatically_with_countback implements question_automatically_gradable_with_countback
26
 *       - question_graded_by_strategy
27
 *
28
 * Other classes:
29
 * - question_classified_response
30
 * - question_answer
31
 * - question_hint
32
 *   - question_hint_with_parts
33
 * - question_first_matching_answer_grading_strategy implements question_grading_strategy
34
 *
35
 * Other interfaces:
36
 * - question_response_answer_comparer
37
 *
38
 * @package    moodlecore
39
 * @subpackage questiontypes
40
 * @copyright  2009 The Open University
41
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
 
44
use core_question\output\question_version_info;
45
 
46
defined('MOODLE_INTERNAL') || die();
47
 
48
 
49
/**
50
 * The definition of a question of a particular type.
51
 *
52
 * This class is a close match to the question table in the database.
53
 * Definitions of question of a particular type normally subclass one of the
54
 * more specific classes {@link question_with_responses},
55
 * {@link question_graded_automatically} or {@link question_information_item}.
56
 *
57
 * @copyright  2009 The Open University
58
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59
 */
60
abstract class question_definition {
61
    /** @var integer id of the question in the datase, or null if this question
62
     * is not in the database. */
63
    public $id;
64
 
65
    /** @var integer question category id. */
66
    public $category;
67
 
68
    /** @var integer question context id. */
69
    public $contextid;
70
 
71
    /** @var integer parent question id. */
72
    public $parent = 0;
73
 
74
    /** @var question_type the question type this question is. */
75
    public $qtype;
76
 
77
    /** @var string question name. */
78
    public $name;
79
 
80
    /** @var string question text. */
81
    public $questiontext;
82
 
83
    /** @var integer question test format. */
84
    public $questiontextformat;
85
 
86
    /** @var string question general feedback. */
87
    public $generalfeedback;
88
 
89
    /** @var integer question test format. */
90
    public $generalfeedbackformat;
91
 
92
    /** @var float what this quetsion is marked out of, by default. */
93
    public $defaultmark = 1;
94
 
95
    /** @var integer How many question numbers this question consumes. */
96
    public $length = 1;
97
 
98
    /** @var number penalty factor of this question. */
99
    public $penalty = 0;
100
 
101
    /** @var string unique identifier of this question. */
102
    public $stamp;
103
 
104
    /** @var string question idnumber. */
105
    public $idnumber;
106
 
107
    /** @var integer timestamp when this question was created. */
108
    public $timecreated;
109
 
110
    /** @var integer timestamp when this question was modified. */
111
    public $timemodified;
112
 
113
    /** @var integer userid of the use who created this question. */
114
    public $createdby;
115
 
116
    /** @var integer userid of the use who modified this question. */
117
    public $modifiedby;
118
 
119
    /** @var array of question_hints. */
120
    public $hints = array();
121
 
122
    /** @var boolean question status hidden/ready/draft in the question bank. */
123
    public $status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
124
 
125
    /** @var int Version id of the question in a question bank */
126
    public $versionid;
127
 
128
    /** @var int Version number of the question in a question bank */
129
    public $version;
130
 
131
    /** @var int Bank entry id for the question */
132
    public $questionbankentryid;
133
 
134
    /** @var ?int The latest version of the question. null if we haven't checked yet. */
135
    protected $latestversion = null;
136
 
137
    /**
138
     * @var array of array of \core_customfield\data_controller objects indexed by fieldid for the questions custom fields.
139
     */
140
    public $customfields = array();
141
 
142
    /**
143
     * Constructor. Normally to get a question, you call
144
     * {@link question_bank::load_question()}, but questions can be created
145
     * directly, for example in unit test code.
146
     */
147
    public function __construct() {
148
    }
149
 
150
    /**
151
     * When a pending definition tries to read its latest version, fill in the latest version for all pending definitions
152
     *
153
     * @param string $name
154
     * @return mixed
155
     */
156
    public function __get($name) {
157
        if ($name === 'latestversion') {
158
            if (isset(question_version_info::$pendingdefinitions[$this->id])) {
159
                question_version_info::populate_latest_versions();
160
            }
161
            return $this->latestversion;
162
        }
163
    }
164
 
165
    /**
166
     * @return string the name of the question type (for example multichoice) that this
167
     * question is.
168
     */
169
    public function get_type_name() {
170
        return $this->qtype->name();
171
    }
172
 
173
    /**
174
     * Creat the appropriate behaviour for an attempt at this quetsion,
175
     * given the desired (archetypal) behaviour.
176
     *
177
     * This default implementation will suit most normal graded questions.
178
     *
179
     * If your question is of a patricular type, then it may need to do something
180
     * different. For example, if your question can only be graded manually, then
181
     * it should probably return a manualgraded behaviour, irrespective of
182
     * what is asked for.
183
     *
184
     * If your question wants to do somthing especially complicated is some situations,
185
     * then you may wish to return a particular behaviour related to the
186
     * one asked for. For example, you migth want to return a
187
     * qbehaviour_interactive_adapted_for_myqtype.
188
     *
189
     * @param question_attempt $qa the attempt we are creating a behaviour for.
190
     * @param string $preferredbehaviour the requested type of behaviour.
191
     * @return question_behaviour the new behaviour object.
192
     */
193
    public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
194
        return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
195
    }
196
 
197
    /**
198
     * Start a new attempt at this question, storing any information that will
199
     * be needed later in the step.
200
     *
201
     * This is where the question can do any initialisation required on a
202
     * per-attempt basis. For example, this is where the multiple choice
203
     * question type randomly shuffles the choices (if that option is set).
204
     *
205
     * Any information about how the question has been set up for this attempt
206
     * should be stored in the $step, by calling $step->set_qt_var(...).
207
     *
208
     * @param question_attempt_step The first step of the {@link question_attempt}
209
     *      being started. Can be used to store state.
210
     * @param int $varant which variant of this question to start. Will be between
211
     *      1 and {@link get_num_variants()} inclusive.
212
     */
213
    public function start_attempt(question_attempt_step $step, $variant) {
214
    }
215
 
216
    /**
217
     * When an in-progress {@link question_attempt} is re-loaded from the
218
     * database, this method is called so that the question can re-initialise
219
     * its internal state as needed by this attempt.
220
     *
221
     * For example, the multiple choice question type needs to set the order
222
     * of the choices to the order that was set up when start_attempt was called
223
     * originally. All the information required to do this should be in the
224
     * $step object, which is the first step of the question_attempt being loaded.
225
     *
226
     * @param question_attempt_step The first step of the {@link question_attempt}
227
     *      being loaded.
228
     */
229
    public function apply_attempt_state(question_attempt_step $step) {
230
    }
231
 
232
    /**
233
     * Verify if an attempt at this question can be re-graded using the other question version.
234
     *
235
     * To put it another way, will {@see update_attempt_state_date_from_old_version()} be able to work?
236
     *
237
     * It is expected that this relationship is symmetrical, so if you can regrade from V1 to V3, then
238
     * you can change back from V3 to V1.
239
     *
240
     * @param question_definition $otherversion a different version of the question to use in the regrade.
241
     * @return string|null null if the regrade can proceed, else a reason why not.
242
     */
243
    public function validate_can_regrade_with_other_version(question_definition $otherversion): ?string {
244
        if (get_class($otherversion) !== get_class($this)) {
245
            return get_string('cannotregradedifferentqtype', 'question');
246
        }
247
 
248
        return null;
249
    }
250
 
251
    /**
252
     * Update the data representing the initial state of an attempt another version of this question, to allow for the changes.
253
     *
254
     * What is required is probably most easily understood using an example. Think about multiple choice questions.
255
     * The first step has a variable '_order' which is a comma-separated list of question_answer ids.
256
     * A different version of the question will have different question_answers with different ids. However, the list of
257
     * choices should be similar, and so we need to shuffle the new list of ids in the same way that the old one was.
258
     *
259
     * Note: be sure to return all the data that was originally in $oldstep, while updating the fields that
260
     * require it. Otherwise you might break features like 'Each attempt builds on last' in the quiz.
261
     *
262
     * This method should only be called if {@see validate_can_regrade_with_other_version()} did not
263
     * flag up a potential problem. So, this method will throw a {@see coding_exception} if it is not
264
     * possible to work out a return value.
265
     *
266
     * @param question_attempt_step $oldstep the first step of a {@see question_attempt} at $oldquestion.
267
     * @param question_definition $oldquestion the previous version of the question, which $oldstate comes from.
268
     * @return array the submit data which can be passed to {@see apply_attempt_state} to start
269
     *     an attempt at this version of this question, corresponding to the attempt at the old question.
270
     * @throws coding_exception if this can't be done.
271
     */
272
    public function update_attempt_state_data_for_new_version(
273
            question_attempt_step $oldstep, question_definition $oldquestion) {
274
        $message = $this->validate_can_regrade_with_other_version($oldquestion);
275
        if ($message) {
276
            throw new coding_exception($message);
277
        }
278
 
279
        return $oldstep->get_qt_data();
280
    }
281
 
282
    /**
283
     * Generate a brief, plain-text, summary of this question. This is used by
284
     * various reports. This should show the particular variant of the question
285
     * as presented to students. For example, the calculated quetsion type would
286
     * fill in the particular numbers that were presented to the student.
287
     * This method will return null if such a summary is not possible, or
288
     * inappropriate.
289
     * @return string|null a plain text summary of this question.
290
     */
291
    public function get_question_summary() {
292
        return $this->html_to_text($this->questiontext, $this->questiontextformat);
293
    }
294
 
295
    /**
296
     * @return int the number of vaiants that this question has.
297
     */
298
    public function get_num_variants() {
299
        return 1;
300
    }
301
 
302
    /**
303
     * @return string that can be used to seed the pseudo-random selection of a
304
     *      variant.
305
     */
306
    public function get_variants_selection_seed() {
307
        return $this->stamp;
308
    }
309
 
310
    /**
311
     * Some questions can return a negative mark if the student gets it wrong.
312
     *
313
     * This method returns the lowest mark the question can return, on the
314
     * fraction scale. that is, where the maximum possible mark is 1.0.
315
     *
316
     * @return float minimum fraction this question will ever return.
317
     */
318
    public function get_min_fraction() {
319
        return 0;
320
    }
321
 
322
    /**
323
     * Some questions can return a mark greater than the maximum.
324
     *
325
     * This method returns the lowest highest the question can return, on the
326
     * fraction scale. that is, where the nominal maximum mark is 1.0.
327
     *
328
     * @return float maximum fraction this question will ever return.
329
     */
330
    public function get_max_fraction() {
331
        return 1;
332
    }
333
 
334
    /**
335
     * Given a response, rest the parts that are wrong.
336
     * @param array $response a response
337
     * @return array a cleaned up response with the wrong bits reset.
338
     */
339
    public function clear_wrong_from_response(array $response) {
340
        return array();
341
    }
342
 
343
    /**
344
     * Return the number of subparts of this response that are right.
345
     * @param array $response a response
346
     * @return array with two elements, the number of correct subparts, and
347
     * the total number of subparts.
348
     */
349
    public function get_num_parts_right(array $response) {
350
        return array(null, null);
351
    }
352
 
353
    /**
354
     * @param moodle_page the page we are outputting to.
355
     * @return qtype_renderer the renderer to use for outputting this question.
356
     */
357
    public function get_renderer(moodle_page $page) {
358
        return $page->get_renderer($this->qtype->plugin_name());
359
    }
360
 
361
    /**
362
     * What data may be included in the form submission when a student submits
363
     * this question in its current state?
364
     *
365
     * This information is used in calls to optional_param. The parameter name
366
     * has {@link question_attempt::get_field_prefix()} automatically prepended.
367
     *
368
     * @return array|string variable name => PARAM_... constant, or, as a special case
369
     *      that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
370
     *      meaning take all the raw submitted data belonging to this question.
371
     */
372
    abstract public function get_expected_data();
373
 
374
    /**
375
     * What data would need to be submitted to get this question correct.
376
     * If there is more than one correct answer, this method should just
377
     * return one possibility. If it is not possible to compute a correct
378
     * response, this method should return null.
379
     *
380
     * @return array|null parameter name => value.
381
     */
382
    abstract public function get_correct_response();
383
 
384
 
385
    /**
386
     * Takes an array of values representing a student response represented in a way that is understandable by a human and
387
     * transforms that to the response as the POST values returned from the HTML form that takes the student response during a
388
     * student attempt. Primarily this is used when reading csv values from a file of student responses in order to be able to
389
     * simulate the student interaction with a quiz.
390
     *
391
     * In most cases the array will just be returned as is. Some question types will need to transform the keys of the array,
392
     * as the meaning of the keys in the html form is deliberately obfuscated so that someone looking at the html does not get an
393
     * advantage. The values that represent the response might also be changed in order to more meaningful to a human.
394
     *
395
     * See the examples of question types that have overridden this in core and also see the csv files of simulated student
396
     * responses used in unit tests in :
397
     * - mod/quiz/tests/fixtures/stepsXX.csv
398
     * - mod/quiz/report/responses/tests/fixtures/steps00.csv
399
     * - mod/quiz/report/statistics/tests/fixtures/stepsXX.csv
400
     *
401
     * Also see {@link https://github.com/jamiepratt/moodle-quiz_simulate}, a quiz report plug in for uploading and downloading
402
     * student responses as csv files.
403
     *
404
     * @param array $simulatedresponse an array of data representing a student response
405
     * @return array a response array as would be returned from the html form (but without prefixes)
406
     */
407
    public function prepare_simulated_post_data($simulatedresponse) {
408
        return $simulatedresponse;
409
    }
410
 
411
    /**
412
     * Does the opposite of {@link prepare_simulated_post_data}.
413
     *
414
     * This takes a student response (the POST values returned from the HTML form that takes the student response during a
415
     * student attempt) it then represents it in a way that is understandable by a human.
416
     *
417
     * Primarily this is used when creating a file of csv from real student responses in order later to be able to
418
     * simulate the same student interaction with a quiz later.
419
     *
420
     * @param string[] $realresponse the response array as was returned from the form during a student attempt (without prefixes).
421
     * @return string[] an array of data representing a student response.
422
     */
423
    public function get_student_response_values_for_simulation($realresponse) {
424
        return $realresponse;
425
    }
426
 
427
    /**
428
     * Apply {@link format_text()} to some content with appropriate settings for
429
     * this question.
430
     *
431
     * @param string $text some content that needs to be output.
432
     * @param int $format the FORMAT_... constant.
433
     * @param question_attempt $qa the question attempt.
434
     * @param string $component used for rewriting file area URLs.
435
     * @param string $filearea used for rewriting file area URLs.
436
     * @param bool $clean Whether the HTML needs to be cleaned. Generally,
437
     *      parts of the question do not need to be cleaned, and student input does.
438
     * @return string the text formatted for output by format_text.
439
     */
440
    public function format_text($text, $format, $qa, $component, $filearea, $itemid,
441
            $clean = false) {
442
        $formatoptions = new stdClass();
443
        $formatoptions->noclean = !$clean;
444
        $formatoptions->para = false;
445
        $text = $qa->rewrite_pluginfile_urls($text, $component, $filearea, $itemid);
446
        return format_text($text, $format, $formatoptions);
447
    }
448
 
449
    /**
450
     * Convert some part of the question text to plain text. This might be used,
451
     * for example, by get_response_summary().
452
     * @param string $text The HTML to reduce to plain text.
453
     * @param int $format the FORMAT_... constant.
454
     * @return string the equivalent plain text.
455
     */
456
    public function html_to_text($text, $format) {
457
        return question_utils::to_plain_text($text, $format);
458
    }
459
 
460
    /** @return the result of applying {@link format_text()} to the question text. */
461
    public function format_questiontext($qa) {
1441 ariadna 462
        $formattext = $this->format_text(
463
            $this->questiontext,
464
            $this->questiontextformat,
465
            $qa,
466
            'question',
467
            'questiontext',
468
            $this->id
469
        );
470
 
471
        return html_writer::nonempty_tag('div', $formattext, ['class' => 'clearfix']);
1 efrain 472
    }
473
 
474
    /** @return the result of applying {@link format_text()} to the general feedback. */
475
    public function format_generalfeedback($qa) {
1441 ariadna 476
        $formattext  = $this->format_text(
477
            $this->generalfeedback,
478
            $this->generalfeedbackformat,
479
            $qa,
480
            'question',
481
            'generalfeedback',
482
            $this->id
483
        );
484
 
485
        return html_writer::nonempty_tag('div', $formattext, ['class' => 'clearfix']);
1 efrain 486
    }
487
 
488
    /**
489
     * Take some HTML that should probably already be a single line, like a
490
     * multiple choice choice, or the corresponding feedback, and make it so that
491
     * it is suitable to go in a place where the HTML must be inline, like inside a <p> tag.
492
     * @param string $html to HTML to fix up.
493
     * @return string the fixed HTML.
494
     */
495
    public function make_html_inline($html) {
496
        $html = preg_replace('~\s*<p>\s*~u', '', $html);
497
        $html = preg_replace('~\s*</p>\s*~u', '<br />', $html);
498
        $html = preg_replace('~(<br\s*/?>)+$~u', '', $html);
499
        return trim($html);
500
    }
501
 
502
    /**
503
     * Checks whether the users is allow to be served a particular file.
504
     * @param question_attempt $qa the question attempt being displayed.
505
     * @param question_display_options $options the options that control display of the question.
506
     * @param string $component the name of the component we are serving files for.
507
     * @param string $filearea the name of the file area.
508
     * @param array $args the remaining bits of the file path.
509
     * @param bool $forcedownload whether the user must be forced to download the file.
510
     * @return bool true if the user can access this file.
511
     */
512
    public function check_file_access($qa, $options, $component, $filearea, $args, $forcedownload) {
513
        if ($component == 'question' && $filearea == 'questiontext') {
514
            // Question text always visible, but check it is the right question id.
515
            return $args[0] == $this->id;
516
 
517
        } else if ($component == 'question' && $filearea == 'generalfeedback') {
518
            return $options->generalfeedback && $args[0] == $this->id;
519
 
520
        } else {
521
            // Unrecognised component or filearea.
522
            return false;
523
        }
524
    }
525
 
526
    /**
527
     * Return the question settings that define this question as structured data.
528
     *
529
     * This is used by external systems such as the Moodle mobile app, which want to display the question themselves,
530
     * rather than using the renderer provided.
531
     *
532
     * This method should only return the data that the student is allowed to see or know, given the current state of
533
     * the question. For example, do not include the 'General feedback' until the student has completed the question,
534
     * and even then, only include it if the question_display_options say it should be visible.
535
     *
536
     * But, within those rules, it is recommended that you return all the settings for the question,
537
     * to give maximum flexibility to the external system providing its own rendering of the question.
538
     *
539
     * @param question_attempt $qa the current attempt for which we are exporting the settings.
540
     * @param question_display_options $options the question display options which say which aspects of the question
541
     * should be visible.
542
     * @return mixed structure representing the question settings. In web services, this will be JSON-encoded.
543
     */
544
    public function get_question_definition_for_external_rendering(question_attempt $qa, question_display_options $options) {
545
 
546
        debugging('This question does not implement the get_question_definition_for_external_rendering() method yet.',
547
            DEBUG_DEVELOPER);
548
        return null;
549
    }
550
 
551
    /**
552
     * Set the latest version.
553
     *
554
     * Making $this->latestversion public would break the magic __get() behaviour above, so allow it to be set externally.
555
     *
556
     * @param int $latestversion
557
     * @return void
558
     */
559
    public function set_latest_version(int $latestversion): void {
560
        $this->latestversion = $latestversion;
561
    }
562
}
563
 
564
 
565
/**
566
 * This class represents a 'question' that actually does not allow the student
567
 * to respond, like the description 'question' type.
568
 *
569
 * @copyright  2009 The Open University
570
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
571
 */
572
class question_information_item extends question_definition {
573
    public function __construct() {
574
        parent::__construct();
575
        $this->defaultmark = 0;
576
        $this->penalty = 0;
577
        $this->length = 0;
578
    }
579
 
580
    public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
581
        return question_engine::make_behaviour('informationitem', $qa, $preferredbehaviour);
582
    }
583
 
584
    public function get_expected_data() {
585
        return array();
586
    }
587
 
588
    public function get_correct_response() {
589
        return array();
590
    }
591
 
592
    public function get_question_summary() {
593
        return null;
594
    }
595
}
596
 
597
 
598
/**
599
 * Interface that a {@link question_definition} must implement to be usable by
600
 * the manual graded behaviour.
601
 *
602
 * @copyright  2009 The Open University
603
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
604
 */
605
interface question_manually_gradable {
606
    /**
607
     * Use by many of the behaviours to determine whether the student
608
     * has provided enough of an answer for the question to be graded automatically,
609
     * or whether it must be considered aborted.
610
     *
611
     * @param array $response responses, as returned by
612
     *      {@link question_attempt_step::get_qt_data()}.
613
     * @return bool whether this response can be graded.
614
     */
615
    public function is_gradable_response(array $response);
616
 
617
    /**
618
     * Used by many of the behaviours, to work out whether the student's
619
     * response to the question is complete. That is, whether the question attempt
620
     * should move to the COMPLETE or INCOMPLETE state.
621
     *
622
     * @param array $response responses, as returned by
623
     *      {@link question_attempt_step::get_qt_data()}.
624
     * @return bool whether this response is a complete answer to this question.
625
     */
626
    public function is_complete_response(array $response);
627
 
628
    /**
629
     * Use by many of the behaviours to determine whether the student's
630
     * response has changed. This is normally used to determine that a new set
631
     * of responses can safely be discarded.
632
     *
633
     * @param array $prevresponse the responses previously recorded for this question,
634
     *      as returned by {@link question_attempt_step::get_qt_data()}
635
     * @param array $newresponse the new responses, in the same format.
636
     * @return bool whether the two sets of responses are the same - that is
637
     *      whether the new set of responses can safely be discarded.
638
     */
639
    public function is_same_response(array $prevresponse, array $newresponse);
640
 
641
    /**
642
     * Produce a plain text summary of a response.
643
     * @param array $response a response, as might be passed to {@link grade_response()}.
644
     * @return string a plain text summary of that response, that could be used in reports.
645
     */
646
    public function summarise_response(array $response);
647
 
648
    /**
649
     * If possible, construct a response that could have lead to the given
650
     * response summary. This is basically the opposite of {@link summarise_response()}
651
     * but it is intended only to be used for testing.
652
     *
653
     * @param string $summary a string, which might have come from summarise_response
654
     * @return array a response that could have lead to that.
655
     */
656
    public function un_summarise_response(string $summary);
657
 
658
    /**
659
     * Categorise the student's response according to the categories defined by
660
     * get_possible_responses.
661
     * @param $response a response, as might be passed to {@link grade_response()}.
662
     * @return array subpartid => {@link question_classified_response} objects.
663
     *      returns an empty array if no analysis is possible.
664
     */
665
    public function classify_response(array $response);
666
}
667
 
668
 
669
/**
670
 * This class is used in the return value from
671
 * {@link question_manually_gradable::classify_response()}.
672
 *
673
 * @copyright  2010 The Open University
674
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
675
 */
676
class question_classified_response {
677
    /**
678
     * @var string the classification of this response the student gave to this
679
     * part of the question. Must match one of the responseclasses returned by
680
     * {@link question_type::get_possible_responses()}.
681
     */
682
    public $responseclassid;
683
    /** @var string the actual response the student gave to this part. */
684
    public $response;
685
    /** @var number the fraction this part of the response earned. */
686
    public $fraction;
687
    /**
688
     * Constructor, just an easy way to set the fields.
689
     * @param string $responseclassid see the field descriptions above.
690
     * @param string $response see the field descriptions above.
691
     * @param number $fraction see the field descriptions above.
692
     */
693
    public function __construct($responseclassid, $response, $fraction) {
694
        $this->responseclassid = $responseclassid;
695
        $this->response = $response;
696
        $this->fraction = $fraction;
697
    }
698
 
699
    public static function no_response() {
700
        return new question_classified_response(null, get_string('noresponse', 'question'), null);
701
    }
702
}
703
 
704
 
705
/**
706
 * Interface that a {@link question_definition} must implement to be usable by
707
 * the various automatic grading behaviours.
708
 *
709
 * @copyright  2009 The Open University
710
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
711
 */
712
interface question_automatically_gradable extends question_manually_gradable {
713
    /**
714
     * In situations where is_gradable_response() returns false, this method
715
     * should generate a description of what the problem is.
716
     * @return string the message.
717
     */
718
    public function get_validation_error(array $response);
719
 
720
    /**
721
     * Grade a response to the question, returning a fraction between
722
     * get_min_fraction() and get_max_fraction(), and the corresponding {@link question_state}
723
     * right, partial or wrong.
724
     * @param array $response responses, as returned by
725
     *      {@link question_attempt_step::get_qt_data()}.
726
     * @return array (float, integer) the fraction, and the state.
727
     */
728
    public function grade_response(array $response);
729
 
730
    /**
731
     * Get one of the question hints. The question_attempt is passed in case
732
     * the question type wants to do something complex. For example, the
733
     * multiple choice with multiple responses question type will turn off most
734
     * of the hint options if the student has selected too many opitions.
735
     * @param int $hintnumber Which hint to display. Indexed starting from 0
736
     * @param question_attempt $qa The question_attempt.
737
     */
738
    public function get_hint($hintnumber, question_attempt $qa);
739
 
740
    /**
741
     * Generate a brief, plain-text, summary of the correct answer to this question.
742
     * This is used by various reports, and can also be useful when testing.
743
     * This method will return null if such a summary is not possible, or
744
     * inappropriate.
745
     * @return string|null a plain text summary of the right answer to this question.
746
     */
747
    public function get_right_answer_summary();
748
}
749
 
750
 
751
/**
752
 * Interface that a {@link question_definition} must implement to be usable by
753
 * the interactivecountback behaviour.
754
 *
755
 * @copyright  2010 The Open University
756
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
757
 */
758
interface question_automatically_gradable_with_countback extends question_automatically_gradable {
759
    /**
760
     * Work out a final grade for this attempt, taking into account all the
761
     * tries the student made.
762
     * @param array $responses the response for each try. Each element of this
763
     * array is a response array, as would be passed to {@link grade_response()}.
764
     * There may be between 1 and $totaltries responses.
765
     * @param int $totaltries The maximum number of tries allowed.
766
     * @return numeric the fraction that should be awarded for this
767
     * sequence of response.
768
     */
769
    public function compute_final_grade($responses, $totaltries);
770
}
771
 
772
 
773
/**
774
 * This class represents a real question. That is, one that is not a
775
 * {@link question_information_item}.
776
 *
777
 * @copyright  2009 The Open University
778
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
779
 */
780
abstract class question_with_responses extends question_definition
781
        implements question_manually_gradable {
782
    public function classify_response(array $response) {
783
        return array();
784
    }
785
 
786
    public function is_gradable_response(array $response) {
787
        return $this->is_complete_response($response);
788
    }
789
 
790
    public function un_summarise_response(string $summary) {
791
        throw new coding_exception('This question type (' . get_class($this) .
792
                ' does not implement the un_summarise_response testing method.');
793
    }
794
}
795
 
796
 
797
/**
798
 * This class represents a question that can be graded automatically.
799
 *
800
 * @copyright  2009 The Open University
801
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
802
 */
803
abstract class question_graded_automatically extends question_with_responses
804
        implements question_automatically_gradable {
805
    /** @var Some question types have the option to show the number of sub-parts correct. */
806
    public $shownumcorrect = false;
807
 
808
    public function get_right_answer_summary() {
809
        $correctresponse = $this->get_correct_response();
810
        if (empty($correctresponse)) {
811
            return null;
812
        }
813
        return $this->summarise_response($correctresponse);
814
    }
815
 
816
    /**
817
     * Check a request for access to a file belonging to a combined feedback field.
818
     * @param question_attempt $qa the question attempt being displayed.
819
     * @param question_display_options $options the options that control display of the question.
820
     * @param string $filearea the name of the file area.
821
     * @param array $args the remaining bits of the file path.
822
     * @return bool whether access to the file should be allowed.
823
     */
824
    protected function check_combined_feedback_file_access($qa, $options, $filearea, $args = null) {
825
        $state = $qa->get_state();
826
 
827
        if ($args === null) {
828
            debugging('You must pass $args as the fourth argument to check_combined_feedback_file_access.',
829
                    DEBUG_DEVELOPER);
830
            $args = array($this->id); // Fake it for now, so the rest of this method works.
831
        }
832
 
833
        if (!$state->is_finished()) {
834
            $response = $qa->get_last_qt_data();
835
            if (!$this->is_gradable_response($response)) {
836
                return false;
837
            }
838
            list($notused, $state) = $this->grade_response($response);
839
        }
840
 
841
        return $options->feedback && $state->get_feedback_class() . 'feedback' == $filearea &&
842
                $args[0] == $this->id;
843
    }
844
 
845
    /**
846
     * Check a request for access to a file belonging to a hint.
847
     * @param question_attempt $qa the question attempt being displayed.
848
     * @param question_display_options $options the options that control display of the question.
849
     * @param array $args the remaining bits of the file path.
850
     * @return bool whether access to the file should be allowed.
851
     */
852
    protected function check_hint_file_access($qa, $options, $args) {
853
        if (!$options->feedback) {
854
            return false;
855
        }
856
        $hint = $qa->get_applicable_hint();
1441 ariadna 857
        // If there is no applicable hint, that means access should not be granted.
858
        if (is_null($hint)) {
859
            return false;
860
        }
1 efrain 861
        $hintid = reset($args); // Itemid is hint id.
862
        return $hintid == $hint->id;
863
    }
864
 
865
    public function get_hint($hintnumber, question_attempt $qa) {
866
        if (!isset($this->hints[$hintnumber])) {
867
            return null;
868
        }
869
        return $this->hints[$hintnumber];
870
    }
871
 
872
    public function format_hint(question_hint $hint, question_attempt $qa) {
873
        return $this->format_text($hint->hint, $hint->hintformat, $qa,
874
                'question', 'hint', $hint->id);
875
    }
876
}
877
 
878
 
879
/**
880
 * This class represents a question that can be graded automatically with
881
 * countback grading in interactive mode.
882
 *
883
 * @copyright  2010 The Open University
884
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
885
 */
886
abstract class question_graded_automatically_with_countback
887
        extends question_graded_automatically
888
        implements question_automatically_gradable_with_countback {
889
 
890
    public function make_behaviour(question_attempt $qa, $preferredbehaviour) {
891
        if ($preferredbehaviour == 'interactive') {
892
            return question_engine::make_behaviour('interactivecountback',
893
                    $qa, $preferredbehaviour);
894
        }
895
        return question_engine::make_archetypal_behaviour($preferredbehaviour, $qa);
896
    }
897
}
898
 
899
 
900
/**
901
 * This class represents a question that can be graded automatically by using
902
 * a {@link question_grading_strategy}.
903
 *
904
 * @copyright  2009 The Open University
905
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
906
 */
907
abstract class question_graded_by_strategy extends question_graded_automatically {
908
    /** @var question_grading_strategy the strategy to use for grading. */
909
    protected $gradingstrategy;
910
 
911
    /** @param question_grading_strategy  $strategy the strategy to use for grading. */
912
    public function __construct(question_grading_strategy $strategy) {
913
        parent::__construct();
914
        $this->gradingstrategy = $strategy;
915
    }
916
 
917
    public function get_correct_response() {
918
        $answer = $this->get_correct_answer();
919
        if (!$answer) {
920
            return array();
921
        }
922
 
923
        return array('answer' => $answer->answer);
924
    }
925
 
926
    /**
927
     * Get an answer that contains the feedback and fraction that should be
928
     * awarded for this resonse.
929
     * @param array $response a response.
930
     * @return question_answer the matching answer.
931
     */
932
    public function get_matching_answer(array $response) {
933
        return $this->gradingstrategy->grade($response);
934
    }
935
 
936
    /**
937
     * @return question_answer an answer that contains the a response that would
938
     *      get full marks.
939
     */
940
    public function get_correct_answer() {
941
        return $this->gradingstrategy->get_correct_answer();
942
    }
943
 
944
    public function grade_response(array $response) {
945
        $answer = $this->get_matching_answer($response);
946
        if ($answer) {
947
            return array($answer->fraction,
948
                    question_state::graded_state_for_fraction($answer->fraction));
949
        } else {
950
            return array(0, question_state::$gradedwrong);
951
        }
952
    }
953
 
954
    public function classify_response(array $response) {
955
        if (empty($response['answer'])) {
956
            return array($this->id => question_classified_response::no_response());
957
        }
958
 
959
        $ans = $this->get_matching_answer($response);
960
        if (!$ans) {
961
            return array($this->id => new question_classified_response(
962
                    0, $response['answer'], 0));
963
        }
964
 
965
        return array($this->id => new question_classified_response(
966
                $ans->id, $response['answer'], $ans->fraction));
967
    }
968
}
969
 
970
 
971
/**
972
 * Class to represent a question answer, loaded from the question_answers table
973
 * in the database.
974
 *
975
 * @copyright  2009 The Open University
976
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
977
 */
978
class question_answer {
979
    /** @var integer the answer id. */
980
    public $id;
981
 
982
    /** @var string the answer. */
983
    public $answer;
984
 
985
    /** @var integer one of the FORMAT_... constans. */
986
    public $answerformat = FORMAT_PLAIN;
987
 
988
    /** @var number the fraction this answer is worth. */
989
    public $fraction;
990
 
991
    /** @var string the feedback for this answer. */
992
    public $feedback;
993
 
994
    /** @var integer one of the FORMAT_... constans. */
995
    public $feedbackformat;
996
 
997
    /**
998
     * Constructor.
999
     * @param int $id the answer.
1000
     * @param string $answer the answer.
1001
     * @param number $fraction the fraction this answer is worth.
1002
     * @param string $feedback the feedback for this answer.
1003
     * @param int $feedbackformat the format of the feedback.
1004
     */
1005
    public function __construct($id, $answer, $fraction, $feedback, $feedbackformat) {
1006
        $this->id = $id;
1007
        $this->answer = $answer;
1008
        $this->fraction = $fraction;
1009
        $this->feedback = $feedback;
1010
        $this->feedbackformat = $feedbackformat;
1011
    }
1012
}
1013
 
1014
 
1015
/**
1016
 * Class to represent a hint associated with a question.
1017
 * Used by iteractive mode, etc. A question has an array of these.
1018
 *
1019
 * @copyright  2010 The Open University
1020
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1021
 */
1022
class question_hint {
1023
    /** @var integer The hint id. */
1024
    public $id;
1025
    /** @var string The feedback hint to be shown. */
1026
    public $hint;
1027
    /** @var integer The corresponding text FORMAT_... type. */
1028
    public $hintformat;
1029
 
1030
    /**
1031
     * Constructor.
1032
     * @param int the hint id from the database.
1033
     * @param string $hint The hint text
1034
     * @param int the corresponding text FORMAT_... type.
1035
     */
1036
    public function __construct($id, $hint, $hintformat) {
1037
        $this->id = $id;
1038
        $this->hint = $hint;
1039
        $this->hintformat = $hintformat;
1040
    }
1041
 
1042
    /**
1043
     * Create a basic hint from a row loaded from the question_hints table in the database.
1044
     * @param object $row with $row->hint set.
1045
     * @return question_hint
1046
     */
1047
    public static function load_from_record($row) {
1048
        return new question_hint($row->id, $row->hint, $row->hintformat);
1049
    }
1050
 
1051
    /**
1052
     * Adjust this display options according to the hint settings.
1053
     * @param question_display_options $options
1054
     */
1055
    public function adjust_display_options(question_display_options $options) {
1056
        // Do nothing.
1057
    }
1058
}
1059
 
1060
 
1061
/**
1062
 * An extension of {@link question_hint} for questions like match and multiple
1063
 * choice with multile answers, where there are options for whether to show the
1064
 * number of parts right at each stage, and to reset the wrong parts.
1065
 *
1066
 * @copyright  2010 The Open University
1067
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1068
 */
1069
class question_hint_with_parts extends question_hint {
1070
    /** @var boolean option to show the number of sub-parts of the question that were right. */
1071
    public $shownumcorrect;
1072
 
1073
    /** @var boolean option to clear the parts of the question that were wrong on retry. */
1074
    public $clearwrong;
1075
 
1076
    /**
1077
     * Constructor.
1078
     * @param int the hint id from the database.
1079
     * @param string $hint The hint text
1080
     * @param int the corresponding text FORMAT_... type.
1081
     * @param bool $shownumcorrect whether the number of right parts should be shown
1082
     * @param bool $clearwrong whether the wrong parts should be reset.
1083
     */
1084
    public function __construct($id, $hint, $hintformat, $shownumcorrect, $clearwrong) {
1085
        parent::__construct($id, $hint, $hintformat);
1086
        $this->shownumcorrect = $shownumcorrect;
1087
        $this->clearwrong = $clearwrong;
1088
    }
1089
 
1090
    /**
1091
     * Create a basic hint from a row loaded from the question_hints table in the database.
1092
     * @param object $row with $row->hint, ->shownumcorrect and ->clearwrong set.
1093
     * @return question_hint_with_parts
1094
     */
1095
    public static function load_from_record($row) {
1096
        return new question_hint_with_parts($row->id, $row->hint, $row->hintformat,
1097
                $row->shownumcorrect, $row->clearwrong);
1098
    }
1099
 
1100
    public function adjust_display_options(question_display_options $options) {
1101
        parent::adjust_display_options($options);
1102
        if ($this->clearwrong) {
1103
            $options->clearwrong = true;
1104
        }
1105
        $options->numpartscorrect = $this->shownumcorrect;
1106
    }
1107
}
1108
 
1109
 
1110
/**
1111
 * This question_grading_strategy interface. Used to share grading code between
1112
 * questions that that subclass {@link question_graded_by_strategy}.
1113
 *
1114
 * @copyright  2009 The Open University
1115
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1116
 */
1117
interface question_grading_strategy {
1118
    /**
1119
     * Return a question answer that describes the outcome (fraction and feeback)
1120
     * for a particular respons.
1121
     * @param array $response the response.
1122
     * @return question_answer the answer describing the outcome.
1123
     */
1124
    public function grade(array $response);
1125
 
1126
    /**
1127
     * @return question_answer an answer that contains the a response that would
1128
     *      get full marks.
1129
     */
1130
    public function get_correct_answer();
1131
}
1132
 
1133
 
1134
/**
1135
 * This interface defines the methods that a {@link question_definition} must
1136
 * implement if it is to be graded by the
1137
 * {@link question_first_matching_answer_grading_strategy}.
1138
 *
1139
 * @copyright  2009 The Open University
1140
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1141
 */
1142
interface question_response_answer_comparer {
1143
    /** @return array of {@link question_answers}. */
1144
    public function get_answers();
1145
 
1146
    /**
1147
     * @param array $response the response.
1148
     * @param question_answer $answer an answer.
1149
     * @return bool whether the response matches the answer.
1150
     */
1151
    public function compare_response_with_answer(array $response, question_answer $answer);
1152
}
1153
 
1154
 
1155
/**
1156
 * This grading strategy is used by question types like shortanswer an numerical.
1157
 * It gets a list of possible answers from the question, and returns the first one
1158
 * that matches the given response. It returns the first answer with fraction 1.0
1159
 * when asked for the correct answer.
1160
 *
1161
 * @copyright  2009 The Open University
1162
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1163
 */
1164
class question_first_matching_answer_grading_strategy implements question_grading_strategy {
1165
    /**
1166
     * @var question_response_answer_comparer (presumably also a
1167
     * {@link question_definition}) the question we are doing the grading for.
1168
     */
1169
    protected $question;
1170
 
1171
    /**
1172
     * @param question_response_answer_comparer $question (presumably also a
1173
     * {@link question_definition}) the question we are doing the grading for.
1174
     */
1175
    public function __construct(question_response_answer_comparer $question) {
1176
        $this->question = $question;
1177
    }
1178
 
1179
    public function grade(array $response) {
1180
        foreach ($this->question->get_answers() as $aid => $answer) {
1181
            if ($this->question->compare_response_with_answer($response, $answer)) {
1182
                $answer->id = $aid;
1183
                return $answer;
1184
            }
1185
        }
1186
        return null;
1187
    }
1188
 
1189
    public function get_correct_answer() {
1190
        foreach ($this->question->get_answers() as $answer) {
1191
            $state = question_state::graded_state_for_fraction($answer->fraction);
1192
            if ($state == question_state::$gradedright) {
1193
                return $answer;
1194
            }
1195
        }
1196
        return null;
1197
    }
1198
}