Merge branch 'MDL-64676-master' of https://github.com/aanabit/moodle
[moodle.git] / question / type / questiontypebase.php
blob294975d1ee95b36d5b09d12bb67ea1f6c2c4f18f
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.
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/>.
17 /**
18 * The default questiontype class.
20 * @package moodlecore
21 * @subpackage questiontypes
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/question/engine/lib.php');
32 /**
33 * This is the base class for Moodle question types.
35 * There are detailed comments on each method, explaining what the method is
36 * for, and the circumstances under which you might need to override it.
38 * Note: the questiontype API should NOT be considered stable yet. Very few
39 * question types have been produced yet, so we do not yet know all the places
40 * where the current API is insufficient. I would rather learn from the
41 * experiences of the first few question type implementors, and improve the
42 * interface to meet their needs, rather the freeze the API prematurely and
43 * condem everyone to working round a clunky interface for ever afterwards.
45 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 class question_type {
49 protected $fileoptions = array(
50 'subdirs' => true,
51 'maxfiles' => -1,
52 'maxbytes' => 0,
55 public function __construct() {
58 /**
59 * @return string the name of this question type.
61 public function name() {
62 return substr(get_class($this), 6);
65 /**
66 * @return string the full frankenstyle name for this plugin.
68 public function plugin_name() {
69 return get_class($this);
72 /**
73 * @return string the name of this question type in the user's language.
74 * You should not need to override this method, the default behaviour should be fine.
76 public function local_name() {
77 return get_string('pluginname', $this->plugin_name());
80 /**
81 * The name this question should appear as in the create new question
82 * dropdown. Override this method to return false if you don't want your
83 * question type to be createable, for example if it is an abstract base type,
84 * otherwise, you should not need to override this method.
86 * @return mixed the desired string, or false to hide this question type in the menu.
88 public function menu_name() {
89 return $this->local_name();
92 /**
93 * @return bool override this to return false if this is not really a
94 * question type, for example the description question type is not
95 * really a question type.
97 public function is_real_question_type() {
98 return true;
102 * @return bool true if this question type sometimes requires manual grading.
104 public function is_manual_graded() {
105 return false;
109 * @param object $question a question of this type.
110 * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt.
111 * @return bool true if a particular instance of this question requires manual grading.
113 public function is_question_manual_graded($question, $otherquestionsinuse) {
114 return $this->is_manual_graded();
118 * @return bool true if this question type can be used by the random question type.
120 public function is_usable_by_random() {
121 return true;
125 * Whether this question type can perform a frequency analysis of student
126 * responses.
128 * If this method returns true, you must implement the get_possible_responses
129 * method, and the question_definition class must implement the
130 * classify_response method.
132 * @return bool whether this report can analyse all the student responses
133 * for things like the quiz statistics report.
135 public function can_analyse_responses() {
136 // This works in most cases.
137 return !$this->is_manual_graded();
141 * @return whether the question_answers.answer field needs to have
142 * restore_decode_content_links_worker called on it.
144 public function has_html_answers() {
145 return false;
149 * If your question type has a table that extends the question table, and
150 * you want the base class to automatically save, backup and restore the extra fields,
151 * override this method to return an array wherer the first element is the table name,
152 * and the subsequent entries are the column names (apart from id and questionid).
154 * @return mixed array as above, or null to tell the base class to do nothing.
156 public function extra_question_fields() {
157 return null;
161 * If you use extra_question_fields, overload this function to return question id field name
162 * in case you table use another name for this column
164 public function questionid_column_name() {
165 return 'questionid';
169 * If your question type has a table that extends the question_answers table,
170 * make this method return an array wherer the first element is the table name,
171 * and the subsequent entries are the column names (apart from id and answerid).
173 * @return mixed array as above, or null to tell the base class to do nothing.
175 public function extra_answer_fields() {
176 return null;
180 * If the quetsion type uses files in responses, then this method should
181 * return an array of all the response variables that might have corresponding
182 * files. For example, the essay qtype returns array('attachments', 'answers').
184 * @return array response variable names that may have associated files.
186 public function response_file_areas() {
187 return array();
191 * Return an instance of the question editing form definition. This looks for a
192 * class called edit_{$this->name()}_question_form in the file
193 * question/type/{$this->name()}/edit_{$this->name()}_question_form.php
194 * and if it exists returns an instance of it.
196 * @param string $submiturl passed on to the constructor call.
197 * @return object an instance of the form definition, or null if one could not be found.
199 public function create_editing_form($submiturl, $question, $category,
200 $contexts, $formeditable) {
201 global $CFG;
202 require_once($CFG->dirroot . '/question/type/edit_question_form.php');
203 $definitionfile = $CFG->dirroot . '/question/type/' . $this->name() .
204 '/edit_' . $this->name() . '_form.php';
205 if (!is_readable($definitionfile) || !is_file($definitionfile)) {
206 throw new coding_exception($this->plugin_name() .
207 ' is missing the definition of its editing formin file ' .
208 $definitionfile . '.');
210 require_once($definitionfile);
211 $classname = $this->plugin_name() . '_edit_form';
212 if (!class_exists($classname)) {
213 throw new coding_exception($this->plugin_name() .
214 ' does not define the class ' . $this->plugin_name() .
215 '_edit_form.');
217 return new $classname($submiturl, $question, $category, $contexts, $formeditable);
221 * @return string the full path of the folder this plugin's files live in.
223 public function plugin_dir() {
224 global $CFG;
225 return $CFG->dirroot . '/question/type/' . $this->name();
229 * @return string the URL of the folder this plugin's files live in.
231 public function plugin_baseurl() {
232 global $CFG;
233 return $CFG->wwwroot . '/question/type/' . $this->name();
237 * This method should be overriden if you want to include a special heading or some other
238 * html on a question editing page besides the question editing form.
240 * @param question_edit_form $mform a child of question_edit_form
241 * @param object $question
242 * @param string $wizardnow is '' for first page.
244 public function display_question_editing_page($mform, $question, $wizardnow) {
245 global $OUTPUT;
246 $heading = $this->get_heading(empty($question->id));
247 echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
248 $mform->display();
252 * Method called by display_question_editing_page and by question.php to get
253 * heading for breadcrumbs.
255 * @return string the heading
257 public function get_heading($adding = false) {
258 if ($adding) {
259 $string = 'pluginnameadding';
260 } else {
261 $string = 'pluginnameediting';
263 return get_string($string, $this->plugin_name());
267 * Set any missing settings for this question to the default values. This is
268 * called before displaying the question editing form.
270 * @param object $questiondata the question data, loaded from the databsae,
271 * or more likely a newly created question object that is only partially
272 * initialised.
274 public function set_default_options($questiondata) {
278 * Saves (creates or updates) a question.
280 * Given some question info and some data about the answers
281 * this function parses, organises and saves the question
282 * It is used by {@link question.php} when saving new data from
283 * a form, and also by {@link import.php} when importing questions
284 * This function in turn calls {@link save_question_options}
285 * to save question-type specific data.
287 * Whether we are saving a new question or updating an existing one can be
288 * determined by testing !empty($question->id). If it is not empty, we are updating.
290 * The question will be saved in category $form->category.
292 * @param object $question the question object which should be updated. For a
293 * new question will be mostly empty.
294 * @param object $form the object containing the information to save, as if
295 * from the question editing form.
296 * @param object $course not really used any more.
297 * @return object On success, return the new question object. On failure,
298 * return an object as follows. If the error object has an errors field,
299 * display that as an error message. Otherwise, the editing form will be
300 * redisplayed with validation errors, from validation_errors field, which
301 * is itself an object, shown next to the form fields. (I don't think this
302 * is accurate any more.)
304 public function save_question($question, $form) {
305 global $USER, $DB, $OUTPUT;
307 list($question->category) = explode(',', $form->category);
308 $context = $this->get_context_by_category_id($question->category);
310 // This default implementation is suitable for most
311 // question types.
313 // First, save the basic question itself.
314 $question->name = trim($form->name);
315 $question->parent = isset($form->parent) ? $form->parent : 0;
316 $question->length = $this->actual_number_of_questions($question);
317 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
319 // The trim call below has the effect of casting any strange values received,
320 // like null or false, to an appropriate string, so we only need to test for
321 // missing values. Be careful not to break the value '0' here.
322 if (!isset($form->questiontext['text'])) {
323 $question->questiontext = '';
324 } else {
325 $question->questiontext = trim($form->questiontext['text']);
327 $question->questiontextformat = !empty($form->questiontext['format']) ?
328 $form->questiontext['format'] : 0;
330 if (empty($form->generalfeedback['text'])) {
331 $question->generalfeedback = '';
332 } else {
333 $question->generalfeedback = trim($form->generalfeedback['text']);
335 $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
336 $form->generalfeedback['format'] : 0;
338 if ($question->name === '') {
339 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
340 if ($question->name === '') {
341 $question->name = '-';
345 if ($question->penalty > 1 or $question->penalty < 0) {
346 $question->errors['penalty'] = get_string('invalidpenalty', 'question');
349 if (isset($form->defaultmark)) {
350 $question->defaultmark = $form->defaultmark;
353 if (isset($form->idnumber) && ((string) $form->idnumber !== '')) {
354 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
355 if (strpos($form->category, ',') !== false) {
356 list($category, $categorycontextid) = explode(',', $form->category);
357 } else {
358 $category = $form->category;
360 if (!$DB->record_exists('question',
361 ['idnumber' => $form->idnumber, 'category' => $category])) {
362 $question->idnumber = $form->idnumber;
366 // If the question is new, create it.
367 if (empty($question->id)) {
368 // Set the unique code.
369 $question->stamp = make_unique_id_code();
370 $question->createdby = $USER->id;
371 $question->timecreated = time();
372 $question->id = $DB->insert_record('question', $question);
375 // Now, whether we are updating a existing question, or creating a new
376 // one, we have to do the files processing and update the record.
377 // Question already exists, update.
378 $question->modifiedby = $USER->id;
379 $question->timemodified = time();
381 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
382 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
383 $context->id, 'question', 'questiontext', (int)$question->id,
384 $this->fileoptions, $question->questiontext);
386 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
387 $question->generalfeedback = file_save_draft_area_files(
388 $form->generalfeedback['itemid'], $context->id,
389 'question', 'generalfeedback', (int)$question->id,
390 $this->fileoptions, $question->generalfeedback);
392 $DB->update_record('question', $question);
394 // Now to save all the answers and type-specific options.
395 $form->id = $question->id;
396 $form->qtype = $question->qtype;
397 $form->category = $question->category;
398 $form->questiontext = $question->questiontext;
399 $form->questiontextformat = $question->questiontextformat;
400 // Current context.
401 $form->context = $context;
403 $result = $this->save_question_options($form);
405 if (!empty($result->error)) {
406 print_error($result->error);
409 if (!empty($result->notice)) {
410 notice($result->notice, "question.php?id={$question->id}");
413 if (!empty($result->noticeyesno)) {
414 throw new coding_exception(
415 '$result->noticeyesno no longer supported in save_question.');
418 // Give the question a unique version stamp determined by question_hash().
419 $DB->set_field('question', 'version', question_hash($question),
420 array('id' => $question->id));
422 return $question;
426 * Saves question-type specific options
428 * This is called by {@link save_question()} to save the question-type specific data
429 * @return object $result->error or $result->notice
430 * @param object $question This holds the information from the editing form,
431 * it is not a standard question object.
433 public function save_question_options($question) {
434 global $DB;
435 $extraquestionfields = $this->extra_question_fields();
437 if (is_array($extraquestionfields)) {
438 $question_extension_table = array_shift($extraquestionfields);
440 $function = 'update_record';
441 $questionidcolname = $this->questionid_column_name();
442 $options = $DB->get_record($question_extension_table,
443 array($questionidcolname => $question->id));
444 if (!$options) {
445 $function = 'insert_record';
446 $options = new stdClass();
447 $options->$questionidcolname = $question->id;
449 foreach ($extraquestionfields as $field) {
450 if (property_exists($question, $field)) {
451 $options->$field = $question->$field;
455 $DB->{$function}($question_extension_table, $options);
460 * Save the answers, with any extra data.
462 * Questions that use answers will call it from {@link save_question_options()}.
463 * @param object $question This holds the information from the editing form,
464 * it is not a standard question object.
465 * @return object $result->error or $result->notice
467 public function save_question_answers($question) {
468 global $DB;
470 $context = $question->context;
471 $oldanswers = $DB->get_records('question_answers',
472 array('question' => $question->id), 'id ASC');
474 // We need separate arrays for answers and extra answer data, so no JOINS there.
475 $extraanswerfields = $this->extra_answer_fields();
476 $isextraanswerfields = is_array($extraanswerfields);
477 $extraanswertable = '';
478 $oldanswerextras = array();
479 if ($isextraanswerfields) {
480 $extraanswertable = array_shift($extraanswerfields);
481 if (!empty($oldanswers)) {
482 $oldanswerextras = $DB->get_records_sql("SELECT * FROM {{$extraanswertable}} WHERE " .
483 'answerid IN (SELECT id FROM {question_answers} WHERE question = ' . $question->id . ')' );
487 // Insert all the new answers.
488 foreach ($question->answer as $key => $answerdata) {
489 // Check for, and ignore, completely blank answer from the form.
490 if ($this->is_answer_empty($question, $key)) {
491 continue;
494 // Update an existing answer if possible.
495 $answer = array_shift($oldanswers);
496 if (!$answer) {
497 $answer = new stdClass();
498 $answer->question = $question->id;
499 $answer->answer = '';
500 $answer->feedback = '';
501 $answer->id = $DB->insert_record('question_answers', $answer);
504 $answer = $this->fill_answer_fields($answer, $question, $key, $context);
505 $DB->update_record('question_answers', $answer);
507 if ($isextraanswerfields) {
508 // Check, if this answer contains some extra field data.
509 if ($this->is_extra_answer_fields_empty($question, $key)) {
510 continue;
513 $answerextra = array_shift($oldanswerextras);
514 if (!$answerextra) {
515 $answerextra = new stdClass();
516 $answerextra->answerid = $answer->id;
517 // Avoid looking for correct default for any possible DB field type
518 // by setting real values.
519 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
520 $answerextra->id = $DB->insert_record($extraanswertable, $answerextra);
521 } else {
522 // Update answerid, as record may be reused from another answer.
523 $answerextra->answerid = $answer->id;
524 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
525 $DB->update_record($extraanswertable, $answerextra);
530 if ($isextraanswerfields) {
531 // Delete any left over extra answer fields records.
532 $oldanswerextraids = array();
533 foreach ($oldanswerextras as $oldextra) {
534 $oldanswerextraids[] = $oldextra->id;
536 $DB->delete_records_list($extraanswertable, 'id', $oldanswerextraids);
539 // Delete any left over old answer records.
540 $fs = get_file_storage();
541 foreach ($oldanswers as $oldanswer) {
542 $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
543 $DB->delete_records('question_answers', array('id' => $oldanswer->id));
548 * Returns true is answer with the $key is empty in the question data and should not be saved in DB.
550 * The questions using question_answers table may want to overload this. Default code will work
551 * for shortanswer and similar question types.
552 * @param object $questiondata This holds the information from the question editing form or import.
553 * @param int $key A key of the answer in question.
554 * @return bool True if answer shouldn't be saved in DB.
556 protected function is_answer_empty($questiondata, $key) {
557 return trim($questiondata->answer[$key]) == '' && $questiondata->fraction[$key] == 0 &&
558 html_is_blank($questiondata->feedback[$key]['text']);
562 * Return $answer, filling necessary fields for the question_answers table.
564 * The questions using question_answers table may want to overload this. Default code will work
565 * for shortanswer and similar question types.
566 * @param stdClass $answer Object to save data.
567 * @param object $questiondata This holds the information from the question editing form or import.
568 * @param int $key A key of the answer in question.
569 * @param object $context needed for working with files.
570 * @return $answer answer with filled data.
572 protected function fill_answer_fields($answer, $questiondata, $key, $context) {
573 $answer->answer = $questiondata->answer[$key];
574 $answer->fraction = $questiondata->fraction[$key];
575 $answer->feedback = $this->import_or_save_files($questiondata->feedback[$key],
576 $context, 'question', 'answerfeedback', $answer->id);
577 $answer->feedbackformat = $questiondata->feedback[$key]['format'];
578 return $answer;
582 * Returns true if extra answer fields for answer with the $key is empty
583 * in the question data and should not be saved in DB.
585 * Questions where extra answer fields are optional will want to overload this.
586 * @param object $questiondata This holds the information from the question editing form or import.
587 * @param int $key A key of the answer in question.
588 * @return bool True if extra answer data shouldn't be saved in DB.
590 protected function is_extra_answer_fields_empty($questiondata, $key) {
591 // No extra answer data in base class.
592 return true;
596 * Return $answerextra, filling necessary fields for the extra answer fields table.
598 * The questions may want to overload it to save files or do other data processing.
599 * @param stdClass $answerextra Object to save data.
600 * @param object $questiondata This holds the information from the question editing form or import.
601 * @param int $key A key of the answer in question.
602 * @param object $context needed for working with files.
603 * @param array $extraanswerfields extra answer fields (without table name).
604 * @return $answer answerextra with filled data.
606 protected function fill_extra_answer_fields($answerextra, $questiondata, $key, $context, $extraanswerfields) {
607 foreach ($extraanswerfields as $field) {
608 // The $questiondata->$field[$key] won't work in PHP, break it down to two strings of code.
609 $fieldarray = $questiondata->$field;
610 $answerextra->$field = $fieldarray[$key];
612 return $answerextra;
615 public function save_hints($formdata, $withparts = false) {
616 global $DB;
617 $context = $formdata->context;
619 $oldhints = $DB->get_records('question_hints',
620 array('questionid' => $formdata->id), 'id ASC');
623 $numhints = $this->count_hints_on_form($formdata, $withparts);
625 for ($i = 0; $i < $numhints; $i += 1) {
626 if (html_is_blank($formdata->hint[$i]['text'])) {
627 $formdata->hint[$i]['text'] = '';
630 if ($withparts) {
631 $clearwrong = !empty($formdata->hintclearwrong[$i]);
632 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
635 if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) {
636 continue;
639 // Update an existing hint if possible.
640 $hint = array_shift($oldhints);
641 if (!$hint) {
642 $hint = new stdClass();
643 $hint->questionid = $formdata->id;
644 $hint->hint = '';
645 $hint->id = $DB->insert_record('question_hints', $hint);
648 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
649 $context, 'question', 'hint', $hint->id);
650 $hint->hintformat = $formdata->hint[$i]['format'];
651 if ($withparts) {
652 $hint->clearwrong = $clearwrong;
653 $hint->shownumcorrect = $shownumcorrect;
655 $hint->options = $this->save_hint_options($formdata, $i, $withparts);
656 $DB->update_record('question_hints', $hint);
659 // Delete any remaining old hints.
660 $fs = get_file_storage();
661 foreach ($oldhints as $oldhint) {
662 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
663 $DB->delete_records('question_hints', array('id' => $oldhint->id));
668 * Count number of hints on the form.
669 * Overload if you use custom hint controls.
670 * @param object $formdata the data from the form.
671 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
672 * @return int count of hints on the form.
674 protected function count_hints_on_form($formdata, $withparts) {
675 if (!empty($formdata->hint)) {
676 $numhints = max(array_keys($formdata->hint)) + 1;
677 } else {
678 $numhints = 0;
681 if ($withparts) {
682 if (!empty($formdata->hintclearwrong)) {
683 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
684 } else {
685 $numclears = 0;
687 if (!empty($formdata->hintshownumcorrect)) {
688 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
689 } else {
690 $numshows = 0;
692 $numhints = max($numhints, $numclears, $numshows);
694 return $numhints;
698 * Determine if the hint with specified number is not empty and should be saved.
699 * Overload if you use custom hint controls.
700 * @param object $formdata the data from the form.
701 * @param int $number number of hint under question.
702 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
703 * @return bool is this particular hint data empty.
705 protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
706 if ($withparts) {
707 return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) &&
708 empty($formdata->hintshownumcorrect[$number]);
709 } else {
710 return empty($formdata->hint[$number]['text']);
715 * Save additional question type data into the hint optional field.
716 * Overload if you use custom hint information.
717 * @param object $formdata the data from the form.
718 * @param int $number number of hint to get options from.
719 * @param bool $withparts whether question have parts.
720 * @return string value to save into the options field of question_hints table.
722 protected function save_hint_options($formdata, $number, $withparts) {
723 return null; // By default, options field is unused.
727 * Can be used to {@link save_question_options()} to transfer the combined
728 * feedback fields from $formdata to $options.
729 * @param object $options the $question->options object being built.
730 * @param object $formdata the data from the form.
731 * @param object $context the context the quetsion is being saved into.
732 * @param bool $withparts whether $options->shownumcorrect should be set.
734 protected function save_combined_feedback_helper($options, $formdata,
735 $context, $withparts = false) {
736 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
737 $context, 'question', 'correctfeedback', $formdata->id);
738 $options->correctfeedbackformat = $formdata->correctfeedback['format'];
740 $options->partiallycorrectfeedback = $this->import_or_save_files(
741 $formdata->partiallycorrectfeedback,
742 $context, 'question', 'partiallycorrectfeedback', $formdata->id);
743 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
745 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
746 $context, 'question', 'incorrectfeedback', $formdata->id);
747 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
749 if ($withparts) {
750 $options->shownumcorrect = !empty($formdata->shownumcorrect);
753 return $options;
757 * Loads the question type specific options for the question.
759 * This function loads any question type specific options for the
760 * question from the database into the question object. This information
761 * is placed in the $question->options field. A question type is
762 * free, however, to decide on a internal structure of the options field.
763 * @return bool Indicates success or failure.
764 * @param object $question The question object for the question. This object
765 * should be updated to include the question type
766 * specific information (it is passed by reference).
768 public function get_question_options($question) {
769 global $CFG, $DB, $OUTPUT;
771 if (!isset($question->options)) {
772 $question->options = new stdClass();
775 $extraquestionfields = $this->extra_question_fields();
776 if (is_array($extraquestionfields)) {
777 $question_extension_table = array_shift($extraquestionfields);
778 $extra_data = $DB->get_record($question_extension_table,
779 array($this->questionid_column_name() => $question->id),
780 implode(', ', $extraquestionfields));
781 if ($extra_data) {
782 foreach ($extraquestionfields as $field) {
783 $question->options->$field = $extra_data->$field;
785 } else {
786 echo $OUTPUT->notification('Failed to load question options from the table ' .
787 $question_extension_table . ' for questionid ' . $question->id);
788 return false;
792 $extraanswerfields = $this->extra_answer_fields();
793 if (is_array($extraanswerfields)) {
794 $answerextensiontable = array_shift($extraanswerfields);
795 // Use LEFT JOIN in case not every answer has extra data.
796 $question->options->answers = $DB->get_records_sql("
797 SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . '
798 FROM {question_answers} qa ' . "
799 LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid
800 WHERE qa.question = ?
801 ORDER BY qa.id", array($question->id));
802 if (!$question->options->answers) {
803 echo $OUTPUT->notification('Failed to load question answers from the table ' .
804 $answerextensiontable . 'for questionid ' . $question->id);
805 return false;
807 } else {
808 // Don't check for success or failure because some question types do
809 // not use the answers table.
810 $question->options->answers = $DB->get_records('question_answers',
811 array('question' => $question->id), 'id ASC');
814 $question->hints = $DB->get_records('question_hints',
815 array('questionid' => $question->id), 'id ASC');
817 return true;
821 * Create an appropriate question_definition for the question of this type
822 * using data loaded from the database.
823 * @param object $questiondata the question data loaded from the database.
824 * @return question_definition the corresponding question_definition.
826 public function make_question($questiondata) {
827 $question = $this->make_question_instance($questiondata);
828 $this->initialise_question_instance($question, $questiondata);
829 return $question;
833 * Create an appropriate question_definition for the question of this type
834 * using data loaded from the database.
835 * @param object $questiondata the question data loaded from the database.
836 * @return question_definition an instance of the appropriate question_definition subclass.
837 * Still needs to be initialised.
839 protected function make_question_instance($questiondata) {
840 question_bank::load_question_definition_classes($this->name());
841 $class = 'qtype_' . $this->name() . '_question';
842 return new $class();
846 * Initialise the common question_definition fields.
847 * @param question_definition $question the question_definition we are creating.
848 * @param object $questiondata the question data loaded from the database.
850 protected function initialise_question_instance(question_definition $question, $questiondata) {
851 $question->id = $questiondata->id;
852 $question->category = $questiondata->category;
853 $question->contextid = $questiondata->contextid;
854 $question->parent = $questiondata->parent;
855 $question->qtype = $this;
856 $question->name = $questiondata->name;
857 $question->questiontext = $questiondata->questiontext;
858 $question->questiontextformat = $questiondata->questiontextformat;
859 $question->generalfeedback = $questiondata->generalfeedback;
860 $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
861 $question->defaultmark = $questiondata->defaultmark + 0;
862 $question->length = $questiondata->length;
863 $question->penalty = $questiondata->penalty;
864 $question->stamp = $questiondata->stamp;
865 $question->version = $questiondata->version;
866 $question->hidden = $questiondata->hidden;
867 $question->idnumber = $questiondata->idnumber;
868 $question->timecreated = $questiondata->timecreated;
869 $question->timemodified = $questiondata->timemodified;
870 $question->createdby = $questiondata->createdby;
871 $question->modifiedby = $questiondata->modifiedby;
873 // Fill extra question fields values.
874 $extraquestionfields = $this->extra_question_fields();
875 if (is_array($extraquestionfields)) {
876 // Omit table name.
877 array_shift($extraquestionfields);
878 foreach ($extraquestionfields as $field) {
879 $question->$field = $questiondata->options->$field;
883 $this->initialise_question_hints($question, $questiondata);
887 * Initialise question_definition::hints field.
888 * @param question_definition $question the question_definition we are creating.
889 * @param object $questiondata the question data loaded from the database.
891 protected function initialise_question_hints(question_definition $question, $questiondata) {
892 if (empty($questiondata->hints)) {
893 return;
895 foreach ($questiondata->hints as $hint) {
896 $question->hints[] = $this->make_hint($hint);
901 * Create a question_hint, or an appropriate subclass for this question,
902 * from a row loaded from the database.
903 * @param object $hint the DB row from the question hints table.
904 * @return question_hint
906 protected function make_hint($hint) {
907 return question_hint::load_from_record($hint);
911 * Initialise the combined feedback fields.
912 * @param question_definition $question the question_definition we are creating.
913 * @param object $questiondata the question data loaded from the database.
914 * @param bool $withparts whether to set the shownumcorrect field.
916 protected function initialise_combined_feedback(question_definition $question,
917 $questiondata, $withparts = false) {
918 $question->correctfeedback = $questiondata->options->correctfeedback;
919 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
920 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
921 $question->partiallycorrectfeedbackformat =
922 $questiondata->options->partiallycorrectfeedbackformat;
923 $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
924 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
925 if ($withparts) {
926 $question->shownumcorrect = $questiondata->options->shownumcorrect;
931 * Initialise question_definition::answers field.
932 * @param question_definition $question the question_definition we are creating.
933 * @param object $questiondata the question data loaded from the database.
934 * @param bool $forceplaintextanswers most qtypes assume that answers are
935 * FORMAT_PLAIN, and dont use the answerformat DB column (it contains
936 * the default 0 = FORMAT_MOODLE). Therefore, by default this method
937 * ingores answerformat. Pass false here to use answerformat. For example
938 * multichoice does this.
940 protected function initialise_question_answers(question_definition $question,
941 $questiondata, $forceplaintextanswers = true) {
942 $question->answers = array();
943 if (empty($questiondata->options->answers)) {
944 return;
946 foreach ($questiondata->options->answers as $a) {
947 $question->answers[$a->id] = $this->make_answer($a);
948 if (!$forceplaintextanswers) {
949 $question->answers[$a->id]->answerformat = $a->answerformat;
955 * Create a question_answer, or an appropriate subclass for this question,
956 * from a row loaded from the database.
957 * @param object $answer the DB row from the question_answers table plus extra answer fields.
958 * @return question_answer
960 protected function make_answer($answer) {
961 return new question_answer($answer->id, $answer->answer,
962 $answer->fraction, $answer->feedback, $answer->feedbackformat);
966 * Deletes the question-type specific data when a question is deleted.
967 * @param int $question the question being deleted.
968 * @param int $contextid the context this quesiotn belongs to.
970 public function delete_question($questionid, $contextid) {
971 global $DB;
973 $this->delete_files($questionid, $contextid);
975 $extraquestionfields = $this->extra_question_fields();
976 if (is_array($extraquestionfields)) {
977 $question_extension_table = array_shift($extraquestionfields);
978 $DB->delete_records($question_extension_table,
979 array($this->questionid_column_name() => $questionid));
982 $extraanswerfields = $this->extra_answer_fields();
983 if (is_array($extraanswerfields)) {
984 $answer_extension_table = array_shift($extraanswerfields);
985 $DB->delete_records_select($answer_extension_table,
986 'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
987 array($questionid));
990 $DB->delete_records('question_answers', array('question' => $questionid));
992 $DB->delete_records('question_hints', array('questionid' => $questionid));
996 * Returns the number of question numbers which are used by the question
998 * This function returns the number of question numbers to be assigned
999 * to the question. Most question types will have length one; they will be
1000 * assigned one number. The 'description' type, however does not use up a
1001 * number and so has a length of zero. Other question types may wish to
1002 * handle a bundle of questions and hence return a number greater than one.
1003 * @return int The number of question numbers which should be
1004 * assigned to the question.
1005 * @param object $question The question whose length is to be determined.
1006 * Question type specific information is included.
1008 public function actual_number_of_questions($question) {
1009 // By default, each question is given one number.
1010 return 1;
1014 * @param object $question
1015 * @return number|null either a fraction estimating what the student would
1016 * score by guessing, or null, if it is not possible to estimate.
1018 public function get_random_guess_score($questiondata) {
1019 return 0;
1023 * Whether or not to break down question stats and response analysis, for a question defined by $questiondata.
1025 * @param object $questiondata The full question definition data.
1026 * @return bool
1028 public function break_down_stats_and_response_analysis_by_variant($questiondata) {
1029 return true;
1033 * This method should return all the possible types of response that are
1034 * recognised for this question.
1036 * The question is modelled as comprising one or more subparts. For each
1037 * subpart, there are one or more classes that that students response
1038 * might fall into, each of those classes earning a certain score.
1040 * For example, in a shortanswer question, there is only one subpart, the
1041 * text entry field. The response the student gave will be classified according
1042 * to which of the possible $question->options->answers it matches.
1044 * For the matching question type, there will be one subpart for each
1045 * question stem, and for each stem, each of the possible choices is a class
1046 * of student's response.
1048 * A response is an object with two fields, ->responseclass is a string
1049 * presentation of that response, and ->fraction, the credit for a response
1050 * in that class.
1052 * Array keys have no specific meaning, but must be unique, and must be
1053 * the same if this function is called repeatedly.
1055 * @param object $question the question definition data.
1056 * @return array keys are subquestionid, values are arrays of possible
1057 * responses to that subquestion.
1059 public function get_possible_responses($questiondata) {
1060 return array();
1064 * Utility method used by {@link qtype_renderer::head_code()}. It looks
1065 * for any of the files script.js or script.php that exist in the plugin
1066 * folder and ensures they get included.
1068 public function find_standard_scripts() {
1069 global $PAGE;
1071 $plugindir = $this->plugin_dir();
1072 $plugindirrel = 'question/type/' . $this->name();
1074 if (file_exists($plugindir . '/script.js')) {
1075 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
1077 if (file_exists($plugindir . '/script.php')) {
1078 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
1083 * Returns true if the editing wizard is finished, false otherwise.
1085 * The default implementation returns true, which is suitable for all question-
1086 * types that only use one editing form. This function is used in
1087 * question.php to decide whether we can regrade any states of the edited
1088 * question and redirect to edit.php.
1090 * The dataset dependent question-type, which is extended by the calculated
1091 * question-type, overwrites this method because it uses multiple pages (i.e.
1092 * a wizard) to set up the question and associated datasets.
1094 * @param object $form The data submitted by the previous page.
1096 * @return bool Whether the wizard's last page was submitted or not.
1098 public function finished_edit_wizard($form) {
1099 // In the default case there is only one edit page.
1100 return true;
1103 // IMPORT/EXPORT FUNCTIONS --------------------------------- .
1106 * Imports question from the Moodle XML format
1108 * Imports question using information from extra_question_fields function
1109 * If some of you fields contains id's you'll need to reimplement this
1111 public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
1112 $question_type = $data['@']['type'];
1113 if ($question_type != $this->name()) {
1114 return false;
1117 $extraquestionfields = $this->extra_question_fields();
1118 if (!is_array($extraquestionfields)) {
1119 return false;
1122 // Omit table name.
1123 array_shift($extraquestionfields);
1124 $qo = $format->import_headers($data);
1125 $qo->qtype = $question_type;
1127 foreach ($extraquestionfields as $field) {
1128 $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
1131 // Run through the answers.
1132 $answers = $data['#']['answer'];
1133 $a_count = 0;
1134 $extraanswersfields = $this->extra_answer_fields();
1135 if (is_array($extraanswersfields)) {
1136 array_shift($extraanswersfields);
1138 foreach ($answers as $answer) {
1139 $ans = $format->import_answer($answer);
1140 if (!$this->has_html_answers()) {
1141 $qo->answer[$a_count] = $ans->answer['text'];
1142 } else {
1143 $qo->answer[$a_count] = $ans->answer;
1145 $qo->fraction[$a_count] = $ans->fraction;
1146 $qo->feedback[$a_count] = $ans->feedback;
1147 if (is_array($extraanswersfields)) {
1148 foreach ($extraanswersfields as $field) {
1149 $qo->{$field}[$a_count] =
1150 $format->getpath($answer, array('#', $field, 0, '#'), '');
1153 ++$a_count;
1155 return $qo;
1159 * Export question to the Moodle XML format
1161 * Export question using information from extra_question_fields function
1162 * If some of you fields contains id's you'll need to reimplement this
1164 public function export_to_xml($question, qformat_xml $format, $extra=null) {
1165 $extraquestionfields = $this->extra_question_fields();
1166 if (!is_array($extraquestionfields)) {
1167 return false;
1170 // Omit table name.
1171 array_shift($extraquestionfields);
1172 $expout='';
1173 foreach ($extraquestionfields as $field) {
1174 $exportedvalue = $format->xml_escape($question->options->$field);
1175 $expout .= " <{$field}>{$exportedvalue}</{$field}>\n";
1178 $extraanswersfields = $this->extra_answer_fields();
1179 if (is_array($extraanswersfields)) {
1180 array_shift($extraanswersfields);
1182 foreach ($question->options->answers as $answer) {
1183 $extra = '';
1184 if (is_array($extraanswersfields)) {
1185 foreach ($extraanswersfields as $field) {
1186 $exportedvalue = $format->xml_escape($answer->$field);
1187 $extra .= " <{$field}>{$exportedvalue}</{$field}>\n";
1191 $expout .= $format->write_answer($answer, $extra);
1193 return $expout;
1197 * Abstract function implemented by each question type. It runs all the code
1198 * required to set up and save a question of any type for testing purposes.
1199 * Alternate DB table prefix may be used to facilitate data deletion.
1201 public function generate_test($name, $courseid=null) {
1202 $form = new stdClass();
1203 $form->name = $name;
1204 $form->questiontextformat = 1;
1205 $form->questiontext = 'test question, generated by script';
1206 $form->defaultmark = 1;
1207 $form->penalty = 0.3333333;
1208 $form->generalfeedback = "Well done";
1210 $context = context_course::instance($courseid);
1211 $newcategory = question_make_default_categories(array($context));
1212 $form->category = $newcategory->id . ',1';
1214 $question = new stdClass();
1215 $question->courseid = $courseid;
1216 $question->qtype = $this->qtype;
1217 return array($form, $question);
1221 * Get question context by category id
1222 * @param int $category
1223 * @return object $context
1225 protected function get_context_by_category_id($category) {
1226 global $DB;
1227 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
1228 $context = context::instance_by_id($contextid, IGNORE_MISSING);
1229 return $context;
1233 * Save the file belonging to one text field.
1235 * @param array $field the data from the form (or from import). This will
1236 * normally have come from the formslib editor element, so it will be an
1237 * array with keys 'text', 'format' and 'itemid'. However, when we are
1238 * importing, it will be an array with keys 'text', 'format' and 'files'
1239 * @param object $context the context the question is in.
1240 * @param string $component indentifies the file area question.
1241 * @param string $filearea indentifies the file area questiontext,
1242 * generalfeedback, answerfeedback, etc.
1243 * @param int $itemid identifies the file area.
1245 * @return string the text for this field, after files have been processed.
1247 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1248 if (!empty($field['itemid'])) {
1249 // This is the normal case. We are safing the questions editing form.
1250 return file_save_draft_area_files($field['itemid'], $context->id, $component,
1251 $filearea, $itemid, $this->fileoptions, trim($field['text']));
1253 } else if (!empty($field['files'])) {
1254 // This is the case when we are doing an import.
1255 foreach ($field['files'] as $file) {
1256 $this->import_file($context, $component, $filearea, $itemid, $file);
1259 return trim($field['text']);
1263 * Move all the files belonging to this question from one context to another.
1264 * @param int $questionid the question being moved.
1265 * @param int $oldcontextid the context it is moving from.
1266 * @param int $newcontextid the context it is moving to.
1268 public function move_files($questionid, $oldcontextid, $newcontextid) {
1269 $fs = get_file_storage();
1270 $fs->move_area_files_to_new_context($oldcontextid,
1271 $newcontextid, 'question', 'questiontext', $questionid);
1272 $fs->move_area_files_to_new_context($oldcontextid,
1273 $newcontextid, 'question', 'generalfeedback', $questionid);
1277 * Move all the files belonging to this question's answers when the question
1278 * is moved from one context to another.
1279 * @param int $questionid the question being moved.
1280 * @param int $oldcontextid the context it is moving from.
1281 * @param int $newcontextid the context it is moving to.
1282 * @param bool $answerstoo whether there is an 'answer' question area,
1283 * as well as an 'answerfeedback' one. Default false.
1285 protected function move_files_in_answers($questionid, $oldcontextid,
1286 $newcontextid, $answerstoo = false) {
1287 global $DB;
1288 $fs = get_file_storage();
1290 $answerids = $DB->get_records_menu('question_answers',
1291 array('question' => $questionid), 'id', 'id,1');
1292 foreach ($answerids as $answerid => $notused) {
1293 if ($answerstoo) {
1294 $fs->move_area_files_to_new_context($oldcontextid,
1295 $newcontextid, 'question', 'answer', $answerid);
1297 $fs->move_area_files_to_new_context($oldcontextid,
1298 $newcontextid, 'question', 'answerfeedback', $answerid);
1303 * Move all the files belonging to this question's hints when the question
1304 * is moved from one context to another.
1305 * @param int $questionid the question being moved.
1306 * @param int $oldcontextid the context it is moving from.
1307 * @param int $newcontextid the context it is moving to.
1308 * @param bool $answerstoo whether there is an 'answer' question area,
1309 * as well as an 'answerfeedback' one. Default false.
1311 protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1312 global $DB;
1313 $fs = get_file_storage();
1315 $hintids = $DB->get_records_menu('question_hints',
1316 array('questionid' => $questionid), 'id', 'id,1');
1317 foreach ($hintids as $hintid => $notused) {
1318 $fs->move_area_files_to_new_context($oldcontextid,
1319 $newcontextid, 'question', 'hint', $hintid);
1324 * Move all the files belonging to this question's answers when the question
1325 * is moved from one context to another.
1326 * @param int $questionid the question being moved.
1327 * @param int $oldcontextid the context it is moving from.
1328 * @param int $newcontextid the context it is moving to.
1329 * @param bool $answerstoo whether there is an 'answer' question area,
1330 * as well as an 'answerfeedback' one. Default false.
1332 protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1333 $newcontextid) {
1334 global $DB;
1335 $fs = get_file_storage();
1337 $fs->move_area_files_to_new_context($oldcontextid,
1338 $newcontextid, 'question', 'correctfeedback', $questionid);
1339 $fs->move_area_files_to_new_context($oldcontextid,
1340 $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1341 $fs->move_area_files_to_new_context($oldcontextid,
1342 $newcontextid, 'question', 'incorrectfeedback', $questionid);
1346 * Delete all the files belonging to this question.
1347 * @param int $questionid the question being deleted.
1348 * @param int $contextid the context the question is in.
1350 protected function delete_files($questionid, $contextid) {
1351 $fs = get_file_storage();
1352 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1353 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1357 * Delete all the files belonging to this question's answers.
1358 * @param int $questionid the question being deleted.
1359 * @param int $contextid the context the question is in.
1360 * @param bool $answerstoo whether there is an 'answer' question area,
1361 * as well as an 'answerfeedback' one. Default false.
1363 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1364 global $DB;
1365 $fs = get_file_storage();
1367 $answerids = $DB->get_records_menu('question_answers',
1368 array('question' => $questionid), 'id', 'id,1');
1369 foreach ($answerids as $answerid => $notused) {
1370 if ($answerstoo) {
1371 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1373 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1378 * Delete all the files belonging to this question's hints.
1379 * @param int $questionid the question being deleted.
1380 * @param int $contextid the context the question is in.
1382 protected function delete_files_in_hints($questionid, $contextid) {
1383 global $DB;
1384 $fs = get_file_storage();
1386 $hintids = $DB->get_records_menu('question_hints',
1387 array('questionid' => $questionid), 'id', 'id,1');
1388 foreach ($hintids as $hintid => $notused) {
1389 $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1394 * Delete all the files belonging to this question's answers.
1395 * @param int $questionid the question being deleted.
1396 * @param int $contextid the context the question is in.
1397 * @param bool $answerstoo whether there is an 'answer' question area,
1398 * as well as an 'answerfeedback' one. Default false.
1400 protected function delete_files_in_combined_feedback($questionid, $contextid) {
1401 global $DB;
1402 $fs = get_file_storage();
1404 $fs->delete_area_files($contextid,
1405 'question', 'correctfeedback', $questionid);
1406 $fs->delete_area_files($contextid,
1407 'question', 'partiallycorrectfeedback', $questionid);
1408 $fs->delete_area_files($contextid,
1409 'question', 'incorrectfeedback', $questionid);
1412 public function import_file($context, $component, $filearea, $itemid, $file) {
1413 $fs = get_file_storage();
1414 $record = new stdClass();
1415 if (is_object($context)) {
1416 $record->contextid = $context->id;
1417 } else {
1418 $record->contextid = $context;
1420 $record->component = $component;
1421 $record->filearea = $filearea;
1422 $record->itemid = $itemid;
1423 $record->filename = $file->name;
1424 $record->filepath = '/';
1425 return $fs->create_file_from_string($record, $this->decode_file($file));
1428 protected function decode_file($file) {
1429 switch ($file->encoding) {
1430 case 'base64':
1431 default:
1432 return base64_decode($file->content);
1439 * This class is used in the return value from
1440 * {@link question_type::get_possible_responses()}.
1442 * @copyright 2010 The Open University
1443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1445 class question_possible_response {
1447 * @var string the classification of this response the student gave to this
1448 * part of the question. Must match one of the responseclasses returned by
1449 * {@link question_type::get_possible_responses()}.
1451 public $responseclass;
1453 /** @var string the (partial) credit awarded for this responses. */
1454 public $fraction;
1457 * Constructor, just an easy way to set the fields.
1458 * @param string $responseclassid see the field descriptions above.
1459 * @param string $response see the field descriptions above.
1460 * @param number $fraction see the field descriptions above.
1462 public function __construct($responseclass, $fraction) {
1463 $this->responseclass = $responseclass;
1464 $this->fraction = $fraction;
1467 public static function no_response() {
1468 return new question_possible_response(get_string('noresponse', 'question'), 0);