MDL-31869: Searching for users in messaging with multiple roles generates a warning
[moodle.git] / question / type / questiontypebase.php
blob0e18786a3af8755f46c2aa3d6033a3e156b42bb5
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' => false,
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 reponses
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));
248 echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
250 $permissionstrs = array();
251 if (!empty($question->id)) {
252 if ($question->formoptions->canedit) {
253 $permissionstrs[] = get_string('permissionedit', 'question');
255 if ($question->formoptions->canmove) {
256 $permissionstrs[] = get_string('permissionmove', 'question');
258 if ($question->formoptions->cansaveasnew) {
259 $permissionstrs[] = get_string('permissionsaveasnew', 'question');
262 if (!$question->formoptions->movecontext && count($permissionstrs)) {
263 echo $OUTPUT->heading(get_string('permissionto', 'question'), 3);
264 $html = '<ul>';
265 foreach ($permissionstrs as $permissionstr) {
266 $html .= '<li>'.$permissionstr.'</li>';
268 $html .= '</ul>';
269 echo $OUTPUT->box($html, 'boxwidthnarrow boxaligncenter generalbox');
271 $mform->display();
275 * Method called by display_question_editing_page and by question.php to get
276 * heading for breadcrumbs.
278 * @return string the heading
280 public function get_heading($adding = false) {
281 if ($adding) {
282 $string = 'pluginnameadding';
283 } else {
284 $string = 'pluginnameediting';
286 return get_string($string, $this->plugin_name());
290 * Set any missing settings for this question to the default values. This is
291 * called before displaying the question editing form.
293 * @param object $questiondata the question data, loaded from the databsae,
294 * or more likely a newly created question object that is only partially
295 * initialised.
297 public function set_default_options($questiondata) {
301 * Saves (creates or updates) a question.
303 * Given some question info and some data about the answers
304 * this function parses, organises and saves the question
305 * It is used by {@link question.php} when saving new data from
306 * a form, and also by {@link import.php} when importing questions
307 * This function in turn calls {@link save_question_options}
308 * to save question-type specific data.
310 * Whether we are saving a new question or updating an existing one can be
311 * determined by testing !empty($question->id). If it is not empty, we are updating.
313 * The question will be saved in category $form->category.
315 * @param object $question the question object which should be updated. For a
316 * new question will be mostly empty.
317 * @param object $form the object containing the information to save, as if
318 * from the question editing form.
319 * @param object $course not really used any more.
320 * @return object On success, return the new question object. On failure,
321 * return an object as follows. If the error object has an errors field,
322 * display that as an error message. Otherwise, the editing form will be
323 * redisplayed with validation errors, from validation_errors field, which
324 * is itself an object, shown next to the form fields. (I don't think this
325 * is accurate any more.)
327 public function save_question($question, $form) {
328 global $USER, $DB, $OUTPUT;
330 list($question->category) = explode(',', $form->category);
331 $context = $this->get_context_by_category_id($question->category);
333 // This default implementation is suitable for most
334 // question types.
336 // First, save the basic question itself
337 $question->name = trim($form->name);
338 $question->parent = isset($form->parent) ? $form->parent : 0;
339 $question->length = $this->actual_number_of_questions($question);
340 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
342 if (empty($form->questiontext['text'])) {
343 $question->questiontext = '';
344 } else {
345 $question->questiontext = trim($form->questiontext['text']);;
347 $question->questiontextformat = !empty($form->questiontext['format']) ?
348 $form->questiontext['format'] : 0;
350 if (empty($form->generalfeedback['text'])) {
351 $question->generalfeedback = '';
352 } else {
353 $question->generalfeedback = trim($form->generalfeedback['text']);
355 $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
356 $form->generalfeedback['format'] : 0;
358 if (empty($question->name)) {
359 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
360 if (empty($question->name)) {
361 $question->name = '-';
365 if ($question->penalty > 1 or $question->penalty < 0) {
366 $question->errors['penalty'] = get_string('invalidpenalty', 'question');
369 if (isset($form->defaultmark)) {
370 $question->defaultmark = $form->defaultmark;
373 // If the question is new, create it.
374 if (empty($question->id)) {
375 // Set the unique code
376 $question->stamp = make_unique_id_code();
377 $question->createdby = $USER->id;
378 $question->timecreated = time();
379 $question->id = $DB->insert_record('question', $question);
382 // Now, whether we are updating a existing question, or creating a new
383 // one, we have to do the files processing and update the record.
384 /// Question already exists, update.
385 $question->modifiedby = $USER->id;
386 $question->timemodified = time();
388 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
389 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
390 $context->id, 'question', 'questiontext', (int)$question->id,
391 $this->fileoptions, $question->questiontext);
393 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
394 $question->generalfeedback = file_save_draft_area_files(
395 $form->generalfeedback['itemid'], $context->id,
396 'question', 'generalfeedback', (int)$question->id,
397 $this->fileoptions, $question->generalfeedback);
399 $DB->update_record('question', $question);
401 // Now to save all the answers and type-specific options
402 $form->id = $question->id;
403 $form->qtype = $question->qtype;
404 $form->category = $question->category;
405 $form->questiontext = $question->questiontext;
406 $form->questiontextformat = $question->questiontextformat;
407 // current context
408 $form->context = $context;
410 $result = $this->save_question_options($form);
412 if (!empty($result->error)) {
413 print_error($result->error);
416 if (!empty($result->notice)) {
417 notice($result->notice, "question.php?id=$question->id");
420 if (!empty($result->noticeyesno)) {
421 throw new coding_exception(
422 '$result->noticeyesno no longer supported in save_question.');
425 // Give the question a unique version stamp determined by question_hash()
426 $DB->set_field('question', 'version', question_hash($question),
427 array('id' => $question->id));
429 return $question;
433 * Saves question-type specific options
435 * This is called by {@link save_question()} to save the question-type specific data
436 * @return object $result->error or $result->noticeyesno or $result->notice
437 * @param object $question This holds the information from the editing form,
438 * it is not a standard question object.
440 public function save_question_options($question) {
441 global $DB;
442 $extraquestionfields = $this->extra_question_fields();
444 if (is_array($extraquestionfields)) {
445 $question_extension_table = array_shift($extraquestionfields);
447 $function = 'update_record';
448 $questionidcolname = $this->questionid_column_name();
449 $options = $DB->get_record($question_extension_table,
450 array($questionidcolname => $question->id));
451 if (!$options) {
452 $function = 'insert_record';
453 $options = new stdClass();
454 $options->$questionidcolname = $question->id;
456 foreach ($extraquestionfields as $field) {
457 if (!isset($question->$field)) {
458 $result = new stdClass();
459 $result->error = "No data for field $field when saving " .
460 $this->name() . ' question id ' . $question->id;
461 return $result;
463 $options->$field = $question->$field;
466 if (!$DB->{$function}($question_extension_table, $options)) {
467 $result = new stdClass();
468 $result->error = 'Could not save question options for ' .
469 $this->name() . ' question id ' . $question->id;
470 return $result;
474 $extraanswerfields = $this->extra_answer_fields();
475 // TODO save the answers, with any extra data.
478 public function save_hints($formdata, $withparts = false) {
479 global $DB;
480 $context = $formdata->context;
482 $oldhints = $DB->get_records('question_hints',
483 array('questionid' => $formdata->id), 'id ASC');
485 if (!empty($formdata->hint)) {
486 $numhints = max(array_keys($formdata->hint)) + 1;
487 } else {
488 $numhints = 0;
491 if ($withparts) {
492 if (!empty($formdata->hintclearwrong)) {
493 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
494 } else {
495 $numclears = 0;
497 if (!empty($formdata->hintshownumcorrect)) {
498 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
499 } else {
500 $numshows = 0;
502 $numhints = max($numhints, $numclears, $numshows);
505 for ($i = 0; $i < $numhints; $i += 1) {
506 if (html_is_blank($formdata->hint[$i]['text'])) {
507 $formdata->hint[$i]['text'] = '';
510 if ($withparts) {
511 $clearwrong = !empty($formdata->hintclearwrong[$i]);
512 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
515 if (empty($formdata->hint[$i]['text']) && empty($clearwrong) &&
516 empty($shownumcorrect)) {
517 continue;
520 // Update an existing hint if possible.
521 $hint = array_shift($oldhints);
522 if (!$hint) {
523 $hint = new stdClass();
524 $hint->questionid = $formdata->id;
525 $hint->hint = '';
526 $hint->id = $DB->insert_record('question_hints', $hint);
529 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
530 $context, 'question', 'hint', $hint->id);
531 $hint->hintformat = $formdata->hint[$i]['format'];
532 if ($withparts) {
533 $hint->clearwrong = $clearwrong;
534 $hint->shownumcorrect = $shownumcorrect;
536 $DB->update_record('question_hints', $hint);
539 // Delete any remaining old hints.
540 $fs = get_file_storage();
541 foreach ($oldhints as $oldhint) {
542 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
543 $DB->delete_records('question_hints', array('id' => $oldhint->id));
548 * Can be used to {@link save_question_options()} to transfer the combined
549 * feedback fields from $formdata to $options.
550 * @param object $options the $question->options object being built.
551 * @param object $formdata the data from the form.
552 * @param object $context the context the quetsion is being saved into.
553 * @param bool $withparts whether $options->shownumcorrect should be set.
555 protected function save_combined_feedback_helper($options, $formdata,
556 $context, $withparts = false) {
557 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
558 $context, 'question', 'correctfeedback', $formdata->id);
559 $options->correctfeedbackformat = $formdata->correctfeedback['format'];
561 $options->partiallycorrectfeedback = $this->import_or_save_files(
562 $formdata->partiallycorrectfeedback,
563 $context, 'question', 'partiallycorrectfeedback', $formdata->id);
564 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
566 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
567 $context, 'question', 'incorrectfeedback', $formdata->id);
568 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
570 if ($withparts) {
571 $options->shownumcorrect = !empty($formdata->shownumcorrect);
574 return $options;
578 * Loads the question type specific options for the question.
580 * This function loads any question type specific options for the
581 * question from the database into the question object. This information
582 * is placed in the $question->options field. A question type is
583 * free, however, to decide on a internal structure of the options field.
584 * @return bool Indicates success or failure.
585 * @param object $question The question object for the question. This object
586 * should be updated to include the question type
587 * specific information (it is passed by reference).
589 public function get_question_options($question) {
590 global $CFG, $DB, $OUTPUT;
592 if (!isset($question->options)) {
593 $question->options = new stdClass();
596 $extraquestionfields = $this->extra_question_fields();
597 if (is_array($extraquestionfields)) {
598 $question_extension_table = array_shift($extraquestionfields);
599 $extra_data = $DB->get_record($question_extension_table,
600 array($this->questionid_column_name() => $question->id),
601 implode(', ', $extraquestionfields));
602 if ($extra_data) {
603 foreach ($extraquestionfields as $field) {
604 $question->options->$field = $extra_data->$field;
606 } else {
607 echo $OUTPUT->notification('Failed to load question options from the table ' .
608 $question_extension_table . ' for questionid ' . $question->id);
609 return false;
613 $extraanswerfields = $this->extra_answer_fields();
614 if (is_array($extraanswerfields)) {
615 $answer_extension_table = array_shift($extraanswerfields);
616 $question->options->answers = $DB->get_records_sql("
617 SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . "
618 FROM {question_answers} qa, {{$answer_extension_table}} qax
619 WHERE qa.question = ? AND qax.answerid = qa.id
620 ORDER BY qa.id", array($question->id));
621 if (!$question->options->answers) {
622 echo $OUTPUT->notification('Failed to load question answers from the table ' .
623 $answer_extension_table . 'for questionid ' . $question->id);
624 return false;
626 } else {
627 // Don't check for success or failure because some question types do
628 // not use the answers table.
629 $question->options->answers = $DB->get_records('question_answers',
630 array('question' => $question->id), 'id ASC');
633 $question->hints = $DB->get_records('question_hints',
634 array('questionid' => $question->id), 'id ASC');
636 return true;
640 * Create an appropriate question_definition for the question of this type
641 * using data loaded from the database.
642 * @param object $questiondata the question data loaded from the database.
643 * @return question_definition the corresponding question_definition.
645 public function make_question($questiondata) {
646 $question = $this->make_question_instance($questiondata);
647 $this->initialise_question_instance($question, $questiondata);
648 return $question;
652 * Create an appropriate question_definition for the question of this type
653 * using data loaded from the database.
654 * @param object $questiondata the question data loaded from the database.
655 * @return question_definition an instance of the appropriate question_definition subclass.
656 * Still needs to be initialised.
658 protected function make_question_instance($questiondata) {
659 question_bank::load_question_definition_classes($this->name());
660 $class = 'qtype_' . $this->name() . '_question';
661 return new $class();
665 * Initialise the common question_definition fields.
666 * @param question_definition $question the question_definition we are creating.
667 * @param object $questiondata the question data loaded from the database.
669 protected function initialise_question_instance(question_definition $question, $questiondata) {
670 $question->id = $questiondata->id;
671 $question->category = $questiondata->category;
672 $question->contextid = $questiondata->contextid;
673 $question->parent = $questiondata->parent;
674 $question->qtype = $this;
675 $question->name = $questiondata->name;
676 $question->questiontext = $questiondata->questiontext;
677 $question->questiontextformat = $questiondata->questiontextformat;
678 $question->generalfeedback = $questiondata->generalfeedback;
679 $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
680 $question->defaultmark = $questiondata->defaultmark + 0;
681 $question->length = $questiondata->length;
682 $question->penalty = $questiondata->penalty;
683 $question->stamp = $questiondata->stamp;
684 $question->version = $questiondata->version;
685 $question->hidden = $questiondata->hidden;
686 $question->timecreated = $questiondata->timecreated;
687 $question->timemodified = $questiondata->timemodified;
688 $question->createdby = $questiondata->createdby;
689 $question->modifiedby = $questiondata->modifiedby;
691 //Fill extra question fields values
692 $extraquestionfields = $this->extra_question_fields();
693 if (is_array($extraquestionfields)) {
694 //omit table name
695 array_shift($extraquestionfields);
696 foreach($extraquestionfields as $field) {
697 $question->$field = $questiondata->options->$field;
701 $this->initialise_question_hints($question, $questiondata);
705 * Initialise question_definition::hints field.
706 * @param question_definition $question the question_definition we are creating.
707 * @param object $questiondata the question data loaded from the database.
709 protected function initialise_question_hints(question_definition $question, $questiondata) {
710 if (empty($questiondata->hints)) {
711 return;
713 foreach ($questiondata->hints as $hint) {
714 $question->hints[] = $this->make_hint($hint);
719 * Create a question_hint, or an appropriate subclass for this question,
720 * from a row loaded from the database.
721 * @param object $hint the DB row from the question hints table.
722 * @return question_hint
724 protected function make_hint($hint) {
725 return question_hint::load_from_record($hint);
729 * Initialise the combined feedback fields.
730 * @param question_definition $question the question_definition we are creating.
731 * @param object $questiondata the question data loaded from the database.
732 * @param bool $withparts whether to set the shownumcorrect field.
734 protected function initialise_combined_feedback(question_definition $question,
735 $questiondata, $withparts = false) {
736 $question->correctfeedback = $questiondata->options->correctfeedback;
737 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
738 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
739 $question->partiallycorrectfeedbackformat =
740 $questiondata->options->partiallycorrectfeedbackformat;
741 $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
742 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
743 if ($withparts) {
744 $question->shownumcorrect = $questiondata->options->shownumcorrect;
749 * Initialise question_definition::answers field.
750 * @param question_definition $question the question_definition we are creating.
751 * @param object $questiondata the question data loaded from the database.
752 * @param bool $forceplaintextanswers most qtypes assume that answers are
753 * FORMAT_PLAIN, and dont use the answerformat DB column (it contains
754 * the default 0 = FORMAT_MOODLE). Therefore, by default this method
755 * ingores answerformat. Pass false here to use answerformat. For example
756 * multichoice does this.
758 protected function initialise_question_answers(question_definition $question,
759 $questiondata, $forceplaintextanswers = true) {
760 $question->answers = array();
761 if (empty($questiondata->options->answers)) {
762 return;
764 foreach ($questiondata->options->answers as $a) {
765 $question->answers[$a->id] = new question_answer($a->id, $a->answer,
766 $a->fraction, $a->feedback, $a->feedbackformat);
767 if (!$forceplaintextanswers) {
768 $question->answers[$a->id]->answerformat = $a->answerformat;
774 * Deletes the question-type specific data when a question is deleted.
775 * @param int $question the question being deleted.
776 * @param int $contextid the context this quesiotn belongs to.
778 public function delete_question($questionid, $contextid) {
779 global $DB;
781 $this->delete_files($questionid, $contextid);
783 $extraquestionfields = $this->extra_question_fields();
784 if (is_array($extraquestionfields)) {
785 $question_extension_table = array_shift($extraquestionfields);
786 $DB->delete_records($question_extension_table,
787 array($this->questionid_column_name() => $questionid));
790 $extraanswerfields = $this->extra_answer_fields();
791 if (is_array($extraanswerfields)) {
792 $answer_extension_table = array_shift($extraanswerfields);
793 $DB->delete_records_select($answer_extension_table,
794 'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
795 array($questionid));
798 $DB->delete_records('question_answers', array('question' => $questionid));
800 $DB->delete_records('question_hints', array('questionid' => $questionid));
804 * Returns the number of question numbers which are used by the question
806 * This function returns the number of question numbers to be assigned
807 * to the question. Most question types will have length one; they will be
808 * assigned one number. The 'description' type, however does not use up a
809 * number and so has a length of zero. Other question types may wish to
810 * handle a bundle of questions and hence return a number greater than one.
811 * @return int The number of question numbers which should be
812 * assigned to the question.
813 * @param object $question The question whose length is to be determined.
814 * Question type specific information is included.
816 public function actual_number_of_questions($question) {
817 // By default, each question is given one number
818 return 1;
822 * @param object $question
823 * @return number|null either a fraction estimating what the student would
824 * score by guessing, or null, if it is not possible to estimate.
826 public function get_random_guess_score($questiondata) {
827 return 0;
831 * This method should return all the possible types of response that are
832 * recognised for this question.
834 * The question is modelled as comprising one or more subparts. For each
835 * subpart, there are one or more classes that that students response
836 * might fall into, each of those classes earning a certain score.
838 * For example, in a shortanswer question, there is only one subpart, the
839 * text entry field. The response the student gave will be classified according
840 * to which of the possible $question->options->answers it matches.
842 * For the matching question type, there will be one subpart for each
843 * question stem, and for each stem, each of the possible choices is a class
844 * of student's response.
846 * A response is an object with two fields, ->responseclass is a string
847 * presentation of that response, and ->fraction, the credit for a response
848 * in that class.
850 * Array keys have no specific meaning, but must be unique, and must be
851 * the same if this function is called repeatedly.
853 * @param object $question the question definition data.
854 * @return array keys are subquestionid, values are arrays of possible
855 * responses to that subquestion.
857 public function get_possible_responses($questiondata) {
858 return array();
862 * Utility method used by {@link qtype_renderer::head_code()}. It looks
863 * for any of the files script.js or script.php that exist in the plugin
864 * folder and ensures they get included.
866 public function find_standard_scripts() {
867 global $PAGE;
869 $plugindir = $this->plugin_dir();
870 $plugindirrel = 'question/type/' . $this->name();
872 if (file_exists($plugindir . '/script.js')) {
873 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
875 if (file_exists($plugindir . '/script.php')) {
876 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
881 * Returns true if the editing wizard is finished, false otherwise.
883 * The default implementation returns true, which is suitable for all question-
884 * types that only use one editing form. This function is used in
885 * question.php to decide whether we can regrade any states of the edited
886 * question and redirect to edit.php.
888 * The dataset dependent question-type, which is extended by the calculated
889 * question-type, overwrites this method because it uses multiple pages (i.e.
890 * a wizard) to set up the question and associated datasets.
892 * @param object $form The data submitted by the previous page.
894 * @return bool Whether the wizard's last page was submitted or not.
896 public function finished_edit_wizard($form) {
897 //In the default case there is only one edit page.
898 return true;
901 /// IMPORT/EXPORT FUNCTIONS /////////////////
904 * Imports question from the Moodle XML format
906 * Imports question using information from extra_question_fields function
907 * If some of you fields contains id's you'll need to reimplement this
909 public function import_from_xml($data, $question, $format, $extra=null) {
910 $question_type = $data['@']['type'];
911 if ($question_type != $this->name()) {
912 return false;
915 $extraquestionfields = $this->extra_question_fields();
916 if (!is_array($extraquestionfields)) {
917 return false;
920 //omit table name
921 array_shift($extraquestionfields);
922 $qo = $format->import_headers($data);
923 $qo->qtype = $question_type;
925 foreach ($extraquestionfields as $field) {
926 $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
929 // run through the answers
930 $answers = $data['#']['answer'];
931 $a_count = 0;
932 $extraanswersfields = $this->extra_answer_fields();
933 if (is_array($extraanswersfields)) {
934 array_shift($extraanswersfields);
936 foreach ($answers as $answer) {
937 $ans = $format->import_answer($answer);
938 if (!$this->has_html_answers()) {
939 $qo->answer[$a_count] = $ans->answer['text'];
940 } else {
941 $qo->answer[$a_count] = $ans->answer;
943 $qo->fraction[$a_count] = $ans->fraction;
944 $qo->feedback[$a_count] = $ans->feedback;
945 if (is_array($extraanswersfields)) {
946 foreach ($extraanswersfields as $field) {
947 $qo->{$field}[$a_count] =
948 $format->getpath($answer, array('#', $field, 0, '#'), '');
951 ++$a_count;
953 return $qo;
957 * Export question to the Moodle XML format
959 * Export question using information from extra_question_fields function
960 * If some of you fields contains id's you'll need to reimplement this
962 public function export_to_xml($question, $format, $extra=null) {
963 $extraquestionfields = $this->extra_question_fields();
964 if (!is_array($extraquestionfields)) {
965 return false;
968 //omit table name
969 array_shift($extraquestionfields);
970 $expout='';
971 foreach ($extraquestionfields as $field) {
972 $exportedvalue = $format->xml_escape($question->options->$field);
973 $expout .= " <$field>{$exportedvalue}</$field>\n";
976 $extraanswersfields = $this->extra_answer_fields();
977 if (is_array($extraanswersfields)) {
978 array_shift($extraanswersfields);
980 foreach ($question->options->answers as $answer) {
981 // TODO this should be re-factored to use $format->write_answer().
982 $percent = 100 * $answer->fraction;
983 $expout .= " <answer fraction=\"$percent\" {$format->format($answer->answerformat)}>\n";
984 $expout .= $format->writetext($answer->answer, 3, false);
985 $expout .= " <feedback {$format->format($answer->feedbackformat)}>\n";
986 $expout .= $format->writetext($answer->feedback, 4, false);
987 $expout .= " </feedback>\n";
988 if (is_array($extraanswersfields)) {
989 foreach ($extraanswersfields as $field) {
990 $exportedvalue = $format->xml_escape($answer->$field);
991 $expout .= " <{$field}>{$exportedvalue}</{$field}>\n";
995 $expout .= " </answer>\n";
997 return $expout;
1001 * Abstract function implemented by each question type. It runs all the code
1002 * required to set up and save a question of any type for testing purposes.
1003 * Alternate DB table prefix may be used to facilitate data deletion.
1005 public function generate_test($name, $courseid=null) {
1006 $form = new stdClass();
1007 $form->name = $name;
1008 $form->questiontextformat = 1;
1009 $form->questiontext = 'test question, generated by script';
1010 $form->defaultmark = 1;
1011 $form->penalty = 0.3333333;
1012 $form->generalfeedback = "Well done";
1014 $context = get_context_instance(CONTEXT_COURSE, $courseid);
1015 $newcategory = question_make_default_categories(array($context));
1016 $form->category = $newcategory->id . ',1';
1018 $question = new stdClass();
1019 $question->courseid = $courseid;
1020 $question->qtype = $this->qtype;
1021 return array($form, $question);
1025 * Get question context by category id
1026 * @param int $category
1027 * @return object $context
1029 protected function get_context_by_category_id($category) {
1030 global $DB;
1031 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
1032 $context = get_context_instance_by_id($contextid);
1033 return $context;
1037 * Save the file belonging to one text field.
1039 * @param array $field the data from the form (or from import). This will
1040 * normally have come from the formslib editor element, so it will be an
1041 * array with keys 'text', 'format' and 'itemid'. However, when we are
1042 * importing, it will be an array with keys 'text', 'format' and 'files'
1043 * @param object $context the context the question is in.
1044 * @param string $component indentifies the file area question.
1045 * @param string $filearea indentifies the file area questiontext,
1046 * generalfeedback, answerfeedback, etc.
1047 * @param int $itemid identifies the file area.
1049 * @return string the text for this field, after files have been processed.
1051 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1052 if (!empty($field['itemid'])) {
1053 // This is the normal case. We are safing the questions editing form.
1054 return file_save_draft_area_files($field['itemid'], $context->id, $component,
1055 $filearea, $itemid, $this->fileoptions, trim($field['text']));
1057 } else if (!empty($field['files'])) {
1058 // This is the case when we are doing an import.
1059 foreach ($field['files'] as $file) {
1060 $this->import_file($context, $component, $filearea, $itemid, $file);
1063 return trim($field['text']);
1067 * Move all the files belonging to this question from one context to another.
1068 * @param int $questionid the question being moved.
1069 * @param int $oldcontextid the context it is moving from.
1070 * @param int $newcontextid the context it is moving to.
1072 public function move_files($questionid, $oldcontextid, $newcontextid) {
1073 $fs = get_file_storage();
1074 $fs->move_area_files_to_new_context($oldcontextid,
1075 $newcontextid, 'question', 'questiontext', $questionid);
1076 $fs->move_area_files_to_new_context($oldcontextid,
1077 $newcontextid, 'question', 'generalfeedback', $questionid);
1081 * Move all the files belonging to this question's answers when the question
1082 * is moved from one context to another.
1083 * @param int $questionid the question being moved.
1084 * @param int $oldcontextid the context it is moving from.
1085 * @param int $newcontextid the context it is moving to.
1086 * @param bool $answerstoo whether there is an 'answer' question area,
1087 * as well as an 'answerfeedback' one. Default false.
1089 protected function move_files_in_answers($questionid, $oldcontextid,
1090 $newcontextid, $answerstoo = false) {
1091 global $DB;
1092 $fs = get_file_storage();
1094 $answerids = $DB->get_records_menu('question_answers',
1095 array('question' => $questionid), 'id', 'id,1');
1096 foreach ($answerids as $answerid => $notused) {
1097 if ($answerstoo) {
1098 $fs->move_area_files_to_new_context($oldcontextid,
1099 $newcontextid, 'question', 'answer', $answerid);
1101 $fs->move_area_files_to_new_context($oldcontextid,
1102 $newcontextid, 'question', 'answerfeedback', $answerid);
1107 * Move all the files belonging to this question's hints when the question
1108 * is moved from one context to another.
1109 * @param int $questionid the question being moved.
1110 * @param int $oldcontextid the context it is moving from.
1111 * @param int $newcontextid the context it is moving to.
1112 * @param bool $answerstoo whether there is an 'answer' question area,
1113 * as well as an 'answerfeedback' one. Default false.
1115 protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1116 global $DB;
1117 $fs = get_file_storage();
1119 $hintids = $DB->get_records_menu('question_hints',
1120 array('questionid' => $questionid), 'id', 'id,1');
1121 foreach ($hintids as $hintid => $notused) {
1122 $fs->move_area_files_to_new_context($oldcontextid,
1123 $newcontextid, 'question', 'hint', $hintid);
1128 * Move all the files belonging to this question's answers when the question
1129 * is moved from one context to another.
1130 * @param int $questionid the question being moved.
1131 * @param int $oldcontextid the context it is moving from.
1132 * @param int $newcontextid the context it is moving to.
1133 * @param bool $answerstoo whether there is an 'answer' question area,
1134 * as well as an 'answerfeedback' one. Default false.
1136 protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1137 $newcontextid) {
1138 global $DB;
1139 $fs = get_file_storage();
1141 $fs->move_area_files_to_new_context($oldcontextid,
1142 $newcontextid, 'question', 'correctfeedback', $questionid);
1143 $fs->move_area_files_to_new_context($oldcontextid,
1144 $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1145 $fs->move_area_files_to_new_context($oldcontextid,
1146 $newcontextid, 'question', 'incorrectfeedback', $questionid);
1150 * Delete all the files belonging to this question.
1151 * @param int $questionid the question being deleted.
1152 * @param int $contextid the context the question is in.
1154 protected function delete_files($questionid, $contextid) {
1155 $fs = get_file_storage();
1156 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1157 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1161 * Delete all the files belonging to this question's answers.
1162 * @param int $questionid the question being deleted.
1163 * @param int $contextid the context the question is in.
1164 * @param bool $answerstoo whether there is an 'answer' question area,
1165 * as well as an 'answerfeedback' one. Default false.
1167 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1168 global $DB;
1169 $fs = get_file_storage();
1171 $answerids = $DB->get_records_menu('question_answers',
1172 array('question' => $questionid), 'id', 'id,1');
1173 foreach ($answerids as $answerid => $notused) {
1174 if ($answerstoo) {
1175 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1177 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1182 * Delete all the files belonging to this question's hints.
1183 * @param int $questionid the question being deleted.
1184 * @param int $contextid the context the question is in.
1186 protected function delete_files_in_hints($questionid, $contextid) {
1187 global $DB;
1188 $fs = get_file_storage();
1190 $hintids = $DB->get_records_menu('question_hints',
1191 array('questionid' => $questionid), 'id', 'id,1');
1192 foreach ($hintids as $hintid => $notused) {
1193 $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1198 * Delete all the files belonging to this question's answers.
1199 * @param int $questionid the question being deleted.
1200 * @param int $contextid the context the question is in.
1201 * @param bool $answerstoo whether there is an 'answer' question area,
1202 * as well as an 'answerfeedback' one. Default false.
1204 protected function delete_files_in_combined_feedback($questionid, $contextid) {
1205 global $DB;
1206 $fs = get_file_storage();
1208 $fs->delete_area_files($contextid,
1209 'question', 'correctfeedback', $questionid);
1210 $fs->delete_area_files($contextid,
1211 'question', 'partiallycorrectfeedback', $questionid);
1212 $fs->delete_area_files($contextid,
1213 'question', 'incorrectfeedback', $questionid);
1216 public function import_file($context, $component, $filearea, $itemid, $file) {
1217 $fs = get_file_storage();
1218 $record = new stdClass();
1219 if (is_object($context)) {
1220 $record->contextid = $context->id;
1221 } else {
1222 $record->contextid = $context;
1224 $record->component = $component;
1225 $record->filearea = $filearea;
1226 $record->itemid = $itemid;
1227 $record->filename = $file->name;
1228 $record->filepath = '/';
1229 return $fs->create_file_from_string($record, $this->decode_file($file));
1232 protected function decode_file($file) {
1233 switch ($file->encoding) {
1234 case 'base64':
1235 default:
1236 return base64_decode($file->content);
1243 * This class is used in the return value from
1244 * {@link question_type::get_possible_responses()}.
1246 * @copyright 2010 The Open University
1247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1249 class question_possible_response {
1251 * @var string the classification of this response the student gave to this
1252 * part of the question. Must match one of the responseclasses returned by
1253 * {@link question_type::get_possible_responses()}.
1255 public $responseclass;
1256 /** @var string the actual response the student gave to this part. */
1257 public $fraction;
1259 * Constructor, just an easy way to set the fields.
1260 * @param string $responseclassid see the field descriptions above.
1261 * @param string $response see the field descriptions above.
1262 * @param number $fraction see the field descriptions above.
1264 public function __construct($responseclass, $fraction) {
1265 $this->responseclass = $responseclass;
1266 $this->fraction = $fraction;
1269 public static function no_response() {
1270 return new question_possible_response(get_string('noresponse', 'question'), 0);