questiontypebase.php 11.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

// This file is part of Moodle - http://moodle.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/>.


/**
 * Question type class for the embedded element in question text question types.
 *
22
 * @package    qtype
23
 * @subpackage gapselect
24
25
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
27
28
29
30
31
32
33
34
35
36
 */


require_once($CFG->libdir . '/questionlib.php');
require_once($CFG->dirroot . '/question/engine/lib.php');
require_once($CFG->dirroot . '/question/format/xml/format.php');


/**
 * The embedded element in question text question type class.
 *
37
38
 * @copyright  2011 The Open University
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 */
40
abstract class qtype_gapselect_base extends question_type {
41
42
43
44
45
46
47
48
49
50
51
    /**
     * Choices are stored in the question_answers table, and any options need to
     * be put into the feedback field somehow. This method is responsible for
     * converting all the options to a single string for this purpose. It is used
     * by {@link save_question_options()}.
     * @param array $choice the form data relating to this choice.
     * @return string ready to store in the database.
     */
    protected abstract function choice_options_to_feedback($choice);

    public function save_question_options($question) {
52
53
        global $DB;
        $context = $question->context;
54
55
        $result = new stdClass();

56
57
        $oldanswers = $DB->get_records('question_answers',
                array('question' => $question->id), 'id ASC');
58
59
60
61
62
63
64
65
66
67

        // Insert all the new answers
        foreach ($question->choices as $key => $choice) {

            if (trim($choice['answer']) == '') {
                continue;
            }

            $feedback = $this->choice_options_to_feedback($choice);

68
            if ($answer = array_shift($oldanswers)) {
69
70
                $answer->answer = $choice['answer'];
                $answer->feedback = $feedback;
71
72
                $DB->update_record('question_answers', $answer);

73
            } else {
74
                $answer = new stdClass();
75
                $answer->question = $question->id;
76
77
                $answer->answer = $choice['answer'];
                $answer->answerformat = FORMAT_HTML;
78
79
                $answer->fraction = 0;
                $answer->feedback = $feedback;
80
81
                $answer->feedbackformat = 0;
                $DB->insert_record('question_answers', $answer);
82
83
84
85
            }
        }

        // Delete old answer records
86
87
        foreach($oldanswers as $oa) {
            delete_records('question_answers', 'id', $oa->id);
88
89
        }

90
        $options = $DB->get_record('question_' . $this->name(), array('questionid' => $question->id));
91
        if (!$options) {
92
            $options = new stdClass();
93
            $options->questionid = $question->id;
94
95
96
97
            $options->correctfeedback = '';
            $options->partiallycorrectfeedback = '';
            $options->incorrectfeedback = '';
            $options->id = $DB->insert_record('question_' . $this->name(), $options);
98
99
100
        }

        $options->shuffleanswers = !empty($question->shuffleanswers);
101
102
        $options = $this->save_combined_feedback_helper($options, $question, $context, true);
        $DB->update_record('question_' . $this->name(), $options);
103
104
105
106
107

        $this->save_hints($question, true);
    }

    public function get_question_options($question) {
108
109
110
        global $DB;
        $question->options = $DB->get_record('question_'.$this->name(),
                array('questionid' => $question->id), '*', MUST_EXIST);
111
112
113
        parent::get_question_options($question);
    }

114
115
116
117
    public function delete_question($questionid, $contextid) {
        global $DB;
        $DB->delete_records('question_'.$this->name(), array('questionid' => $questionid));
        return parent::delete_question($questionid, $contextid);
118
119
120
121
122
123
124
125
126
127
128
129
130
131
    }

    /**
     * Used by {@link initialise_question_instance()} to set up the choice-specific data.
     * @param object $choicedata as loaded from the question_answers table.
     * @return object an appropriate object for representing the choice.
     */
    protected abstract function make_choice($choicedata);

    protected function initialise_question_instance(question_definition $question, $questiondata) {
        parent::initialise_question_instance($question, $questiondata);

        $question->shufflechoices = $questiondata->options->shuffleanswers;

132
        $this->initialise_combined_feedback($question, $questiondata, true);
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

        $question->choices = array();
        $choiceindexmap= array();

        // Store the choices in arrays by group.
        $i = 1;
        foreach ($questiondata->options->answers as $choicedata) {
            $choice = $this->make_choice($choicedata);

            if (array_key_exists($choice->choice_group(), $question->choices)) {
                $question->choices[$choice->choice_group()][] = $choice;
            } else {
                $question->choices[$choice->choice_group()][1] = $choice;
            }

            end($question->choices[$choice->choice_group()]);
            $choiceindexmap[$i] = array($choice->choice_group(),
                    key($question->choices[$choice->choice_group()]));
            $i += 1;
        }

        $question->places = array();
        $question->textfragments = array();
        $question->rightchoices = array();
        // Break up the question text, and store the fragments, places and right answers.

        $bits = preg_split('/\[\[(\d+)]]/', $question->questiontext, null, PREG_SPLIT_DELIM_CAPTURE);
        $question->textfragments[0] = array_shift($bits);
        $i = 1;

        while (!empty($bits)) {
            $choice = array_shift($bits);

            list($group, $choiceindex) = $choiceindexmap[$choice];
            $question->places[$i] = $group;
            $question->rightchoices[$i] = $choiceindex;

            $question->textfragments[$i] = array_shift($bits);
            $i += 1;
        }
    }

