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