Updated the HEAD build version to 20090925
[moodle.git] / question / type / calculated / edit_calculated_form.php
CommitLineData
4d41f4ee 1<?php // $Id$
271ffe3f 2/**
3 * Defines the editing form for the calculated question type.
4 *
5 * @copyright &copy; 2007 Jamie Pratt
6 * @author Jamie Pratt me@jamiep.org
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
9e20fbc2 8 * @package questionbank
9 * @subpackage questiontypes
271ffe3f 10 */
11
12/**
13 * calculated editing form definition.
14 */
15class question_edit_calculated_form extends question_edit_form {
9aa022fe 16 /**
17 * Handle to the question type for this question.
18 *
19 * @var question_calculated_qtype
20 */
21 var $qtypeobj;
2aef1fe5 22
28a27ef1 23 /**
24 * Get the list of form elements to repeat, one for each answer.
25 * @param object $mform the form being built.
26 * @param $label the label to use for each option.
27 * @param $gradeoptions the possible grades for each answer.
28 * @param $repeatedoptions reference to array of repeated options to fill
29 * @param $answersoption reference to return the name of $question->options field holding an array of answers
30 * @return array of form fields.
31 */
32 /* function get_per_answer_fields(&$mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) {
33 $repeated = array();
34 $repeated[] =& $mform->createElement('header', 'answerhdr', $label);
35 $repeated[] =& $mform->createElement('text', 'answer', get_string('answer', 'quiz'), array('size' => 50));
36 $repeated[] =& $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions);
37 $repeated[] =& $mform->createElement('htmleditor', 'feedback', get_string('feedback', 'quiz'),
38 array('course' => $this->coursefilesid));
39 $repeatedoptions['answer']['type'] = PARAM_RAW;
40 $repeatedoptions['fraction']['default'] = 0;
41 $answersoption = 'answers';
42 return $repeated;
43 }*/
2aef1fe5 44 function get_per_answer_fields(&$mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) {
28a27ef1 45 // $repeated = parent::get_per_answer_fields($mform, $label, $gradeoptions, $repeatedoptions, $answersoption);
46 $repeated = array();
47 $repeated[] =& $mform->createElement('header', 'answerhdr', $label);
48 // if ($this->editasmultichoice == 1){
49 $repeated[] =& $mform->createElement('text', 'answer', get_string('answer', 'quiz'), array('size' => 50));
50 $repeated[] =& $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions);
51 $repeated[] =& $mform->createElement('htmleditor', 'feedback', get_string('feedback', 'quiz'),
52 array('course' => $this->coursefilesid));
53 $repeatedoptions['answer']['type'] = PARAM_RAW;
54 $repeatedoptions['fraction']['default'] = 0;
55 $answersoption = 'answers';
56
2aef1fe5 57 $mform->setType('answer', PARAM_NOTAGS);
58
59 $addrepeated = array();
28a27ef1 60 if ($this->editasmultichoice == 1){
61 $addrepeated[] =& $mform->createElement('hidden', 'tolerance');
62 $addrepeated[] =& $mform->createElement('hidden', 'tolerancetype');
63 }else {
64 $addrepeated[] =& $mform->createElement('text', 'tolerance', get_string('tolerance', 'qtype_calculated'));
65 $addrepeated[] =& $mform->createElement('select', 'tolerancetype', get_string('tolerancetype', 'quiz'), $this->qtypeobj->tolerance_types());
66 }
2aef1fe5 67 $repeatedoptions['tolerance']['type'] = PARAM_NUMBER;
68 $repeatedoptions['tolerance']['default'] = 0.01;
2aef1fe5 69
70 $addrepeated[] =& $mform->createElement('select', 'correctanswerlength', get_string('correctanswershows', 'qtype_calculated'), range(0, 9));
71 $repeatedoptions['correctanswerlength']['default'] = 2;
72
73 $answerlengthformats = array('1' => get_string('decimalformat', 'quiz'), '2' => get_string('significantfiguresformat', 'quiz'));
74 $addrepeated[] =& $mform->createElement('select', 'correctanswerformat', get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
75 array_splice($repeated, 3, 0, $addrepeated);
28a27ef1 76 if ($this->editasmultichoice == 1){
77 $repeated[1]->setLabel('...<strong>{={x}+..}</strong>...');
78 }else {
79 $repeated[1]->setLabel(get_string('correctanswerformula', 'quiz').'=');
80
81 }
2aef1fe5 82
83 return $repeated;
84 }
85
271ffe3f 86 /**
87 * Add question-type specific form fields.
88 *
9aa022fe 89 * @param MoodleQuickForm $mform the form being built.
271ffe3f 90 */
91 function definition_inner(&$mform) {
9aa022fe 92 global $QTYPES;
92186abc 93 $this->qtypeobj =& $QTYPES[$this->qtype()];
28a27ef1 94 // echo code left for testing period
95 // echo "<p>question ".optional_param('multichoice', '', PARAM_RAW)." optional<pre>";print_r($this->question);echo "</pre></p>";
a6d46515 96 $label = get_string("sharedwildcards", "qtype_datasetdependent");
97 $mform->addElement('hidden', 'initialcategory', 1);
98 $html2 = $this->qtypeobj->print_dataset_definitions_category($this->question);
99 $mform->insertElementBefore($mform->createElement('static','listcategory',$label,$html2),'name');
100 $addfieldsname='updatecategory';
101 $addstring=get_string("updatecategory", "qtype_calculated");
102 $mform->registerNoSubmitButton($addfieldsname);
28a27ef1 103 $this->editasmultichoice = 0 ;
104 if ( isset($this->question->options->multichoice) && $this->question->options->multichoice == '1'){
105 $this->editasmultichoice = 1 ;
106 }else {
107 if ( !isset($this->question->id ) && '' != optional_param('createoptionbutton', '', PARAM_RAW) && 1 == optional_param('multichoice', '', PARAM_RAW)){
108 $this->editasmultichoice = 1 ;
109 }
110 if ( !isset($this->question->id )== 0 && '' != optional_param('createoptionbutton', '', PARAM_RAW) && 0 == optional_param('multichoice', '', PARAM_RAW)){
111 $this->editasmultichoice = 0 ;
112 }
113 }
114
115 /* if ( '' != optional_param('changetomultichoice', '', PARAM_RAW)){
116 $this->editasmultichoice = 1 ;
117 }
118 if ( '' != optional_param('changetocalculated', '', PARAM_RAW)){
119 $this->editasmultichoice = 0 ;
120 }*/
271e6dec 121
a6d46515 122 $mform->insertElementBefore( $mform->createElement('submit', $addfieldsname, $addstring),'listcategory');
28a27ef1 123 $mform->registerNoSubmitButton('createoptionbutton');
124
125 if(!isset($this->question->id ) ){
126 $mform->addElement('header', 'choicehdr',get_string('Choosingcreationmode', 'qtype_calculated'));
127 $createoptions = Array();
128
129 $createoptions['0']=get_string('Regularcalculated', 'qtype_calculated');
130 $createoptions['1']=get_string('Multiplechoicecalculated', 'qtype_calculated');
131 $addgrp1 = array();
132 $addgrp1[] =& $mform->createElement('submit', 'createoptionbutton', get_string('Createas', 'qtype_calculatedsimple'));
133 $addgrp1[] =& $mform->createElement('select', "multichoice",'' , $createoptions);
134 $mform->addGroup($addgrp1, 'addgrp1', '', ' ', false);
135 }else {
136 $mform->addElement('hidden', 'multichoice',$this->editasmultichoice);
137 }
138
139 if ($this->editasmultichoice == 1){
140 $mform->addElement('header', 'choicehdr',get_string('multichoicecalculatedquestion', 'qtype_calculated'));
141 $menu = array(get_string('answersingleno', 'qtype_multichoice'), get_string('answersingleyes', 'qtype_multichoice'));
142 $mform->addElement('select', 'single', get_string('answerhowmany', 'qtype_multichoice'), $menu);
143 $mform->setDefault('single', 1);
144
145 $mform->addElement('advcheckbox', 'shuffleanswers', get_string('shuffleanswers', 'qtype_multichoice'), null, null, array(0,1));
146 $mform->setHelpButton('shuffleanswers', array('multichoiceshuffle', get_string('shuffleanswers','qtype_multichoice'), 'qtype_multichoice'));
147 $mform->setDefault('shuffleanswers', 1);
148
149 $numberingoptions = $QTYPES['multichoice']->get_numbering_styles();
150 $menu = array();
151 foreach ($numberingoptions as $numberingoption) {
152 $menu[$numberingoption] = get_string('answernumbering' . $numberingoption, 'qtype_multichoice');
153 }
154 $mform->addElement('select', 'answernumbering', get_string('answernumbering', 'qtype_multichoice'), $menu);
155 $mform->setDefault('answernumbering', 'abc');
156 }else { //editing as regular
157 $mform->addElement('header', 'choicehdr', get_string('regularcalculatedquestion', 'qtype_calculated'));
158 $mform->addElement('hidden','single', '1');
159 $mform->addElement('hidden','shuffleanswers', '1');
160 $mform->addElement('hidden','answernumbering', 'abc');
161 }
271ffe3f 162
271ffe3f 163 $creategrades = get_grade_options();
28a27ef1 164 if ($this->editasmultichoice == 1){
165 $this->add_per_answer_fields($mform, get_string('choiceno', 'qtype_multichoice', '{no}'),
166 $creategrades->gradeoptionsfull, max(5, QUESTION_NUMANS_START));
167 }else{
168 $this->add_per_answer_fields($mform, get_string('answerhdr', 'qtype_calculated', '{no}'),
2aef1fe5 169 $creategrades->gradeoptions, 1, 1);
28a27ef1 170 }
171
92186abc 172
271e6dec 173 $repeated = array();
28a27ef1 174 if ($this->editasmultichoice == 1){
175 $nounits = optional_param('nounits', 1, PARAM_INT);
176 $mform->addElement('hidden', 'nounits', $nounits);
177 $mform->setConstants(array('nounits'=>$nounits));
178 for ($i=0; $i< $nounits; $i++) {
179 $mform->addElement('hidden','unit'."[$i]", optional_param('unit'."[$i]", '', PARAM_NOTAGS));
180 $mform->addElement('hidden', 'multiplier'."[$i]", optional_param('multiplier'."[$i]", '', PARAM_NUMBER));
181 }
271ffe3f 182
28a27ef1 183 }else {
184 $repeated[] =& $mform->createElement('header', 'unithdr', get_string('unithdr', 'qtype_numerical', '{no}'));
185 $repeated[] =& $mform->createElement('text', 'unit', get_string('unit', 'quiz'));
186 $repeated[] =& $mform->createElement('text', 'multiplier', get_string('multiplier', 'quiz'));
187
3a298174 188 $mform->setType('unit', PARAM_NOTAGS);
271ffe3f 189
3a298174 190 $mform->setType('multiplier', PARAM_NUMBER);
9aa022fe 191
192 if (isset($this->question->options)){
193 $countunits = count($this->question->options->units);
194 } else {
195 $countunits = 0;
196 }
271e6dec 197 if ($this->question->formoptions->repeatelements){
198 $repeatsatstart = $countunits + 1;
199 } else {
200 $repeatsatstart = $countunits;
201 }
3a298174 202 $this->repeat_elements($repeated, $repeatsatstart, array(), 'nounits', 'addunits', 2, get_string('addmoreunitblanks', 'qtype_calculated', '{no}'));
271ffe3f 203
28a27ef1 204 }
79bb7202 205 if ($mform->elementExists('multiplier[0]')){
206 $firstunit =& $mform->getElement('multiplier[0]');
207 $firstunit->freeze();
208 $firstunit->setValue('1.0');
209 $firstunit->setPersistantFreeze(true);
210 }
28a27ef1 211 if ($this->editasmultichoice == 1){
212 $mform->setType('addunits','hidden');
213 $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'qtype_multichoice'));
214
215 foreach (array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback') as $feedbackname) {
216 $mform->addElement('htmleditor', $feedbackname, get_string($feedbackname, 'qtype_multichoice'),
217 array('course' => $this->coursefilesid));
218 $mform->setType($feedbackname, PARAM_RAW);
219 }
220 }else {
221 foreach (array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback') as $feedbackname) {
222 $mform->addElement('hidden', $feedbackname);
223 $mform->setType($feedbackname, PARAM_RAW);
224 }
225 }
9aa022fe 226 //hidden elements
e593233a 227 $mform->addElement('hidden', 'synchronize', '');
228 if (isset($this->question->options)&& isset($this->question->options->synchronize) ){
229 $mform->setDefault("synchronize", $this->question->options->synchronize);
230 } else {
231 $mform->setDefault("synchronize", 0 );
232 }
60b5ecd3 233 $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
234 $mform->setType('wizard', PARAM_ALPHA);
92186abc 235
271ffe3f 236
237 }
238
32db0d42 239 function set_data($question) {
28a27ef1 240 if (isset($this->editasmultichoice)){
241 $default_values['multichoice']= 1 ; //$this->editasmultichoice ;
242 }
271ffe3f 243 if (isset($question->options)){
244 $answers = $question->options->answers;
245 if (count($answers)) {
246 $key = 0;
247 foreach ($answers as $answer){
9af77e9d 248 $default_values['answer['.$key.']'] = $answer->answer;
92186abc 249 $default_values['fraction['.$key.']'] = $answer->fraction;
250 $default_values['tolerance['.$key.']'] = $answer->tolerance;
f7089b63 251 $default_values['tolerancetype['.$key.']'] = $answer->tolerancetype;
92186abc 252 $default_values['correctanswerlength['.$key.']'] = $answer->correctanswerlength;
9aa022fe 253 $default_values['correctanswerformat['.$key.']'] = $answer->correctanswerformat;
271ffe3f 254 $default_values['feedback['.$key.']'] = $answer->feedback;
255 $key++;
256 }
257 }
28a27ef1 258 if (isset($question->options->units)){
259 $units = array_values($question->options->units);
260 // make sure the default unit is at index 0
261 usort($units, create_function('$a, $b',
262 'if (1.0 === (float)$a->multiplier) { return -1; } else '.
263 'if (1.0 === (float)$b->multiplier) { return 1; } else { return 0; }'));
264 if (count($units)) {
265 $key = 0;
266 foreach ($units as $unit){
267 $default_values['unit['.$key.']'] = $unit->unit;
268 $default_values['multiplier['.$key.']'] = $unit->multiplier;
269 $key++;
270 }
9aa022fe 271 }
272 }
92186abc 273 }
28a27ef1 274 if (isset($question->options->single)){
275 $default_values['single'] = $question->options->single;
276 $default_values['answernumbering'] = $question->options->answernumbering;
277 $default_values['shuffleanswers'] = $question->options->shuffleanswers;
278 $default_values['correctfeedback'] = $question->options->correctfeedback;
279 $default_values['partiallycorrectfeedback'] = $question->options->partiallycorrectfeedback;
280 $default_values['incorrectfeedback'] = $question->options->incorrectfeedback;
281 }
8fc3e643 282 $default_values['submitbutton'] = get_string('nextpage', 'qtype_calculated');
283 $default_values['makecopy'] = get_string('makecopynextpage', 'qtype_calculated');
271e6dec 284 /* set the wild cards category display given that on loading the category element is
285 unselected when processing this function but have a valid value when processing the
0dd3e11c 286 update category button. The value can be obtain by
287 $qu->category =$this->_form->_elements[$this->_form->_elementIndex['category']]->_values[0];
288 but is coded using existing functions
271e6dec 289 */
0dd3e11c 290 $qu = new stdClass;
291 $el = new stdClass;
271e6dec 292 /* no need to call elementExists() here */
79bb7202 293 if ($this->_form->elementExists('category')){
294 $el=$this->_form->getElement('category');
295 } else {
296 $el=$this->_form->getElement('categorymoveto');
297 }
0dd3e11c 298 if($value =$el->getSelected()) {
299 $qu->category =$value[0];
300 }else {
301 $qu->category=$question->category;// on load $question->category is set by question.php
271e6dec 302 }
0dd3e11c 303 $html2 = $this->qtypeobj->print_dataset_definitions_category($qu);
79bb7202 304 $this->_form->_elements[$this->_form->_elementIndex['listcategory']]->_text = $html2 ;
305 $question = (object)((array)$question + $default_values);
92186abc 306
32db0d42 307 parent::set_data($question);
271ffe3f 308 }
309
310 function qtype() {
311 return 'calculated';
312 }
313
a78890d5 314 function validation($data, $files) {
28a27ef1 315 // echo code left for testing period
316
317 // echo "<p>question <pre>";print_r($this->question);echo "</pre></p>";
318 // echo "<p>data <pre>";print_r($data);echo "</pre></p>";
319
fe93ba83 320 $errors = parent::validation($data, $files);
bfdc0bce 321 //verifying for errors in {=...} in question text;
322 $qtext = "";
323 $qtextremaining = $data['questiontext'] ;
324 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']);
325 foreach ($possibledatasets as $name => $value) {
326 $qtextremaining = str_replace('{'.$name.'}', '1', $qtextremaining);
327 }
271e6dec 328 // echo "numericalquestion qtextremaining <pre>";print_r($possibledatasets);
6dbcacee 329 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
bfdc0bce 330 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
331 $qtext =$qtext.$qtextsplits[0];
332 $qtextremaining = $qtextsplits[1];
333 if (!empty($regs1[1]) && $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])) {
334 if(!isset($errors['questiontext'])){
335 $errors['questiontext'] = $formulaerrors.':'.$regs1[1] ;
336 }else {
337 $errors['questiontext'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
271e6dec 338 }
bfdc0bce 339 }
271e6dec 340 }
9af77e9d 341 $answers = $data['answer'];
271ffe3f 342 $answercount = 0;
a6d46515 343 $maxgrade = false;
f6232d58 344 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']);
345 $mandatorydatasets = array();
346 foreach ($answers as $key => $answer){
a6d46515 347 $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
271e6dec 348 }
a6d46515 349 if ( count($mandatorydatasets )==0){
350 // $errors['questiontext']=get_string('atleastonewildcard', 'qtype_datasetdependent');
f6232d58 351 foreach ($answers as $key => $answer){
9af77e9d 352 $errors['answer['.$key.']'] = get_string('atleastonewildcard', 'qtype_datasetdependent');
271e6dec 353 }
354 }
28a27ef1 355 if ($data['multichoice']== 1 ){
356 foreach ($answers as $key => $answer){
357 $trimmedanswer = trim($answer);
358 if (($trimmedanswer!='')||$answercount==0){
359 //verifying for errors in {=...} in answer text;
360 $qanswer = "";
361 $qanswerremaining = $trimmedanswer ;
362 $possibledatasets = $this->qtypeobj->find_dataset_names($trimmedanswer);
363 foreach ($possibledatasets as $name => $value) {
364 $qanswerremaining = str_replace('{'.$name.'}', '1', $qanswerremaining);
365 }
366 // echo "numericalquestion qanswerremaining <pre>";print_r($possibledatasets);
367 while (preg_match('~\{=([^[:space:]}]*)}~', $qanswerremaining, $regs1)) {
368 $qanswersplits = explode($regs1[0], $qanswerremaining, 2);
369 $qanswer =$qanswer.$qanswersplits[0];
370 $qanswerremaining = $qanswersplits[1];
371 if (!empty($regs1[1]) && $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])) {
372 if(!isset($errors['answer['.$key.']'])){
373 $errors['answer['.$key.']'] = $formulaerrors.':'.$regs1[1] ;
374 }else {
375 $errors['answer['.$key.']'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
376 }
377 }
378 }
379 }
380 if ($trimmedanswer!=''){
381 if ('2' == $data['correctanswerformat'][$key]
382 && '0' == $data['correctanswerlength'][$key]) {
383 $errors['correctanswerlength['.$key.']'] = get_string('zerosignificantfiguresnotallowed','quiz');
384 }
385 if (!is_numeric($data['tolerance'][$key])){
386 $errors['tolerance['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
387 }
388 if ($data['fraction'][$key] == 1) {
389 $maxgrade = true;
390 }
391
392 $answercount++;
393 }
394
395 }
396 }else{
9aa022fe 397 foreach ($answers as $key => $answer){
398 //check no of choices
a6d46515 399 // the * for everykind of answer not actually implemented
271ffe3f 400 $trimmedanswer = trim($answer);
845b703b 401 if (($trimmedanswer!='')||$answercount==0){
9aa022fe 402 $eqerror = qtype_calculated_find_formula_errors($trimmedanswer);
403 if (FALSE !== $eqerror){
9af77e9d 404 $errors['answer['.$key.']'] = $eqerror;
9aa022fe 405 }
8fc3e643 406 }
845b703b 407 if ($trimmedanswer!=''){
9aa022fe 408 if ('2' == $data['correctanswerformat'][$key]
409 && '0' == $data['correctanswerlength'][$key]) {
410 $errors['correctanswerlength['.$key.']'] = get_string('zerosignificantfiguresnotallowed','quiz');
411 }
412 if (!is_numeric($data['tolerance'][$key])){
413 $errors['tolerance['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
414 }
a6d46515 415 if ($data['fraction'][$key] == 1) {
416 $maxgrade = true;
417 }
9aa022fe 418
271ffe3f 419 $answercount++;
420 }
9aa022fe 421 //check grades
422
423 //TODO how should grade checking work here??
424 /*if ($answer != '') {
425 if ($data['fraction'][$key] > 0) {
426 $totalfraction += $data['fraction'][$key];
427 }
428 if ($data['fraction'][$key] > $maxfraction) {
429 $maxfraction = $data['fraction'][$key];
430 }
431 }*/
432 }
28a27ef1 433 }
9aa022fe 434 //grade checking :
435 /// Perform sanity checks on fractional grades
436 /*if ( ) {
437 if ($maxfraction != 1) {
438 $maxfraction = $maxfraction * 100;
439 $errors['fraction[0]'] = get_string('errfractionsnomax', 'qtype_multichoice', $maxfraction);
440 }
441 } else {
442 $totalfraction = round($totalfraction,2);
443 if ($totalfraction != 1) {
444 $totalfraction = $totalfraction * 100;
445 $errors['fraction[0]'] = get_string('errfractionsaddwrong', 'qtype_multichoice', $totalfraction);
446 }
447 }*/
448 $units = $data['unit'];
449 if (count($units)) {
450 foreach ($units as $key => $unit){
451 if (is_numeric($unit)){
452 $errors['unit['.$key.']'] = get_string('mustnotbenumeric', 'qtype_calculated');
453 }
454 $trimmedunit = trim($unit);
455 $trimmedmultiplier = trim($data['multiplier'][$key]);
456 if (!empty($trimmedunit)){
457 if (empty($trimmedmultiplier)){
458 $errors['multiplier['.$key.']'] = get_string('youmustenteramultiplierhere', 'qtype_calculated');
459 }
460 if (!is_numeric($trimmedmultiplier)){
461 $errors['multiplier['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
462 }
463
464 }
465 }
271ffe3f 466 }
467 if ($answercount==0){
9af77e9d 468 $errors['answer[0]'] = get_string('atleastoneanswer', 'qtype_calculated');
271ffe3f 469 }
a6d46515 470 if ($maxgrade == false) {
471 $errors['fraction[0]'] = get_string('fractionsnomax', 'question');
472 }
9aa022fe 473
271ffe3f 474 return $errors;
475 }
476}
6dbcacee 477?>