MDL-67153 question bank: let qtype add actions to the edit menu
[moodle.git] / question / type / questiontypebase.php
CommitLineData
f29aeb5a 1<?php
f29aeb5a
TH
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.
13//
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/>.
16
516cf3eb 17/**
4323d029 18 * The default questiontype class.
19 *
7764183a 20 * @package moodlecore
4323d029 21 * @subpackage questiontypes
7764183a
TH
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
271e6dec 24 */
516cf3eb 25
f29aeb5a 26
a17b297d
TH
27defined('MOODLE_INTERNAL') || die();
28
d1b7e03d 29require_once($CFG->dirroot . '/question/engine/lib.php');
516cf3eb 30
f29aeb5a 31
32b0adfa 32/**
33 * This is the base class for Moodle question types.
271ffe3f 34 *
32b0adfa 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.
271ffe3f 37 *
32b0adfa 38 * Note: the questiontype API should NOT be considered stable yet. Very few
22cebed5 39 * question types have been produced yet, so we do not yet know all the places
271ffe3f 40 * where the current API is insufficient. I would rather learn from the
32b0adfa 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.
271e6dec 44 *
7764183a
TH
45 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32b0adfa 47 */
d1b7e03d 48class question_type {
f29aeb5a 49 protected $fileoptions = array(
f383a58a 50 'subdirs' => true,
f29aeb5a
TH
51 'maxfiles' => -1,
52 'maxbytes' => 0,
53 );
516cf3eb 54
d1b7e03d 55 public function __construct() {
869309b8 56 }
57
4995b9c1 58 /**
d1b7e03d 59 * @return string the name of this question type.
869309b8 60 */
d1b7e03d
TH
61 public function name() {
62 return substr(get_class($this), 6);
a2156789 63 }
271ffe3f 64
f29aeb5a
TH
65 /**
66 * @return string the full frankenstyle name for this plugin.
67 */
68 public function plugin_name() {
69 return get_class($this);
70 }
71
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.
75 */
76 public function local_name() {
0b94d6bf 77 return get_string('pluginname', $this->plugin_name());
f29aeb5a
TH
78 }
79
869309b8 80 /**
81 * The name this question should appear as in the create new question
f29aeb5a
TH
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.
869309b8 85 *
86 * @return mixed the desired string, or false to hide this question type in the menu.
87 */
d1b7e03d 88 public function menu_name() {
f29aeb5a
TH
89 return $this->local_name();
90 }
91
f29aeb5a 92 /**
f7970e3c 93 * @return bool override this to return false if this is not really a
f29aeb5a
TH
94 * question type, for example the description question type is not
95 * really a question type.
96 */
97 public function is_real_question_type() {
98 return true;
b974f947 99 }
100
a2156789 101 /**
f7970e3c 102 * @return bool true if this question type sometimes requires manual grading.
a2156789 103 */
d1b7e03d 104 public function is_manual_graded() {
a2156789 105 return false;
106 }
107
f24493ec 108 /**
109 * @param object $question a question of this type.
110 * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt.
f7970e3c 111 * @return bool true if a particular instance of this question requires manual grading.
f24493ec 112 */
d1b7e03d 113 public function is_question_manual_graded($question, $otherquestionsinuse) {
f24493ec 114 return $this->is_manual_graded();
115 }
116
869309b8 117 /**
f7970e3c 118 * @return bool true if this question type can be used by the random question type.
869309b8 119 */
d1b7e03d
TH
120 public function is_usable_by_random() {
121 return true;
869309b8 122 }
123
a2156789 124 /**
d1b7e03d
TH
125 * Whether this question type can perform a frequency analysis of student
126 * responses.
127 *
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.
131 *
562684e3 132 * @return bool whether this report can analyse all the student responses
d1b7e03d 133 * for things like the quiz statistics report.
a2156789 134 */
d1b7e03d
TH
135 public function can_analyse_responses() {
136 // This works in most cases.
137 return !$this->is_manual_graded();
a2156789 138 }
139
869309b8 140 /**
d1b7e03d
TH
141 * @return whether the question_answers.answer field needs to have
142 * restore_decode_content_links_worker called on it.
869309b8 143 */
d1b7e03d 144 public function has_html_answers() {
869309b8 145 return false;
146 }
d001dac7 147
295043c2 148 /**
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).
153 *
154 * @return mixed array as above, or null to tell the base class to do nothing.
155 */
d1b7e03d 156 public function extra_question_fields() {
295043c2 157 return null;
158 }
159
d001dac7 160 /**
eaeb6b51
TH
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
163 */
56565037 164 public function questionid_column_name() {
d001dac7 165 return 'questionid';
166 }
167
295043c2 168 /**
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).
172 *
173 * @return mixed array as above, or null to tell the base class to do nothing.
174 */
56565037 175 public function extra_answer_fields() {
6b5f24d3
TH
176 return null;
177 }
178
179 /**
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').
183 *
184 * @return array response variable names that may have associated files.
185 */
186 public function response_file_areas() {
187 return array();
188 }
295043c2 189
36703ed7 190 /**
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
f29aeb5a 193 * question/type/{$this->name()}/edit_{$this->name()}_question_form.php
36703ed7 194 * and if it exists returns an instance of it.
195 *
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.
198 */
eaeb6b51
TH
199 public function create_editing_form($submiturl, $question, $category,
200 $contexts, $formeditable) {
36703ed7 201 global $CFG;
1fa39364
TH
202 require_once($CFG->dirroot . '/question/type/edit_question_form.php');
203 $definitionfile = $CFG->dirroot . '/question/type/' . $this->name() .
eaeb6b51 204 '/edit_' . $this->name() . '_form.php';
1fa39364
TH
205 if (!is_readable($definitionfile) || !is_file($definitionfile)) {
206 throw new coding_exception($this->plugin_name() .
afe24f85
TH
207 ' is missing the definition of its editing formin file ' .
208 $definitionfile . '.');
36703ed7 209 }
1fa39364 210 require_once($definitionfile);
6e34cd29 211 $classname = $this->plugin_name() . '_edit_form';
36703ed7 212 if (!class_exists($classname)) {
1fa39364
TH
213 throw new coding_exception($this->plugin_name() .
214 ' does not define the class ' . $this->plugin_name() .
215 '_edit_form.');
36703ed7 216 }
271e6dec 217 return new $classname($submiturl, $question, $category, $contexts, $formeditable);
36703ed7 218 }
219
99ba746d 220 /**
221 * @return string the full path of the folder this plugin's files live in.
222 */
d1b7e03d 223 public function plugin_dir() {
99ba746d 224 global $CFG;
225 return $CFG->dirroot . '/question/type/' . $this->name();
226 }
227
228 /**
229 * @return string the URL of the folder this plugin's files live in.
230 */
d1b7e03d 231 public function plugin_baseurl() {
99ba746d 232 global $CFG;
233 return $CFG->wwwroot . '/question/type/' . $this->name();
234 }
235
c9491626
TH
236 /**
237 * Get extra actions for a question of this type to add to the question bank edit menu.
238 *
239 * This method is called if the {@link edit_menu_column} is being used in the
240 * question bank, which it is by default since Moodle 3.8. If applicable for
241 * your question type, you can return arn array of {@link action_menu_link}s.
242 * These will be added at the end of the Edit menu for this question.
243 *
244 * The $question object passed in will have a hard-to-predict set of fields,
245 * because the fields present depend on which columns are included in the
246 * question bank view. However, you can rely on 'id', 'createdby',
247 * 'contextid', 'hidden' and 'category' (id) being present, and so you
248 * can call question_has_capability_on without causing performance problems.
249 *
250 * @param stdClass $question the available information about the particular question the action is for.
251 * @return action_menu_link[] any actions you want to add to the Edit menu for this question.
252 */
253 public function get_extra_question_bank_actions(stdClass $question): array {
254 return [];
255 }
256
7b41a4a9 257 /**
258 * This method should be overriden if you want to include a special heading or some other
259 * html on a question editing page besides the question editing form.
260 *
261 * @param question_edit_form $mform a child of question_edit_form
262 * @param object $question
263 * @param string $wizardnow is '' for first page.
264 */
f29aeb5a
TH
265 public function display_question_editing_page($mform, $question, $wizardnow) {
266 global $OUTPUT;
267 $heading = $this->get_heading(empty($question->id));
0b94d6bf 268 echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
9ab75b2b 269 $mform->display();
270 }
271e6dec 271
9ab75b2b 272 /**
eaeb6b51
TH
273 * Method called by display_question_editing_page and by question.php to get
274 * heading for breadcrumbs.
271e6dec 275 *
d1b7e03d 276 * @return string the heading
9ab75b2b 277 */
eaeb6b51 278 public function get_heading($adding = false) {
f29aeb5a 279 if ($adding) {
226b3124 280 $string = 'pluginnameadding';
226b3124
TH
281 } else {
282 $string = 'pluginnameediting';
c2f8c4be 283 }
0b94d6bf 284 return get_string($string, $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 /**
eaeb6b51
TH
299 * Saves (creates or updates) a question.
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}
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
314 * new question will be mostly empty.
315 * @param object $form the object containing the information to save, as if
316 * from the question editing form.
317 * @param object $course not really used any more.
318 * @return object On success, return the new question object. On failure,
319 * return an object as follows. If the error object has an errors field,
320 * display that as an error message. Otherwise, the editing form will be
321 * redisplayed with validation errors, from validation_errors field, which
322 * is itself an object, shown next to the form fields. (I don't think this
323 * is accurate any more.)
324 */
c7df5006 325 public function save_question($question, $form) {
f29aeb5a
TH
326 global $USER, $DB, $OUTPUT;
327
328 list($question->category) = explode(',', $form->category);
329 $context = $this->get_context_by_category_id($question->category);
fe6ce234 330
516cf3eb 331 // This default implementation is suitable for most
332 // question types.
271ffe3f 333
3d9645ae 334 // First, save the basic question itself.
24e8b9b6 335 $question->name = trim($form->name);
24e8b9b6 336 $question->parent = isset($form->parent) ? $form->parent : 0;
516cf3eb 337 $question->length = $this->actual_number_of_questions($question);
338 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
339
ca4f7f61
DW
340 // The trim call below has the effect of casting any strange values received,
341 // like null or false, to an appropriate string, so we only need to test for
342 // missing values. Be careful not to break the value '0' here.
343 if (!isset($form->questiontext['text'])) {
f29aeb5a 344 $question->questiontext = '';
516cf3eb 345 } else {
0e35ba6f 346 $question->questiontext = trim($form->questiontext['text']);
516cf3eb 347 }
eaeb6b51
TH
348 $question->questiontextformat = !empty($form->questiontext['format']) ?
349 $form->questiontext['format'] : 0;
516cf3eb 350
f29aeb5a 351 if (empty($form->generalfeedback['text'])) {
a4514d91 352 $question->generalfeedback = '';
1b8a7434 353 } else {
f29aeb5a 354 $question->generalfeedback = trim($form->generalfeedback['text']);
1b8a7434 355 }
eaeb6b51
TH
356 $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
357 $form->generalfeedback['format'] : 0;
1b8a7434 358
1f17e41e 359 if ($question->name === '') {
f29aeb5a 360 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
1f17e41e 361 if ($question->name === '') {
516cf3eb 362 $question->name = '-';
363 }
364 }
365
366 if ($question->penalty > 1 or $question->penalty < 0) {
5e8a85aa 367 $question->errors['penalty'] = get_string('invalidpenalty', 'question');
516cf3eb 368 }
369
d1b7e03d
TH
370 if (isset($form->defaultmark)) {
371 $question->defaultmark = $form->defaultmark;
516cf3eb 372 }
373
6189fda4
JB
374 if (isset($form->idnumber) && ((string) $form->idnumber !== '')) {
375 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
376 if (strpos($form->category, ',') !== false) {
377 list($category, $categorycontextid) = explode(',', $form->category);
378 } else {
379 $category = $form->category;
380 }
381 if (!$DB->record_exists('question',
382 ['idnumber' => $form->idnumber, 'category' => $category])) {
383 $question->idnumber = $form->idnumber;
384 }
385 }
386
f29aeb5a 387 // If the question is new, create it.
93e435b9 388 $newquestion = false;
f29aeb5a 389 if (empty($question->id)) {
3d9645ae 390 // Set the unique code.
cbe20043 391 $question->stamp = make_unique_id_code();
271e6dec 392 $question->createdby = $USER->id;
393 $question->timecreated = time();
f29aeb5a 394 $question->id = $DB->insert_record('question', $question);
93e435b9 395 $newquestion = true;
516cf3eb 396 }
397
f29aeb5a
TH
398 // Now, whether we are updating a existing question, or creating a new
399 // one, we have to do the files processing and update the record.
3d9645ae 400 // Question already exists, update.
f29aeb5a
TH
401 $question->modifiedby = $USER->id;
402 $question->timemodified = time();
403
404 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
eaeb6b51
TH
405 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
406 $context->id, 'question', 'questiontext', (int)$question->id,
407 $this->fileoptions, $question->questiontext);
f29aeb5a
TH
408 }
409 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
eaeb6b51
TH
410 $question->generalfeedback = file_save_draft_area_files(
411 $form->generalfeedback['itemid'], $context->id,
412 'question', 'generalfeedback', (int)$question->id,
413 $this->fileoptions, $question->generalfeedback);
f29aeb5a
TH
414 }
415 $DB->update_record('question', $question);
416
93e435b9
SB
417 if ($newquestion) {
418 // Log the creation of this question.
4ca60a56 419 $event = \core\event\question_created::create_from_question_instance($question, $context);
93e435b9
SB
420 $event->trigger();
421 } else {
422 // Log the update of this question.
4ca60a56 423 $event = \core\event\question_updated::create_from_question_instance($question, $context);
93e435b9
SB
424 $event->trigger();
425 }
426
3d9645ae 427 // Now to save all the answers and type-specific options.
6459b8fc 428 $form->id = $question->id;
429 $form->qtype = $question->qtype;
516cf3eb 430 $form->category = $question->category;
6459b8fc 431 $form->questiontext = $question->questiontext;
f29aeb5a 432 $form->questiontextformat = $question->questiontextformat;
3d9645ae 433 // Current context.
f29aeb5a 434 $form->context = $context;
516cf3eb 435
436 $result = $this->save_question_options($form);
437
438 if (!empty($result->error)) {
f29aeb5a 439 print_error($result->error);
516cf3eb 440 }
441
442 if (!empty($result->notice)) {
f4fe3968 443 notice($result->notice, "question.php?id={$question->id}");
516cf3eb 444 }
445
446 if (!empty($result->noticeyesno)) {
eaeb6b51
TH
447 throw new coding_exception(
448 '$result->noticeyesno no longer supported in save_question.');
516cf3eb 449 }
450
3d9645ae 451 // Give the question a unique version stamp determined by question_hash().
eaeb6b51
TH
452 $DB->set_field('question', 'version', question_hash($question),
453 array('id' => $question->id));
cbe20043 454
516cf3eb 455 return $question;
456 }
271ffe3f 457
516cf3eb 458 /**
d1b7e03d
TH
459 * Saves question-type specific options
460 *
461 * This is called by {@link save_question()} to save the question-type specific data
f0c6c181 462 * @return object $result->error or $result->notice
d1b7e03d
TH
463 * @param object $question This holds the information from the editing form,
464 * it is not a standard question object.
465 */
466 public function save_question_options($question) {
f29aeb5a 467 global $DB;
eaeb6b51 468 $extraquestionfields = $this->extra_question_fields();
295043c2 469
eaeb6b51
TH
470 if (is_array($extraquestionfields)) {
471 $question_extension_table = array_shift($extraquestionfields);
271e6dec 472
295043c2 473 $function = 'update_record';
d001dac7 474 $questionidcolname = $this->questionid_column_name();
eaeb6b51
TH
475 $options = $DB->get_record($question_extension_table,
476 array($questionidcolname => $question->id));
295043c2 477 if (!$options) {
478 $function = 'insert_record';
0ff4bd08 479 $options = new stdClass();
d001dac7 480 $options->$questionidcolname = $question->id;
295043c2 481 }
eaeb6b51 482 foreach ($extraquestionfields as $field) {
a8e577de 483 if (property_exists($question, $field)) {
8d54191d 484 $options->$field = $question->$field;
295043c2 485 }
295043c2 486 }
271e6dec 487
8d54191d 488 $DB->{$function}($question_extension_table, $options);
295043c2 489 }
f0c6c181 490 }
295043c2 491
f0c6c181
OS
492 /**
493 * Save the answers, with any extra data.
494 *
495 * Questions that use answers will call it from {@link save_question_options()}.
496 * @param object $question This holds the information from the editing form,
497 * it is not a standard question object.
498 * @return object $result->error or $result->notice
499 */
500 public function save_question_answers($question) {
501 global $DB;
502
503 $context = $question->context;
504 $oldanswers = $DB->get_records('question_answers',
505 array('question' => $question->id), 'id ASC');
506
507 // We need separate arrays for answers and extra answer data, so no JOINS there.
eaeb6b51 508 $extraanswerfields = $this->extra_answer_fields();
f0c6c181
OS
509 $isextraanswerfields = is_array($extraanswerfields);
510 $extraanswertable = '';
511 $oldanswerextras = array();
512 if ($isextraanswerfields) {
513 $extraanswertable = array_shift($extraanswerfields);
514 if (!empty($oldanswers)) {
515 $oldanswerextras = $DB->get_records_sql("SELECT * FROM {{$extraanswertable}} WHERE " .
516 'answerid IN (SELECT id FROM {question_answers} WHERE question = ' . $question->id . ')' );
517 }
518 }
519
520 // Insert all the new answers.
521 foreach ($question->answer as $key => $answerdata) {
522 // Check for, and ignore, completely blank answer from the form.
523 if ($this->is_answer_empty($question, $key)) {
524 continue;
525 }
526
527 // Update an existing answer if possible.
528 $answer = array_shift($oldanswers);
529 if (!$answer) {
530 $answer = new stdClass();
531 $answer->question = $question->id;
532 $answer->answer = '';
533 $answer->feedback = '';
534 $answer->id = $DB->insert_record('question_answers', $answer);
535 }
536
537 $answer = $this->fill_answer_fields($answer, $question, $key, $context);
538 $DB->update_record('question_answers', $answer);
539
540 if ($isextraanswerfields) {
541 // Check, if this answer contains some extra field data.
542 if ($this->is_extra_answer_fields_empty($question, $key)) {
543 continue;
544 }
545
546 $answerextra = array_shift($oldanswerextras);
547 if (!$answerextra) {
548 $answerextra = new stdClass();
549 $answerextra->answerid = $answer->id;
550 // Avoid looking for correct default for any possible DB field type
551 // by setting real values.
552 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
553 $answerextra->id = $DB->insert_record($extraanswertable, $answerextra);
554 } else {
555 // Update answerid, as record may be reused from another answer.
556 $answerextra->answerid = $answer->id;
557 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields);
558 $DB->update_record($extraanswertable, $answerextra);
559 }
560 }
561 }
562
563 if ($isextraanswerfields) {
564 // Delete any left over extra answer fields records.
565 $oldanswerextraids = array();
566 foreach ($oldanswerextras as $oldextra) {
567 $oldanswerextraids[] = $oldextra->id;
568 }
569 $DB->delete_records_list($extraanswertable, 'id', $oldanswerextraids);
570 }
571
572 // Delete any left over old answer records.
573 $fs = get_file_storage();
574 foreach ($oldanswers as $oldanswer) {
575 $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
576 $DB->delete_records('question_answers', array('id' => $oldanswer->id));
577 }
578 }
579
580 /**
581 * Returns true is answer with the $key is empty in the question data and should not be saved in DB.
582 *
583 * The questions using question_answers table may want to overload this. Default code will work
584 * for shortanswer and similar question types.
585 * @param object $questiondata This holds the information from the question editing form or import.
586 * @param int $key A key of the answer in question.
587 * @return bool True if answer shouldn't be saved in DB.
588 */
589 protected function is_answer_empty($questiondata, $key) {
590 return trim($questiondata->answer[$key]) == '' && $questiondata->fraction[$key] == 0 &&
591 html_is_blank($questiondata->feedback[$key]['text']);
592 }
593
594 /**
595 * Return $answer, filling necessary fields for the question_answers table.
596 *
597 * The questions using question_answers table may want to overload this. Default code will work
598 * for shortanswer and similar question types.
599 * @param stdClass $answer Object to save data.
600 * @param object $questiondata This holds the information from the question editing form or import.
601 * @param int $key A key of the answer in question.
602 * @param object $context needed for working with files.
603 * @return $answer answer with filled data.
604 */
605 protected function fill_answer_fields($answer, $questiondata, $key, $context) {
606 $answer->answer = $questiondata->answer[$key];
607 $answer->fraction = $questiondata->fraction[$key];
608 $answer->feedback = $this->import_or_save_files($questiondata->feedback[$key],
609 $context, 'question', 'answerfeedback', $answer->id);
610 $answer->feedbackformat = $questiondata->feedback[$key]['format'];
611 return $answer;
612 }
613
614 /**
96eead3f 615 * Returns true if extra answer fields for answer with the $key is empty
f0c6c181
OS
616 * in the question data and should not be saved in DB.
617 *
618 * Questions where extra answer fields are optional will want to overload this.
619 * @param object $questiondata This holds the information from the question editing form or import.
620 * @param int $key A key of the answer in question.
621 * @return bool True if extra answer data shouldn't be saved in DB.
622 */
623 protected function is_extra_answer_fields_empty($questiondata, $key) {
624 // No extra answer data in base class.
625 return true;
626 }
627
628 /**
629 * Return $answerextra, filling necessary fields for the extra answer fields table.
630 *
631 * The questions may want to overload it to save files or do other data processing.
632 * @param stdClass $answerextra Object to save data.
633 * @param object $questiondata This holds the information from the question editing form or import.
634 * @param int $key A key of the answer in question.
635 * @param object $context needed for working with files.
636 * @param array $extraanswerfields extra answer fields (without table name).
637 * @return $answer answerextra with filled data.
638 */
639 protected function fill_extra_answer_fields($answerextra, $questiondata, $key, $context, $extraanswerfields) {
640 foreach ($extraanswerfields as $field) {
641 // The $questiondata->$field[$key] won't work in PHP, break it down to two strings of code.
642 $fieldarray = $questiondata->$field;
643 $answerextra->$field = $fieldarray[$key];
644 }
645 return $answerextra;
516cf3eb 646 }
647
d1b7e03d 648 public function save_hints($formdata, $withparts = false) {
f29aeb5a 649 global $DB;
7a719748
TH
650 $context = $formdata->context;
651
e5060e22
JP
652 $oldhints = $DB->get_records('question_hints',
653 array('questionid' => $formdata->id), 'id ASC');
295043c2 654
295043c2 655
0b287dd2 656 $numhints = $this->count_hints_on_form($formdata, $withparts);
d1b7e03d
TH
657
658 for ($i = 0; $i < $numhints; $i += 1) {
7a719748
TH
659 if (html_is_blank($formdata->hint[$i]['text'])) {
660 $formdata->hint[$i]['text'] = '';
d1b7e03d
TH
661 }
662
663 if ($withparts) {
7a719748
TH
664 $clearwrong = !empty($formdata->hintclearwrong[$i]);
665 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
d1b7e03d
TH
666 }
667
0b287dd2 668 if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) {
d1b7e03d
TH
669 continue;
670 }
671
f3ca24e4 672 // Update an existing hint if possible.
7a719748
TH
673 $hint = array_shift($oldhints);
674 if (!$hint) {
675 $hint = new stdClass();
676 $hint->questionid = $formdata->id;
677 $hint->hint = '';
678 $hint->id = $DB->insert_record('question_hints', $hint);
679 }
680
7a719748
TH
681 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
682 $context, 'question', 'hint', $hint->id);
683 $hint->hintformat = $formdata->hint[$i]['format'];
684 if ($withparts) {
685 $hint->clearwrong = $clearwrong;
686 $hint->shownumcorrect = $shownumcorrect;
687 }
0b287dd2 688 $hint->options = $this->save_hint_options($formdata, $i, $withparts);
7a719748
TH
689 $DB->update_record('question_hints', $hint);
690 }
691
692 // Delete any remaining old hints.
693 $fs = get_file_storage();
c73c9836 694 foreach ($oldhints as $oldhint) {
7a719748
TH
695 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
696 $DB->delete_records('question_hints', array('id' => $oldhint->id));
d1b7e03d
TH
697 }
698 }
699
0b287dd2
OS
700 /**
701 * Count number of hints on the form.
702 * Overload if you use custom hint controls.
703 * @param object $formdata the data from the form.
704 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
705 * @return int count of hints on the form.
706 */
707 protected function count_hints_on_form($formdata, $withparts) {
708 if (!empty($formdata->hint)) {
709 $numhints = max(array_keys($formdata->hint)) + 1;
710 } else {
711 $numhints = 0;
712 }
713
714 if ($withparts) {
715 if (!empty($formdata->hintclearwrong)) {
716 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
717 } else {
718 $numclears = 0;
719 }
720 if (!empty($formdata->hintshownumcorrect)) {
721 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
722 } else {
723 $numshows = 0;
724 }
725 $numhints = max($numhints, $numclears, $numshows);
726 }
727 return $numhints;
728 }
729
730 /**
731 * Determine if the hint with specified number is not empty and should be saved.
732 * Overload if you use custom hint controls.
733 * @param object $formdata the data from the form.
734 * @param int $number number of hint under question.
735 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
736 * @return bool is this particular hint data empty.
737 */
738 protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
739 if ($withparts) {
740 return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) &&
741 empty($formdata->hintshownumcorrect[$number]);
742 } else {
743 return empty($formdata->hint[$number]['text']);
744 }
745 }
746
747 /**
748 * Save additional question type data into the hint optional field.
749 * Overload if you use custom hint information.
750 * @param object $formdata the data from the form.
751 * @param int $number number of hint to get options from.
752 * @param bool $withparts whether question have parts.
753 * @return string value to save into the options field of question_hints table.
754 */
755 protected function save_hint_options($formdata, $number, $withparts) {
756 return null; // By default, options field is unused.
757 }
758
1c2ed7c5
TH
759 /**
760 * Can be used to {@link save_question_options()} to transfer the combined
761 * feedback fields from $formdata to $options.
762 * @param object $options the $question->options object being built.
763 * @param object $formdata the data from the form.
764 * @param object $context the context the quetsion is being saved into.
f7970e3c 765 * @param bool $withparts whether $options->shownumcorrect should be set.
1c2ed7c5 766 */
eaeb6b51
TH
767 protected function save_combined_feedback_helper($options, $formdata,
768 $context, $withparts = false) {
1c2ed7c5
TH
769 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
770 $context, 'question', 'correctfeedback', $formdata->id);
771 $options->correctfeedbackformat = $formdata->correctfeedback['format'];
eaeb6b51
TH
772
773 $options->partiallycorrectfeedback = $this->import_or_save_files(
774 $formdata->partiallycorrectfeedback,
1c2ed7c5
TH
775 $context, 'question', 'partiallycorrectfeedback', $formdata->id);
776 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
eaeb6b51 777
1c2ed7c5
TH
778 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
779 $context, 'question', 'incorrectfeedback', $formdata->id);
780 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
781
782 if ($withparts) {
783 $options->shownumcorrect = !empty($formdata->shownumcorrect);
784 }
785
786 return $options;
787 }
788
d1b7e03d
TH
789 /**
790 * Loads the question type specific options for the question.
791 *
792 * This function loads any question type specific options for the
793 * question from the database into the question object. This information
794 * is placed in the $question->options field. A question type is
795 * free, however, to decide on a internal structure of the options field.
796 * @return bool Indicates success or failure.
797 * @param object $question The question object for the question. This object
798 * should be updated to include the question type
799 * specific information (it is passed by reference).
800 */
801 public function get_question_options($question) {
f29aeb5a
TH
802 global $CFG, $DB, $OUTPUT;
803
804 if (!isset($question->options)) {
805 $question->options = new stdClass();
806 }
d1b7e03d 807
eaeb6b51
TH
808 $extraquestionfields = $this->extra_question_fields();
809 if (is_array($extraquestionfields)) {
810 $question_extension_table = array_shift($extraquestionfields);
811 $extra_data = $DB->get_record($question_extension_table,
812 array($this->questionid_column_name() => $question->id),
813 implode(', ', $extraquestionfields));
295043c2 814 if ($extra_data) {
eaeb6b51 815 foreach ($extraquestionfields as $field) {
295043c2 816 $question->options->$field = $extra_data->$field;
817 }
818 } else {
eaeb6b51
TH
819 echo $OUTPUT->notification('Failed to load question options from the table ' .
820 $question_extension_table . ' for questionid ' . $question->id);
295043c2 821 return false;
822 }
823 }
824
eaeb6b51
TH
825 $extraanswerfields = $this->extra_answer_fields();
826 if (is_array($extraanswerfields)) {
62766728
OS
827 $answerextensiontable = array_shift($extraanswerfields);
828 // Use LEFT JOIN in case not every answer has extra data.
f29aeb5a 829 $question->options->answers = $DB->get_records_sql("
62766728
OS
830 SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . '
831 FROM {question_answers} qa ' . "
832 LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid
833 WHERE qa.question = ?
da8cd9f4 834 ORDER BY qa.id", array($question->id));
295043c2 835 if (!$question->options->answers) {
eaeb6b51 836 echo $OUTPUT->notification('Failed to load question answers from the table ' .
62766728 837 $answerextensiontable . 'for questionid ' . $question->id);
295043c2 838 return false;
839 }
840 } else {
eaeb6b51
TH
841 // Don't check for success or failure because some question types do
842 // not use the answers table.
843 $question->options->answers = $DB->get_records('question_answers',
844 array('question' => $question->id), 'id ASC');
295043c2 845 }
846
eaeb6b51
TH
847 $question->hints = $DB->get_records('question_hints',
848 array('questionid' => $question->id), 'id ASC');
d1b7e03d 849
516cf3eb 850 return true;
851 }
852
853 /**
d1b7e03d
TH
854 * Create an appropriate question_definition for the question of this type
855 * using data loaded from the database.
856 * @param object $questiondata the question data loaded from the database.
857 * @return question_definition the corresponding question_definition.
858 */
859 public function make_question($questiondata) {
860 $question = $this->make_question_instance($questiondata);
861 $this->initialise_question_instance($question, $questiondata);
862 return $question;
863 }
0429cd86 864
d1b7e03d
TH
865 /**
866 * Create an appropriate question_definition for the question of this type
867 * using data loaded from the database.
868 * @param object $questiondata the question data loaded from the database.
869 * @return question_definition an instance of the appropriate question_definition subclass.
870 * Still needs to be initialised.
871 */
872 protected function make_question_instance($questiondata) {
873 question_bank::load_question_definition_classes($this->name());
874 $class = 'qtype_' . $this->name() . '_question';
875 return new $class();
876 }
877
878 /**
879 * Initialise the common question_definition fields.
880 * @param question_definition $question the question_definition we are creating.
881 * @param object $questiondata the question data loaded from the database.
882 */
883 protected function initialise_question_instance(question_definition $question, $questiondata) {
884 $question->id = $questiondata->id;
885 $question->category = $questiondata->category;
56e82d99 886 $question->contextid = $questiondata->contextid;
d1b7e03d
TH
887 $question->parent = $questiondata->parent;
888 $question->qtype = $this;
889 $question->name = $questiondata->name;
890 $question->questiontext = $questiondata->questiontext;
891 $question->questiontextformat = $questiondata->questiontextformat;
892 $question->generalfeedback = $questiondata->generalfeedback;
1c2ed7c5 893 $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
d1b7e03d
TH
894 $question->defaultmark = $questiondata->defaultmark + 0;
895 $question->length = $questiondata->length;
896 $question->penalty = $questiondata->penalty;
897 $question->stamp = $questiondata->stamp;
898 $question->version = $questiondata->version;
899 $question->hidden = $questiondata->hidden;
6189fda4 900 $question->idnumber = $questiondata->idnumber;
d1b7e03d
TH
901 $question->timecreated = $questiondata->timecreated;
902 $question->timemodified = $questiondata->timemodified;
903 $question->createdby = $questiondata->createdby;
904 $question->modifiedby = $questiondata->modifiedby;
905
3d9645ae 906 // Fill extra question fields values.
10677751
OS
907 $extraquestionfields = $this->extra_question_fields();
908 if (is_array($extraquestionfields)) {
3d9645ae 909 // Omit table name.
10677751 910 array_shift($extraquestionfields);
3d9645ae 911 foreach ($extraquestionfields as $field) {
10677751
OS
912 $question->$field = $questiondata->options->$field;
913 }
914 }
915
d1b7e03d
TH
916 $this->initialise_question_hints($question, $questiondata);
917 }
918
919 /**
920 * Initialise question_definition::hints field.
921 * @param question_definition $question the question_definition we are creating.
922 * @param object $questiondata the question data loaded from the database.
923 */
924 protected function initialise_question_hints(question_definition $question, $questiondata) {
925 if (empty($questiondata->hints)) {
926 return;
927 }
928 foreach ($questiondata->hints as $hint) {
929 $question->hints[] = $this->make_hint($hint);
930 }
0429cd86 931 }
932
933 /**
d1b7e03d
TH
934 * Create a question_hint, or an appropriate subclass for this question,
935 * from a row loaded from the database.
936 * @param object $hint the DB row from the question hints table.
937 * @return question_hint
9203b705 938 */
d1b7e03d
TH
939 protected function make_hint($hint) {
940 return question_hint::load_from_record($hint);
941 }
942
1c2ed7c5
TH
943 /**
944 * Initialise the combined feedback fields.
945 * @param question_definition $question the question_definition we are creating.
946 * @param object $questiondata the question data loaded from the database.
f7970e3c 947 * @param bool $withparts whether to set the shownumcorrect field.
1c2ed7c5 948 */
eaeb6b51
TH
949 protected function initialise_combined_feedback(question_definition $question,
950 $questiondata, $withparts = false) {
1c2ed7c5
TH
951 $question->correctfeedback = $questiondata->options->correctfeedback;
952 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
953 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
eaeb6b51
TH
954 $question->partiallycorrectfeedbackformat =
955 $questiondata->options->partiallycorrectfeedbackformat;
1c2ed7c5
TH
956 $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
957 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
958 if ($withparts) {
959 $question->shownumcorrect = $questiondata->options->shownumcorrect;
960 }
961 }
962
d1b7e03d
TH
963 /**
964 * Initialise question_definition::answers field.
965 * @param question_definition $question the question_definition we are creating.
966 * @param object $questiondata the question data loaded from the database.
35c9b652
TH
967 * @param bool $forceplaintextanswers most qtypes assume that answers are
968 * FORMAT_PLAIN, and dont use the answerformat DB column (it contains
969 * the default 0 = FORMAT_MOODLE). Therefore, by default this method
970 * ingores answerformat. Pass false here to use answerformat. For example
971 * multichoice does this.
972 */
973 protected function initialise_question_answers(question_definition $question,
974 $questiondata, $forceplaintextanswers = true) {
d1b7e03d
TH
975 $question->answers = array();
976 if (empty($questiondata->options->answers)) {
977 return;
978 }
979 foreach ($questiondata->options->answers as $a) {
92e83e2d 980 $question->answers[$a->id] = $this->make_answer($a);
35c9b652
TH
981 if (!$forceplaintextanswers) {
982 $question->answers[$a->id]->answerformat = $a->answerformat;
983 }
d1b7e03d
TH
984 }
985 }
9203b705 986
92e83e2d
OS
987 /**
988 * Create a question_answer, or an appropriate subclass for this question,
989 * from a row loaded from the database.
990 * @param object $answer the DB row from the question_answers table plus extra answer fields.
991 * @return question_answer
992 */
993 protected function make_answer($answer) {
994 return new question_answer($answer->id, $answer->answer,
995 $answer->fraction, $answer->feedback, $answer->feedbackformat);
996 }
997
d1b7e03d 998 /**
f29aeb5a 999 * Deletes the question-type specific data when a question is deleted.
f7970e3c
TH
1000 * @param int $question the question being deleted.
1001 * @param int $contextid the context this quesiotn belongs to.
f29aeb5a
TH
1002 */
1003 public function delete_question($questionid, $contextid) {
1004 global $DB;
1005
1006 $this->delete_files($questionid, $contextid);
516cf3eb 1007
eaeb6b51
TH
1008 $extraquestionfields = $this->extra_question_fields();
1009 if (is_array($extraquestionfields)) {
1010 $question_extension_table = array_shift($extraquestionfields);
f29aeb5a
TH
1011 $DB->delete_records($question_extension_table,
1012 array($this->questionid_column_name() => $questionid));
295043c2 1013 }
1014
eaeb6b51
TH
1015 $extraanswerfields = $this->extra_answer_fields();
1016 if (is_array($extraanswerfields)) {
1017 $answer_extension_table = array_shift($extraanswerfields);
f29aeb5a 1018 $DB->delete_records_select($answer_extension_table,
eaeb6b51
TH
1019 'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
1020 array($questionid));
295043c2 1021 }
1022
f29aeb5a 1023 $DB->delete_records('question_answers', array('question' => $questionid));
d1b7e03d 1024
f29aeb5a 1025 $DB->delete_records('question_hints', array('questionid' => $questionid));
516cf3eb 1026 }
1027
1028 /**
eaeb6b51
TH
1029 * Returns the number of question numbers which are used by the question
1030 *
1031 * This function returns the number of question numbers to be assigned
1032 * to the question. Most question types will have length one; they will be
1033 * assigned one number. The 'description' type, however does not use up a
1034 * number and so has a length of zero. Other question types may wish to
1035 * handle a bundle of questions and hence return a number greater than one.
1036 * @return int The number of question numbers which should be
1037 * assigned to the question.
1038 * @param object $question The question whose length is to be determined.
1039 * Question type specific information is included.
1040 */
d1b7e03d 1041 public function actual_number_of_questions($question) {
3d9645ae 1042 // By default, each question is given one number.
516cf3eb 1043 return 1;
1044 }
1045
6f51ed72 1046 /**
1047 * @param object $question
d1b7e03d
TH
1048 * @return number|null either a fraction estimating what the student would
1049 * score by guessing, or null, if it is not possible to estimate.
6f51ed72 1050 */
c7df5006 1051 public function get_random_guess_score($questiondata) {
6f51ed72 1052 return 0;
1053 }
516cf3eb 1054
3d6f2466
JP
1055 /**
1056 * Whether or not to break down question stats and response analysis, for a question defined by $questiondata.
1057 *
1058 * @param object $questiondata The full question definition data.
1059 * @return bool
1060 */
1061 public function break_down_stats_and_response_analysis_by_variant($questiondata) {
1062 return true;
1063 }
1064
516cf3eb 1065 /**
d1b7e03d 1066 * This method should return all the possible types of response that are
f9b0500f 1067 * recognised for this question.
271e6dec 1068 *
d1b7e03d
TH
1069 * The question is modelled as comprising one or more subparts. For each
1070 * subpart, there are one or more classes that that students response
1071 * might fall into, each of those classes earning a certain score.
50da63eb 1072 *
d1b7e03d
TH
1073 * For example, in a shortanswer question, there is only one subpart, the
1074 * text entry field. The response the student gave will be classified according
1075 * to which of the possible $question->options->answers it matches.
271e6dec 1076 *
d1b7e03d
TH
1077 * For the matching question type, there will be one subpart for each
1078 * question stem, and for each stem, each of the possible choices is a class
1079 * of student's response.
1080 *
1081 * A response is an object with two fields, ->responseclass is a string
1082 * presentation of that response, and ->fraction, the credit for a response
1083 * in that class.
1084 *
1085 * Array keys have no specific meaning, but must be unique, and must be
1086 * the same if this function is called repeatedly.
1087 *
1088 * @param object $question the question definition data.
1089 * @return array keys are subquestionid, values are arrays of possible
1090 * responses to that subquestion.
99ba746d 1091 */
c7df5006 1092 public function get_possible_responses($questiondata) {
d1b7e03d 1093 return array();
50da63eb 1094 }
5fceb049 1095
50da63eb 1096 /**
46e40567
TH
1097 * Utility method used by {@link qtype_renderer::head_code()}. It looks
1098 * for any of the files script.js or script.php that exist in the plugin
1099 * folder and ensures they get included.
50da63eb 1100 */
c76145d3 1101 public function find_standard_scripts() {
f29aeb5a
TH
1102 global $PAGE;
1103
99ba746d 1104 $plugindir = $this->plugin_dir();
f29aeb5a 1105 $plugindirrel = 'question/type/' . $this->name();
50da63eb 1106
1107 if (file_exists($plugindir . '/script.js')) {
f29aeb5a 1108 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
50da63eb 1109 }
1110 if (file_exists($plugindir . '/script.php')) {
f29aeb5a 1111 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
516cf3eb 1112 }
fe9b5cfd 1113 }
1114
62e76c67 1115 /**
eaeb6b51
TH
1116 * Returns true if the editing wizard is finished, false otherwise.
1117 *
1118 * The default implementation returns true, which is suitable for all question-
1119 * types that only use one editing form. This function is used in
1120 * question.php to decide whether we can regrade any states of the edited
1121 * question and redirect to edit.php.
1122 *
1123 * The dataset dependent question-type, which is extended by the calculated
1124 * question-type, overwrites this method because it uses multiple pages (i.e.
1125 * a wizard) to set up the question and associated datasets.
1126 *
1127 * @param object $form The data submitted by the previous page.
1128 *
1129 * @return bool Whether the wizard's last page was submitted or not.
1130 */
f29aeb5a 1131 public function finished_edit_wizard($form) {
3d9645ae 1132 // In the default case there is only one edit page.
d1b7e03d 1133 return true;
62e76c67 1134 }
1135
3d9645ae 1136 // IMPORT/EXPORT FUNCTIONS --------------------------------- .
88bc20c3 1137
1138 /*
1139 * Imports question from the Moodle XML format
1140 *
1141 * Imports question using information from extra_question_fields function
1142 * If some of you fields contains id's you'll need to reimplement this
1143 */
a031b0f3 1144 public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
88bc20c3 1145 $question_type = $data['@']['type'];
1146 if ($question_type != $this->name()) {
1147 return false;
1148 }
1149
1150 $extraquestionfields = $this->extra_question_fields();
1151 if (!is_array($extraquestionfields)) {
1152 return false;
1153 }
1154
3d9645ae 1155 // Omit table name.
88bc20c3 1156 array_shift($extraquestionfields);
1157 $qo = $format->import_headers($data);
1158 $qo->qtype = $question_type;
1159
1160 foreach ($extraquestionfields as $field) {
05cef658 1161 $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
88bc20c3 1162 }
1163
3d9645ae 1164 // Run through the answers.
88bc20c3 1165 $answers = $data['#']['answer'];
1166 $a_count = 0;
05cef658
JP
1167 $extraanswersfields = $this->extra_answer_fields();
1168 if (is_array($extraanswersfields)) {
1169 array_shift($extraanswersfields);
1170 }
1171 foreach ($answers as $answer) {
1172 $ans = $format->import_answer($answer);
1173 if (!$this->has_html_answers()) {
1174 $qo->answer[$a_count] = $ans->answer['text'];
1175 } else {
88bc20c3 1176 $qo->answer[$a_count] = $ans->answer;
88bc20c3 1177 }
05cef658
JP
1178 $qo->fraction[$a_count] = $ans->fraction;
1179 $qo->feedback[$a_count] = $ans->feedback;
1180 if (is_array($extraanswersfields)) {
1181 foreach ($extraanswersfields as $field) {
1182 $qo->{$field}[$a_count] =
1183 $format->getpath($answer, array('#', $field, 0, '#'), '');
1184 }
1185 }
1186 ++$a_count;
88bc20c3 1187 }
1188 return $qo;
1189 }
1190
1191 /*
1192 * Export question to the Moodle XML format
1193 *
1194 * Export question using information from extra_question_fields function
1195 * If some of you fields contains id's you'll need to reimplement this
1196 */
a031b0f3 1197 public function export_to_xml($question, qformat_xml $format, $extra=null) {
88bc20c3 1198 $extraquestionfields = $this->extra_question_fields();
1199 if (!is_array($extraquestionfields)) {
1200 return false;
1201 }
1202
3d9645ae 1203 // Omit table name.
88bc20c3 1204 array_shift($extraquestionfields);
1205 $expout='';
1206 foreach ($extraquestionfields as $field) {
1b343d52 1207 $exportedvalue = $format->xml_escape($question->options->$field);
f4fe3968 1208 $expout .= " <{$field}>{$exportedvalue}</{$field}>\n";
88bc20c3 1209 }
1210
05cef658
JP
1211 $extraanswersfields = $this->extra_answer_fields();
1212 if (is_array($extraanswersfields)) {
1213 array_shift($extraanswersfields);
1214 }
1215 foreach ($question->options->answers as $answer) {
04fcd1f5 1216 $extra = '';
05cef658
JP
1217 if (is_array($extraanswersfields)) {
1218 foreach ($extraanswersfields as $field) {
1b343d52 1219 $exportedvalue = $format->xml_escape($answer->$field);
04fcd1f5 1220 $extra .= " <{$field}>{$exportedvalue}</{$field}>\n";
05cef658 1221 }
88bc20c3 1222 }
05cef658 1223
04fcd1f5 1224 $expout .= $format->write_answer($answer, $extra);
88bc20c3 1225 }
1226 return $expout;
1227 }
1228
b9bd6da4 1229 /**
1230 * Abstract function implemented by each question type. It runs all the code
1231 * required to set up and save a question of any type for testing purposes.
1232 * Alternate DB table prefix may be used to facilitate data deletion.
1233 */
d1b7e03d 1234 public function generate_test($name, $courseid=null) {
b9bd6da4 1235 $form = new stdClass();
1236 $form->name = $name;
1237 $form->questiontextformat = 1;
1238 $form->questiontext = 'test question, generated by script';
d1b7e03d
TH
1239 $form->defaultmark = 1;
1240 $form->penalty = 0.3333333;
b9bd6da4 1241 $form->generalfeedback = "Well done";
1242
21c08c63 1243 $context = context_course::instance($courseid);
b9bd6da4 1244 $newcategory = question_make_default_categories(array($context));
1245 $form->category = $newcategory->id . ',1';
1246
1247 $question = new stdClass();
1248 $question->courseid = $courseid;
1249 $question->qtype = $this->qtype;
1250 return array($form, $question);
1251 }
f29aeb5a
TH
1252
1253 /**
1254 * Get question context by category id
1255 * @param int $category
1256 * @return object $context
1257 */
c7df5006 1258 protected function get_context_by_category_id($category) {
f29aeb5a
TH
1259 global $DB;
1260 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
5fbe2118 1261 $context = context::instance_by_id($contextid, IGNORE_MISSING);
f29aeb5a
TH
1262 return $context;
1263 }
1264
1265 /**
1266 * Save the file belonging to one text field.
1267 *
1268 * @param array $field the data from the form (or from import). This will
1269 * normally have come from the formslib editor element, so it will be an
1270 * array with keys 'text', 'format' and 'itemid'. However, when we are
1271 * importing, it will be an array with keys 'text', 'format' and 'files'
1272 * @param object $context the context the question is in.
1273 * @param string $component indentifies the file area question.
eaeb6b51
TH
1274 * @param string $filearea indentifies the file area questiontext,
1275 * generalfeedback, answerfeedback, etc.
f7970e3c 1276 * @param int $itemid identifies the file area.
f29aeb5a
TH
1277 *
1278 * @return string the text for this field, after files have been processed.
1279 */
1280 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1281 if (!empty($field['itemid'])) {
1282 // This is the normal case. We are safing the questions editing form.
1283 return file_save_draft_area_files($field['itemid'], $context->id, $component,
1284 $filearea, $itemid, $this->fileoptions, trim($field['text']));
1285
1286 } else if (!empty($field['files'])) {
1287 // This is the case when we are doing an import.
1288 foreach ($field['files'] as $file) {
1289 $this->import_file($context, $component, $filearea, $itemid, $file);
1290 }
1291 }
1292 return trim($field['text']);
1293 }
1294
1295 /**
1296 * Move all the files belonging to this question from one context to another.
f7970e3c
TH
1297 * @param int $questionid the question being moved.
1298 * @param int $oldcontextid the context it is moving from.
1299 * @param int $newcontextid the context it is moving to.
f29aeb5a
TH
1300 */
1301 public function move_files($questionid, $oldcontextid, $newcontextid) {
1302 $fs = get_file_storage();
1303 $fs->move_area_files_to_new_context($oldcontextid,
1304 $newcontextid, 'question', 'questiontext', $questionid);
1305 $fs->move_area_files_to_new_context($oldcontextid,
1306 $newcontextid, 'question', 'generalfeedback', $questionid);
1307 }
1308
1309 /**
1310 * Move all the files belonging to this question's answers when the question
1311 * is moved from one context to another.
f7970e3c
TH
1312 * @param int $questionid the question being moved.
1313 * @param int $oldcontextid the context it is moving from.
1314 * @param int $newcontextid the context it is moving to.
1315 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1316 * as well as an 'answerfeedback' one. Default false.
1317 */
eaeb6b51
TH
1318 protected function move_files_in_answers($questionid, $oldcontextid,
1319 $newcontextid, $answerstoo = false) {
f29aeb5a
TH
1320 global $DB;
1321 $fs = get_file_storage();
1322
1323 $answerids = $DB->get_records_menu('question_answers',
1324 array('question' => $questionid), 'id', 'id,1');
1325 foreach ($answerids as $answerid => $notused) {
1326 if ($answerstoo) {
1327 $fs->move_area_files_to_new_context($oldcontextid,
1328 $newcontextid, 'question', 'answer', $answerid);
1329 }
1330 $fs->move_area_files_to_new_context($oldcontextid,
1331 $newcontextid, 'question', 'answerfeedback', $answerid);
1332 }
1333 }
1334
d44480f6
TH
1335 /**
1336 * Move all the files belonging to this question's hints when the question
1337 * is moved from one context to another.
1338 * @param int $questionid the question being moved.
1339 * @param int $oldcontextid the context it is moving from.
1340 * @param int $newcontextid the context it is moving to.
1341 * @param bool $answerstoo whether there is an 'answer' question area,
1342 * as well as an 'answerfeedback' one. Default false.
1343 */
1344 protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1345 global $DB;
1346 $fs = get_file_storage();
1347
1348 $hintids = $DB->get_records_menu('question_hints',
1349 array('questionid' => $questionid), 'id', 'id,1');
1350 foreach ($hintids as $hintid => $notused) {
1351 $fs->move_area_files_to_new_context($oldcontextid,
1352 $newcontextid, 'question', 'hint', $hintid);
1353 }
1354 }
1355
a23bda41
TH
1356 /**
1357 * Move all the files belonging to this question's answers when the question
1358 * is moved from one context to another.
1359 * @param int $questionid the question being moved.
1360 * @param int $oldcontextid the context it is moving from.
1361 * @param int $newcontextid the context it is moving to.
1362 * @param bool $answerstoo whether there is an 'answer' question area,
1363 * as well as an 'answerfeedback' one. Default false.
1364 */
1365 protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1366 $newcontextid) {
1367 global $DB;
1368 $fs = get_file_storage();
1369
1370 $fs->move_area_files_to_new_context($oldcontextid,
1371 $newcontextid, 'question', 'correctfeedback', $questionid);
1372 $fs->move_area_files_to_new_context($oldcontextid,
1373 $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1374 $fs->move_area_files_to_new_context($oldcontextid,
1375 $newcontextid, 'question', 'incorrectfeedback', $questionid);
1376 }
1377
f29aeb5a
TH
1378 /**
1379 * Delete all the files belonging to this question.
f7970e3c
TH
1380 * @param int $questionid the question being deleted.
1381 * @param int $contextid the context the question is in.
f29aeb5a
TH
1382 */
1383 protected function delete_files($questionid, $contextid) {
1384 $fs = get_file_storage();
1385 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1386 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1387 }
1388
1389 /**
1390 * Delete all the files belonging to this question's answers.
f7970e3c
TH
1391 * @param int $questionid the question being deleted.
1392 * @param int $contextid the context the question is in.
1393 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1394 * as well as an 'answerfeedback' one. Default false.
1395 */
1396 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1397 global $DB;
1398 $fs = get_file_storage();
1399
1400 $answerids = $DB->get_records_menu('question_answers',
1401 array('question' => $questionid), 'id', 'id,1');
1402 foreach ($answerids as $answerid => $notused) {
1403 if ($answerstoo) {
1404 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1405 }
1406 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1407 }
1408 }
1409
d44480f6
TH
1410 /**
1411 * Delete all the files belonging to this question's hints.
1412 * @param int $questionid the question being deleted.
1413 * @param int $contextid the context the question is in.
1414 */
1415 protected function delete_files_in_hints($questionid, $contextid) {
1416 global $DB;
1417 $fs = get_file_storage();
1418
1419 $hintids = $DB->get_records_menu('question_hints',
1420 array('questionid' => $questionid), 'id', 'id,1');
1421 foreach ($hintids as $hintid => $notused) {
1422 $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1423 }
1424 }
1425
a23bda41
TH
1426 /**
1427 * Delete all the files belonging to this question's answers.
1428 * @param int $questionid the question being deleted.
1429 * @param int $contextid the context the question is in.
1430 * @param bool $answerstoo whether there is an 'answer' question area,
1431 * as well as an 'answerfeedback' one. Default false.
1432 */
1433 protected function delete_files_in_combined_feedback($questionid, $contextid) {
1434 global $DB;
1435 $fs = get_file_storage();
1436
1437 $fs->delete_area_files($contextid,
1438 'question', 'correctfeedback', $questionid);
1439 $fs->delete_area_files($contextid,
1440 'question', 'partiallycorrectfeedback', $questionid);
1441 $fs->delete_area_files($contextid,
1442 'question', 'incorrectfeedback', $questionid);
1443 }
1444
f902a54e 1445 public function import_file($context, $component, $filearea, $itemid, $file) {
f29aeb5a 1446 $fs = get_file_storage();
0ff4bd08 1447 $record = new stdClass();
f29aeb5a
TH
1448 if (is_object($context)) {
1449 $record->contextid = $context->id;
1450 } else {
1451 $record->contextid = $context;
1452 }
1453 $record->component = $component;
1454 $record->filearea = $filearea;
1455 $record->itemid = $itemid;
1456 $record->filename = $file->name;
1457 $record->filepath = '/';
1458 return $fs->create_file_from_string($record, $this->decode_file($file));
1459 }
1460
c7df5006 1461 protected function decode_file($file) {
f29aeb5a 1462 switch ($file->encoding) {
eaeb6b51
TH
1463 case 'base64':
1464 default:
1465 return base64_decode($file->content);
f29aeb5a
TH
1466 }
1467 }
d1b7e03d 1468}
aeb15530 1469
cde2709a 1470
d1b7e03d
TH
1471/**
1472 * This class is used in the return value from
1473 * {@link question_type::get_possible_responses()}.
1474 *
7764183a
TH
1475 * @copyright 2010 The Open University
1476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1477 */
1478class question_possible_response {
9203b705 1479 /**
d1b7e03d
TH
1480 * @var string the classification of this response the student gave to this
1481 * part of the question. Must match one of the responseclasses returned by
1482 * {@link question_type::get_possible_responses()}.
9203b705 1483 */
d1b7e03d 1484 public $responseclass;
ba6425ab
TH
1485
1486 /** @var string the (partial) credit awarded for this responses. */
d1b7e03d 1487 public $fraction;
ba6425ab 1488
9203b705 1489 /**
d1b7e03d
TH
1490 * Constructor, just an easy way to set the fields.
1491 * @param string $responseclassid see the field descriptions above.
1492 * @param string $response see the field descriptions above.
1493 * @param number $fraction see the field descriptions above.
9203b705 1494 */
d1b7e03d
TH
1495 public function __construct($responseclass, $fraction) {
1496 $this->responseclass = $responseclass;
1497 $this->fraction = $fraction;
cde2709a
DC
1498 }
1499
d1b7e03d
TH
1500 public static function no_response() {
1501 return new question_possible_response(get_string('noresponse', 'question'), 0);
cde2709a 1502 }
fe6ce234 1503}