MDL-61444 question: hardFreeze tags element if no caps
[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')) {
c599a682 205 $mform->addElement('header', 'tagsheader', get_string('tags'));
4509be22 206 $mform->addElement('tags', 'tags', get_string('tags'),
b355a1c9 207 array('itemtype' => 'question', 'component' => 'core_question'));
c599a682 208
4509be22 209 if (!question_has_capability_on($this->question, 'tag')) {
1657d0b6 210 $mform->hardFreeze('tags');
4509be22
SL
211 }
212 }
213
2b7da645 214 if (!empty($this->question->id)) {
eaeb6b51
TH
215 $mform->addElement('header', 'createdmodifiedheader',
216 get_string('createdmodifiedheader', 'question'));
7f389342 217 $a = new stdClass();
2b7da645 218 if (!empty($this->question->createdby)) {
271e6dec 219 $a->time = userdate($this->question->timecreated);
eaeb6b51
TH
220 $a->user = fullname($DB->get_record(
221 'user', array('id' => $this->question->createdby)));
271e6dec 222 } else {
223 $a->time = get_string('unknown', 'question');
224 $a->user = get_string('unknown', 'question');
225 }
eaeb6b51
TH
226 $mform->addElement('static', 'created', get_string('created', 'question'),
227 get_string('byandon', 'question', $a));
2b7da645 228 if (!empty($this->question->modifiedby)) {
7f389342 229 $a = new stdClass();
271e6dec 230 $a->time = userdate($this->question->timemodified);
eaeb6b51
TH
231 $a->user = fullname($DB->get_record(
232 'user', array('id' => $this->question->modifiedby)));
233 $mform->addElement('static', 'modified', get_string('modified', 'question'),
234 get_string('byandon', 'question', $a));
271e6dec 235 }
236 }
237
72553162 238 $this->add_hidden_fields();
36703ed7 239
72553162
TH
240 $mform->addElement('hidden', 'qtype');
241 $mform->setType('qtype', PARAM_ALPHA);
fa583f5f 242
e0c41591
K
243 $mform->addElement('hidden', 'makecopy');
244 $mform->setType('makecopy', PARAM_INT);
245
375ed78a 246 $buttonarray = array();
8011be18 247 $buttonarray[] = $mform->createElement('submit', 'updatebutton',
7756e2bc 248 get_string('savechangesandcontinueediting', 'question'));
8011be18
TH
249 if ($this->can_preview()) {
250 $previewlink = $PAGE->get_renderer('core_question')->question_preview_link(
251 $this->question->id, $this->context, true);
7756e2bc 252 $buttonarray[] = $mform->createElement('static', 'previewlink', '', $previewlink);
375ed78a 253 }
7756e2bc 254
8011be18
TH
255 $mform->addGroup($buttonarray, 'updatebuttonar', '', array(' '), false);
256 $mform->closeHeaderBefore('updatebuttonar');
7756e2bc
K
257
258 $this->add_action_buttons(true, get_string('savechanges'));
271e6dec 259
435d3279 260 if ((!empty($this->question->id)) && (!($this->question->formoptions->canedit ||
eaeb6b51 261 $this->question->formoptions->cansaveasnew))) {
271e6dec 262 $mform->hardFreezeAllVisibleExcept(array('categorymoveto', 'buttonar', 'currentgrp'));
263 }
36703ed7 264 }
fa583f5f 265
36703ed7 266 /**
267 * Add any question-type specific form fields.
1d284fbd 268 *
269 * @param object $mform the form being built.
36703ed7 270 */
2b7da645 271 protected function definition_inner($mform) {
36703ed7 272 // By default, do nothing.
273 }
1d284fbd 274
8011be18
TH
275 /**
276 * Is the question being edited in a state where it can be previewed?
277 * @return bool whether to show the preview link.
278 */
279 protected function can_preview() {
280 return empty($this->question->beingcopied) && !empty($this->question->id) &&
281 $this->question->formoptions->canedit;
282 }
283
2aef1fe5 284 /**
285 * Get the list of form elements to repeat, one for each answer.
286 * @param object $mform the form being built.
287 * @param $label the label to use for each option.
288 * @param $gradeoptions the possible grades for each answer.
289 * @param $repeatedoptions reference to array of repeated options to fill
eaeb6b51
TH
290 * @param $answersoption reference to return the name of $question->options
291 * field holding an array of answers
2aef1fe5 292 * @return array of form fields.
293 */
2a6c5c52 294 protected function get_per_answer_fields($mform, $label, $gradeoptions,
eaeb6b51 295 &$repeatedoptions, &$answersoption) {
2aef1fe5 296 $repeated = array();
c7218aef
CC
297 $answeroptions = array();
298 $answeroptions[] = $mform->createElement('text', 'answer',
299 $label, array('size' => 40));
300 $answeroptions[] = $mform->createElement('select', 'fraction',
eaeb6b51 301 get_string('grade'), $gradeoptions);
c7218aef
CC
302 $repeated[] = $mform->createElement('group', 'answeroptions',
303 $label, $answeroptions, null, false);
eaeb6b51
TH
304 $repeated[] = $mform->createElement('editor', 'feedback',
305 get_string('feedback', 'question'), array('rows' => 5), $this->editoroptions);
2aef1fe5 306 $repeatedoptions['answer']['type'] = PARAM_RAW;
307 $repeatedoptions['fraction']['default'] = 0;
308 $answersoption = 'answers';
309 return $repeated;
310 }
311
312 /**
313 * Add a set of form fields, obtained from get_per_answer_fields, to the form,
314 * one for each existing answer, with some blanks for some new ones.
315 * @param object $mform the form being built.
316 * @param $label the label to use for each option.
317 * @param $gradeoptions the possible grades for each answer.
eaeb6b51
TH
318 * @param $minoptions the minimum number of answer blanks to display.
319 * Default QUESTION_NUMANS_START.
2aef1fe5 320 * @param $addoptions the number of answer blanks to add. Default QUESTION_NUMANS_ADD.
321 */
eaeb6b51
TH
322 protected function add_per_answer_fields(&$mform, $label, $gradeoptions,
323 $minoptions = QUESTION_NUMANS_START, $addoptions = QUESTION_NUMANS_ADD) {
c7218aef
CC
324 $mform->addElement('header', 'answerhdr',
325 get_string('answers', 'question'), '');
326 $mform->setExpanded('answerhdr', 1);
2aef1fe5 327 $answersoption = '';
328 $repeatedoptions = array();
eaeb6b51
TH
329 $repeated = $this->get_per_answer_fields($mform, $label, $gradeoptions,
330 $repeatedoptions, $answersoption);
2aef1fe5 331
2b7da645 332 if (isset($this->question->options)) {
c3c65f41 333 $repeatsatstart = count($this->question->options->$answersoption);
2aef1fe5 334 } else {
c3c65f41 335 $repeatsatstart = $minoptions;
2aef1fe5 336 }
337
eaeb6b51
TH
338 $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
339 'noanswers', 'addanswers', $addoptions,
c7218aef 340 $this->get_more_choices_string(), true);
55748620
TH
341 }
342
343 /**
344 * Language string to use for 'Add {no} more {whatever we call answers}'.
345 */
346 protected function get_more_choices_string() {
347 return get_string('addmorechoiceblanks', 'question');
2aef1fe5 348 }
349
2b7da645
TH
350 protected function add_combined_feedback_fields($withshownumpartscorrect = false) {
351 $mform = $this->_form;
352
eaeb6b51
TH
353 $mform->addElement('header', 'combinedfeedbackhdr',
354 get_string('combinedfeedback', 'question'));
2b7da645 355
eaeb6b51
TH
356 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
357 foreach ($fields as $feedbackname) {
086cced7
CC
358 $element = $mform->addElement('editor', $feedbackname,
359 get_string($feedbackname, 'question'),
2b7da645
TH
360 array('rows' => 5), $this->editoroptions);
361 $mform->setType($feedbackname, PARAM_RAW);
086cced7 362 // Using setValue() as setDefault() does not work for the editor class.
e0c41591 363 $element->setValue(array('text' => get_string($feedbackname.'default', 'question')));
2b7da645
TH
364
365 if ($withshownumpartscorrect && $feedbackname == 'partiallycorrectfeedback') {
f7094147 366 $mform->addElement('advcheckbox', 'shownumcorrect',
eaeb6b51 367 get_string('options', 'question'),
d5ffb789 368 get_string('shownumpartscorrectwhenfinished', 'question'));
f0a64f01 369 $mform->setDefault('shownumcorrect', true);
2b7da645
TH
370 }
371 }
372 }
373
6dbc3460
CC
374 /**
375 * Create the form elements required by one hint.
376 * @param string $withclearwrong whether this quesiton type uses the 'Clear wrong' option on hints.
377 * @param string $withshownumpartscorrect whether this quesiton type uses the 'Show num parts correct' option on hints.
378 * @return array form field elements for one hint.
379 */
2b7da645
TH
380 protected function get_hint_fields($withclearwrong = false, $withshownumpartscorrect = false) {
381 $mform = $this->_form;
382
6dbc3460 383 $repeatedoptions = array();
2b7da645 384 $repeated = array();
6dbc3460 385 $repeated[] = $mform->createElement('editor', 'hint', get_string('hintn', 'question'),
7a719748 386 array('rows' => 5), $this->editoroptions);
2b7da645
TH
387 $repeatedoptions['hint']['type'] = PARAM_RAW;
388
6dbc3460 389 $optionelements = array();
2b7da645 390 if ($withclearwrong) {
6dbc3460 391 $optionelements[] = $mform->createElement('advcheckbox', 'hintclearwrong',
eaeb6b51 392 get_string('options', 'question'), get_string('clearwrongparts', 'question'));
2b7da645
TH
393 }
394 if ($withshownumpartscorrect) {
6dbc3460 395 $optionelements[] = $mform->createElement('advcheckbox', 'hintshownumcorrect', '',
eaeb6b51 396 get_string('shownumpartscorrect', 'question'));
2b7da645
TH
397 }
398
6dbc3460
CC
399 if (count($optionelements)) {
400 $repeated[] = $mform->createElement('group', 'hintoptions',
401 get_string('hintnoptions', 'question'), $optionelements, null, false);
402 }
403
2b7da645
TH
404 return array($repeated, $repeatedoptions);
405 }
406
eaeb6b51
TH
407 protected function add_interactive_settings($withclearwrong = false,
408 $withshownumpartscorrect = false) {
2b7da645
TH
409 $mform = $this->_form;
410
eaeb6b51
TH
411 $mform->addElement('header', 'multitriesheader',
412 get_string('settingsformultipletries', 'question'));
2b7da645
TH
413
414 $penalties = array(
415 1.0000000,
416 0.5000000,
417 0.3333333,
418 0.2500000,
419 0.2000000,
420 0.1000000,
421 0.0000000
422 );
423 if (!empty($this->question->penalty) && !in_array($this->question->penalty, $penalties)) {
424 $penalties[] = $this->question->penalty;
425 sort($penalties);
426 }
427 $penaltyoptions = array();
428 foreach ($penalties as $penalty) {
f4fe3968 429 $penaltyoptions["{$penalty}"] = (100 * $penalty) . '%';
2b7da645 430 }
eaeb6b51
TH
431 $mform->addElement('select', 'penalty',
432 get_string('penaltyforeachincorrecttry', 'question'), $penaltyoptions);
068b4594 433 $mform->addHelpButton('penalty', 'penaltyforeachincorrecttry', 'question');
2b7da645
TH
434 $mform->setDefault('penalty', 0.3333333);
435
436 if (isset($this->question->hints)) {
437 $counthints = count($this->question->hints);
438 } else {
439 $counthints = 0;
440 }
441
442 if ($this->question->formoptions->repeatelements) {
443 $repeatsatstart = max(self::DEFAULT_NUM_HINTS, $counthints);
444 } else {
445 $repeatsatstart = $counthints;
446 }
447
448 list($repeated, $repeatedoptions) = $this->get_hint_fields(
449 $withclearwrong, $withshownumpartscorrect);
450 $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions,
6dbc3460 451 'numhints', 'addhint', 1, get_string('addanotherhint', 'question'), true);
2b7da645
TH
452 }
453
454 public function set_data($question) {
f9b0500f 455 question_bank::get_qtype($question->qtype)->set_default_options($question);
2b7da645 456
c7218aef 457 // Prepare question text.
fe6ce234
DC
458 $draftid = file_get_submitted_draft_itemid('questiontext');
459
460 if (!empty($question->questiontext)) {
461 $questiontext = $question->questiontext;
462 } else {
1a2de1c7
TH
463 $questiontext = $this->_form->getElement('questiontext')->getValue();
464 $questiontext = $questiontext['text'];
271ffe3f 465 }
eaeb6b51
TH
466 $questiontext = file_prepare_draft_area($draftid, $this->context->id,
467 'question', 'questiontext', empty($question->id) ? null : (int) $question->id,
468 $this->fileoptions, $questiontext);
fe6ce234
DC
469
470 $question->questiontext = array();
471 $question->questiontext['text'] = $questiontext;
eaeb6b51
TH
472 $question->questiontext['format'] = empty($question->questiontextformat) ?
473 editors_get_preferred_format() : $question->questiontextformat;
fe6ce234
DC
474 $question->questiontext['itemid'] = $draftid;
475
c7218aef 476 // Prepare general feedback.
fe6ce234
DC
477 $draftid = file_get_submitted_draft_itemid('generalfeedback');
478
479 if (empty($question->generalfeedback)) {
1a2de1c7
TH
480 $generalfeedback = $this->_form->getElement('generalfeedback')->getValue();
481 $question->generalfeedback = $generalfeedback['text'];
fe6ce234
DC
482 }
483
eaeb6b51
TH
484 $feedback = file_prepare_draft_area($draftid, $this->context->id,
485 'question', 'generalfeedback', empty($question->id) ? null : (int) $question->id,
486 $this->fileoptions, $question->generalfeedback);
fe6ce234
DC
487 $question->generalfeedback = array();
488 $question->generalfeedback['text'] = $feedback;
eaeb6b51
TH
489 $question->generalfeedback['format'] = empty($question->generalfeedbackformat) ?
490 editors_get_preferred_format() : $question->generalfeedbackformat;
fe6ce234 491 $question->generalfeedback['itemid'] = $draftid;
295043c2 492
9152f6a5 493 // Remove unnecessary trailing 0s form grade fields.
cfd24d98 494 if (isset($question->defaultgrade)) {
495 $question->defaultgrade = 0 + $question->defaultgrade;
496 }
497 if (isset($question->penalty)) {
498 $question->penalty = 0 + $question->penalty;
499 }
9152f6a5 500
295043c2 501 // Set any options.
eaeb6b51
TH
502 $extraquestionfields = question_bank::get_qtype($question->qtype)->extra_question_fields();
503 if (is_array($extraquestionfields) && !empty($question->options)) {
504 array_shift($extraquestionfields);
505 foreach ($extraquestionfields as $field) {
a8e577de 506 if (property_exists($question->options, $field)) {
8e652f02 507 $question->$field = $question->options->$field;
508 }
295043c2 509 }
510 }
c9c989a0 511
c7218aef 512 // Subclass adds data_preprocessing code here.
fe6ce234 513 $question = $this->data_preprocessing($question);
2b7da645 514
32db0d42 515 parent::set_data($question);
36703ed7 516 }
1d284fbd 517
fe6ce234 518 /**
fdd015b7
TH
519 * Perform an preprocessing needed on the data passed to {@link set_data()}
520 * before it is used to initialise the form.
521 * @param object $question the data being passed to the form.
522 * @return object $question the modified data.
fe6ce234 523 */
c7df5006 524 protected function data_preprocessing($question) {
7a719748
TH
525 return $question;
526 }
527
fdd015b7
TH
528 /**
529 * Perform the necessary preprocessing for the fields added by
530 * {@link add_per_answer_fields()}.
531 * @param object $question the data being passed to the form.
532 * @return object $question the modified data.
533 */
2a6c5c52 534 protected function data_preprocessing_answers($question, $withanswerfiles = false) {
7a719748
TH
535 if (empty($question->options->answers)) {
536 return $question;
537 }
538
539 $key = 0;
eaeb6b51 540 foreach ($question->options->answers as $answer) {
2a6c5c52 541 if ($withanswerfiles) {
c7218aef 542 // Prepare the feedback editor to display files in draft area.
2a6c5c52 543 $draftitemid = file_get_submitted_draft_itemid('answer['.$key.']');
544 $question->answer[$key]['text'] = file_prepare_draft_area(
3d9645ae 545 $draftitemid, // Draftid
2a6c5c52 546 $this->context->id, // context
547 'question', // component
548 'answer', // filarea
549 !empty($answer->id) ? (int) $answer->id : null, // itemid
550 $this->fileoptions, // options
3d9645ae 551 $answer->answer // text.
2a6c5c52 552 );
553 $question->answer[$key]['itemid'] = $draftitemid;
554 $question->answer[$key]['format'] = $answer->answerformat;
555 } else {
556 $question->answer[$key] = $answer->answer;
557 }
558
7a719748
TH
559 $question->fraction[$key] = 0 + $answer->fraction;
560 $question->feedback[$key] = array();
561
562 // Evil hack alert. Formslib can store defaults in two ways for
eaeb6b51
TH
563 // repeat elements:
564 // ->_defaultValues['fraction[0]'] and
565 // ->_defaultValues['fraction'][0].
566 // The $repeatedoptions['fraction']['default'] = 0 bit above means
567 // that ->_defaultValues['fraction[0]'] has already been set, but we
568 // are using object notation here, so we will be setting
569 // ->_defaultValues['fraction'][0]. That does not work, so we have
c7218aef 570 // to unset ->_defaultValues['fraction[0]'].
f4fe3968 571 unset($this->_form->_defaultValues["fraction[{$key}]"]);
7a719748 572
c7218aef 573 // Prepare the feedback editor to display files in draft area.
7a719748
TH
574 $draftitemid = file_get_submitted_draft_itemid('feedback['.$key.']');
575 $question->feedback[$key]['text'] = file_prepare_draft_area(
3d9645ae 576 $draftitemid, // Draftid
7a719748
TH
577 $this->context->id, // context
578 'question', // component
579 'answerfeedback', // filarea
580 !empty($answer->id) ? (int) $answer->id : null, // itemid
581 $this->fileoptions, // options
3d9645ae 582 $answer->feedback // text.
7a719748
TH
583 );
584 $question->feedback[$key]['itemid'] = $draftitemid;
585 $question->feedback[$key]['format'] = $answer->feedbackformat;
586 $key++;
587 }
a68207b6
OS
588
589 // Now process extra answer fields.
590 $extraanswerfields = question_bank::get_qtype($question->qtype)->extra_answer_fields();
591 if (is_array($extraanswerfields)) {
592 // Omit table name.
593 array_shift($extraanswerfields);
594 $question = $this->data_preprocessing_extra_answer_fields($question, $extraanswerfields);
595 }
596
7a719748
TH
597 return $question;
598 }
599
a68207b6
OS
600 /**
601 * Perform the necessary preprocessing for the extra answer fields.
602 *
603 * Questions that do something not trivial when editing extra answer fields
604 * will want to override this.
605 * @param object $question the data being passed to the form.
606 * @param array $extraanswerfields extra answer fields (without table name).
607 * @return object $question the modified data.
608 */
609 protected function data_preprocessing_extra_answer_fields($question, $extraanswerfields) {
610 // Setting $question->$field[$key] won't work in PHP, so we need set an array of answer values to $question->$field.
611 // As we may have several extra fields with data for several answers in each, we use an array of arrays.
612 // Index in $extrafieldsdata is an extra answer field name, value - array of it's data for each answer.
613 $extrafieldsdata = array();
614 // First, prepare an array if empty arrays for each extra answer fields data.
615 foreach ($extraanswerfields as $field) {
616 $extrafieldsdata[$field] = array();
617 }
618
619 // Fill arrays with data from $question->options->answers.
620 $key = 0;
621 foreach ($question->options->answers as $answer) {
622 foreach ($extraanswerfields as $field) {
623 // See hack comment in {@link data_preprocessing_answers()}.
0e30442c 624 unset($this->_form->_defaultValues["{$field}[{$key}]"]);
a68207b6
OS
625 $extrafieldsdata[$field][$key] = $this->data_preprocessing_extra_answer_field($answer, $field);
626 }
627 $key++;
628 }
629
630 // Set this data in the $question object.
631 foreach ($extraanswerfields as $field) {
632 $question->$field = $extrafieldsdata[$field];
633 }
634 return $question;
635 }
636
637 /**
638 * Perfmorm preprocessing for particular extra answer field.
639 *
640 * Questions with non-trivial DB - form element relationship will
641 * want to override this.
642 * @param object $answer an answer object to get extra field from.
643 * @param string $field extra answer field name.
644 * @return field value to be set to the form.
645 */
646 protected function data_preprocessing_extra_answer_field($answer, $field) {
647 return $answer->$field;
648 }
649
fdd015b7
TH
650 /**
651 * Perform the necessary preprocessing for the fields added by
652 * {@link add_combined_feedback_fields()}.
653 * @param object $question the data being passed to the form.
654 * @return object $question the modified data.
655 */
eaeb6b51
TH
656 protected function data_preprocessing_combined_feedback($question,
657 $withshownumcorrect = false) {
c9c989a0
TH
658 if (empty($question->options)) {
659 return $question;
660 }
661
eaeb6b51
TH
662 $fields = array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback');
663 foreach ($fields as $feedbackname) {
c9c989a0 664 $draftid = file_get_submitted_draft_itemid($feedbackname);
8b9dfc2b
TH
665 $feedback = array();
666 $feedback['text'] = file_prepare_draft_area(
3d9645ae 667 $draftid, // Draftid
c9c989a0 668 $this->context->id, // context
93cadb1e 669 'question', // component
c9c989a0
TH
670 $feedbackname, // filarea
671 !empty($question->id) ? (int) $question->id : null, // itemid
672 $this->fileoptions, // options
3d9645ae 673 $question->options->$feedbackname // text.
c9c989a0
TH
674 );
675 $feedbackformat = $feedbackname . 'format';
8b9dfc2b
TH
676 $feedback['format'] = $question->options->$feedbackformat;
677 $feedback['itemid'] = $draftid;
678
679 $question->$feedbackname = $feedback;
c9c989a0
TH
680 }
681
682 if ($withshownumcorrect) {
683 $question->shownumcorrect = $question->options->shownumcorrect;
684 }
685
686 return $question;
687 }
688
fdd015b7
TH
689 /**
690 * Perform the necessary preprocessing for the hint fields.
691 * @param object $question the data being passed to the form.
692 * @return object $question the modified data.
693 */
eaeb6b51
TH
694 protected function data_preprocessing_hints($question, $withclearwrong = false,
695 $withshownumpartscorrect = false) {
7a719748
TH
696 if (empty($question->hints)) {
697 return $question;
698 }
699
700 $key = 0;
eaeb6b51 701 foreach ($question->hints as $hint) {
7a719748
TH
702 $question->hint[$key] = array();
703
c7218aef 704 // Prepare feedback editor to display files in draft area.
7a719748
TH
705 $draftitemid = file_get_submitted_draft_itemid('hint['.$key.']');
706 $question->hint[$key]['text'] = file_prepare_draft_area(
3d9645ae 707 $draftitemid, // Draftid
7a719748
TH
708 $this->context->id, // context
709 'question', // component
710 'hint', // filarea
711 !empty($hint->id) ? (int) $hint->id : null, // itemid
712 $this->fileoptions, // options
3d9645ae 713 $hint->hint // text.
7a719748
TH
714 );
715 $question->hint[$key]['itemid'] = $draftitemid;
716 $question->hint[$key]['format'] = $hint->hintformat;
717 $key++;
7a719748 718
8b9dfc2b
TH
719 if ($withclearwrong) {
720 $question->hintclearwrong[] = $hint->clearwrong;
721 }
722 if ($withshownumpartscorrect) {
723 $question->hintshownumcorrect[] = $hint->shownumcorrect;
724 }
725 }
7a719748 726
fe6ce234
DC
727 return $question;
728 }
729
2b7da645
TH
730 public function validation($fromform, $files) {
731 $errors = parent::validation($fromform, $files);
51c5e605 732 if (empty($fromform['makecopy']) && isset($this->question->id)
eaeb6b51
TH
733 && ($this->question->formoptions->canedit ||
734 $this->question->formoptions->cansaveasnew)
51c5e605 735 && empty($fromform['usecurrentcat']) && !$this->question->formoptions->canmove) {
2b7da645
TH
736 $errors['currentgrp'] = get_string('nopermissionmove', 'question');
737 }
00cefd92 738
9275220d
SR
739 // Category.
740 if (empty($fromform['category'])) {
741 // User has provided an invalid category.
742 $errors['category'] = get_string('required');
743 }
744
00cefd92 745 // Default mark.
1aecaa3d 746 if (array_key_exists('defaultmark', $fromform) && $fromform['defaultmark'] < 0) {
00cefd92
TH
747 $errors['defaultmark'] = get_string('defaultmarkmustbepositive', 'question');
748 }
749
2b7da645
TH
750 return $errors;
751 }
752
36703ed7 753 /**
754 * Override this in the subclass to question type name.
eaeb6b51
TH
755 * @return the question type name, should be the same as the name() method
756 * in the question type class.
36703ed7 757 */
2b7da645 758 public abstract function qtype();
2a22be64 759
dff72cde
SH
760 /**
761 * Returns an array of editor options with collapsed options turned off.
0c0dfa8f 762 * @deprecated since 2.6
dff72cde
SH
763 * @return array
764 */
765 protected function get_non_collabsible_editor_options() {
0c0dfa8f
DW
766 debugging('get_non_collabsible_editor_options() is deprecated, use $this->editoroptions instead.', DEBUG_DEVELOPER);
767 return $this->editoroptions;
2a22be64 768 }
0c0dfa8f 769
36703ed7 770}