MDL-20636 Fix codechecker issues in qtype_truefalse.
[moodle.git] / question / type / questiontype.php
CommitLineData
f29aeb5a
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
516cf3eb 18/**
4323d029 19 * The default questiontype class.
20 *
7764183a 21 * @package moodlecore
4323d029 22 * @subpackage questiontypes
7764183a
TH
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
271e6dec 25 */
516cf3eb 26
f29aeb5a 27
a17b297d
TH
28defined('MOODLE_INTERNAL') || die();
29
d1b7e03d 30require_once($CFG->dirroot . '/question/engine/lib.php');
516cf3eb 31
f29aeb5a 32
32b0adfa 33/**
34 * This is the base class for Moodle question types.
271ffe3f 35 *
32b0adfa 36 * There are detailed comments on each method, explaining what the method is
37 * for, and the circumstances under which you might need to override it.
271ffe3f 38 *
32b0adfa 39 * Note: the questiontype API should NOT be considered stable yet. Very few
22cebed5 40 * question types have been produced yet, so we do not yet know all the places
271ffe3f 41 * where the current API is insufficient. I would rather learn from the
32b0adfa 42 * experiences of the first few question type implementors, and improve the
43 * interface to meet their needs, rather the freeze the API prematurely and
44 * condem everyone to working round a clunky interface for ever afterwards.
271e6dec 45 *
7764183a
TH
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32b0adfa 48 */
d1b7e03d 49class question_type {
f29aeb5a
TH
50 protected $fileoptions = array(
51 'subdirs' => false,
52 'maxfiles' => -1,
53 'maxbytes' => 0,
54 );
516cf3eb 55
d1b7e03d 56 public function __construct() {
869309b8 57 }
58
4995b9c1 59 /**
d1b7e03d 60 * @return string the name of this question type.
869309b8 61 */
d1b7e03d
TH
62 public function name() {
63 return substr(get_class($this), 6);
a2156789 64 }
271ffe3f 65
f29aeb5a
TH
66 /**
67 * @return string the full frankenstyle name for this plugin.
68 */
69 public function plugin_name() {
70 return get_class($this);
71 }
72
73 /**
74 * @return string the name of this question type in the user's language.
75 * You should not need to override this method, the default behaviour should be fine.
76 */
77 public function local_name() {
78 return get_string($this->name(), $this->plugin_name());
79 }
80
869309b8 81 /**
82 * The name this question should appear as in the create new question
f29aeb5a
TH
83 * dropdown. Override this method to return false if you don't want your
84 * question type to be createable, for example if it is an abstract base type,
85 * otherwise, you should not need to override this method.
869309b8 86 *
87 * @return mixed the desired string, or false to hide this question type in the menu.
88 */
d1b7e03d 89 public function menu_name() {
f29aeb5a
TH
90 return $this->local_name();
91 }
92
93 /**
94 * Returns a list of other question types that this one requires in order to
95 * work. For example, the calculated question type is a subclass of the
96 * numerical question type, which is a subclass of the shortanswer question
97 * type; and the randomsamatch question type requires the shortanswer type
98 * to be installed.
99 *
100 * @return array any other question types that this one relies on. An empty
101 * array if none.
102 */
103 public function requires_qtypes() {
104 return array();
105 }
106
107 /**
f7970e3c 108 * @return bool override this to return false if this is not really a
f29aeb5a
TH
109 * question type, for example the description question type is not
110 * really a question type.
111 */
112 public function is_real_question_type() {
113 return true;
b974f947 114 }
115
a2156789 116 /**
f7970e3c 117 * @return bool true if this question type sometimes requires manual grading.
a2156789 118 */
d1b7e03d 119 public function is_manual_graded() {
a2156789 120 return false;
121 }
122
f24493ec 123 /**
124 * @param object $question a question of this type.
125 * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt.
f7970e3c 126 * @return bool true if a particular instance of this question requires manual grading.
f24493ec 127 */
d1b7e03d 128 public function is_question_manual_graded($question, $otherquestionsinuse) {
f24493ec 129 return $this->is_manual_graded();
130 }
131
869309b8 132 /**
f7970e3c 133 * @return bool true if this question type can be used by the random question type.
869309b8 134 */
d1b7e03d
TH
135 public function is_usable_by_random() {
136 return true;
869309b8 137 }
138
a2156789 139 /**
d1b7e03d
TH
140 * Whether this question type can perform a frequency analysis of student
141 * responses.
142 *
143 * If this method returns true, you must implement the get_possible_responses
144 * method, and the question_definition class must implement the
145 * classify_response method.
146 *
f7970e3c 147 * @return bool whether this report can analyse all the student reponses
d1b7e03d 148 * for things like the quiz statistics report.
a2156789 149 */
d1b7e03d
TH
150 public function can_analyse_responses() {
151 // This works in most cases.
152 return !$this->is_manual_graded();
a2156789 153 }
154
869309b8 155 /**
d1b7e03d
TH
156 * @return whether the question_answers.answer field needs to have
157 * restore_decode_content_links_worker called on it.
869309b8 158 */
d1b7e03d 159 public function has_html_answers() {
869309b8 160 return false;
161 }
d001dac7 162
295043c2 163 /**
164 * If your question type has a table that extends the question table, and
165 * you want the base class to automatically save, backup and restore the extra fields,
166 * override this method to return an array wherer the first element is the table name,
167 * and the subsequent entries are the column names (apart from id and questionid).
168 *
169 * @return mixed array as above, or null to tell the base class to do nothing.
170 */
d1b7e03d 171 public function extra_question_fields() {
295043c2 172 return null;
173 }
174
d001dac7 175 /**
176 * If you use extra_question_fields, overload this function to return question id field name
177 * in case you table use another name for this column
178 */
d1b7e03d 179 protected function questionid_column_name() {
d001dac7 180 return 'questionid';
181 }
182
295043c2 183 /**
184 * If your question type has a table that extends the question_answers table,
185 * make this method return an array wherer the first element is the table name,
186 * and the subsequent entries are the column names (apart from id and answerid).
187 *
188 * @return mixed array as above, or null to tell the base class to do nothing.
189 */
6b5f24d3
TH
190 protected function extra_answer_fields() {
191 return null;
192 }
193
194 /**
195 * If the quetsion type uses files in responses, then this method should
196 * return an array of all the response variables that might have corresponding
197 * files. For example, the essay qtype returns array('attachments', 'answers').
198 *
199 * @return array response variable names that may have associated files.
200 */
201 public function response_file_areas() {
202 return array();
203 }
295043c2 204
36703ed7 205 /**
206 * Return an instance of the question editing form definition. This looks for a
207 * class called edit_{$this->name()}_question_form in the file
f29aeb5a 208 * question/type/{$this->name()}/edit_{$this->name()}_question_form.php
36703ed7 209 * and if it exists returns an instance of it.
210 *
211 * @param string $submiturl passed on to the constructor call.
212 * @return object an instance of the form definition, or null if one could not be found.
213 */
d1b7e03d 214 public function create_editing_form($submiturl, $question, $category, $contexts, $formeditable) {
36703ed7 215 global $CFG;
216 require_once("{$CFG->dirroot}/question/type/edit_question_form.php");
271ffe3f 217 $definition_file = $CFG->dirroot.'/question/type/'.$this->name().'/edit_'.$this->name().'_form.php';
36703ed7 218 if (!(is_readable($definition_file) && is_file($definition_file))) {
219 return null;
220 }
221 require_once($definition_file);
6e34cd29 222 $classname = $this->plugin_name() . '_edit_form';
36703ed7 223 if (!class_exists($classname)) {
224 return null;
225 }
271e6dec 226 return new $classname($submiturl, $question, $category, $contexts, $formeditable);
36703ed7 227 }
228
99ba746d 229 /**
230 * @return string the full path of the folder this plugin's files live in.
231 */
d1b7e03d 232 public function plugin_dir() {
99ba746d 233 global $CFG;
234 return $CFG->dirroot . '/question/type/' . $this->name();
235 }
236
237 /**
238 * @return string the URL of the folder this plugin's files live in.
239 */
d1b7e03d 240 public function plugin_baseurl() {
99ba746d 241 global $CFG;
242 return $CFG->wwwroot . '/question/type/' . $this->name();
243 }
244
7b41a4a9 245 /**
246 * This method should be overriden if you want to include a special heading or some other
247 * html on a question editing page besides the question editing form.
248 *
249 * @param question_edit_form $mform a child of question_edit_form
250 * @param object $question
251 * @param string $wizardnow is '' for first page.
252 */
f29aeb5a
TH
253 public function display_question_editing_page($mform, $question, $wizardnow) {
254 global $OUTPUT;
255 $heading = $this->get_heading(empty($question->id));
256
257 echo $OUTPUT->heading_with_help($heading, $this->name(), $this->plugin_name());
258
271e6dec 259 $permissionstrs = array();
260 if (!empty($question->id)){
261 if ($question->formoptions->canedit){
262 $permissionstrs[] = get_string('permissionedit', 'question');
263 }
264 if ($question->formoptions->canmove){
265 $permissionstrs[] = get_string('permissionmove', 'question');
266 }
267 if ($question->formoptions->cansaveasnew){
268 $permissionstrs[] = get_string('permissionsaveasnew', 'question');
269 }
270 }
271 if (!$question->formoptions->movecontext && count($permissionstrs)){
f29aeb5a 272 echo $OUTPUT->heading(get_string('permissionto', 'question'), 3);
271e6dec 273 $html = '<ul>';
274 foreach ($permissionstrs as $permissionstr){
275 $html .= '<li>'.$permissionstr.'</li>';
276 }
277 $html .= '</ul>';
f29aeb5a 278 echo $OUTPUT->box($html, 'boxwidthnarrow boxaligncenter generalbox');
271e6dec 279 }
9ab75b2b 280 $mform->display();
281 }
271e6dec 282
9ab75b2b 283 /**
284 * Method called by display_question_editing_page and by question.php to get heading for breadcrumbs.
271e6dec 285 *
d1b7e03d 286 * @return string the heading
9ab75b2b 287 */
d1b7e03d 288 public function get_heading($adding = false){
f29aeb5a 289 if ($adding) {
d1b7e03d 290 $action = 'adding';
271e6dec 291 } else {
d1b7e03d 292 $action = 'editing';
c2f8c4be 293 }
f29aeb5a 294 return get_string($action . $this->name(), $this->plugin_name());
d1b7e03d
TH
295 }
296
297 /**
298 * Set any missing settings for this question to the default values. This is
299 * called before displaying the question editing form.
300 *
301 * @param object $questiondata the question data, loaded from the databsae,
302 * or more likely a newly created question object that is only partially
303 * initialised.
304 */
305 public function set_default_options($questiondata) {
7b41a4a9 306 }
307
516cf3eb 308 /**
24e8b9b6 309 * Saves (creates or updates) a question.
516cf3eb 310 *
311 * Given some question info and some data about the answers
312 * this function parses, organises and saves the question
313 * It is used by {@link question.php} when saving new data from
314 * a form, and also by {@link import.php} when importing questions
315 * This function in turn calls {@link save_question_options}
24e8b9b6 316 * to save question-type specific data.
317 *
318 * Whether we are saving a new question or updating an existing one can be
319 * determined by testing !empty($question->id). If it is not empty, we are updating.
320 *
321 * The question will be saved in category $form->category.
322 *
323 * @param object $question the question object which should be updated. For a new question will be mostly empty.
324 * @param object $form the object containing the information to save, as if from the question editing form.
325 * @param object $course not really used any more.
695d225c 326 * @return object On success, return the new question object. On failure,
271ffe3f 327 * return an object as follows. If the error object has an errors field,
32b0adfa 328 * display that as an error message. Otherwise, the editing form will be
695d225c 329 * redisplayed with validation errors, from validation_errors field, which
24e8b9b6 330 * is itself an object, shown next to the form fields. (I don't think this is accurate any more.)
516cf3eb 331 */
c7df5006 332 public function save_question($question, $form) {
f29aeb5a
TH
333 global $USER, $DB, $OUTPUT;
334
335 list($question->category) = explode(',', $form->category);
336 $context = $this->get_context_by_category_id($question->category);
fe6ce234 337
516cf3eb 338 // This default implementation is suitable for most
339 // question types.
271ffe3f 340
516cf3eb 341 // First, save the basic question itself
24e8b9b6 342 $question->name = trim($form->name);
24e8b9b6 343 $question->parent = isset($form->parent) ? $form->parent : 0;
516cf3eb 344 $question->length = $this->actual_number_of_questions($question);
345 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
346
f29aeb5a
TH
347 if (empty($form->questiontext['text'])) {
348 $question->questiontext = '';
516cf3eb 349 } else {
f29aeb5a 350 $question->questiontext = trim($form->questiontext['text']);;
516cf3eb 351 }
f29aeb5a 352 $question->questiontextformat = !empty($form->questiontext['format'])?$form->questiontext['format']:0;
516cf3eb 353
f29aeb5a 354 if (empty($form->generalfeedback['text'])) {
a4514d91 355 $question->generalfeedback = '';
1b8a7434 356 } else {
f29aeb5a 357 $question->generalfeedback = trim($form->generalfeedback['text']);
1b8a7434 358 }
f29aeb5a 359 $question->generalfeedbackformat = !empty($form->generalfeedback['format'])?$form->generalfeedback['format']:0;
1b8a7434 360
516cf3eb 361 if (empty($question->name)) {
f29aeb5a 362 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
516cf3eb 363 if (empty($question->name)) {
364 $question->name = '-';
365 }
366 }
367
368 if ($question->penalty > 1 or $question->penalty < 0) {
5e8a85aa 369 $question->errors['penalty'] = get_string('invalidpenalty', 'question');
516cf3eb 370 }
371
d1b7e03d
TH
372 if (isset($form->defaultmark)) {
373 $question->defaultmark = $form->defaultmark;
516cf3eb 374 }
375
f29aeb5a
TH
376 // If the question is new, create it.
377 if (empty($question->id)) {
cbe20043 378 // Set the unique code
379 $question->stamp = make_unique_id_code();
271e6dec 380 $question->createdby = $USER->id;
381 $question->timecreated = time();
f29aeb5a 382 $question->id = $DB->insert_record('question', $question);
516cf3eb 383 }
384
f29aeb5a
TH
385 // Now, whether we are updating a existing question, or creating a new
386 // one, we have to do the files processing and update the record.
387 /// Question already exists, update.
388 $question->modifiedby = $USER->id;
389 $question->timemodified = time();
390
391 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
392 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'], $context->id, 'question', 'questiontext', (int)$question->id, $this->fileoptions, $question->questiontext);
393 }
394 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
395 $question->generalfeedback = file_save_draft_area_files($form->generalfeedback['itemid'], $context->id, 'question', 'generalfeedback', (int)$question->id, $this->fileoptions, $question->generalfeedback);
396 }
397 $DB->update_record('question', $question);
398
516cf3eb 399 // Now to save all the answers and type-specific options
6459b8fc 400 $form->id = $question->id;
401 $form->qtype = $question->qtype;
516cf3eb 402 $form->category = $question->category;
6459b8fc 403 $form->questiontext = $question->questiontext;
f29aeb5a
TH
404 $form->questiontextformat = $question->questiontextformat;
405 // current context
406 $form->context = $context;
516cf3eb 407
408 $result = $this->save_question_options($form);
409
410 if (!empty($result->error)) {
f29aeb5a 411 print_error($result->error);
516cf3eb 412 }
413
414 if (!empty($result->notice)) {
415 notice($result->notice, "question.php?id=$question->id");
416 }
417
418 if (!empty($result->noticeyesno)) {
f29aeb5a 419 throw new coding_exception('$result->noticeyesno no longer supported in save_question.');
516cf3eb 420 }
421
cbe20043 422 // Give the question a unique version stamp determined by question_hash()
f29aeb5a 423 $DB->set_field('question', 'version', question_hash($question), array('id' => $question->id));
cbe20043 424
516cf3eb 425 return $question;
426 }
271ffe3f 427
516cf3eb 428 /**
d1b7e03d
TH
429 * Saves question-type specific options
430 *
431 * This is called by {@link save_question()} to save the question-type specific data
432 * @return object $result->error or $result->noticeyesno or $result->notice
433 * @param object $question This holds the information from the editing form,
434 * it is not a standard question object.
435 */
436 public function save_question_options($question) {
f29aeb5a 437 global $DB;
295043c2 438 $extra_question_fields = $this->extra_question_fields();
439
440 if (is_array($extra_question_fields)) {
441 $question_extension_table = array_shift($extra_question_fields);
271e6dec 442
295043c2 443 $function = 'update_record';
d001dac7 444 $questionidcolname = $this->questionid_column_name();
f29aeb5a 445 $options = $DB->get_record($question_extension_table, array($questionidcolname => $question->id));
295043c2 446 if (!$options) {
447 $function = 'insert_record';
0ff4bd08 448 $options = new stdClass();
d001dac7 449 $options->$questionidcolname = $question->id;
295043c2 450 }
451 foreach ($extra_question_fields as $field) {
452 if (!isset($question->$field)) {
0ff4bd08 453 $result = new stdClass();
295043c2 454 $result->error = "No data for field $field when saving " .
455 $this->name() . ' question id ' . $question->id;
456 return $result;
457 }
458 $options->$field = $question->$field;
459 }
271e6dec 460
f29aeb5a 461 if (!$DB->{$function}($question_extension_table, $options)) {
0ff4bd08 462 $result = new stdClass();
295043c2 463 $result->error = 'Could not save question options for ' .
464 $this->name() . ' question id ' . $question->id;
465 return $result;
466 }
467 }
468
469 $extra_answer_fields = $this->extra_answer_fields();
470 // TODO save the answers, with any extra data.
516cf3eb 471 }
472
d1b7e03d 473 public function save_hints($formdata, $withparts = false) {
f29aeb5a 474 global $DB;
7a719748
TH
475 $context = $formdata->context;
476
477 $oldhints = $DB->get_records('question_hints', array('questionid' => $formdata->id));
295043c2 478
d1b7e03d
TH
479 if (!empty($formdata->hint)) {
480 $numhints = max(array_keys($formdata->hint)) + 1;
481 } else {
482 $numhints = 0;
516cf3eb 483 }
295043c2 484
d1b7e03d
TH
485 if ($withparts) {
486 if (!empty($formdata->hintclearwrong)) {
487 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
488 } else {
489 $numclears = 0;
490 }
491 if (!empty($formdata->hintshownumcorrect)) {
492 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
493 } else {
494 $numshows = 0;
495 }
496 $numhints = max($numhints, $numclears, $numshows);
497 }
498
499 for ($i = 0; $i < $numhints; $i += 1) {
7a719748
TH
500 if (html_is_blank($formdata->hint[$i]['text'])) {
501 $formdata->hint[$i]['text'] = '';
d1b7e03d
TH
502 }
503
504 if ($withparts) {
7a719748
TH
505 $clearwrong = !empty($formdata->hintclearwrong[$i]);
506 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
d1b7e03d
TH
507 }
508
7a719748 509 if (empty($formdata->hint[$i]['text']) && empty($clearwrong) && empty($shownumcorrect)) {
d1b7e03d
TH
510 continue;
511 }
512
f3ca24e4 513 // Update an existing hint if possible.
7a719748
TH
514 $hint = array_shift($oldhints);
515 if (!$hint) {
516 $hint = new stdClass();
517 $hint->questionid = $formdata->id;
518 $hint->hint = '';
519 $hint->id = $DB->insert_record('question_hints', $hint);
520 }
521
7a719748
TH
522 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
523 $context, 'question', 'hint', $hint->id);
524 $hint->hintformat = $formdata->hint[$i]['format'];
525 if ($withparts) {
526 $hint->clearwrong = $clearwrong;
527 $hint->shownumcorrect = $shownumcorrect;
528 }
529 $DB->update_record('question_hints', $hint);
530 }
531
532 // Delete any remaining old hints.
533 $fs = get_file_storage();
c73c9836 534 foreach ($oldhints as $oldhint) {
7a719748
TH
535 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
536 $DB->delete_records('question_hints', array('id' => $oldhint->id));
d1b7e03d
TH
537 }
538 }
539
1c2ed7c5
TH
540 /**
541 * Can be used to {@link save_question_options()} to transfer the combined
542 * feedback fields from $formdata to $options.
543 * @param object $options the $question->options object being built.
544 * @param object $formdata the data from the form.
545 * @param object $context the context the quetsion is being saved into.
f7970e3c 546 * @param bool $withparts whether $options->shownumcorrect should be set.
1c2ed7c5
TH
547 */
548 protected function save_combined_feedback_helper($options, $formdata, $context, $withparts = false) {
549 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
550 $context, 'question', 'correctfeedback', $formdata->id);
551 $options->correctfeedbackformat = $formdata->correctfeedback['format'];
552 $options->partiallycorrectfeedback = $this->import_or_save_files($formdata->partiallycorrectfeedback,
553 $context, 'question', 'partiallycorrectfeedback', $formdata->id);
554 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
555 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
556 $context, 'question', 'incorrectfeedback', $formdata->id);
557 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
558
559 if ($withparts) {
560 $options->shownumcorrect = !empty($formdata->shownumcorrect);
561 }
562
563 return $options;
564 }
565
d1b7e03d
TH
566 /**
567 * Loads the question type specific options for the question.
568 *
569 * This function loads any question type specific options for the
570 * question from the database into the question object. This information
571 * is placed in the $question->options field. A question type is
572 * free, however, to decide on a internal structure of the options field.
573 * @return bool Indicates success or failure.
574 * @param object $question The question object for the question. This object
575 * should be updated to include the question type
576 * specific information (it is passed by reference).
577 */
578 public function get_question_options($question) {
f29aeb5a
TH
579 global $CFG, $DB, $OUTPUT;
580
581 if (!isset($question->options)) {
582 $question->options = new stdClass();
583 }
d1b7e03d 584
295043c2 585 $extra_question_fields = $this->extra_question_fields();
586 if (is_array($extra_question_fields)) {
587 $question_extension_table = array_shift($extra_question_fields);
f29aeb5a 588 $extra_data = $DB->get_record($question_extension_table, array($this->questionid_column_name() => $question->id), implode(', ', $extra_question_fields));
295043c2 589 if ($extra_data) {
590 foreach ($extra_question_fields as $field) {
591 $question->options->$field = $extra_data->$field;
592 }
593 } else {
f29aeb5a 594 echo $OUTPUT->notification("Failed to load question options from the table $question_extension_table for questionid " .
295043c2 595 $question->id);
596 return false;
597 }
598 }
599
600 $extra_answer_fields = $this->extra_answer_fields();
601 if (is_array($extra_answer_fields)) {
602 $answer_extension_table = array_shift($extra_answer_fields);
f29aeb5a
TH
603 $question->options->answers = $DB->get_records_sql("
604 SELECT qa.*, qax." . implode(', qax.', $extra_answer_fields) . "
605 FROM {question_answers} qa, {$answer_extension_table} qax
606 WHERE qa.questionid = ? AND qax.answerid = qa.id", array($question->id));
295043c2 607 if (!$question->options->answers) {
f29aeb5a 608 echo $OUTPUT->notification("Failed to load question answers from the table $answer_extension_table for questionid " .
295043c2 609 $question->id);
610 return false;
611 }
612 } else {
ca9000df 613 // Don't check for success or failure because some question types do not use the answers table.
f29aeb5a 614 $question->options->answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC');
295043c2 615 }
616
f29aeb5a 617 $question->hints = $DB->get_records('question_hints', array('questionid' => $question->id), 'id ASC');
d1b7e03d 618
516cf3eb 619 return true;
620 }
621
622 /**
d1b7e03d
TH
623 * Create an appropriate question_definition for the question of this type
624 * using data loaded from the database.
625 * @param object $questiondata the question data loaded from the database.
626 * @return question_definition the corresponding question_definition.
627 */
628 public function make_question($questiondata) {
629 $question = $this->make_question_instance($questiondata);
630 $this->initialise_question_instance($question, $questiondata);
631 return $question;
632 }
0429cd86 633
d1b7e03d
TH
634 /**
635 * Create an appropriate question_definition for the question of this type
636 * using data loaded from the database.
637 * @param object $questiondata the question data loaded from the database.
638 * @return question_definition an instance of the appropriate question_definition subclass.
639 * Still needs to be initialised.
640 */
641 protected function make_question_instance($questiondata) {
642 question_bank::load_question_definition_classes($this->name());
643 $class = 'qtype_' . $this->name() . '_question';
644 return new $class();
645 }
646
647 /**
648 * Initialise the common question_definition fields.
649 * @param question_definition $question the question_definition we are creating.
650 * @param object $questiondata the question data loaded from the database.
651 */
652 protected function initialise_question_instance(question_definition $question, $questiondata) {
653 $question->id = $questiondata->id;
654 $question->category = $questiondata->category;
56e82d99 655 $question->contextid = $questiondata->contextid;
d1b7e03d
TH
656 $question->parent = $questiondata->parent;
657 $question->qtype = $this;
658 $question->name = $questiondata->name;
659 $question->questiontext = $questiondata->questiontext;
660 $question->questiontextformat = $questiondata->questiontextformat;
661 $question->generalfeedback = $questiondata->generalfeedback;
1c2ed7c5 662 $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
d1b7e03d
TH
663 $question->defaultmark = $questiondata->defaultmark + 0;
664 $question->length = $questiondata->length;
665 $question->penalty = $questiondata->penalty;
666 $question->stamp = $questiondata->stamp;
667 $question->version = $questiondata->version;
668 $question->hidden = $questiondata->hidden;
669 $question->timecreated = $questiondata->timecreated;
670 $question->timemodified = $questiondata->timemodified;
671 $question->createdby = $questiondata->createdby;
672 $question->modifiedby = $questiondata->modifiedby;
673
674 $this->initialise_question_hints($question, $questiondata);
675 }
676
677 /**
678 * Initialise question_definition::hints field.
679 * @param question_definition $question the question_definition we are creating.
680 * @param object $questiondata the question data loaded from the database.
681 */
682 protected function initialise_question_hints(question_definition $question, $questiondata) {
683 if (empty($questiondata->hints)) {
684 return;
685 }
686 foreach ($questiondata->hints as $hint) {
687 $question->hints[] = $this->make_hint($hint);
688 }
0429cd86 689 }
690
691 /**
d1b7e03d
TH
692 * Create a question_hint, or an appropriate subclass for this question,
693 * from a row loaded from the database.
694 * @param object $hint the DB row from the question hints table.
695 * @return question_hint
9203b705 696 */
d1b7e03d
TH
697 protected function make_hint($hint) {
698 return question_hint::load_from_record($hint);
699 }
700
1c2ed7c5
TH
701 /**
702 * Initialise the combined feedback fields.
703 * @param question_definition $question the question_definition we are creating.
704 * @param object $questiondata the question data loaded from the database.
f7970e3c 705 * @param bool $withparts whether to set the shownumcorrect field.
1c2ed7c5
TH
706 */
707 protected function initialise_combined_feedback(question_definition $question, $questiondata, $withparts = false) {
708 $question->correctfeedback = $questiondata->options->correctfeedback;
709 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
710 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
711 $question->partiallycorrectfeedbackformat = $questiondata->options->partiallycorrectfeedbackformat;
712 $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
713 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
714 if ($withparts) {
715 $question->shownumcorrect = $questiondata->options->shownumcorrect;
716 }
717 }
718
d1b7e03d
TH
719 /**
720 * Initialise question_definition::answers field.
721 * @param question_definition $question the question_definition we are creating.
722 * @param object $questiondata the question data loaded from the database.
723 */
724 protected function initialise_question_answers(question_definition $question, $questiondata) {
725 $question->answers = array();
726 if (empty($questiondata->options->answers)) {
727 return;
728 }
729 foreach ($questiondata->options->answers as $a) {
5f7cfba7
TH
730 $question->answers[$a->id] = new question_answer($a->id, $a->answer,
731 $a->fraction, $a->feedback, $a->feedbackformat);
d1b7e03d
TH
732 }
733 }
9203b705 734
d1b7e03d 735 /**
f29aeb5a 736 * Deletes the question-type specific data when a question is deleted.
f7970e3c
TH
737 * @param int $question the question being deleted.
738 * @param int $contextid the context this quesiotn belongs to.
f29aeb5a
TH
739 */
740 public function delete_question($questionid, $contextid) {
741 global $DB;
742
743 $this->delete_files($questionid, $contextid);
516cf3eb 744
295043c2 745 $extra_question_fields = $this->extra_question_fields();
746 if (is_array($extra_question_fields)) {
747 $question_extension_table = array_shift($extra_question_fields);
f29aeb5a
TH
748 $DB->delete_records($question_extension_table,
749 array($this->questionid_column_name() => $questionid));
295043c2 750 }
751
752 $extra_answer_fields = $this->extra_answer_fields();
753 if (is_array($extra_answer_fields)) {
754 $answer_extension_table = array_shift($extra_answer_fields);
f29aeb5a
TH
755 $DB->delete_records_select($answer_extension_table,
756 "answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)", array($questionid));
295043c2 757 }
758
f29aeb5a 759 $DB->delete_records('question_answers', array('question' => $questionid));
d1b7e03d 760
f29aeb5a 761 $DB->delete_records('question_hints', array('questionid' => $questionid));
516cf3eb 762 }
763
764 /**
765 * Returns the number of question numbers which are used by the question
766 *
767 * This function returns the number of question numbers to be assigned
768 * to the question. Most question types will have length one; they will be
dfa47f96 769 * assigned one number. The 'description' type, however does not use up a
516cf3eb 770 * number and so has a length of zero. Other question types may wish to
771 * handle a bundle of questions and hence return a number greater than one.
f7970e3c 772 * @return int The number of question numbers which should be
516cf3eb 773 * assigned to the question.
774 * @param object $question The question whose length is to be determined.
775 * Question type specific information is included.
776 */
d1b7e03d 777 public function actual_number_of_questions($question) {
516cf3eb 778 // By default, each question is given one number
779 return 1;
780 }
781
6f51ed72 782 /**
783 * @param object $question
d1b7e03d
TH
784 * @return number|null either a fraction estimating what the student would
785 * score by guessing, or null, if it is not possible to estimate.
6f51ed72 786 */
c7df5006 787 public function get_random_guess_score($questiondata) {
6f51ed72 788 return 0;
789 }
516cf3eb 790
516cf3eb 791 /**
d1b7e03d 792 * This method should return all the possible types of response that are
f9b0500f 793 * recognised for this question.
271e6dec 794 *
d1b7e03d
TH
795 * The question is modelled as comprising one or more subparts. For each
796 * subpart, there are one or more classes that that students response
797 * might fall into, each of those classes earning a certain score.
50da63eb 798 *
d1b7e03d
TH
799 * For example, in a shortanswer question, there is only one subpart, the
800 * text entry field. The response the student gave will be classified according
801 * to which of the possible $question->options->answers it matches.
271e6dec 802 *
d1b7e03d
TH
803 * For the matching question type, there will be one subpart for each
804 * question stem, and for each stem, each of the possible choices is a class
805 * of student's response.
806 *
807 * A response is an object with two fields, ->responseclass is a string
808 * presentation of that response, and ->fraction, the credit for a response
809 * in that class.
810 *
811 * Array keys have no specific meaning, but must be unique, and must be
812 * the same if this function is called repeatedly.
813 *
814 * @param object $question the question definition data.
815 * @return array keys are subquestionid, values are arrays of possible
816 * responses to that subquestion.
99ba746d 817 */
c7df5006 818 public function get_possible_responses($questiondata) {
d1b7e03d 819 return array();
50da63eb 820 }
5fceb049 821
50da63eb 822 /**
f29aeb5a
TH
823 * Like @see{get_html_head_contributions}, but this method is for CSS and
824 * JavaScript required on the question editing page question/question.php.
50da63eb 825 */
d1b7e03d 826 public function get_editing_head_contributions() {
50da63eb 827 // By default, we link to any of the files styles.css, styles.php,
828 // script.js or script.php that exist in the plugin folder.
829 // Core question types should not use this mechanism. Their styles
830 // should be included in the standard theme.
f29aeb5a 831 $this->find_standard_scripts();
50da63eb 832 }
271e6dec 833
50da63eb 834 /**
f29aeb5a 835 * Utility method used by @see{get_html_head_contributions} and
50da63eb 836 * @see{get_editing_head_contributions}. This looks for any of the files
f29aeb5a
TH
837 * script.js or script.php that exist in the plugin folder and ensures they
838 * get included.
50da63eb 839 */
c76145d3 840 public function find_standard_scripts() {
f29aeb5a
TH
841 global $PAGE;
842
99ba746d 843 $plugindir = $this->plugin_dir();
f29aeb5a 844 $plugindirrel = 'question/type/' . $this->name();
50da63eb 845
846 if (file_exists($plugindir . '/script.js')) {
f29aeb5a 847 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
50da63eb 848 }
849 if (file_exists($plugindir . '/script.php')) {
f29aeb5a 850 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
516cf3eb 851 }
fe9b5cfd 852 }
853
62e76c67 854 /**
d1b7e03d
TH
855 * Returns true if the editing wizard is finished, false otherwise.
856 *
857 * The default implementation returns true, which is suitable for all question-
858 * types that only use one editing form. This function is used in
859 * question.php to decide whether we can regrade any states of the edited
860 * question and redirect to edit.php.
861 *
862 * The dataset dependent question-type, which is extended by the calculated
863 * question-type, overwrites this method because it uses multiple pages (i.e.
864 * a wizard) to set up the question and associated datasets.
865 *
866 * @param object $form The data submitted by the previous page.
867 *
f7970e3c 868 * @return bool Whether the wizard's last page was submitted or not.
d1b7e03d 869 */
f29aeb5a 870 public function finished_edit_wizard($form) {
d1b7e03d
TH
871 //In the default case there is only one edit page.
872 return true;
62e76c67 873 }
874
88bc20c3 875/// IMPORT/EXPORT FUNCTIONS /////////////////
876
877 /*
878 * Imports question from the Moodle XML format
879 *
880 * Imports question using information from extra_question_fields function
881 * If some of you fields contains id's you'll need to reimplement this
882 */
d1b7e03d 883 public function import_from_xml($data, $question, $format, $extra=null) {
88bc20c3 884 $question_type = $data['@']['type'];
885 if ($question_type != $this->name()) {
886 return false;
887 }
888
889 $extraquestionfields = $this->extra_question_fields();
890 if (!is_array($extraquestionfields)) {
891 return false;
892 }
893
894 //omit table name
895 array_shift($extraquestionfields);
896 $qo = $format->import_headers($data);
897 $qo->qtype = $question_type;
898
899 foreach ($extraquestionfields as $field) {
f29aeb5a 900 $qo->$field = $format->getpath($data, array('#',$field,0,'#'), $qo->$field);
88bc20c3 901 }
902
903 // run through the answers
904 $answers = $data['#']['answer'];
905 $a_count = 0;
906 $extraasnwersfields = $this->extra_answer_fields();
907 if (is_array($extraasnwersfields)) {
908 //TODO import the answers, with any extra data.
909 } else {
910 foreach ($answers as $answer) {
911 $ans = $format->import_answer($answer);
912 $qo->answer[$a_count] = $ans->answer;
913 $qo->fraction[$a_count] = $ans->fraction;
914 $qo->feedback[$a_count] = $ans->feedback;
915 ++$a_count;
916 }
917 }
918 return $qo;
919 }
920
921 /*
922 * Export question to the Moodle XML format
923 *
924 * Export question using information from extra_question_fields function
925 * If some of you fields contains id's you'll need to reimplement this
926 */
d1b7e03d 927 public function export_to_xml($question, $format, $extra=null) {
88bc20c3 928 $extraquestionfields = $this->extra_question_fields();
929 if (!is_array($extraquestionfields)) {
930 return false;
931 }
932
933 //omit table name
934 array_shift($extraquestionfields);
935 $expout='';
936 foreach ($extraquestionfields as $field) {
2d01a916
TH
937 $exportedvalue = $question->options->$field;
938 if (!empty($exportedvalue) && htmlspecialchars($exportedvalue) != $exportedvalue) {
939 $exportedvalue = '<![CDATA[' . $exportedvalue . ']]>';
940 }
941 $expout .= " <$field>{$exportedvalue}</$field>\n";
88bc20c3 942 }
943
944 $extraasnwersfields = $this->extra_answer_fields();
945 if (is_array($extraasnwersfields)) {
946 //TODO export answers with any extra data
947 } else {
948 foreach ($question->options->answers as $answer) {
949 $percent = 100 * $answer->fraction;
950 $expout .= " <answer fraction=\"$percent\">\n";
951 $expout .= $format->writetext($answer->answer, 3, false);
952 $expout .= " <feedback>\n";
953 $expout .= $format->writetext($answer->feedback, 4, false);
954 $expout .= " </feedback>\n";
955 $expout .= " </answer>\n";
956 }
957 }
958 return $expout;
959 }
960
b9bd6da4 961 /**
962 * Abstract function implemented by each question type. It runs all the code
963 * required to set up and save a question of any type for testing purposes.
964 * Alternate DB table prefix may be used to facilitate data deletion.
965 */
d1b7e03d 966 public function generate_test($name, $courseid=null) {
b9bd6da4 967 $form = new stdClass();
968 $form->name = $name;
969 $form->questiontextformat = 1;
970 $form->questiontext = 'test question, generated by script';
d1b7e03d
TH
971 $form->defaultmark = 1;
972 $form->penalty = 0.3333333;
b9bd6da4 973 $form->generalfeedback = "Well done";
974
975 $context = get_context_instance(CONTEXT_COURSE, $courseid);
976 $newcategory = question_make_default_categories(array($context));
977 $form->category = $newcategory->id . ',1';
978
979 $question = new stdClass();
980 $question->courseid = $courseid;
981 $question->qtype = $this->qtype;
982 return array($form, $question);
983 }
f29aeb5a
TH
984
985 /**
986 * Get question context by category id
987 * @param int $category
988 * @return object $context
989 */
c7df5006 990 protected function get_context_by_category_id($category) {
f29aeb5a
TH
991 global $DB;
992 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
993 $context = get_context_instance_by_id($contextid);
994 return $context;
995 }
996
997 /**
998 * Save the file belonging to one text field.
999 *
1000 * @param array $field the data from the form (or from import). This will
1001 * normally have come from the formslib editor element, so it will be an
1002 * array with keys 'text', 'format' and 'itemid'. However, when we are
1003 * importing, it will be an array with keys 'text', 'format' and 'files'
1004 * @param object $context the context the question is in.
1005 * @param string $component indentifies the file area question.
1006 * @param string $filearea indentifies the file area questiontext, generalfeedback,answerfeedback.
f7970e3c 1007 * @param int $itemid identifies the file area.
f29aeb5a
TH
1008 *
1009 * @return string the text for this field, after files have been processed.
1010 */
1011 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1012 if (!empty($field['itemid'])) {
1013 // This is the normal case. We are safing the questions editing form.
1014 return file_save_draft_area_files($field['itemid'], $context->id, $component,
1015 $filearea, $itemid, $this->fileoptions, trim($field['text']));
1016
1017 } else if (!empty($field['files'])) {
1018 // This is the case when we are doing an import.
1019 foreach ($field['files'] as $file) {
1020 $this->import_file($context, $component, $filearea, $itemid, $file);
1021 }
1022 }
1023 return trim($field['text']);
1024 }
1025
1026 /**
1027 * Move all the files belonging to this question from one context to another.
f7970e3c
TH
1028 * @param int $questionid the question being moved.
1029 * @param int $oldcontextid the context it is moving from.
1030 * @param int $newcontextid the context it is moving to.
f29aeb5a
TH
1031 */
1032 public function move_files($questionid, $oldcontextid, $newcontextid) {
1033 $fs = get_file_storage();
1034 $fs->move_area_files_to_new_context($oldcontextid,
1035 $newcontextid, 'question', 'questiontext', $questionid);
1036 $fs->move_area_files_to_new_context($oldcontextid,
1037 $newcontextid, 'question', 'generalfeedback', $questionid);
1038 }
1039
1040 /**
1041 * Move all the files belonging to this question's answers when the question
1042 * is moved from one context to another.
f7970e3c
TH
1043 * @param int $questionid the question being moved.
1044 * @param int $oldcontextid the context it is moving from.
1045 * @param int $newcontextid the context it is moving to.
1046 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1047 * as well as an 'answerfeedback' one. Default false.
1048 */
1049 protected function move_files_in_answers($questionid, $oldcontextid, $newcontextid, $answerstoo = false) {
1050 global $DB;
1051 $fs = get_file_storage();
1052
1053 $answerids = $DB->get_records_menu('question_answers',
1054 array('question' => $questionid), 'id', 'id,1');
1055 foreach ($answerids as $answerid => $notused) {
1056 if ($answerstoo) {
1057 $fs->move_area_files_to_new_context($oldcontextid,
1058 $newcontextid, 'question', 'answer', $answerid);
1059 }
1060 $fs->move_area_files_to_new_context($oldcontextid,
1061 $newcontextid, 'question', 'answerfeedback', $answerid);
1062 }
1063 }
1064
1065 /**
1066 * Delete all the files belonging to this question.
f7970e3c
TH
1067 * @param int $questionid the question being deleted.
1068 * @param int $contextid the context the question is in.
f29aeb5a
TH
1069 */
1070 protected function delete_files($questionid, $contextid) {
1071 $fs = get_file_storage();
1072 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1073 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1074 }
1075
1076 /**
1077 * Delete all the files belonging to this question's answers.
f7970e3c
TH
1078 * @param int $questionid the question being deleted.
1079 * @param int $contextid the context the question is in.
1080 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1081 * as well as an 'answerfeedback' one. Default false.
1082 */
1083 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1084 global $DB;
1085 $fs = get_file_storage();
1086
1087 $answerids = $DB->get_records_menu('question_answers',
1088 array('question' => $questionid), 'id', 'id,1');
1089 foreach ($answerids as $answerid => $notused) {
1090 if ($answerstoo) {
1091 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1092 }
1093 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1094 }
1095 }
1096
c7df5006 1097 protected function import_file($context, $component, $filearea, $itemid, $file) {
f29aeb5a 1098 $fs = get_file_storage();
0ff4bd08 1099 $record = new stdClass();
f29aeb5a
TH
1100 if (is_object($context)) {
1101 $record->contextid = $context->id;
1102 } else {
1103 $record->contextid = $context;
1104 }
1105 $record->component = $component;
1106 $record->filearea = $filearea;
1107 $record->itemid = $itemid;
1108 $record->filename = $file->name;
1109 $record->filepath = '/';
1110 return $fs->create_file_from_string($record, $this->decode_file($file));
1111 }
1112
c7df5006 1113 protected function decode_file($file) {
f29aeb5a
TH
1114 switch ($file->encoding) {
1115 case 'base64':
1116 default:
1117 return base64_decode($file->content);
1118 }
1119 }
d1b7e03d 1120}
aeb15530 1121
cde2709a 1122
d1b7e03d
TH
1123/**
1124 * This class is used in the return value from
1125 * {@link question_type::get_possible_responses()}.
1126 *
7764183a
TH
1127 * @copyright 2010 The Open University
1128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1129 */
1130class question_possible_response {
9203b705 1131 /**
d1b7e03d
TH
1132 * @var string the classification of this response the student gave to this
1133 * part of the question. Must match one of the responseclasses returned by
1134 * {@link question_type::get_possible_responses()}.
9203b705 1135 */
d1b7e03d
TH
1136 public $responseclass;
1137 /** @var string the actual response the student gave to this part. */
1138 public $fraction;
9203b705 1139 /**
d1b7e03d
TH
1140 * Constructor, just an easy way to set the fields.
1141 * @param string $responseclassid see the field descriptions above.
1142 * @param string $response see the field descriptions above.
1143 * @param number $fraction see the field descriptions above.
9203b705 1144 */
d1b7e03d
TH
1145 public function __construct($responseclass, $fraction) {
1146 $this->responseclass = $responseclass;
1147 $this->fraction = $fraction;
cde2709a
DC
1148 }
1149
d1b7e03d
TH
1150 public static function no_response() {
1151 return new question_possible_response(get_string('noresponse', 'question'), 0);
cde2709a 1152 }
fe6ce234 1153}