MDL-20636 Finish conversion of the Opaque qtype/behaviour.
[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 464 global $DB;
7a719748
TH
465 $context = $formdata->context;
466
467 $oldhints = $DB->get_records('question_hints', array('questionid' => $formdata->id));
295043c2 468
d1b7e03d
TH
469 if (!empty($formdata->hint)) {
470 $numhints = max(array_keys($formdata->hint)) + 1;
471 } else {
472 $numhints = 0;
516cf3eb 473 }
295043c2 474
d1b7e03d
TH
475 if ($withparts) {
476 if (!empty($formdata->hintclearwrong)) {
477 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
478 } else {
479 $numclears = 0;
480 }
481 if (!empty($formdata->hintshownumcorrect)) {
482 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
483 } else {
484 $numshows = 0;
485 }
486 $numhints = max($numhints, $numclears, $numshows);
487 }
488
489 for ($i = 0; $i < $numhints; $i += 1) {
7a719748
TH
490 if (html_is_blank($formdata->hint[$i]['text'])) {
491 $formdata->hint[$i]['text'] = '';
d1b7e03d
TH
492 }
493
494 if ($withparts) {
7a719748
TH
495 $clearwrong = !empty($formdata->hintclearwrong[$i]);
496 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
d1b7e03d
TH
497 }
498
7a719748 499 if (empty($formdata->hint[$i]['text']) && empty($clearwrong) && empty($shownumcorrect)) {
d1b7e03d
TH
500 continue;
501 }
502
7a719748
TH
503 // Update an existing answer if possible.
504 $hint = array_shift($oldhints);
505 if (!$hint) {
506 $hint = new stdClass();
507 $hint->questionid = $formdata->id;
508 $hint->hint = '';
509 $hint->id = $DB->insert_record('question_hints', $hint);
510 }
511
512 $hint->hint = '';
513 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
514 $context, 'question', 'hint', $hint->id);
515 $hint->hintformat = $formdata->hint[$i]['format'];
516 if ($withparts) {
517 $hint->clearwrong = $clearwrong;
518 $hint->shownumcorrect = $shownumcorrect;
519 }
520 $DB->update_record('question_hints', $hint);
521 }
522
523 // Delete any remaining old hints.
524 $fs = get_file_storage();
525 foreach($oldhints as $oldhint) {
526 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
527 $DB->delete_records('question_hints', array('id' => $oldhint->id));
d1b7e03d
TH
528 }
529 }
530
531 /**
532 * Loads the question type specific options for the question.
533 *
534 * This function loads any question type specific options for the
535 * question from the database into the question object. This information
536 * is placed in the $question->options field. A question type is
537 * free, however, to decide on a internal structure of the options field.
538 * @return bool Indicates success or failure.
539 * @param object $question The question object for the question. This object
540 * should be updated to include the question type
541 * specific information (it is passed by reference).
542 */
543 public function get_question_options($question) {
f29aeb5a
TH
544 global $CFG, $DB, $OUTPUT;
545
546 if (!isset($question->options)) {
547 $question->options = new stdClass();
548 }
d1b7e03d 549
295043c2 550 $extra_question_fields = $this->extra_question_fields();
551 if (is_array($extra_question_fields)) {
552 $question_extension_table = array_shift($extra_question_fields);
f29aeb5a 553 $extra_data = $DB->get_record($question_extension_table, array($this->questionid_column_name() => $question->id), implode(', ', $extra_question_fields));
295043c2 554 if ($extra_data) {
555 foreach ($extra_question_fields as $field) {
556 $question->options->$field = $extra_data->$field;
557 }
558 } else {
f29aeb5a 559 echo $OUTPUT->notification("Failed to load question options from the table $question_extension_table for questionid " .
295043c2 560 $question->id);
561 return false;
562 }
563 }
564
565 $extra_answer_fields = $this->extra_answer_fields();
566 if (is_array($extra_answer_fields)) {
567 $answer_extension_table = array_shift($extra_answer_fields);
f29aeb5a
TH
568 $question->options->answers = $DB->get_records_sql("
569 SELECT qa.*, qax." . implode(', qax.', $extra_answer_fields) . "
570 FROM {question_answers} qa, {$answer_extension_table} qax
571 WHERE qa.questionid = ? AND qax.answerid = qa.id", array($question->id));
295043c2 572 if (!$question->options->answers) {
f29aeb5a 573 echo $OUTPUT->notification("Failed to load question answers from the table $answer_extension_table for questionid " .
295043c2 574 $question->id);
575 return false;
576 }
577 } else {
ca9000df 578 // Don't check for success or failure because some question types do not use the answers table.
f29aeb5a 579 $question->options->answers = $DB->get_records('question_answers', array('question' => $question->id), 'id ASC');
295043c2 580 }
581
f29aeb5a 582 $question->hints = $DB->get_records('question_hints', array('questionid' => $question->id), 'id ASC');
d1b7e03d 583
516cf3eb 584 return true;
585 }
586
587 /**
d1b7e03d
TH
588 * Create an appropriate question_definition for the question of this type
589 * using data loaded from the database.
590 * @param object $questiondata the question data loaded from the database.
591 * @return question_definition the corresponding question_definition.
592 */
593 public function make_question($questiondata) {
594 $question = $this->make_question_instance($questiondata);
595 $this->initialise_question_instance($question, $questiondata);
596 return $question;
597 }
0429cd86 598
d1b7e03d
TH
599 /**
600 * Create an appropriate question_definition for the question of this type
601 * using data loaded from the database.
602 * @param object $questiondata the question data loaded from the database.
603 * @return question_definition an instance of the appropriate question_definition subclass.
604 * Still needs to be initialised.
605 */
606 protected function make_question_instance($questiondata) {
607 question_bank::load_question_definition_classes($this->name());
608 $class = 'qtype_' . $this->name() . '_question';
609 return new $class();
610 }
611
612 /**
613 * Initialise the common question_definition fields.
614 * @param question_definition $question the question_definition we are creating.
615 * @param object $questiondata the question data loaded from the database.
616 */
617 protected function initialise_question_instance(question_definition $question, $questiondata) {
618 $question->id = $questiondata->id;
619 $question->category = $questiondata->category;
620 $question->parent = $questiondata->parent;
621 $question->qtype = $this;
622 $question->name = $questiondata->name;
623 $question->questiontext = $questiondata->questiontext;
624 $question->questiontextformat = $questiondata->questiontextformat;
625 $question->generalfeedback = $questiondata->generalfeedback;
626 $question->defaultmark = $questiondata->defaultmark + 0;
627 $question->length = $questiondata->length;
628 $question->penalty = $questiondata->penalty;
629 $question->stamp = $questiondata->stamp;
630 $question->version = $questiondata->version;
631 $question->hidden = $questiondata->hidden;
632 $question->timecreated = $questiondata->timecreated;
633 $question->timemodified = $questiondata->timemodified;
634 $question->createdby = $questiondata->createdby;
635 $question->modifiedby = $questiondata->modifiedby;
636
637 $this->initialise_question_hints($question, $questiondata);
638 }
639
640 /**
641 * Initialise question_definition::hints field.
642 * @param question_definition $question the question_definition we are creating.
643 * @param object $questiondata the question data loaded from the database.
644 */
645 protected function initialise_question_hints(question_definition $question, $questiondata) {
646 if (empty($questiondata->hints)) {
647 return;
648 }
649 foreach ($questiondata->hints as $hint) {
650 $question->hints[] = $this->make_hint($hint);
651 }
0429cd86 652 }
653
654 /**
d1b7e03d
TH
655 * Create a question_hint, or an appropriate subclass for this question,
656 * from a row loaded from the database.
657 * @param object $hint the DB row from the question hints table.
658 * @return question_hint
9203b705 659 */
d1b7e03d
TH
660 protected function make_hint($hint) {
661 return question_hint::load_from_record($hint);
662 }
663
664 /**
665 * Initialise question_definition::answers field.
666 * @param question_definition $question the question_definition we are creating.
667 * @param object $questiondata the question data loaded from the database.
668 */
669 protected function initialise_question_answers(question_definition $question, $questiondata) {
670 $question->answers = array();
671 if (empty($questiondata->options->answers)) {
672 return;
673 }
674 foreach ($questiondata->options->answers as $a) {
5f7cfba7
TH
675 $question->answers[$a->id] = new question_answer($a->id, $a->answer,
676 $a->fraction, $a->feedback, $a->feedbackformat);
d1b7e03d
TH
677 }
678 }
9203b705 679
d1b7e03d 680 /**
f29aeb5a
TH
681 * Deletes the question-type specific data when a question is deleted.
682 * @param integer $question the question being deleted.
683 * @param integer $contextid the context this quesiotn belongs to.
684 */
685 public function delete_question($questionid, $contextid) {
686 global $DB;
687
688 $this->delete_files($questionid, $contextid);
516cf3eb 689
295043c2 690 $extra_question_fields = $this->extra_question_fields();
691 if (is_array($extra_question_fields)) {
692 $question_extension_table = array_shift($extra_question_fields);
f29aeb5a
TH
693 $DB->delete_records($question_extension_table,
694 array($this->questionid_column_name() => $questionid));
295043c2 695 }
696
697 $extra_answer_fields = $this->extra_answer_fields();
698 if (is_array($extra_answer_fields)) {
699 $answer_extension_table = array_shift($extra_answer_fields);
f29aeb5a
TH
700 $DB->delete_records_select($answer_extension_table,
701 "answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)", array($questionid));
295043c2 702 }
703
f29aeb5a 704 $DB->delete_records('question_answers', array('question' => $questionid));
d1b7e03d 705
f29aeb5a 706 $DB->delete_records('question_hints', array('questionid' => $questionid));
516cf3eb 707 }
708
709 /**
710 * Returns the number of question numbers which are used by the question
711 *
712 * This function returns the number of question numbers to be assigned
713 * to the question. Most question types will have length one; they will be
dfa47f96 714 * assigned one number. The 'description' type, however does not use up a
516cf3eb 715 * number and so has a length of zero. Other question types may wish to
716 * handle a bundle of questions and hence return a number greater than one.
717 * @return integer The number of question numbers which should be
718 * assigned to the question.
719 * @param object $question The question whose length is to be determined.
720 * Question type specific information is included.
721 */
d1b7e03d 722 public function actual_number_of_questions($question) {
516cf3eb 723 // By default, each question is given one number
724 return 1;
725 }
726
6f51ed72 727 /**
728 * @param object $question
d1b7e03d
TH
729 * @return number|null either a fraction estimating what the student would
730 * score by guessing, or null, if it is not possible to estimate.
6f51ed72 731 */
d1b7e03d 732 function get_random_guess_score($questiondata) {
6f51ed72 733 return 0;
734 }
516cf3eb 735
516cf3eb 736 /**
d1b7e03d
TH
737 * This method should return all the possible types of response that are
738 * recognised for this question.
271e6dec 739 *
d1b7e03d
TH
740 * The question is modelled as comprising one or more subparts. For each
741 * subpart, there are one or more classes that that students response
742 * might fall into, each of those classes earning a certain score.
50da63eb 743 *
d1b7e03d
TH
744 * For example, in a shortanswer question, there is only one subpart, the
745 * text entry field. The response the student gave will be classified according
746 * to which of the possible $question->options->answers it matches.
271e6dec 747 *
d1b7e03d
TH
748 * For the matching question type, there will be one subpart for each
749 * question stem, and for each stem, each of the possible choices is a class
750 * of student's response.
751 *
752 * A response is an object with two fields, ->responseclass is a string
753 * presentation of that response, and ->fraction, the credit for a response
754 * in that class.
755 *
756 * Array keys have no specific meaning, but must be unique, and must be
757 * the same if this function is called repeatedly.
758 *
759 * @param object $question the question definition data.
760 * @return array keys are subquestionid, values are arrays of possible
761 * responses to that subquestion.
99ba746d 762 */
d1b7e03d
TH
763 function get_possible_responses($questiondata) {
764 return array();
50da63eb 765 }
5fceb049 766
50da63eb 767 /**
f29aeb5a
TH
768 * Like @see{get_html_head_contributions}, but this method is for CSS and
769 * JavaScript required on the question editing page question/question.php.
50da63eb 770 */
d1b7e03d 771 public function get_editing_head_contributions() {
50da63eb 772 // By default, we link to any of the files styles.css, styles.php,
773 // script.js or script.php that exist in the plugin folder.
774 // Core question types should not use this mechanism. Their styles
775 // should be included in the standard theme.
f29aeb5a 776 $this->find_standard_scripts();
50da63eb 777 }
271e6dec 778
50da63eb 779 /**
f29aeb5a 780 * Utility method used by @see{get_html_head_contributions} and
50da63eb 781 * @see{get_editing_head_contributions}. This looks for any of the files
f29aeb5a
TH
782 * script.js or script.php that exist in the plugin folder and ensures they
783 * get included.
50da63eb 784 */
c76145d3 785 public function find_standard_scripts() {
f29aeb5a
TH
786 global $PAGE;
787
99ba746d 788 $plugindir = $this->plugin_dir();
f29aeb5a 789 $plugindirrel = 'question/type/' . $this->name();
50da63eb 790
791 if (file_exists($plugindir . '/script.js')) {
f29aeb5a 792 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
50da63eb 793 }
794 if (file_exists($plugindir . '/script.php')) {
f29aeb5a 795 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
516cf3eb 796 }
fe9b5cfd 797 }
798
62e76c67 799 /**
d1b7e03d
TH
800 * Returns true if the editing wizard is finished, false otherwise.
801 *
802 * The default implementation returns true, which is suitable for all question-
803 * types that only use one editing form. This function is used in
804 * question.php to decide whether we can regrade any states of the edited
805 * question and redirect to edit.php.
806 *
807 * The dataset dependent question-type, which is extended by the calculated
808 * question-type, overwrites this method because it uses multiple pages (i.e.
809 * a wizard) to set up the question and associated datasets.
810 *
811 * @param object $form The data submitted by the previous page.
812 *
813 * @return boolean Whether the wizard's last page was submitted or not.
814 */
f29aeb5a 815 public function finished_edit_wizard($form) {
d1b7e03d
TH
816 //In the default case there is only one edit page.
817 return true;
62e76c67 818 }
819
88bc20c3 820/// IMPORT/EXPORT FUNCTIONS /////////////////
821
822 /*
823 * Imports question from the Moodle XML format
824 *
825 * Imports question using information from extra_question_fields function
826 * If some of you fields contains id's you'll need to reimplement this
827 */
d1b7e03d 828 public function import_from_xml($data, $question, $format, $extra=null) {
88bc20c3 829 $question_type = $data['@']['type'];
830 if ($question_type != $this->name()) {
831 return false;
832 }
833
834 $extraquestionfields = $this->extra_question_fields();
835 if (!is_array($extraquestionfields)) {
836 return false;
837 }
838
839 //omit table name
840 array_shift($extraquestionfields);
841 $qo = $format->import_headers($data);
842 $qo->qtype = $question_type;
843
844 foreach ($extraquestionfields as $field) {
f29aeb5a 845 $qo->$field = $format->getpath($data, array('#',$field,0,'#'), $qo->$field);
88bc20c3 846 }
847
848 // run through the answers
849 $answers = $data['#']['answer'];
850 $a_count = 0;
851 $extraasnwersfields = $this->extra_answer_fields();
852 if (is_array($extraasnwersfields)) {
853 //TODO import the answers, with any extra data.
854 } else {
855 foreach ($answers as $answer) {
856 $ans = $format->import_answer($answer);
857 $qo->answer[$a_count] = $ans->answer;
858 $qo->fraction[$a_count] = $ans->fraction;
859 $qo->feedback[$a_count] = $ans->feedback;
860 ++$a_count;
861 }
862 }
863 return $qo;
864 }
865
866 /*
867 * Export question to the Moodle XML format
868 *
869 * Export question using information from extra_question_fields function
870 * If some of you fields contains id's you'll need to reimplement this
871 */
d1b7e03d 872 public function export_to_xml($question, $format, $extra=null) {
88bc20c3 873 $extraquestionfields = $this->extra_question_fields();
874 if (!is_array($extraquestionfields)) {
875 return false;
876 }
877
878 //omit table name
879 array_shift($extraquestionfields);
880 $expout='';
881 foreach ($extraquestionfields as $field) {
2d01a916
TH
882 $exportedvalue = $question->options->$field;
883 if (!empty($exportedvalue) && htmlspecialchars($exportedvalue) != $exportedvalue) {
884 $exportedvalue = '<![CDATA[' . $exportedvalue . ']]>';
885 }
886 $expout .= " <$field>{$exportedvalue}</$field>\n";
88bc20c3 887 }
888
889 $extraasnwersfields = $this->extra_answer_fields();
890 if (is_array($extraasnwersfields)) {
891 //TODO export answers with any extra data
892 } else {
893 foreach ($question->options->answers as $answer) {
894 $percent = 100 * $answer->fraction;
895 $expout .= " <answer fraction=\"$percent\">\n";
896 $expout .= $format->writetext($answer->answer, 3, false);
897 $expout .= " <feedback>\n";
898 $expout .= $format->writetext($answer->feedback, 4, false);
899 $expout .= " </feedback>\n";
900 $expout .= " </answer>\n";
901 }
902 }
903 return $expout;
904 }
905
b9bd6da4 906 /**
907 * Abstract function implemented by each question type. It runs all the code
908 * required to set up and save a question of any type for testing purposes.
909 * Alternate DB table prefix may be used to facilitate data deletion.
910 */
d1b7e03d 911 public function generate_test($name, $courseid=null) {
b9bd6da4 912 $form = new stdClass();
913 $form->name = $name;
914 $form->questiontextformat = 1;
915 $form->questiontext = 'test question, generated by script';
d1b7e03d
TH
916 $form->defaultmark = 1;
917 $form->penalty = 0.3333333;
b9bd6da4 918 $form->generalfeedback = "Well done";
919
920 $context = get_context_instance(CONTEXT_COURSE, $courseid);
921 $newcategory = question_make_default_categories(array($context));
922 $form->category = $newcategory->id . ',1';
923
924 $question = new stdClass();
925 $question->courseid = $courseid;
926 $question->qtype = $this->qtype;
927 return array($form, $question);
928 }
f29aeb5a
TH
929
930 /**
931 * Get question context by category id
932 * @param int $category
933 * @return object $context
934 */
935 function get_context_by_category_id($category) {
936 global $DB;
937 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
938 $context = get_context_instance_by_id($contextid);
939 return $context;
940 }
941
942 /**
943 * Save the file belonging to one text field.
944 *
945 * @param array $field the data from the form (or from import). This will
946 * normally have come from the formslib editor element, so it will be an
947 * array with keys 'text', 'format' and 'itemid'. However, when we are
948 * importing, it will be an array with keys 'text', 'format' and 'files'
949 * @param object $context the context the question is in.
950 * @param string $component indentifies the file area question.
951 * @param string $filearea indentifies the file area questiontext, generalfeedback,answerfeedback.
952 * @param integer $itemid identifies the file area.
953 *
954 * @return string the text for this field, after files have been processed.
955 */
956 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
957 if (!empty($field['itemid'])) {
958 // This is the normal case. We are safing the questions editing form.
959 return file_save_draft_area_files($field['itemid'], $context->id, $component,
960 $filearea, $itemid, $this->fileoptions, trim($field['text']));
961
962 } else if (!empty($field['files'])) {
963 // This is the case when we are doing an import.
964 foreach ($field['files'] as $file) {
965 $this->import_file($context, $component, $filearea, $itemid, $file);
966 }
967 }
968 return trim($field['text']);
969 }
970
971 /**
972 * Move all the files belonging to this question from one context to another.
973 * @param integer $questionid the question being moved.
974 * @param integer $oldcontextid the context it is moving from.
975 * @param integer $newcontextid the context it is moving to.
976 */
977 public function move_files($questionid, $oldcontextid, $newcontextid) {
978 $fs = get_file_storage();
979 $fs->move_area_files_to_new_context($oldcontextid,
980 $newcontextid, 'question', 'questiontext', $questionid);
981 $fs->move_area_files_to_new_context($oldcontextid,
982 $newcontextid, 'question', 'generalfeedback', $questionid);
983 }
984
985 /**
986 * Move all the files belonging to this question's answers when the question
987 * is moved from one context to another.
988 * @param integer $questionid the question being moved.
989 * @param integer $oldcontextid the context it is moving from.
990 * @param integer $newcontextid the context it is moving to.
991 * @param boolean $answerstoo whether there is an 'answer' question area,
992 * as well as an 'answerfeedback' one. Default false.
993 */
994 protected function move_files_in_answers($questionid, $oldcontextid, $newcontextid, $answerstoo = false) {
995 global $DB;
996 $fs = get_file_storage();
997
998 $answerids = $DB->get_records_menu('question_answers',
999 array('question' => $questionid), 'id', 'id,1');
1000 foreach ($answerids as $answerid => $notused) {
1001 if ($answerstoo) {
1002 $fs->move_area_files_to_new_context($oldcontextid,
1003 $newcontextid, 'question', 'answer', $answerid);
1004 }
1005 $fs->move_area_files_to_new_context($oldcontextid,
1006 $newcontextid, 'question', 'answerfeedback', $answerid);
1007 }
1008 }
1009
1010 /**
1011 * Delete all the files belonging to this question.
1012 * @param integer $questionid the question being deleted.
1013 * @param integer $contextid the context the question is in.
1014 */
1015 protected function delete_files($questionid, $contextid) {
1016 $fs = get_file_storage();
1017 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1018 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1019 }
1020
1021 /**
1022 * Delete all the files belonging to this question's answers.
1023 * @param integer $questionid the question being deleted.
1024 * @param integer $contextid the context the question is in.
1025 * @param boolean $answerstoo whether there is an 'answer' question area,
1026 * as well as an 'answerfeedback' one. Default false.
1027 */
1028 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1029 global $DB;
1030 $fs = get_file_storage();
1031
1032 $answerids = $DB->get_records_menu('question_answers',
1033 array('question' => $questionid), 'id', 'id,1');
1034 foreach ($answerids as $answerid => $notused) {
1035 if ($answerstoo) {
1036 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1037 }
1038 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1039 }
1040 }
1041
1042 function import_file($context, $component, $filearea, $itemid, $file) {
1043 $fs = get_file_storage();
1044 $record = new stdclass;
1045 if (is_object($context)) {
1046 $record->contextid = $context->id;
1047 } else {
1048 $record->contextid = $context;
1049 }
1050 $record->component = $component;
1051 $record->filearea = $filearea;
1052 $record->itemid = $itemid;
1053 $record->filename = $file->name;
1054 $record->filepath = '/';
1055 return $fs->create_file_from_string($record, $this->decode_file($file));
1056 }
1057
1058 function decode_file($file) {
1059 switch ($file->encoding) {
1060 case 'base64':
1061 default:
1062 return base64_decode($file->content);
1063 }
1064 }
d1b7e03d 1065}
aeb15530 1066
cde2709a 1067
d1b7e03d
TH
1068/**
1069 * This class is used in the return value from
1070 * {@link question_type::get_possible_responses()}.
1071 *
1072 * @copyright 2010 The Open University
1073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1074 */
1075class question_possible_response {
9203b705 1076 /**
d1b7e03d
TH
1077 * @var string the classification of this response the student gave to this
1078 * part of the question. Must match one of the responseclasses returned by
1079 * {@link question_type::get_possible_responses()}.
9203b705 1080 */
d1b7e03d
TH
1081 public $responseclass;
1082 /** @var string the actual response the student gave to this part. */
1083 public $fraction;
9203b705 1084 /**
d1b7e03d
TH
1085 * Constructor, just an easy way to set the fields.
1086 * @param string $responseclassid see the field descriptions above.
1087 * @param string $response see the field descriptions above.
1088 * @param number $fraction see the field descriptions above.
9203b705 1089 */
d1b7e03d
TH
1090 public function __construct($responseclass, $fraction) {
1091 $this->responseclass = $responseclass;
1092 $this->fraction = $fraction;
cde2709a
DC
1093 }
1094
d1b7e03d
TH
1095 public static function no_response() {
1096 return new question_possible_response(get_string('noresponse', 'question'), 0);
cde2709a 1097 }
fe6ce234 1098}