MDL-43479 quiz response analysis : suppress break down by variants
[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
7b41a4a9 236 /**
237 * This method should be overriden if you want to include a special heading or some other
238 * html on a question editing page besides the question editing form.
239 *
240 * @param question_edit_form $mform a child of question_edit_form
241 * @param object $question
242 * @param string $wizardnow is '' for first page.
243 */
f29aeb5a
TH
244 public function display_question_editing_page($mform, $question, $wizardnow) {
245 global $OUTPUT;
246 $heading = $this->get_heading(empty($question->id));
247
0b94d6bf 248 echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name());
f29aeb5a 249
271e6dec 250 $permissionstrs = array();
eaeb6b51
TH
251 if (!empty($question->id)) {
252 if ($question->formoptions->canedit) {
271e6dec 253 $permissionstrs[] = get_string('permissionedit', 'question');
254 }
eaeb6b51 255 if ($question->formoptions->canmove) {
271e6dec 256 $permissionstrs[] = get_string('permissionmove', 'question');
257 }
eaeb6b51 258 if ($question->formoptions->cansaveasnew) {
271e6dec 259 $permissionstrs[] = get_string('permissionsaveasnew', 'question');
260 }
261 }
435d3279 262 if (count($permissionstrs)) {
f29aeb5a 263 echo $OUTPUT->heading(get_string('permissionto', 'question'), 3);
271e6dec 264 $html = '<ul>';
eaeb6b51 265 foreach ($permissionstrs as $permissionstr) {
271e6dec 266 $html .= '<li>'.$permissionstr.'</li>';
267 }
268 $html .= '</ul>';
f29aeb5a 269 echo $OUTPUT->box($html, 'boxwidthnarrow boxaligncenter generalbox');
271e6dec 270 }
9ab75b2b 271 $mform->display();
272 }
271e6dec 273
9ab75b2b 274 /**
eaeb6b51
TH
275 * Method called by display_question_editing_page and by question.php to get
276 * heading for breadcrumbs.
271e6dec 277 *
d1b7e03d 278 * @return string the heading
9ab75b2b 279 */
eaeb6b51 280 public function get_heading($adding = false) {
f29aeb5a 281 if ($adding) {
226b3124 282 $string = 'pluginnameadding';
226b3124
TH
283 } else {
284 $string = 'pluginnameediting';
c2f8c4be 285 }
0b94d6bf 286 return get_string($string, $this->plugin_name());
d1b7e03d
TH
287 }
288
289 /**
290 * Set any missing settings for this question to the default values. This is
291 * called before displaying the question editing form.
292 *
293 * @param object $questiondata the question data, loaded from the databsae,
294 * or more likely a newly created question object that is only partially
295 * initialised.
296 */
297 public function set_default_options($questiondata) {
7b41a4a9 298 }
299
516cf3eb 300 /**
eaeb6b51
TH
301 * Saves (creates or updates) a question.
302 *
303 * Given some question info and some data about the answers
304 * this function parses, organises and saves the question
305 * It is used by {@link question.php} when saving new data from
306 * a form, and also by {@link import.php} when importing questions
307 * This function in turn calls {@link save_question_options}
308 * to save question-type specific data.
309 *
310 * Whether we are saving a new question or updating an existing one can be
311 * determined by testing !empty($question->id). If it is not empty, we are updating.
312 *
313 * The question will be saved in category $form->category.
314 *
315 * @param object $question the question object which should be updated. For a
316 * new question will be mostly empty.
317 * @param object $form the object containing the information to save, as if
318 * from the question editing form.
319 * @param object $course not really used any more.
320 * @return object On success, return the new question object. On failure,
321 * return an object as follows. If the error object has an errors field,
322 * display that as an error message. Otherwise, the editing form will be
323 * redisplayed with validation errors, from validation_errors field, which
324 * is itself an object, shown next to the form fields. (I don't think this
325 * is accurate any more.)
326 */
c7df5006 327 public function save_question($question, $form) {
f29aeb5a
TH
328 global $USER, $DB, $OUTPUT;
329
330 list($question->category) = explode(',', $form->category);
331 $context = $this->get_context_by_category_id($question->category);
fe6ce234 332
516cf3eb 333 // This default implementation is suitable for most
334 // question types.
271ffe3f 335
3d9645ae 336 // First, save the basic question itself.
24e8b9b6 337 $question->name = trim($form->name);
24e8b9b6 338 $question->parent = isset($form->parent) ? $form->parent : 0;
516cf3eb 339 $question->length = $this->actual_number_of_questions($question);
340 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
341
f29aeb5a
TH
342 if (empty($form->questiontext['text'])) {
343 $question->questiontext = '';
516cf3eb 344 } else {
0e35ba6f 345 $question->questiontext = trim($form->questiontext['text']);
516cf3eb 346 }
eaeb6b51
TH
347 $question->questiontextformat = !empty($form->questiontext['format']) ?
348 $form->questiontext['format'] : 0;
516cf3eb 349
f29aeb5a 350 if (empty($form->generalfeedback['text'])) {
a4514d91 351 $question->generalfeedback = '';
1b8a7434 352 } else {
f29aeb5a 353 $question->generalfeedback = trim($form->generalfeedback['text']);
1b8a7434 354 }
eaeb6b51
TH
355 $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ?
356 $form->generalfeedback['format'] : 0;
1b8a7434 357
516cf3eb 358 if (empty($question->name)) {
f29aeb5a 359 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15);
516cf3eb 360 if (empty($question->name)) {
361 $question->name = '-';
362 }
363 }
364
365 if ($question->penalty > 1 or $question->penalty < 0) {
5e8a85aa 366 $question->errors['penalty'] = get_string('invalidpenalty', 'question');
516cf3eb 367 }
368
d1b7e03d
TH
369 if (isset($form->defaultmark)) {
370 $question->defaultmark = $form->defaultmark;
516cf3eb 371 }
372
f29aeb5a
TH
373 // If the question is new, create it.
374 if (empty($question->id)) {
3d9645ae 375 // Set the unique code.
cbe20043 376 $question->stamp = make_unique_id_code();
271e6dec 377 $question->createdby = $USER->id;
378 $question->timecreated = time();
f29aeb5a 379 $question->id = $DB->insert_record('question', $question);
516cf3eb 380 }
381
f29aeb5a
TH
382 // Now, whether we are updating a existing question, or creating a new
383 // one, we have to do the files processing and update the record.
3d9645ae 384 // Question already exists, update.
f29aeb5a
TH
385 $question->modifiedby = $USER->id;
386 $question->timemodified = time();
387
388 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
eaeb6b51
TH
389 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'],
390 $context->id, 'question', 'questiontext', (int)$question->id,
391 $this->fileoptions, $question->questiontext);
f29aeb5a
TH
392 }
393 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
eaeb6b51
TH
394 $question->generalfeedback = file_save_draft_area_files(
395 $form->generalfeedback['itemid'], $context->id,
396 'question', 'generalfeedback', (int)$question->id,
397 $this->fileoptions, $question->generalfeedback);
f29aeb5a
TH
398 }
399 $DB->update_record('question', $question);
400
3d9645ae 401 // Now to save all the answers and type-specific options.
6459b8fc 402 $form->id = $question->id;
403 $form->qtype = $question->qtype;
516cf3eb 404 $form->category = $question->category;
6459b8fc 405 $form->questiontext = $question->questiontext;
f29aeb5a 406 $form->questiontextformat = $question->questiontextformat;
3d9645ae 407 // Current context.
f29aeb5a 408 $form->context = $context;
516cf3eb 409
410 $result = $this->save_question_options($form);
411
412 if (!empty($result->error)) {
f29aeb5a 413 print_error($result->error);
516cf3eb 414 }
415
416 if (!empty($result->notice)) {
417 notice($result->notice, "question.php?id=$question->id");
418 }
419
420 if (!empty($result->noticeyesno)) {
eaeb6b51
TH
421 throw new coding_exception(
422 '$result->noticeyesno no longer supported in save_question.');
516cf3eb 423 }
424
3d9645ae 425 // Give the question a unique version stamp determined by question_hash().
eaeb6b51
TH
426 $DB->set_field('question', 'version', question_hash($question),
427 array('id' => $question->id));
cbe20043 428
516cf3eb 429 return $question;
430 }
271ffe3f 431
516cf3eb 432 /**
d1b7e03d
TH
433 * Saves question-type specific options
434 *
435 * This is called by {@link save_question()} to save the question-type specific data
436 * @return object $result->error or $result->noticeyesno or $result->notice
437 * @param object $question This holds the information from the editing form,
438 * it is not a standard question object.
439 */
440 public function save_question_options($question) {
f29aeb5a 441 global $DB;
eaeb6b51 442 $extraquestionfields = $this->extra_question_fields();
295043c2 443
eaeb6b51
TH
444 if (is_array($extraquestionfields)) {
445 $question_extension_table = array_shift($extraquestionfields);
271e6dec 446
295043c2 447 $function = 'update_record';
d001dac7 448 $questionidcolname = $this->questionid_column_name();
eaeb6b51
TH
449 $options = $DB->get_record($question_extension_table,
450 array($questionidcolname => $question->id));
295043c2 451 if (!$options) {
452 $function = 'insert_record';
0ff4bd08 453 $options = new stdClass();
d001dac7 454 $options->$questionidcolname = $question->id;
295043c2 455 }
eaeb6b51 456 foreach ($extraquestionfields as $field) {
a8e577de 457 if (property_exists($question, $field)) {
8d54191d 458 $options->$field = $question->$field;
295043c2 459 }
295043c2 460 }
271e6dec 461
8d54191d 462 $DB->{$function}($question_extension_table, $options);
295043c2 463 }
464
eaeb6b51 465 $extraanswerfields = $this->extra_answer_fields();
295043c2 466 // TODO save the answers, with any extra data.
516cf3eb 467 }
468
d1b7e03d 469 public function save_hints($formdata, $withparts = false) {
f29aeb5a 470 global $DB;
7a719748
TH
471 $context = $formdata->context;
472
e5060e22
JP
473 $oldhints = $DB->get_records('question_hints',
474 array('questionid' => $formdata->id), 'id ASC');
295043c2 475
295043c2 476
0b287dd2 477 $numhints = $this->count_hints_on_form($formdata, $withparts);
d1b7e03d
TH
478
479 for ($i = 0; $i < $numhints; $i += 1) {
7a719748
TH
480 if (html_is_blank($formdata->hint[$i]['text'])) {
481 $formdata->hint[$i]['text'] = '';
d1b7e03d
TH
482 }
483
484 if ($withparts) {
7a719748
TH
485 $clearwrong = !empty($formdata->hintclearwrong[$i]);
486 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]);
d1b7e03d
TH
487 }
488
0b287dd2 489 if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) {
d1b7e03d
TH
490 continue;
491 }
492
f3ca24e4 493 // Update an existing hint if possible.
7a719748
TH
494 $hint = array_shift($oldhints);
495 if (!$hint) {
496 $hint = new stdClass();
497 $hint->questionid = $formdata->id;
498 $hint->hint = '';
499 $hint->id = $DB->insert_record('question_hints', $hint);
500 }
501
7a719748
TH
502 $hint->hint = $this->import_or_save_files($formdata->hint[$i],
503 $context, 'question', 'hint', $hint->id);
504 $hint->hintformat = $formdata->hint[$i]['format'];
505 if ($withparts) {
506 $hint->clearwrong = $clearwrong;
507 $hint->shownumcorrect = $shownumcorrect;
508 }
0b287dd2 509 $hint->options = $this->save_hint_options($formdata, $i, $withparts);
7a719748
TH
510 $DB->update_record('question_hints', $hint);
511 }
512
513 // Delete any remaining old hints.
514 $fs = get_file_storage();
c73c9836 515 foreach ($oldhints as $oldhint) {
7a719748
TH
516 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id);
517 $DB->delete_records('question_hints', array('id' => $oldhint->id));
d1b7e03d
TH
518 }
519 }
520
0b287dd2
OS
521 /**
522 * Count number of hints on the form.
523 * Overload if you use custom hint controls.
524 * @param object $formdata the data from the form.
525 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
526 * @return int count of hints on the form.
527 */
528 protected function count_hints_on_form($formdata, $withparts) {
529 if (!empty($formdata->hint)) {
530 $numhints = max(array_keys($formdata->hint)) + 1;
531 } else {
532 $numhints = 0;
533 }
534
535 if ($withparts) {
536 if (!empty($formdata->hintclearwrong)) {
537 $numclears = max(array_keys($formdata->hintclearwrong)) + 1;
538 } else {
539 $numclears = 0;
540 }
541 if (!empty($formdata->hintshownumcorrect)) {
542 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1;
543 } else {
544 $numshows = 0;
545 }
546 $numhints = max($numhints, $numclears, $numshows);
547 }
548 return $numhints;
549 }
550
551 /**
552 * Determine if the hint with specified number is not empty and should be saved.
553 * Overload if you use custom hint controls.
554 * @param object $formdata the data from the form.
555 * @param int $number number of hint under question.
556 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options.
557 * @return bool is this particular hint data empty.
558 */
559 protected function is_hint_empty_in_form_data($formdata, $number, $withparts) {
560 if ($withparts) {
561 return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) &&
562 empty($formdata->hintshownumcorrect[$number]);
563 } else {
564 return empty($formdata->hint[$number]['text']);
565 }
566 }
567
568 /**
569 * Save additional question type data into the hint optional field.
570 * Overload if you use custom hint information.
571 * @param object $formdata the data from the form.
572 * @param int $number number of hint to get options from.
573 * @param bool $withparts whether question have parts.
574 * @return string value to save into the options field of question_hints table.
575 */
576 protected function save_hint_options($formdata, $number, $withparts) {
577 return null; // By default, options field is unused.
578 }
579
1c2ed7c5
TH
580 /**
581 * Can be used to {@link save_question_options()} to transfer the combined
582 * feedback fields from $formdata to $options.
583 * @param object $options the $question->options object being built.
584 * @param object $formdata the data from the form.
585 * @param object $context the context the quetsion is being saved into.
f7970e3c 586 * @param bool $withparts whether $options->shownumcorrect should be set.
1c2ed7c5 587 */
eaeb6b51
TH
588 protected function save_combined_feedback_helper($options, $formdata,
589 $context, $withparts = false) {
1c2ed7c5
TH
590 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback,
591 $context, 'question', 'correctfeedback', $formdata->id);
592 $options->correctfeedbackformat = $formdata->correctfeedback['format'];
eaeb6b51
TH
593
594 $options->partiallycorrectfeedback = $this->import_or_save_files(
595 $formdata->partiallycorrectfeedback,
1c2ed7c5
TH
596 $context, 'question', 'partiallycorrectfeedback', $formdata->id);
597 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format'];
eaeb6b51 598
1c2ed7c5
TH
599 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback,
600 $context, 'question', 'incorrectfeedback', $formdata->id);
601 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format'];
602
603 if ($withparts) {
604 $options->shownumcorrect = !empty($formdata->shownumcorrect);
605 }
606
607 return $options;
608 }
609
d1b7e03d
TH
610 /**
611 * Loads the question type specific options for the question.
612 *
613 * This function loads any question type specific options for the
614 * question from the database into the question object. This information
615 * is placed in the $question->options field. A question type is
616 * free, however, to decide on a internal structure of the options field.
617 * @return bool Indicates success or failure.
618 * @param object $question The question object for the question. This object
619 * should be updated to include the question type
620 * specific information (it is passed by reference).
621 */
622 public function get_question_options($question) {
f29aeb5a
TH
623 global $CFG, $DB, $OUTPUT;
624
625 if (!isset($question->options)) {
626 $question->options = new stdClass();
627 }
d1b7e03d 628
eaeb6b51
TH
629 $extraquestionfields = $this->extra_question_fields();
630 if (is_array($extraquestionfields)) {
631 $question_extension_table = array_shift($extraquestionfields);
632 $extra_data = $DB->get_record($question_extension_table,
633 array($this->questionid_column_name() => $question->id),
634 implode(', ', $extraquestionfields));
295043c2 635 if ($extra_data) {
eaeb6b51 636 foreach ($extraquestionfields as $field) {
295043c2 637 $question->options->$field = $extra_data->$field;
638 }
639 } else {
eaeb6b51
TH
640 echo $OUTPUT->notification('Failed to load question options from the table ' .
641 $question_extension_table . ' for questionid ' . $question->id);
295043c2 642 return false;
643 }
644 }
645
eaeb6b51
TH
646 $extraanswerfields = $this->extra_answer_fields();
647 if (is_array($extraanswerfields)) {
648 $answer_extension_table = array_shift($extraanswerfields);
f29aeb5a 649 $question->options->answers = $DB->get_records_sql("
eaeb6b51 650 SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . "
e5060e22 651 FROM {question_answers} qa, {{$answer_extension_table}} qax
da8cd9f4
JP
652 WHERE qa.question = ? AND qax.answerid = qa.id
653 ORDER BY qa.id", array($question->id));
295043c2 654 if (!$question->options->answers) {
eaeb6b51
TH
655 echo $OUTPUT->notification('Failed to load question answers from the table ' .
656 $answer_extension_table . 'for questionid ' . $question->id);
295043c2 657 return false;
658 }
659 } else {
eaeb6b51
TH
660 // Don't check for success or failure because some question types do
661 // not use the answers table.
662 $question->options->answers = $DB->get_records('question_answers',
663 array('question' => $question->id), 'id ASC');
295043c2 664 }
665
eaeb6b51
TH
666 $question->hints = $DB->get_records('question_hints',
667 array('questionid' => $question->id), 'id ASC');
d1b7e03d 668
516cf3eb 669 return true;
670 }
671
672 /**
d1b7e03d
TH
673 * Create an appropriate question_definition for the question of this type
674 * using data loaded from the database.
675 * @param object $questiondata the question data loaded from the database.
676 * @return question_definition the corresponding question_definition.
677 */
678 public function make_question($questiondata) {
679 $question = $this->make_question_instance($questiondata);
680 $this->initialise_question_instance($question, $questiondata);
681 return $question;
682 }
0429cd86 683
d1b7e03d
TH
684 /**
685 * Create an appropriate question_definition for the question of this type
686 * using data loaded from the database.
687 * @param object $questiondata the question data loaded from the database.
688 * @return question_definition an instance of the appropriate question_definition subclass.
689 * Still needs to be initialised.
690 */
691 protected function make_question_instance($questiondata) {
692 question_bank::load_question_definition_classes($this->name());
693 $class = 'qtype_' . $this->name() . '_question';
694 return new $class();
695 }
696
697 /**
698 * Initialise the common question_definition fields.
699 * @param question_definition $question the question_definition we are creating.
700 * @param object $questiondata the question data loaded from the database.
701 */
702 protected function initialise_question_instance(question_definition $question, $questiondata) {
703 $question->id = $questiondata->id;
704 $question->category = $questiondata->category;
56e82d99 705 $question->contextid = $questiondata->contextid;
d1b7e03d
TH
706 $question->parent = $questiondata->parent;
707 $question->qtype = $this;
708 $question->name = $questiondata->name;
709 $question->questiontext = $questiondata->questiontext;
710 $question->questiontextformat = $questiondata->questiontextformat;
711 $question->generalfeedback = $questiondata->generalfeedback;
1c2ed7c5 712 $question->generalfeedbackformat = $questiondata->generalfeedbackformat;
d1b7e03d
TH
713 $question->defaultmark = $questiondata->defaultmark + 0;
714 $question->length = $questiondata->length;
715 $question->penalty = $questiondata->penalty;
716 $question->stamp = $questiondata->stamp;
717 $question->version = $questiondata->version;
718 $question->hidden = $questiondata->hidden;
719 $question->timecreated = $questiondata->timecreated;
720 $question->timemodified = $questiondata->timemodified;
721 $question->createdby = $questiondata->createdby;
722 $question->modifiedby = $questiondata->modifiedby;
723
3d9645ae 724 // Fill extra question fields values.
10677751
OS
725 $extraquestionfields = $this->extra_question_fields();
726 if (is_array($extraquestionfields)) {
3d9645ae 727 // Omit table name.
10677751 728 array_shift($extraquestionfields);
3d9645ae 729 foreach ($extraquestionfields as $field) {
10677751
OS
730 $question->$field = $questiondata->options->$field;
731 }
732 }
733
d1b7e03d
TH
734 $this->initialise_question_hints($question, $questiondata);
735 }
736
737 /**
738 * Initialise question_definition::hints field.
739 * @param question_definition $question the question_definition we are creating.
740 * @param object $questiondata the question data loaded from the database.
741 */
742 protected function initialise_question_hints(question_definition $question, $questiondata) {
743 if (empty($questiondata->hints)) {
744 return;
745 }
746 foreach ($questiondata->hints as $hint) {
747 $question->hints[] = $this->make_hint($hint);
748 }
0429cd86 749 }
750
751 /**
d1b7e03d
TH
752 * Create a question_hint, or an appropriate subclass for this question,
753 * from a row loaded from the database.
754 * @param object $hint the DB row from the question hints table.
755 * @return question_hint
9203b705 756 */
d1b7e03d
TH
757 protected function make_hint($hint) {
758 return question_hint::load_from_record($hint);
759 }
760
1c2ed7c5
TH
761 /**
762 * Initialise the combined feedback fields.
763 * @param question_definition $question the question_definition we are creating.
764 * @param object $questiondata the question data loaded from the database.
f7970e3c 765 * @param bool $withparts whether to set the shownumcorrect field.
1c2ed7c5 766 */
eaeb6b51
TH
767 protected function initialise_combined_feedback(question_definition $question,
768 $questiondata, $withparts = false) {
1c2ed7c5
TH
769 $question->correctfeedback = $questiondata->options->correctfeedback;
770 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat;
771 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback;
eaeb6b51
TH
772 $question->partiallycorrectfeedbackformat =
773 $questiondata->options->partiallycorrectfeedbackformat;
1c2ed7c5
TH
774 $question->incorrectfeedback = $questiondata->options->incorrectfeedback;
775 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat;
776 if ($withparts) {
777 $question->shownumcorrect = $questiondata->options->shownumcorrect;
778 }
779 }
780
d1b7e03d
TH
781 /**
782 * Initialise question_definition::answers field.
783 * @param question_definition $question the question_definition we are creating.
784 * @param object $questiondata the question data loaded from the database.
35c9b652
TH
785 * @param bool $forceplaintextanswers most qtypes assume that answers are
786 * FORMAT_PLAIN, and dont use the answerformat DB column (it contains
787 * the default 0 = FORMAT_MOODLE). Therefore, by default this method
788 * ingores answerformat. Pass false here to use answerformat. For example
789 * multichoice does this.
790 */
791 protected function initialise_question_answers(question_definition $question,
792 $questiondata, $forceplaintextanswers = true) {
d1b7e03d
TH
793 $question->answers = array();
794 if (empty($questiondata->options->answers)) {
795 return;
796 }
797 foreach ($questiondata->options->answers as $a) {
5f7cfba7
TH
798 $question->answers[$a->id] = new question_answer($a->id, $a->answer,
799 $a->fraction, $a->feedback, $a->feedbackformat);
35c9b652
TH
800 if (!$forceplaintextanswers) {
801 $question->answers[$a->id]->answerformat = $a->answerformat;
802 }
d1b7e03d
TH
803 }
804 }
9203b705 805
d1b7e03d 806 /**
f29aeb5a 807 * Deletes the question-type specific data when a question is deleted.
f7970e3c
TH
808 * @param int $question the question being deleted.
809 * @param int $contextid the context this quesiotn belongs to.
f29aeb5a
TH
810 */
811 public function delete_question($questionid, $contextid) {
812 global $DB;
813
814 $this->delete_files($questionid, $contextid);
516cf3eb 815
eaeb6b51
TH
816 $extraquestionfields = $this->extra_question_fields();
817 if (is_array($extraquestionfields)) {
818 $question_extension_table = array_shift($extraquestionfields);
f29aeb5a
TH
819 $DB->delete_records($question_extension_table,
820 array($this->questionid_column_name() => $questionid));
295043c2 821 }
822
eaeb6b51
TH
823 $extraanswerfields = $this->extra_answer_fields();
824 if (is_array($extraanswerfields)) {
825 $answer_extension_table = array_shift($extraanswerfields);
f29aeb5a 826 $DB->delete_records_select($answer_extension_table,
eaeb6b51
TH
827 'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)',
828 array($questionid));
295043c2 829 }
830
f29aeb5a 831 $DB->delete_records('question_answers', array('question' => $questionid));
d1b7e03d 832
f29aeb5a 833 $DB->delete_records('question_hints', array('questionid' => $questionid));
516cf3eb 834 }
835
836 /**
eaeb6b51
TH
837 * Returns the number of question numbers which are used by the question
838 *
839 * This function returns the number of question numbers to be assigned
840 * to the question. Most question types will have length one; they will be
841 * assigned one number. The 'description' type, however does not use up a
842 * number and so has a length of zero. Other question types may wish to
843 * handle a bundle of questions and hence return a number greater than one.
844 * @return int The number of question numbers which should be
845 * assigned to the question.
846 * @param object $question The question whose length is to be determined.
847 * Question type specific information is included.
848 */
d1b7e03d 849 public function actual_number_of_questions($question) {
3d9645ae 850 // By default, each question is given one number.
516cf3eb 851 return 1;
852 }
853
6f51ed72 854 /**
855 * @param object $question
d1b7e03d
TH
856 * @return number|null either a fraction estimating what the student would
857 * score by guessing, or null, if it is not possible to estimate.
6f51ed72 858 */
c7df5006 859 public function get_random_guess_score($questiondata) {
6f51ed72 860 return 0;
861 }
516cf3eb 862
3d6f2466
JP
863 /**
864 * Whether or not to break down question stats and response analysis, for a question defined by $questiondata.
865 *
866 * @param object $questiondata The full question definition data.
867 * @return bool
868 */
869 public function break_down_stats_and_response_analysis_by_variant($questiondata) {
870 return true;
871 }
872
516cf3eb 873 /**
d1b7e03d 874 * This method should return all the possible types of response that are
f9b0500f 875 * recognised for this question.
271e6dec 876 *
d1b7e03d
TH
877 * The question is modelled as comprising one or more subparts. For each
878 * subpart, there are one or more classes that that students response
879 * might fall into, each of those classes earning a certain score.
50da63eb 880 *
d1b7e03d
TH
881 * For example, in a shortanswer question, there is only one subpart, the
882 * text entry field. The response the student gave will be classified according
883 * to which of the possible $question->options->answers it matches.
271e6dec 884 *
d1b7e03d
TH
885 * For the matching question type, there will be one subpart for each
886 * question stem, and for each stem, each of the possible choices is a class
887 * of student's response.
888 *
889 * A response is an object with two fields, ->responseclass is a string
890 * presentation of that response, and ->fraction, the credit for a response
891 * in that class.
892 *
893 * Array keys have no specific meaning, but must be unique, and must be
894 * the same if this function is called repeatedly.
895 *
896 * @param object $question the question definition data.
897 * @return array keys are subquestionid, values are arrays of possible
898 * responses to that subquestion.
99ba746d 899 */
c7df5006 900 public function get_possible_responses($questiondata) {
d1b7e03d 901 return array();
50da63eb 902 }
5fceb049 903
50da63eb 904 /**
46e40567
TH
905 * Utility method used by {@link qtype_renderer::head_code()}. It looks
906 * for any of the files script.js or script.php that exist in the plugin
907 * folder and ensures they get included.
50da63eb 908 */
c76145d3 909 public function find_standard_scripts() {
f29aeb5a
TH
910 global $PAGE;
911
99ba746d 912 $plugindir = $this->plugin_dir();
f29aeb5a 913 $plugindirrel = 'question/type/' . $this->name();
50da63eb 914
915 if (file_exists($plugindir . '/script.js')) {
f29aeb5a 916 $PAGE->requires->js('/' . $plugindirrel . '/script.js');
50da63eb 917 }
918 if (file_exists($plugindir . '/script.php')) {
f29aeb5a 919 $PAGE->requires->js('/' . $plugindirrel . '/script.php');
516cf3eb 920 }
fe9b5cfd 921 }
922
62e76c67 923 /**
eaeb6b51
TH
924 * Returns true if the editing wizard is finished, false otherwise.
925 *
926 * The default implementation returns true, which is suitable for all question-
927 * types that only use one editing form. This function is used in
928 * question.php to decide whether we can regrade any states of the edited
929 * question and redirect to edit.php.
930 *
931 * The dataset dependent question-type, which is extended by the calculated
932 * question-type, overwrites this method because it uses multiple pages (i.e.
933 * a wizard) to set up the question and associated datasets.
934 *
935 * @param object $form The data submitted by the previous page.
936 *
937 * @return bool Whether the wizard's last page was submitted or not.
938 */
f29aeb5a 939 public function finished_edit_wizard($form) {
3d9645ae 940 // In the default case there is only one edit page.
d1b7e03d 941 return true;
62e76c67 942 }
943
3d9645ae 944 // IMPORT/EXPORT FUNCTIONS --------------------------------- .
88bc20c3 945
946 /*
947 * Imports question from the Moodle XML format
948 *
949 * Imports question using information from extra_question_fields function
950 * If some of you fields contains id's you'll need to reimplement this
951 */
a031b0f3 952 public function import_from_xml($data, $question, qformat_xml $format, $extra=null) {
88bc20c3 953 $question_type = $data['@']['type'];
954 if ($question_type != $this->name()) {
955 return false;
956 }
957
958 $extraquestionfields = $this->extra_question_fields();
959 if (!is_array($extraquestionfields)) {
960 return false;
961 }
962
3d9645ae 963 // Omit table name.
88bc20c3 964 array_shift($extraquestionfields);
965 $qo = $format->import_headers($data);
966 $qo->qtype = $question_type;
967
968 foreach ($extraquestionfields as $field) {
05cef658 969 $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), '');
88bc20c3 970 }
971
3d9645ae 972 // Run through the answers.
88bc20c3 973 $answers = $data['#']['answer'];
974 $a_count = 0;
05cef658
JP
975 $extraanswersfields = $this->extra_answer_fields();
976 if (is_array($extraanswersfields)) {
977 array_shift($extraanswersfields);
978 }
979 foreach ($answers as $answer) {
980 $ans = $format->import_answer($answer);
981 if (!$this->has_html_answers()) {
982 $qo->answer[$a_count] = $ans->answer['text'];
983 } else {
88bc20c3 984 $qo->answer[$a_count] = $ans->answer;
88bc20c3 985 }
05cef658
JP
986 $qo->fraction[$a_count] = $ans->fraction;
987 $qo->feedback[$a_count] = $ans->feedback;
988 if (is_array($extraanswersfields)) {
989 foreach ($extraanswersfields as $field) {
990 $qo->{$field}[$a_count] =
991 $format->getpath($answer, array('#', $field, 0, '#'), '');
992 }
993 }
994 ++$a_count;
88bc20c3 995 }
996 return $qo;
997 }
998
999 /*
1000 * Export question to the Moodle XML format
1001 *
1002 * Export question using information from extra_question_fields function
1003 * If some of you fields contains id's you'll need to reimplement this
1004 */
a031b0f3 1005 public function export_to_xml($question, qformat_xml $format, $extra=null) {
88bc20c3 1006 $extraquestionfields = $this->extra_question_fields();
1007 if (!is_array($extraquestionfields)) {
1008 return false;
1009 }
1010
3d9645ae 1011 // Omit table name.
88bc20c3 1012 array_shift($extraquestionfields);
1013 $expout='';
1014 foreach ($extraquestionfields as $field) {
1b343d52 1015 $exportedvalue = $format->xml_escape($question->options->$field);
2d01a916 1016 $expout .= " <$field>{$exportedvalue}</$field>\n";
88bc20c3 1017 }
1018
05cef658
JP
1019 $extraanswersfields = $this->extra_answer_fields();
1020 if (is_array($extraanswersfields)) {
1021 array_shift($extraanswersfields);
1022 }
1023 foreach ($question->options->answers as $answer) {
04fcd1f5 1024 $extra = '';
05cef658
JP
1025 if (is_array($extraanswersfields)) {
1026 foreach ($extraanswersfields as $field) {
1b343d52 1027 $exportedvalue = $format->xml_escape($answer->$field);
04fcd1f5 1028 $extra .= " <{$field}>{$exportedvalue}</{$field}>\n";
05cef658 1029 }
88bc20c3 1030 }
05cef658 1031
04fcd1f5 1032 $expout .= $format->write_answer($answer, $extra);
88bc20c3 1033 }
1034 return $expout;
1035 }
1036
b9bd6da4 1037 /**
1038 * Abstract function implemented by each question type. It runs all the code
1039 * required to set up and save a question of any type for testing purposes.
1040 * Alternate DB table prefix may be used to facilitate data deletion.
1041 */
d1b7e03d 1042 public function generate_test($name, $courseid=null) {
b9bd6da4 1043 $form = new stdClass();
1044 $form->name = $name;
1045 $form->questiontextformat = 1;
1046 $form->questiontext = 'test question, generated by script';
d1b7e03d
TH
1047 $form->defaultmark = 1;
1048 $form->penalty = 0.3333333;
b9bd6da4 1049 $form->generalfeedback = "Well done";
1050
21c08c63 1051 $context = context_course::instance($courseid);
b9bd6da4 1052 $newcategory = question_make_default_categories(array($context));
1053 $form->category = $newcategory->id . ',1';
1054
1055 $question = new stdClass();
1056 $question->courseid = $courseid;
1057 $question->qtype = $this->qtype;
1058 return array($form, $question);
1059 }
f29aeb5a
TH
1060
1061 /**
1062 * Get question context by category id
1063 * @param int $category
1064 * @return object $context
1065 */
c7df5006 1066 protected function get_context_by_category_id($category) {
f29aeb5a
TH
1067 global $DB;
1068 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category));
5fbe2118 1069 $context = context::instance_by_id($contextid, IGNORE_MISSING);
f29aeb5a
TH
1070 return $context;
1071 }
1072
1073 /**
1074 * Save the file belonging to one text field.
1075 *
1076 * @param array $field the data from the form (or from import). This will
1077 * normally have come from the formslib editor element, so it will be an
1078 * array with keys 'text', 'format' and 'itemid'. However, when we are
1079 * importing, it will be an array with keys 'text', 'format' and 'files'
1080 * @param object $context the context the question is in.
1081 * @param string $component indentifies the file area question.
eaeb6b51
TH
1082 * @param string $filearea indentifies the file area questiontext,
1083 * generalfeedback, answerfeedback, etc.
f7970e3c 1084 * @param int $itemid identifies the file area.
f29aeb5a
TH
1085 *
1086 * @return string the text for this field, after files have been processed.
1087 */
1088 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) {
1089 if (!empty($field['itemid'])) {
1090 // This is the normal case. We are safing the questions editing form.
1091 return file_save_draft_area_files($field['itemid'], $context->id, $component,
1092 $filearea, $itemid, $this->fileoptions, trim($field['text']));
1093
1094 } else if (!empty($field['files'])) {
1095 // This is the case when we are doing an import.
1096 foreach ($field['files'] as $file) {
1097 $this->import_file($context, $component, $filearea, $itemid, $file);
1098 }
1099 }
1100 return trim($field['text']);
1101 }
1102
1103 /**
1104 * Move all the files belonging to this question from one context to another.
f7970e3c
TH
1105 * @param int $questionid the question being moved.
1106 * @param int $oldcontextid the context it is moving from.
1107 * @param int $newcontextid the context it is moving to.
f29aeb5a
TH
1108 */
1109 public function move_files($questionid, $oldcontextid, $newcontextid) {
1110 $fs = get_file_storage();
1111 $fs->move_area_files_to_new_context($oldcontextid,
1112 $newcontextid, 'question', 'questiontext', $questionid);
1113 $fs->move_area_files_to_new_context($oldcontextid,
1114 $newcontextid, 'question', 'generalfeedback', $questionid);
1115 }
1116
1117 /**
1118 * Move all the files belonging to this question's answers when the question
1119 * is moved from one context to another.
f7970e3c
TH
1120 * @param int $questionid the question being moved.
1121 * @param int $oldcontextid the context it is moving from.
1122 * @param int $newcontextid the context it is moving to.
1123 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1124 * as well as an 'answerfeedback' one. Default false.
1125 */
eaeb6b51
TH
1126 protected function move_files_in_answers($questionid, $oldcontextid,
1127 $newcontextid, $answerstoo = false) {
f29aeb5a
TH
1128 global $DB;
1129 $fs = get_file_storage();
1130
1131 $answerids = $DB->get_records_menu('question_answers',
1132 array('question' => $questionid), 'id', 'id,1');
1133 foreach ($answerids as $answerid => $notused) {
1134 if ($answerstoo) {
1135 $fs->move_area_files_to_new_context($oldcontextid,
1136 $newcontextid, 'question', 'answer', $answerid);
1137 }
1138 $fs->move_area_files_to_new_context($oldcontextid,
1139 $newcontextid, 'question', 'answerfeedback', $answerid);
1140 }
1141 }
1142
d44480f6
TH
1143 /**
1144 * Move all the files belonging to this question's hints when the question
1145 * is moved from one context to another.
1146 * @param int $questionid the question being moved.
1147 * @param int $oldcontextid the context it is moving from.
1148 * @param int $newcontextid the context it is moving to.
1149 * @param bool $answerstoo whether there is an 'answer' question area,
1150 * as well as an 'answerfeedback' one. Default false.
1151 */
1152 protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) {
1153 global $DB;
1154 $fs = get_file_storage();
1155
1156 $hintids = $DB->get_records_menu('question_hints',
1157 array('questionid' => $questionid), 'id', 'id,1');
1158 foreach ($hintids as $hintid => $notused) {
1159 $fs->move_area_files_to_new_context($oldcontextid,
1160 $newcontextid, 'question', 'hint', $hintid);
1161 }
1162 }
1163
a23bda41
TH
1164 /**
1165 * Move all the files belonging to this question's answers when the question
1166 * is moved from one context to another.
1167 * @param int $questionid the question being moved.
1168 * @param int $oldcontextid the context it is moving from.
1169 * @param int $newcontextid the context it is moving to.
1170 * @param bool $answerstoo whether there is an 'answer' question area,
1171 * as well as an 'answerfeedback' one. Default false.
1172 */
1173 protected function move_files_in_combined_feedback($questionid, $oldcontextid,
1174 $newcontextid) {
1175 global $DB;
1176 $fs = get_file_storage();
1177
1178 $fs->move_area_files_to_new_context($oldcontextid,
1179 $newcontextid, 'question', 'correctfeedback', $questionid);
1180 $fs->move_area_files_to_new_context($oldcontextid,
1181 $newcontextid, 'question', 'partiallycorrectfeedback', $questionid);
1182 $fs->move_area_files_to_new_context($oldcontextid,
1183 $newcontextid, 'question', 'incorrectfeedback', $questionid);
1184 }
1185
f29aeb5a
TH
1186 /**
1187 * Delete all the files belonging to this question.
f7970e3c
TH
1188 * @param int $questionid the question being deleted.
1189 * @param int $contextid the context the question is in.
f29aeb5a
TH
1190 */
1191 protected function delete_files($questionid, $contextid) {
1192 $fs = get_file_storage();
1193 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid);
1194 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid);
1195 }
1196
1197 /**
1198 * Delete all the files belonging to this question's answers.
f7970e3c
TH
1199 * @param int $questionid the question being deleted.
1200 * @param int $contextid the context the question is in.
1201 * @param bool $answerstoo whether there is an 'answer' question area,
f29aeb5a
TH
1202 * as well as an 'answerfeedback' one. Default false.
1203 */
1204 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) {
1205 global $DB;
1206 $fs = get_file_storage();
1207
1208 $answerids = $DB->get_records_menu('question_answers',
1209 array('question' => $questionid), 'id', 'id,1');
1210 foreach ($answerids as $answerid => $notused) {
1211 if ($answerstoo) {
1212 $fs->delete_area_files($contextid, 'question', 'answer', $answerid);
1213 }
1214 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid);
1215 }
1216 }
1217
d44480f6
TH
1218 /**
1219 * Delete all the files belonging to this question's hints.
1220 * @param int $questionid the question being deleted.
1221 * @param int $contextid the context the question is in.
1222 */
1223 protected function delete_files_in_hints($questionid, $contextid) {
1224 global $DB;
1225 $fs = get_file_storage();
1226
1227 $hintids = $DB->get_records_menu('question_hints',
1228 array('questionid' => $questionid), 'id', 'id,1');
1229 foreach ($hintids as $hintid => $notused) {
1230 $fs->delete_area_files($contextid, 'question', 'hint', $hintid);
1231 }
1232 }
1233
a23bda41
TH
1234 /**
1235 * Delete all the files belonging to this question's answers.
1236 * @param int $questionid the question being deleted.
1237 * @param int $contextid the context the question is in.
1238 * @param bool $answerstoo whether there is an 'answer' question area,
1239 * as well as an 'answerfeedback' one. Default false.
1240 */
1241 protected function delete_files_in_combined_feedback($questionid, $contextid) {
1242 global $DB;
1243 $fs = get_file_storage();
1244
1245 $fs->delete_area_files($contextid,
1246 'question', 'correctfeedback', $questionid);
1247 $fs->delete_area_files($contextid,
1248 'question', 'partiallycorrectfeedback', $questionid);
1249 $fs->delete_area_files($contextid,
1250 'question', 'incorrectfeedback', $questionid);
1251 }
1252
f902a54e 1253 public function import_file($context, $component, $filearea, $itemid, $file) {
f29aeb5a 1254 $fs = get_file_storage();
0ff4bd08 1255 $record = new stdClass();
f29aeb5a
TH
1256 if (is_object($context)) {
1257 $record->contextid = $context->id;
1258 } else {
1259 $record->contextid = $context;
1260 }
1261 $record->component = $component;
1262 $record->filearea = $filearea;
1263 $record->itemid = $itemid;
1264 $record->filename = $file->name;
1265 $record->filepath = '/';
1266 return $fs->create_file_from_string($record, $this->decode_file($file));
1267 }
1268
c7df5006 1269 protected function decode_file($file) {
f29aeb5a 1270 switch ($file->encoding) {
eaeb6b51
TH
1271 case 'base64':
1272 default:
1273 return base64_decode($file->content);
f29aeb5a
TH
1274 }
1275 }
d1b7e03d 1276}
aeb15530 1277
cde2709a 1278
d1b7e03d
TH
1279/**
1280 * This class is used in the return value from
1281 * {@link question_type::get_possible_responses()}.
1282 *
7764183a
TH
1283 * @copyright 2010 The Open University
1284 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
1285 */
1286class question_possible_response {
9203b705 1287 /**
d1b7e03d
TH
1288 * @var string the classification of this response the student gave to this
1289 * part of the question. Must match one of the responseclasses returned by
1290 * {@link question_type::get_possible_responses()}.
9203b705 1291 */
d1b7e03d 1292 public $responseclass;
ba6425ab
TH
1293
1294 /** @var string the (partial) credit awarded for this responses. */
d1b7e03d 1295 public $fraction;
ba6425ab 1296
9203b705 1297 /**
d1b7e03d
TH
1298 * Constructor, just an easy way to set the fields.
1299 * @param string $responseclassid see the field descriptions above.
1300 * @param string $response see the field descriptions above.
1301 * @param number $fraction see the field descriptions above.
9203b705 1302 */
d1b7e03d
TH
1303 public function __construct($responseclass, $fraction) {
1304 $this->responseclass = $responseclass;
1305 $this->fraction = $fraction;
cde2709a
DC
1306 }
1307
d1b7e03d
TH
1308 public static function no_response() {
1309 return new question_possible_response(get_string('noresponse', 'question'), 0);
cde2709a 1310 }
fe6ce234 1311}