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