    protected function make_hint($hint) {
        return question_hint_with_parts::load_from_record($hint);
    }

    public function get_random_guess_score($questiondata) {
        $question = $this->make_question($questiondata);
        return $question->get_random_guess_score();
    }

    /**
     * This function should reverse {@link choice_options_to_feedback()}.
     * @param string $feedback the data loaded from the database.
     * @return array the choice options.
     */
    protected abstract function feedback_to_choice_options($feedback);

    /**
     * This method gets the choices (answers)
     * in a 2 dimentional array.
     *
     * @param object $question
     * @return array of groups
     */
    protected function get_array_of_choices($question) {
        $subquestions = $question->options->answers;
        $count = 0;
        foreach ($subquestions as $key=>$subquestion) {
            $answers[$count]['id'] = $subquestion->id;
            $answers[$count]['answer'] = $subquestion->answer;
            $answers[$count]['fraction'] = $subquestion->fraction;
            $answers[$count] += $this->feedback_to_choice_options($subquestion->feedback);
            $answers[$count]['choice'] = $count+1;
            ++$count;
        }
        return $answers;
    }

212
213
    /**
     * This method gets the choices (answers) and sort them by groups
214
215
216
217
218
219
220
221
     * in a 2 dimentional array.
     *
     * @param object $question
     * @return array of groups
     */
    protected function get_array_of_groups($question, $state) {
        $answers = $this->get_array_of_choices($question);
        $arr = array();
222
223
224
225
        for ($group=1; $group < count($answers); $group++) {
            $players = $this->get_group_of_players($question, $state, $answers, $group);
            if ($players) {
                $arr[$group]= $players;
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
            }
        }
        return $arr;
    }

    /**
     * This method gets the correct answers in a 2 dimentional array.
     *
     * @param object $question
     * @return array of groups
     */
    protected function get_correct_answers($question) {
        $arrayofchoices = $this->get_array_of_choices($question);
        $arrayofplaceholdeers = $this->get_array_of_placeholders($question);

241
        $correctplayers = array();
242
243
244
        foreach($arrayofplaceholdeers as $ph) {
            foreach($arrayofchoices as $key=>$choice) {
                if(($key+1) == $ph) {
245
                    $correctplayers[]= $choice;
246
247
248
                }
            }
        }
249
        return $correctplayers;
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    }

    protected function get_array_of_placeholders($question) {
        $qtext = $question->questiontext;
        $error = '<b> ERROR</b>: Please check the form for this question. ';
        if(!$qtext) {
            echo $error . 'The question text is empty!';
            return false;
        }

        //get the slots
        $slots = $this->getEmbeddedTextArray($question);

        if(!$slots) {
            echo $error . 'The question text is not in the correct format!';
            return false;
        }

        $output = array();
        foreach ($slots as $slot) {
270
            $output[] = substr($slot, 2, strlen($slot) - 4); //2 is for '[[' and 4 is for '[[]]'.
271
272
273
274
        }
        return $output;
     }

275
276
277
278
279
    protected function get_group_of_players($question, $state, $subquestions, $group) {
        $goupofanswers = array();
        foreach ($subquestions as $key => $subquestion) {
            if ($subquestion[$this->choice_group_key()] == $group) {
                $goupofanswers[] = $subquestion;
280
281
282
            }
        }

283
        // Shuffle answers within this group
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        if ($question->options->shuffleanswers == 1) {
            shuffle($goupofanswers);
        }
        return $goupofanswers;
    }

    public function get_possible_responses($questiondata) {
        $question = $this->make_question($questiondata);

        $parts = array();
        foreach ($question->places as $place => $group) {
            $choices = array();

            foreach ($question->choices[$group] as $i => $choice) {
                $choices[$i] = new question_possible_response(
299
                        $question->html_to_text($choice->text),
300
301
302
303
304
305
306
307
308
309
                        $question->rightchoices[$place] == $i);
            }
            $choices[null] = question_possible_response::no_response();

            $parts[$place] = $choices;
        }

        return $parts;
    }

310
311
312
313
314
315
316
317
318
319
320
    function move_files($questionid, $oldcontextid, $newcontextid) {
        parent::move_files($questionid, $oldcontextid, $newcontextid);

        $fs = get_file_storage();
        $fs->move_area_files_to_new_context($oldcontextid,
                $newcontextid, 'question', 'correctfeedback', $questionid);
        $fs->move_area_files_to_new_context($oldcontextid,
                $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
        $fs->move_area_files_to_new_context($oldcontextid,
                $newcontextid, 'question', 'incorrectfeedback', $questionid);
    }
321

322
323
324
325
326
327
328
329
    protected function delete_files($questionid, $contextid) {
        parent::delete_files($questionid, $contextid);

        $fs = get_file_storage();
        $fs->delete_area_files($contextid, 'question', 'correctfeedback', $questionid);
        $fs->delete_area_files($contextid, 'question', 'partiallycorrectfeedback', $questionid);
        $fs->delete_area_files($contextid, 'question', 'incorrectfeedback', $questionid);
    }
330
}