MDL-33653 questions, a way to save changes and continue editing
[moodle.git] / question / type / calculatedmulti / edit_calculatedmulti_form.php
CommitLineData
2d279432 1<?php
d3603157
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
2d279432 17/**
d3603157 18 * Defines the editing form for calculated multiple-choice questions.
2d279432 19 *
b04a4319 20 * @package qtype
d3603157 21 * @subpackage calculatedmulti
b04a4319
TH
22 * @copyright 2007 Jamie Pratt me@jamiep.org
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2d279432
PP
24 */
25
d3603157 26
a17b297d
TH
27defined('MOODLE_INTERNAL') || die();
28
29
2d279432 30/**
d3603157 31 * Calculated multiple-choice question editing form.
b04a4319
TH
32 *
33 * @copyright 2007 Jamie Pratt me@jamiep.org
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2d279432 35 */
29b68914 36class qtype_calculatedmulti_edit_form extends question_edit_form {
2d279432
PP
37 /**
38 * Handle to the question type for this question.
39 *
40 * @var question_calculatedmulti_qtype
41 */
fe6ce234 42 public $qtypeobj;
29b68914 43 public $questiondisplay;
d90b016b 44 public $initialname = '';
29b68914 45 public $reload = false;
cdece95e 46
29b68914
TH
47 public function __construct($submiturl, $question, $category,
48 $contexts, $formeditable = true) {
2d279432 49 $this->question = $question;
cdece95e 50 $this->qtypeobj = question_bank::get_qtype('calculatedmulti');
7d087744 51 $this->reload = optional_param('reload', false, PARAM_BOOL);
29b68914 52 if (!$this->reload) {
c7218aef 53 // Use database data as this is first pass.
29b68914 54 if (isset($this->question->id)) {
c7218aef 55 // Remove prefix #{..}# if exists.
29b68914 56 $this->initialname = $question->name;
d90b016b 57 $regs= array();
29b68914 58 if (preg_match('~#\{([^[:space:]]*)#~', $question->name , $regs)) {
d90b016b 59 $question->name = str_replace($regs[0], '', $question->name);
fe6ce234 60 };
d90b016b 61 }
fe6ce234 62 }
29b68914 63 parent::__construct($submiturl, $question, $category, $contexts, $formeditable);
2d279432
PP
64 }
65
29b68914
TH
66 public function get_per_answer_fields($mform, $label, $gradeoptions,
67 &$repeatedoptions, &$answersoption) {
fe6ce234 68 $repeated = array();
c7218aef
CC
69 $answeroptions = array();
70 $answeroptions[] = $mform->createElement('text', 'answer',
71 $label, array('size' => 50));
72 $answeroptions[] = $mform->createElement('select', 'fraction',
29b68914 73 get_string('grade'), $gradeoptions);
c7218aef
CC
74 $repeated[] = $mform->createElement('group', 'answeroptions',
75 $label, $answeroptions, null, false);
76
77 // Added answeroptions help button in definition_inner() after called to add_per_answer_fields.
78
2d279432
PP
79 $repeatedoptions['answer']['type'] = PARAM_RAW;
80 $repeatedoptions['fraction']['default'] = 0;
81 $answersoption = 'answers';
82
83 $mform->setType('answer', PARAM_NOTAGS);
84
c3f21ec5
CC
85 $repeated[] = $mform->createElement('hidden', 'tolerance');
86 $repeated[] = $mform->createElement('hidden', 'tolerancetype', 1);
61cca0b7 87 $repeatedoptions['tolerance']['type'] = PARAM_FLOAT;
2d279432 88 $repeatedoptions['tolerance']['default'] = 0.01;
dfd89b0b 89 $repeatedoptions['tolerancetype']['type'] = PARAM_INT;
2d279432 90
c7218aef
CC
91 // Create display group.
92 $answerdisplay = array();
93 $answerdisplay[] = $mform->createElement('select', 'correctanswerlength',
94 get_string('answerdisplay', 'qtype_calculated'), range(0, 9));
2d279432
PP
95 $repeatedoptions['correctanswerlength']['default'] = 2;
96
29b68914
TH
97 $answerlengthformats = array(
98 '1' => get_string('decimalformat', 'qtype_numerical'),
99 '2' => get_string('significantfiguresformat', 'qtype_calculated')
100 );
c7218aef 101 $answerdisplay[] = $mform->createElement('select', 'correctanswerformat',
29b68914 102 get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
c7218aef
CC
103 $repeated[] = $mform->createElement('group', 'answerdisplay',
104 get_string('answerdisplay', 'qtype_calculated'), $answerdisplay, null, false);
105
106 // Add feedback.
107 $repeated[] = $mform->createElement('editor', 'feedback',
108 get_string('feedback', 'question'), null, $this->editoroptions);
2d279432
PP
109
110 return $repeated;
111 }
112
c7df5006 113 protected function definition_inner($mform) {
29b68914
TH
114
115 $label = get_string('sharedwildcards', 'qtype_calculated');
2d279432 116 $mform->addElement('hidden', 'initialcategory', 1);
d90b016b 117 $mform->addElement('hidden', 'reload', 1);
2d279432 118 $mform->setType('initialcategory', PARAM_INT);
dfd89b0b 119 $mform->setType('reload', PARAM_BOOL);
2d279432 120
29b68914
TH
121 $html2 = '';
122 $mform->insertElementBefore(
123 $mform->createElement('static', 'listcategory', $label, $html2), 'name');
124 if (isset($this->question->id)) {
125 $mform->insertElementBefore($mform->createElement('static', 'initialname',
126 get_string('questionstoredname', 'qtype_calculated'),
127 $this->initialname), 'name');
d90b016b 128 };
29b68914
TH
129 $addfieldsname = 'updatecategory';
130 $addstring = get_string('updatecategory', 'qtype_calculated');
fe6ce234 131 $mform->registerNoSubmitButton($addfieldsname);
29b68914 132 $this->editasmultichoice = 1;
2d279432 133
29b68914
TH
134 $mform->insertElementBefore(
135 $mform->createElement('submit', $addfieldsname, $addstring), 'listcategory');
2d279432 136 $mform->registerNoSubmitButton('createoptionbutton');
29b68914 137 $mform->addElement('hidden', 'multichoice', $this->editasmultichoice);
fe6ce234 138 $mform->setType('multichoice', PARAM_INT);
2d279432 139
29b68914
TH
140 $menu = array(get_string('answersingleno', 'qtype_multichoice'),
141 get_string('answersingleyes', 'qtype_multichoice'));
142 $mform->addElement('select', 'single',
143 get_string('answerhowmany', 'qtype_multichoice'), $menu);
fe6ce234
DC
144 $mform->setDefault('single', 1);
145
29b68914
TH
146 $mform->addElement('advcheckbox', 'shuffleanswers',
147 get_string('shuffleanswers', 'qtype_multichoice'), null, null, array(0, 1));
ed14ad02 148 $mform->addHelpButton('shuffleanswers', 'shuffleanswers', 'qtype_multichoice');
fe6ce234
DC
149 $mform->setDefault('shuffleanswers', 1);
150
cdece95e 151 $numberingoptions = question_bank::get_qtype('multichoice')->get_numbering_styles();
29b68914 152 $mform->addElement('select', 'answernumbering',
cdece95e 153 get_string('answernumbering', 'qtype_multichoice'), $numberingoptions);
fe6ce234 154 $mform->setDefault('answernumbering', 'abc');
2d279432 155
fe6ce234 156 $this->add_per_answer_fields($mform, get_string('choiceno', 'qtype_multichoice', '{no}'),
92111e8d 157 question_bank::fraction_options_full(), max(5, QUESTION_NUMANS_START));
c7218aef 158 $mform->addHelpButton('answeroptions[0]', 'answeroptions', 'qtype_calculatedmulti');
2d279432
PP
159
160 $repeated = array();
fe6ce234
DC
161 $nounits = optional_param('nounits', 1, PARAM_INT);
162 $mform->addElement('hidden', 'nounits', $nounits);
163 $mform->setType('nounits', PARAM_INT);
164 $mform->setConstants(array('nounits'=>$nounits));
29b68914
TH
165 for ($i = 0; $i < $nounits; $i++) {
166 $mform->addElement('hidden', 'unit'."[$i]",
7d087744 167 optional_param("unit[$i]", '', PARAM_NOTAGS));
fe6ce234 168 $mform->setType('unit'."[$i]", PARAM_NOTAGS);
29b68914 169 $mform->addElement('hidden', 'multiplier'."[$i]",
61cca0b7
RT
170 optional_param("multiplier[$i]", '', PARAM_FLOAT));
171 $mform->setType("multiplier[$i]", PARAM_FLOAT);
fe6ce234 172 }
2d279432 173
b130270d
TH
174 $this->add_combined_feedback_fields(true);
175 $mform->disabledIf('shownumcorrect', 'single', 'eq', 1);
176
177 $this->add_interactive_settings(true, true);
178
c7218aef 179 // Hidden elements.
2d279432
PP
180 $mform->addElement('hidden', 'synchronize', '');
181 $mform->setType('synchronize', PARAM_INT);
29b68914
TH
182 if (isset($this->question->options) && isset($this->question->options->synchronize)) {
183 $mform->setDefault('synchronize', $this->question->options->synchronize);
2d279432 184 } else {
29b68914 185 $mform->setDefault('synchronize', 0);
2d279432
PP
186 }
187 $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
188 $mform->setType('wizard', PARAM_ALPHA);
2d279432
PP
189 }
190
29b68914 191 public function data_preprocessing($question) {
5cf69d7f 192 $question = parent::data_preprocessing($question);
0cba6a8d 193 $question = $this->data_preprocessing_answers($question, false);
5cf69d7f
TH
194 $question = $this->data_preprocessing_combined_feedback($question, true);
195 $question = $this->data_preprocessing_hints($question, true, true);
196
29b68914 197 if (isset($question->options)) {
5cf69d7f
TH
198 $question->synchronize = $question->options->synchronize;
199 $question->single = $question->options->single;
200 $question->answernumbering = $question->options->answernumbering;
201 $question->shuffleanswers = $question->options->shuffleanswers;
fe6ce234 202 }
5cf69d7f
TH
203
204 return $question;
205 }
206
072db71c
PS
207 protected function data_preprocessing_answers($question, $withanswerfiles = false) {
208 $question = parent::data_preprocessing_answers($question, $withanswerfiles);
5cf69d7f
TH
209 if (empty($question->options->answers)) {
210 return $question;
fe6ce234 211 }
5cf69d7f
TH
212
213 $key = 0;
214 foreach ($question->options->answers as $answer) {
215 // See comment in the parent method about this hack.
216 unset($this->_form->_defaultValues["tolerance[$key]"]);
217 unset($this->_form->_defaultValues["tolerancetype[$key]"]);
218 unset($this->_form->_defaultValues["correctanswerlength[$key]"]);
219 unset($this->_form->_defaultValues["correctanswerformat[$key]"]);
220
221 $question->tolerance[$key] = $answer->tolerance;
222 $question->tolerancetype[$key] = $answer->tolerancetype;
223 $question->correctanswerlength[$key] = $answer->correctanswerlength;
224 $question->correctanswerformat[$key] = $answer->correctanswerformat;
225 $key++;
2d279432 226 }
5cf69d7f 227
fe6ce234 228 return $question;
2d279432
PP
229 }
230
29b68914 231 public function validation($data, $files) {
2d279432 232 $errors = parent::validation($data, $files);
29b68914 233
c7218aef 234 // Verifying for errors in {=...} in question text.
29b68914 235 $qtext = '';
fe6ce234
DC
236 $qtextremaining = $data['questiontext']['text'];
237 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
238 foreach ($possibledatasets as $name => $value) {
2d279432
PP
239 $qtextremaining = str_replace('{'.$name.'}', '1', $qtextremaining);
240 }
29b68914 241
fe6ce234 242 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
2d279432 243 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
29b68914 244 $qtext = $qtext.$qtextsplits[0];
2d279432 245 $qtextremaining = $qtextsplits[1];
29b68914
TH
246 if (!empty($regs1[1]) && $formulaerrors =
247 qtype_calculated_find_formula_errors($regs1[1])) {
248 if (!isset($errors['questiontext'])) {
249 $errors['questiontext'] = $formulaerrors.':'.$regs1[1];
250 } else {
2d279432
PP
251 $errors['questiontext'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
252 }
253 }
254 }
255 $answers = $data['answer'];
256 $answercount = 0;
257 $maxgrade = false;
fe6ce234 258 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
2d279432 259 $mandatorydatasets = array();
29b68914 260 foreach ($answers as $key => $answer) {
2d279432
PP
261 $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
262 }
29b68914
TH
263 if (count($mandatorydatasets) == 0) {
264 foreach ($answers as $key => $answer) {
11a66e2c 265 $errors['answeroptions['.$key.']'] =
efe3e87b 266 get_string('atleastonewildcard', 'qtype_calculated');
2d279432
PP
267 }
268 }
0cba6a8d 269 $totalfraction = 0;
270 $maxfraction = -1;
271 foreach ($answers as $key => $answer) {
272 $trimmedanswer = trim($answer);
273 $fraction = (float) $data['fraction'][$key];
274 if (empty($trimmedanswer) && $trimmedanswer != '0' && empty($fraction)) {
275 continue;
276 }
277 if (empty($trimmedanswer)) {
11a66e2c 278 $errors['answeroptions['.$key.']'] = get_string('errgradesetanswerblank', 'qtype_multichoice');
0cba6a8d 279 }
280 if ($trimmedanswer != '' || $answercount == 0) {
c7218aef 281 // Verifying for errors in {=...} in answer text.
0cba6a8d 282 $qanswer = '';
283 $qanswerremaining = $trimmedanswer;
284 $possibledatasets = $this->qtypeobj->find_dataset_names($trimmedanswer);
285 foreach ($possibledatasets as $name => $value) {
286 $qanswerremaining = str_replace('{'.$name.'}', '1', $qanswerremaining);
287 }
29b68914 288
0cba6a8d 289 while (preg_match('~\{=([^[:space:]}]*)}~', $qanswerremaining, $regs1)) {
290 $qanswersplits = explode($regs1[0], $qanswerremaining, 2);
291 $qanswer = $qanswer . $qanswersplits[0];
292 $qanswerremaining = $qanswersplits[1];
293 if (!empty($regs1[1]) && $formulaerrors =
294 qtype_calculated_find_formula_errors($regs1[1])) {
11a66e2c
CC
295 if (!isset($errors['answeroptions['.$key.']'])) {
296 $errors['answeroptions['.$key.']'] = $formulaerrors.':'.$regs1[1];
0cba6a8d 297 } else {
11a66e2c 298 $errors['answeroptions['.$key.']'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
2d279432
PP
299 }
300 }
301 }
0cba6a8d 302 }
303 if ($trimmedanswer != '') {
304 if ('2' == $data['correctanswerformat'][$key] &&
305 '0' == $data['correctanswerlength'][$key]) {
306 $errors['correctanswerlength['.$key.']'] =
307 get_string('zerosignificantfiguresnotallowed', 'qtype_calculated');
2d279432 308 }
0cba6a8d 309 if (!is_numeric($data['tolerance'][$key])) {
310 $errors['tolerance['.$key.']'] =
55748620 311 get_string('xmustbenumeric', 'qtype_numerical',
c4b2600d 312 get_string('acceptederror', 'qtype_numerical'));
fe6ce234 313 }
0cba6a8d 314 if ($data['fraction'][$key] > 0) {
315 $totalfraction += $data['fraction'][$key];
2d279432 316 }
0cba6a8d 317 if ($data['fraction'][$key] > $maxfraction) {
318 $maxfraction = $data['fraction'][$key];
2d279432 319 }
0cba6a8d 320
321 $answercount++;
2d279432 322 }
0cba6a8d 323 }
324 if ($answercount == 0) {
11a66e2c
CC
325 $errors['answeroptions[0]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
326 $errors['answeroptions[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
0cba6a8d 327 } else if ($answercount == 1) {
11a66e2c 328 $errors['answeroptions[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
fe6ce234 329
0cba6a8d 330 }
c7218aef 331 // Perform sanity checks on fractional grades.
0cba6a8d 332 if ($data['single']== 1 ) {
333 if ($maxfraction != 1) {
11a66e2c 334 $errors['answeroptions[0]'] = get_string('errfractionsnomax', 'qtype_multichoice',
0cba6a8d 335 $maxfraction * 100);
2d279432 336 }
0cba6a8d 337 } else {
338 $totalfraction = round($totalfraction, 2);
339 if ($totalfraction != 1) {
340 $totalfraction = $totalfraction * 100;
11a66e2c 341 $errors['answeroptions[0]'] =
0cba6a8d 342 get_string('errfractionsaddwrong', 'qtype_multichoice', $totalfraction);
2d279432 343 }
2d279432
PP
344 }
345 return $errors;
346 }
cdece95e
TH
347
348 public function qtype() {
349 return 'calculatedmulti';
350 }
2d279432 351}