weekly release 3.6dev
[moodle.git] / question / type / edit_question_form.php
CommitLineData
aeb15530 1<?php
fe6ce234
DC
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
36703ed7 17/**
18 * A base class for question editing forms.
19 *
7764183a 20 * @package moodlecore
2b7da645 21 * @subpackage questiontypes
b04a4319
TH
22 * @copyright 2006 The Open University
23 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
fe6ce234 24 */
36703ed7 25
2b7da645 26
a17b297d
TH
27defined('MOODLE_INTERNAL') || die();
28
603bd001
PS
29global $CFG;
30require_once($CFG->libdir.'/formslib.php');
31
a17b297d 32
72553162
TH
33abstract class question_wizard_form extends moodleform {
34 /**
35 * Add all the hidden form fields used by question/question.php.
36 */
37 protected function add_hidden_fields() {
38 $mform = $this->_form;
39
40 $mform->addElement('hidden', 'id');
41 $mform->setType('id', PARAM_INT);
42
43 $mform->addElement('hidden', 'inpopup');
44 $mform->setType('inpopup', PARAM_INT);
45
46 $mform->addElement('hidden', 'cmid');
47 $mform->setType('cmid', PARAM_INT);
48
49 $mform->addElement('hidden', 'courseid');
50 $mform->setType('courseid', PARAM_INT);
51
52 $mform->addElement('hidden', 'returnurl');
53 $mform->setType('returnurl', PARAM_LOCALURL);
54
55 $mform->addElement('hidden', 'scrollpos');
56 $mform->setType('scrollpos', PARAM_INT);
57
58 $mform->addElement('hidden', 'appendqnumstring');
59 $mform->setType('appendqnumstring', PARAM_ALPHA);
60 }
61}
62
36703ed7 63/**
64 * Form definition base class. This defines the common fields that
65 * all question types need. Question types should define their own
66 * class that inherits from this one, and implements the definition_inner()
67 * method.
271e6dec 68 *
7764183a
TH
69 * @copyright 2006 The Open University
70 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
36703ed7 71 */
72553162 72abstract class question_edit_form extends question_wizard_form {
2b7da645
TH
73 const DEFAULT_NUM_HINTS = 2;
74
271ffe3f 75 /**
76 * Question object with options and answers already loaded by get_question_options
77 * Be careful how you use this it is needed sometimes to set up the structure of the
32db0d42 78 * form in definition_inner but data is always loaded into the form with set_data.
271ffe3f 79 * @var object
80 */
2b7da645
TH
81 protected $question;
82
83 protected $contexts;
84 protected $category;
85 protected $categorycontext;
271e6dec 86
fe6ce234
DC
87 /** @var object current context */
88 public $context;
89 /** @var array html editor options */
90 public $editoroptions;
91 /** @var array options to preapre draft area */
92 public $fileoptions;
93 /** @var object instance of question type */
94 public $instance;
95
2b7da645 96 public function __construct($submiturl, $question, $category, $contexts, $formeditable = true) {
fe6ce234 97 global $DB;
271e6dec 98
271ffe3f 99 $this->question = $question;
271e6dec 100 $this->contexts = $contexts;
101
eaeb6b51
TH
102 $record = $DB->get_record('question_categories',
103 array('id' => $question->category), 'contextid');
d197ea43 104 $this->context = context::instance_by_id($record->contextid);
fe6ce234 105
eaeb6b51 106 $this->editoroptions = array('subdirs' => 1, 'maxfiles' => EDITOR_UNLIMITED_FILES,
0c0dfa8f 107 'context' => $this->context);
41dcc2a5 108 $this->fileoptions = array('subdirs' => 1, 'maxfiles' => -1, 'maxbytes' => -1);
fe6ce234 109
271e6dec 110 $this->category = $category;
d197ea43 111 $this->categorycontext = context::instance_by_id($category->contextid);
271e6dec 112
2b7da645 113 parent::__construct($submiturl, null, 'post', '', null, $formeditable);
271ffe3f 114 }
8e652f02 115
36703ed7 116 /**
117 * Build the form definition.
1d284fbd 118 *
295043c2 119 * This adds all the form fields that the default question type supports.
36703ed7 120 * If your question type does not support all these fields, then you can
121 * override this method and remove the ones you don't want with $mform->removeElement().
122 */
c7df5006 123 protected function definition() {
8011be18 124 global $COURSE, $CFG, $DB, $PAGE;
1d284fbd 125
36703ed7 126 $qtype = $this->qtype();
f4fe3968 127 $langfile = "qtype_{$qtype}";
1d284fbd 128
f9b0500f 129 $mform = $this->_form;
36703ed7 130
131 // Standard fields at the start of the form.
271ffe3f 132 $mform->addElement('header', 'generalheader', get_string("general", 'form'));
1d284fbd 133
2b7da645 134 if (!isset($this->question->id)) {
76cf77e4
TH
135 if (!empty($this->question->formoptions->mustbeusable)) {
136 $contexts = $this->contexts->having_add_and_use();
137 } else {
138 $contexts = $this->contexts->having_cap('moodle/question:add');
139 }
140
c7218aef 141 // Adding question.
2b7da645 142 $mform->addElement('questioncategory', 'category', get_string('category', 'question'),
76cf77e4 143 array('contexts' => $contexts));
eaeb6b51
TH
144 } else if (!($this->question->formoptions->canmove ||
145 $this->question->formoptions->cansaveasnew)) {
5d548d3e 146 // Editing question with no permission to move from category.
2b7da645 147 $mform->addElement('questioncategory', 'category', get_string('category', 'question'),
271e6dec 148 array('contexts' => array($this->categorycontext)));
f276267d
TH
149 $mform->addElement('hidden', 'usecurrentcat', 1);
150 $mform->setType('usecurrentcat', PARAM_BOOL);
151 $mform->setConstant('usecurrentcat', 1);
271e6dec 152 } else {
c7218aef 153 // Editing question with permission to move from category or save as new q.
271e6dec 154 $currentgrp = array();
eaeb6b51
TH
155 $currentgrp[0] = $mform->createElement('questioncategory', 'category',
156 get_string('categorycurrent', 'question'),
271e6dec 157 array('contexts' => array($this->categorycontext)));
eaeb6b51
TH
158 if ($this->question->formoptions->canedit ||
159 $this->question->formoptions->cansaveasnew) {
c7218aef 160 // Not move only form.
eaeb6b51
TH
161 $currentgrp[1] = $mform->createElement('checkbox', 'usecurrentcat', '',
162 get_string('categorycurrentuse', 'question'));
271e6dec 163 $mform->setDefault('usecurrentcat', 1);
164 }
165 $currentgrp[0]->freeze();
166 $currentgrp[0]->setPersistantFreeze(false);
eaeb6b51
TH
167 $mform->addGroup($currentgrp, 'currentgrp',
168 get_string('categorycurrent', 'question'), null, false);
271e6dec 169
eaeb6b51
TH
170 $mform->addElement('questioncategory', 'categorymoveto',
171 get_string('categorymoveto', 'question'),
271e6dec 172 array('contexts' => array($this->categorycontext)));
eaeb6b51
TH
173 if ($this->question->formoptions->canedit ||
174 $this->question->formoptions->cansaveasnew) {
c7218aef 175 // Not move only form.
271e6dec 176 $mform->disabledIf('categorymoveto', 'usecurrentcat', 'checked');
177 }
178 }
375ed78a 179
eaeb6b51 180 $mform->addElement('text', 'name', get_string('questionname', 'question'),
b9b38ea7 181 array('size' => 50, 'maxlength' => 255));
271ffe3f 182 $mform->setType('name', PARAM_TEXT);
36703ed7 183 $mform->addRule('name', null, 'required', null, 'client');
1d284fbd 184
2b7da645 185 $mform->addElement('editor', 'questiontext', get_string('questiontext', 'question'),
0c0dfa8f 186 array('rows' => 15), $this->editoroptions);
36703ed7 187 $mform->setType('questiontext', PARAM_RAW);
363f8224 188 $mform->addRule('questiontext', null, 'required', null, 'client');
1d284fbd 189
2b7da645 190 $mform->addElement('text', 'defaultmark', get_string('defaultmark', 'question'),
d2acbd1a 191 array('size' => 7));
7664182d 192 $mform->setType('defaultmark', PARAM_FLOAT);
2b7da645
TH
193 $mform->setDefault('defaultmark', 1);
194 $mform->addRule('defaultmark', null, 'required', null, 'client');
36703ed7 195
2b7da645 196 $mform->addElement('editor', 'generalfeedback', get_string('generalfeedback', 'question'),
0c0dfa8f 197 array('rows' => 10), $this->editoroptions);
36703ed7 198 $mform->setType('generalfeedback', PARAM_RAW);
2b7da645 199 $mform->addHelpButton('generalfeedback', 'generalfeedback', 'question');
1d284fbd 200
36703ed7 201 // Any questiontype specific fields.
202 $this->definition_inner($mform);
203
4509be22 204 if (core_tag_tag::is_enabled('core_question', 'question')) {
081eb156 205 $this->add_tag_fields($mform);
4509be22
SL
206 }
207
2b7da645 208 if (!empty($this->question->id)) {
eaeb6b51
TH
209 $mform->addElement('header', 'createdmodifiedheader',
210 get_string('createdmodifiedheader', 'question'));
7f389342 211 $a = new stdClass();
2b7da645 212 if (!empty($this->question->createdby)) {
271e6dec 213 $a->time = userdate($this->question->timecreated);
eaeb6b51
TH
214 $a->user = fullname($DB->get_record(
215 'user', array('id' => $this->question->createdby)));
271e6dec 216 } else {
217 $a->time = get_string('unknown', 'question');
218 $a->user = get_string('unknown', 'question');
219 }
eaeb6b51
TH
220 $mform->addElement('static', 'created', get_string('created', 'question'),
221 get_string('byandon', 'question', $a));
2b7da645 222 if (!empty($this->question->modifiedby)) {
7f389342 223 $a = new stdClass();
271e6dec 224 $a->time = userdate($this->question->timemodified);
eaeb6b51
TH
225 $a->user = fullname($DB->get_record(
226 'user', array('id' => $this->question->modifiedby)));
227 $mform->addElement('static', 'modified', get_string('modified', 'question'),
228 get_string('byandon', 'question', $a));
271e6dec 229 }
230 }
231
72553162 232 $this->add_hidden_fields();
36703ed7 233
72553162
TH
234 $mform->addElement('hidden', 'qtype');
235 $mform->setType('qtype', PARAM_ALPHA);
fa583f5f 236
e0c41591
K
237 $mform->addElement('hidden', 'makecopy');
238 $mform->setType('makecopy', PARAM_INT);
239
375ed78a 240 $buttonarray = array();
8011be18 241 $buttonarray[] = $mform->createElement('submit', 'updatebutton',
7756e2bc 242 get_string('savechangesandcontinueediting', 'question'));
8011be18
TH
243 if ($this->can_preview()) {
244 $previewlink = $PAGE->get_renderer('core_question')->question_preview_link(
245 $this->question->id, $this->context, true);
7756e2bc 246 $buttonarray[] = $mform->createElement('static', 'previewlink', '', $previewlink);
375ed78a 247 }
7756e2bc 248
8011be18
TH
249 $mform->addGroup($buttonarray, 'updatebuttonar', '', array(' '), false);
250 $mform->closeHeaderBefore('updatebuttonar');
7756e2bc
K
251
252 $this->add_action_buttons(true, get_string('savechanges'));
271e6dec 253
435d3279 254 if ((!empty($this->question->id)) && (!($this->question->formoptions->canedit ||
eaeb6b51 255 $this->question->formoptions->cansaveasnew))) {
271e6dec 256 $mform->hardFreezeAllVisibleExcept(array('categorymoveto', 'buttonar', 'currentgrp'));
257 }
36703ed7 258 }
fa583f5f 259
36703ed7 260 /**
261 * Add any question-type specific form fields.
1d284fbd 262 *
263 * @param object $mform the form being built.
36703ed7 264 */
2b7da645 265 protected function definition_inner($mform) {
36703ed7 266 // By default, do nothing.
267 }
1d284fbd 268
8011be18
TH
269 /**
270 * Is the question being edited in a state where it can be previewed?
271 * @return bool whether to show the preview link.
272 */
273 protected function can_preview() {
274 return empty($this->question->beingcopied) && !empty($this->question->id) &&
275 $this->question->formoptions->canedit;
276 }
277
2aef1fe5 278 /**
279 * Get the list of form elements to repeat, one for each answer.
280 * @param object $mform the form being built.
281 * @param $label the label to use for each option.
282 * @param $gradeoptions the possible grades for each answer.
283 * @param $repeatedoptions reference to array of repeated options to fill
eaeb6b51
TH
284 * @param $answersoption reference to return the name of $question->options
285 * field holding an array of answers
2aef1fe5 286 * @return array of form fields.
287 */
2a6c5c52 288 protected function get_per_answer_fields($mform, $label, $gradeoptions,
eaeb6b51 289 &$repeatedoptions, &$answersoption) {
2aef1fe5 290 $repeated = array();
c7218aef
CC
291 $answeroptions = array();
292 $answeroptions[] = $mform->createElement('text', 'answer',
293 $label, array('size' => 40));
294 $answeroptions[] = $mform->createElement('select', 'fraction',
eaeb6b51 295 get_string('grade'), $gradeoptions);
c7218aef
CC
296 $repeated[] = $mform->createElement('group', 'answeroptions',
297 $label, $answeroptions, null, false);
eaeb6b51
TH
298 $repeated[] = $mform->createElement('editor', 'feedback',
299 get_string('feedback', 'question'), array('rows' => 5), $this->editoroptions);
2aef1fe5 300 $repeatedoptions['answer']['type'] = PARAM_RAW;
301 $repeatedoptions['fraction']['default'] = 0;
302 $answersoption = 'answers';
303 return $repeated;
304 }
305
081eb156
RW
306 /**
307 * Add the tag and course tag fields to the mform.
308 *
309 * If the form is being built in a course context then add the field
310 * for course tags.
311 *
312 * If the question category doesn't belong to a course context or we
313 * aren't editing in a course context then add the tags element to allow
314 * tags to be added to the question category context.
315 *
316 * @param object $mform The form being built
317 */
318 protected function add_tag_fields($mform) {
3722c7d6
SR
319 global $CFG, $DB;
320
081eb156
RW
321 $hastagcapability = question_has_capability_on($this->question, 'tag');
322 // Is the question category in a course context?
323 $qcontext = $this->categorycontext;
324 $qcoursecontext = $qcontext->get_course_context(false);
325 $iscourseoractivityquestion = !empty($qcoursecontext);
326 // Is the current context we're editing in a course context?
327 $editingcontext = $this->contexts->lowest();
328 $editingcoursecontext = $editingcontext->get_course_context(false);
329 $iseditingcontextcourseoractivity = !empty($editingcoursecontext);
330
331 $mform->addElement('header', 'tagsheader', get_string('tags'));
b71f21bd
SL
332 $tags = \core_tag_tag::get_tags_by_area_in_contexts('core_question', 'question', $this->contexts->all());
333 $tagstrings = [];
334 foreach ($tags as $tag) {
335 $tagstrings[$tag->name] = $tag->name;
336 }
3722c7d6
SR
337
338 $showstandard = core_tag_area::get_showstandard('core_question', 'question');
339 if ($showstandard != core_tag_tag::HIDE_STANDARD) {
340 $namefield = empty($CFG->keeptagnamecase) ? 'name' : 'rawname';
341 $standardtags = $DB->get_records('tag',
342 array('isstandard' => 1, 'tagcollid' => core_tag_area::get_collection('core', 'question')),
343 $namefield, 'id,' . $namefield);
344 foreach ($standardtags as $standardtag) {
345 $tagstrings[$standardtag->$namefield] = $standardtag->$namefield;
346 }
347 }
348
b71f21bd
SL
349 $options = [
350 'tags' => true,
351 'multiple' => true,
352 'noselectionstring' => get_string('anytags', 'quiz'),
353 ];
354 $mform->addElement('autocomplete', 'tags', get_string('tags'), $tagstrings, $options);
081eb156
RW
355
356 if (!$hastagcapability) {
357 $mform->hardFreeze('tags');
358 }
359
360 if ($iseditingcontextcourseoractivity && !$iscourseoractivityquestion) {
361 // If the question is being edited in a course or activity context
362 // and the question isn't a course or activity level question then
363 // allow course tags to be added to the course.
364 $coursetagheader = get_string('questionformtagheader', 'core_question',
365 $editingcoursecontext->get_context_name(true));
366 $mform->addElement('header', 'coursetagsheader', $coursetagheader);
b71f21bd 367 $mform->addElement('autocomplete', 'coursetags', get_string('tags'), $tagstrings, $options);
081eb156
RW
368
369 if (!$hastagcapability) {
370 $mform->hardFreeze('coursetags');
371 }
372 }
373 }
374
2aef1fe5 375 /**
376 * Add a set of form fields, obtained from get_per_answer_fields, to the form,
377 * one for each existing answer, with some blanks for some new ones.
378 * @param object $mform the form being built.
379 * @param $label the label to use for each option.
380 * @param $gradeoptions the possible grades for each answer.
eaeb6b51
TH
381 * @param $minoptions the minimum number of answer blanks to display.
382 * Default QUESTION_NUMANS_START.
2aef1fe5 383 * @param $addoptions the number of answer blanks to add. Default QUESTION_NUMANS_ADD.
384 */
eaeb6b51
TH
385 protected function add_per_answer_fields(&$mform, $label, $gradeoptions,
386 $minoptions = QUESTION_NUMANS_START, $addoptions = QUESTION_NUMANS_ADD) {
c7218aef
CC
387 $mform->addElement('header', 'answerhdr',
388 get_string('answers', 'question'), '');
389 $mform->setExpanded('answerhdr', 1);
2aef1fe5 390 $answersoption = '';
391 $repeatedoptions = array();
eaeb6b51
TH
392 $repeated = $this->get_per_answer_fields($mform, $label, $gradeoptions,
393 $repeatedoptions, $answersoption);
2aef1fe5 394
2b7da645 395 if (isset($this->question->options)) {
c3c65f41 396 $repeatsatstart = count($this->question->options->$answersoption);
2aef1fe5 397 } else {
c3c65f41 398 $repeatsatstart = $minoptions;
2aef1fe5 399 }
400
eaeb6b51
TH
401 $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
402 'noanswers', 'addanswers', $addoptions,
c7218aef 403 $this->get_more_choices_string(), true);
55748620
TH
404 }
405
406 /**
407 * Language string to use for 'Add {no} more {whatever we call answers}'.
408 */
409 protected function get_more_choices_string() {
410 return get_string('addmorechoiceblanks', 'question');
2aef1fe5 411 }
412
2b7da645
TH
413 protected function add_combined_feedback_fields($withshownumpartscorrect = false) {
414 $mform = $this->_form;
415
eaeb6b51
TH
416 $mform->addElement('header', 'combinedfeedbackhdr',
417 get_string('combinedfeedback', 'question'));
2b7da645 418
eaeb6b51
TH
419 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
420 foreach ($fields as $feedbackname) {
086cced7
CC
421 $element = $mform->addElement('editor', $feedbackname,
422 get_string($feedbackname, 'question'),
2b7da645
TH
423 array('rows' => 5), $this->editoroptions);
424 $mform->setType($feedbackname, PARAM_RAW);
086cced7 425 // Using setValue() as setDefault() does not work for the editor class.
e0c41591 426 $element->setValue(array('text' => get_string($feedbackname.'default', 'question')));
2b7da645
TH
427
428 if ($withshownumpartscorrect && $feedbackname == 'partiallycorrectfeedback') {
f7094147 429 $mform->addElement('advcheckbox', 'shownumcorrect',
eaeb6b51 430 get_string('options', 'question'),
d5ffb789 431 get_string('shownumpartscorrectwhenfinished', 'question'));
f0a64f01 432 $mform->setDefault('shownumcorrect', true);
2b7da645
TH
433 }
434 }
435 }
436
6dbc3460
CC
437 /**
438 * Create the form elements required by one hint.
439 * @param string $withclearwrong whether this quesiton type uses the 'Clear wrong' option on hints.
440 * @param string $withshownumpartscorrect whether this quesiton type uses the 'Show num parts correct' option on hints.
441 * @return array form field elements for one hint.
442 */
2b7da645
TH
443 protected function get_hint_fields($withclearwrong = false, $withshownumpartscorrect = false) {
444 $mform = $this->_form;
445
6dbc3460 446 $repeatedoptions = array();
2b7da645 447 $repeated = array();
6dbc3460 448 $repeated[] = $mform->createElement('editor', 'hint', get_string('hintn', 'question'),
7a719748 449 array('rows' => 5), $this->editoroptions);
2b7da645
TH
450 $repeatedoptions['hint']['type'] = PARAM_RAW;
451
6dbc3460 452 $optionelements = array();
2b7da645 453 if ($withclearwrong) {
6dbc3460 454 $optionelements[] = $mform->createElement('advcheckbox', 'hintclearwrong',
eaeb6b51 455 get_string('options', 'question'), get_string('clearwrongparts', 'question'));
2b7da645
TH
456 }
457 if ($withshownumpartscorrect) {
6dbc3460 458 $optionelements[] = $mform->createElement('advcheckbox', 'hintshownumcorrect', '',
eaeb6b51 459 get_string('shownumpartscorrect', 'question'));
2b7da645
TH
460 }
461
6dbc3460
CC
462 if (count($optionelements)) {
463 $repeated[] = $mform->createElement('group', 'hintoptions',
464 get_string('hintnoptions', 'question'), $optionelements, null, false);
465 }
466
2b7da645
TH
467 return array($repeated, $repeatedoptions);
468 }
469
eaeb6b51
TH
470 protected function add_interactive_settings($withclearwrong = false,
471 $withshownumpartscorrect = false) {
2b7da645
TH
472 $mform = $this->_form;
473
eaeb6b51
TH
474 $mform->addElement('header', 'multitriesheader',
475 get_string('settingsformultipletries', 'question'));
2b7da645
TH
476
477 $penalties = array(
478 1.0000000,
479 0.5000000,
480 0.3333333,
481 0.2500000,
482 0.2000000,
483 0.1000000,
484 0.0000000
485 );
486 if (!empty($this->question->penalty) && !in_array($this->question->penalty, $penalties)) {
487 $penalties[] = $this->question->penalty;
488 sort($penalties);
489 }
490 $penaltyoptions = array();
491 foreach ($penalties as $penalty) {
f4fe3968 492 $penaltyoptions["{$penalty}"] = (100 * $penalty) . '%';
2b7da645 493 }
eaeb6b51
TH
494 $mform->addElement('select', 'penalty',
495 get_string('penaltyforeachincorrecttry', 'question'), $penaltyoptions);
068b4594 496 $mform->addHelpButton('penalty', 'penaltyforeachincorrecttry', 'question');
2b7da645
TH
497 $mform->setDefault('penalty', 0.3333333);
498
499 if (isset($this->question->hints)) {
500 $counthints = count($this->question->hints);
501 } else {
502 $counthints = 0;
503 }
504
505 if ($this->question->formoptions->repeatelements) {
506 $repeatsatstart = max(self::DEFAULT_NUM_HINTS, $counthints);
507 } else {
508 $repeatsatstart = $counthints;
509 }
510
511 list($repeated, $repeatedoptions) = $this->get_hint_fields(
512 $withclearwrong, $withshownumpartscorrect);
513 $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
6dbc3460 514 'numhints', 'addhint', 1, get_string('addanotherhint', 'question'), true);
2b7da645
TH
515 }
516
517 public function set_data($question) {
f9b0500f 518 question_bank::get_qtype($question->qtype)->set_default_options($question);
2b7da645 519
c7218aef 520 // Prepare question text.
fe6ce234
DC
521 $draftid = file_get_submitted_draft_itemid('questiontext');
522
523 if (!empty($question->questiontext)) {
524 $questiontext = $question->questiontext;
525 } else {
1a2de1c7
TH
526 $questiontext = $this->_form->getElement('questiontext')->getValue();
527 $questiontext = $questiontext['text'];
271ffe3f 528 }
eaeb6b51
TH
529 $questiontext = file_prepare_draft_area($draftid, $this->context->id,
530 'question', 'questiontext', empty($question->id) ? null : (int) $question->id,
531 $this->fileoptions, $questiontext);
fe6ce234
DC
532
533 $question->questiontext = array();
534 $question->questiontext['text'] = $questiontext;
eaeb6b51
TH
535 $question->questiontext['format'] = empty($question->questiontextformat) ?
536 editors_get_preferred_format() : $question->questiontextformat;
fe6ce234
DC
537 $question->questiontext['itemid'] = $draftid;
538
c7218aef 539 // Prepare general feedback.
fe6ce234
DC
540 $draftid = file_get_submitted_draft_itemid('generalfeedback');
541
542 if (empty($question->generalfeedback)) {
1a2de1c7
TH
543 $generalfeedback = $this->_form->getElement('generalfeedback')->getValue();
544 $question->generalfeedback = $generalfeedback['text'];
fe6ce234
DC
545 }
546
eaeb6b51
TH
547 $feedback = file_prepare_draft_area($draftid, $this->context->id,
548 'question', 'generalfeedback', empty($question->id) ? null : (int) $question->id,
549 $this->fileoptions, $question->generalfeedback);
fe6ce234
DC
550 $question->generalfeedback = array();
551 $question->generalfeedback['text'] = $feedback;
eaeb6b51
TH
552 $question->generalfeedback['format'] = empty($question->generalfeedbackformat) ?
553 editors_get_preferred_format() : $question->generalfeedbackformat;
fe6ce234 554 $question->generalfeedback['itemid'] = $draftid;
295043c2 555
9152f6a5 556 // Remove unnecessary trailing 0s form grade fields.
cfd24d98 557 if (isset($question->defaultgrade)) {
558 $question->defaultgrade = 0 + $question->defaultgrade;
559 }
560 if (isset($question->penalty)) {
561 $question->penalty = 0 + $question->penalty;
562 }
9152f6a5 563
295043c2 564 // Set any options.
eaeb6b51
TH
565 $extraquestionfields = question_bank::get_qtype($question->qtype)->extra_question_fields();
566 if (is_array($extraquestionfields) && !empty($question->options)) {
567 array_shift($extraquestionfields);
568 foreach ($extraquestionfields as $field) {
a8e577de 569 if (property_exists($question->options, $field)) {
8e652f02 570 $question->$field = $question->options->$field;
571 }
295043c2 572 }
573 }
c9c989a0 574
c7218aef 575 // Subclass adds data_preprocessing code here.
fe6ce234 576 $question = $this->data_preprocessing($question);
2b7da645 577
32db0d42 578 parent::set_data($question);
36703ed7 579 }
1d284fbd 580
fe6ce234 581 /**
fdd015b7
TH
582 * Perform an preprocessing needed on the data passed to {@link set_data()}
583 * before it is used to initialise the form.
584 * @param object $question the data being passed to the form.
585 * @return object $question the modified data.
fe6ce234 586 */
c7df5006 587 protected function data_preprocessing($question) {
7a719748
TH
588 return $question;
589 }
590
fdd015b7
TH
591 /**
592 * Perform the necessary preprocessing for the fields added by
593 * {@link add_per_answer_fields()}.
594 * @param object $question the data being passed to the form.
595 * @return object $question the modified data.
596 */
2a6c5c52 597 protected function data_preprocessing_answers($question, $withanswerfiles = false) {
7a719748
TH
598 if (empty($question->options->answers)) {
599 return $question;
600 }
601
602 $key = 0;
eaeb6b51 603 foreach ($question->options->answers as $answer) {
2a6c5c52 604 if ($withanswerfiles) {
c7218aef 605 // Prepare the feedback editor to display files in draft area.
2a6c5c52 606 $draftitemid = file_get_submitted_draft_itemid('answer['.$key.']');
607 $question->answer[$key]['text'] = file_prepare_draft_area(
3d9645ae 608 $draftitemid, // Draftid
2a6c5c52 609 $this->context->id, // context
610 'question', // component
611 'answer', // filarea
612 !empty($answer->id) ? (int) $answer->id : null, // itemid
613 $this->fileoptions, // options
3d9645ae 614 $answer->answer // text.
2a6c5c52 615 );
616 $question->answer[$key]['itemid'] = $draftitemid;
617 $question->answer[$key]['format'] = $answer->answerformat;
618 } else {
619 $question->answer[$key] = $answer->answer;
620 }
621
7a719748
TH
622 $question->fraction[$key] = 0 + $answer->fraction;
623 $question->feedback[$key] = array();
624
625 // Evil hack alert. Formslib can store defaults in two ways for
eaeb6b51
TH
626 // repeat elements:
627 // ->_defaultValues['fraction[0]'] and
628 // ->_defaultValues['fraction'][0].
629 // The $repeatedoptions['fraction']['default'] = 0 bit above means
630 // that ->_defaultValues['fraction[0]'] has already been set, but we
631 // are using object notation here, so we will be setting
632 // ->_defaultValues['fraction'][0]. That does not work, so we have
c7218aef 633 // to unset ->_defaultValues['fraction[0]'].
f4fe3968 634 unset($this->_form->_defaultValues["fraction[{$key}]"]);
7a719748 635
c7218aef 636 // Prepare the feedback editor to display files in draft area.
7a719748
TH
637 $draftitemid = file_get_submitted_draft_itemid('feedback['.$key.']');
638 $question->feedback[$key]['text'] = file_prepare_draft_area(
3d9645ae 639 $draftitemid, // Draftid
7a719748
TH
640 $this->context->id, // context
641 'question', // component
642 'answerfeedback', // filarea
643 !empty($answer->id) ? (int) $answer->id : null, // itemid
644 $this->fileoptions, // options
3d9645ae 645 $answer->feedback // text.
7a719748
TH
646 );
647 $question->feedback[$key]['itemid'] = $draftitemid;
648 $question->feedback[$key]['format'] = $answer->feedbackformat;
649 $key++;
650 }
a68207b6
OS
651
652 // Now process extra answer fields.
653 $extraanswerfields = question_bank::get_qtype($question->qtype)->extra_answer_fields();
654 if (is_array($extraanswerfields)) {
655 // Omit table name.
656 array_shift($extraanswerfields);
657 $question = $this->data_preprocessing_extra_answer_fields($question, $extraanswerfields);
658 }
659
7a719748
TH
660 return $question;
661 }
662
a68207b6
OS
663 /**
664 * Perform the necessary preprocessing for the extra answer fields.
665 *
666 * Questions that do something not trivial when editing extra answer fields
667 * will want to override this.
668 * @param object $question the data being passed to the form.
669 * @param array $extraanswerfields extra answer fields (without table name).
670 * @return object $question the modified data.
671 */
672 protected function data_preprocessing_extra_answer_fields($question, $extraanswerfields) {
673 // Setting $question->$field[$key] won't work in PHP, so we need set an array of answer values to $question->$field.
674 // As we may have several extra fields with data for several answers in each, we use an array of arrays.
675 // Index in $extrafieldsdata is an extra answer field name, value - array of it's data for each answer.
676 $extrafieldsdata = array();
677 // First, prepare an array if empty arrays for each extra answer fields data.
678 foreach ($extraanswerfields as $field) {
679 $extrafieldsdata[$field] = array();
680 }
681
682 // Fill arrays with data from $question->options->answers.
683 $key = 0;
684 foreach ($question->options->answers as $answer) {
685 foreach ($extraanswerfields as $field) {
686 // See hack comment in {@link data_preprocessing_answers()}.
0e30442c 687 unset($this->_form->_defaultValues["{$field}[{$key}]"]);
a68207b6
OS
688 $extrafieldsdata[$field][$key] = $this->data_preprocessing_extra_answer_field($answer, $field);
689 }
690 $key++;
691 }
692
693 // Set this data in the $question object.
694 foreach ($extraanswerfields as $field) {
695 $question->$field = $extrafieldsdata[$field];
696 }
697 return $question;
698 }
699
700 /**
701 * Perfmorm preprocessing for particular extra answer field.
702 *
703 * Questions with non-trivial DB - form element relationship will
704 * want to override this.
705 * @param object $answer an answer object to get extra field from.
706 * @param string $field extra answer field name.
707 * @return field value to be set to the form.
708 */
709 protected function data_preprocessing_extra_answer_field($answer, $field) {
710 return $answer->$field;
711 }
712
fdd015b7
TH
713 /**
714 * Perform the necessary preprocessing for the fields added by
715 * {@link add_combined_feedback_fields()}.
716 * @param object $question the data being passed to the form.
717 * @return object $question the modified data.
718 */
eaeb6b51
TH
719 protected function data_preprocessing_combined_feedback($question,
720 $withshownumcorrect = false) {
c9c989a0
TH
721 if (empty($question->options)) {
722 return $question;
723 }
724
eaeb6b51
TH
725 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
726 foreach ($fields as $feedbackname) {
c9c989a0 727 $draftid = file_get_submitted_draft_itemid($feedbackname);
8b9dfc2b
TH
728 $feedback = array();
729 $feedback['text'] = file_prepare_draft_area(
3d9645ae 730 $draftid, // Draftid
c9c989a0 731 $this->context->id, // context
93cadb1e 732 'question', // component
c9c989a0
TH
733 $feedbackname, // filarea
734 !empty($question->id) ? (int) $question->id : null, // itemid
735 $this->fileoptions, // options
3d9645ae 736 $question->options->$feedbackname // text.
c9c989a0
TH
737 );
738 $feedbackformat = $feedbackname . 'format';
8b9dfc2b
TH
739 $feedback['format'] = $question->options->$feedbackformat;
740 $feedback['itemid'] = $draftid;
741
742 $question->$feedbackname = $feedback;
c9c989a0
TH
743 }
744
745 if ($withshownumcorrect) {
746 $question->shownumcorrect = $question->options->shownumcorrect;
747 }
748
749 return $question;
750 }
751
fdd015b7
TH
752 /**
753 * Perform the necessary preprocessing for the hint fields.
754 * @param object $question the data being passed to the form.
755 * @return object $question the modified data.
756 */
eaeb6b51
TH
757 protected function data_preprocessing_hints($question, $withclearwrong = false,
758 $withshownumpartscorrect = false) {
7a719748
TH
759 if (empty($question->hints)) {
760 return $question;
761 }
762
763 $key = 0;
eaeb6b51 764 foreach ($question->hints as $hint) {
7a719748
TH
765 $question->hint[$key] = array();
766
c7218aef 767 // Prepare feedback editor to display files in draft area.
7a719748
TH
768 $draftitemid = file_get_submitted_draft_itemid('hint['.$key.']');
769 $question->hint[$key]['text'] = file_prepare_draft_area(
3d9645ae 770 $draftitemid, // Draftid
7a719748
TH
771 $this->context->id, // context
772 'question', // component
773 'hint', // filarea
774 !empty($hint->id) ? (int) $hint->id : null, // itemid
775 $this->fileoptions, // options
3d9645ae 776 $hint->hint // text.
7a719748
TH
777 );
778 $question->hint[$key]['itemid'] = $draftitemid;
779 $question->hint[$key]['format'] = $hint->hintformat;
780 $key++;
7a719748 781
8b9dfc2b
TH
782 if ($withclearwrong) {
783 $question->hintclearwrong[] = $hint->clearwrong;
784 }
785 if ($withshownumpartscorrect) {
786 $question->hintshownumcorrect[] = $hint->shownumcorrect;
787 }
788 }
7a719748 789
fe6ce234
DC
790 return $question;
791 }
792
2b7da645
TH
793 public function validation($fromform, $files) {
794 $errors = parent::validation($fromform, $files);
51c5e605 795 if (empty($fromform['makecopy']) && isset($this->question->id)
eaeb6b51
TH
796 && ($this->question->formoptions->canedit ||
797 $this->question->formoptions->cansaveasnew)
51c5e605 798 && empty($fromform['usecurrentcat']) && !$this->question->formoptions->canmove) {
2b7da645
TH
799 $errors['currentgrp'] = get_string('nopermissionmove', 'question');
800 }
00cefd92 801
9275220d
SR
802 // Category.
803 if (empty($fromform['category'])) {
804 // User has provided an invalid category.
805 $errors['category'] = get_string('required');
806 }
807
00cefd92 808 // Default mark.
1aecaa3d 809 if (array_key_exists('defaultmark', $fromform) && $fromform['defaultmark'] < 0) {
00cefd92
TH
810 $errors['defaultmark'] = get_string('defaultmarkmustbepositive', 'question');
811 }
812
2b7da645
TH
813 return $errors;
814 }
815
36703ed7 816 /**
817 * Override this in the subclass to question type name.
eaeb6b51
TH
818 * @return the question type name, should be the same as the name() method
819 * in the question type class.
36703ed7 820 */
2b7da645 821 public abstract function qtype();
2a22be64 822
dff72cde
SH
823 /**
824 * Returns an array of editor options with collapsed options turned off.
0c0dfa8f 825 * @deprecated since 2.6
dff72cde
SH
826 * @return array
827 */
828 protected function get_non_collabsible_editor_options() {
0c0dfa8f
DW
829 debugging('get_non_collabsible_editor_options() is deprecated, use $this->editoroptions instead.', DEBUG_DEVELOPER);
830 return $this->editoroptions;
2a22be64 831 }
0c0dfa8f 832
36703ed7 833}