"MDL-13766, use file_storage to bypass capability check for recent plugin"
[moodle.git] / question / type / calculatedsimple / edit_calculatedsimple_form.php
CommitLineData
aeb15530 1<?php
83a15d02 2/**
3 * Defines the editing form for the calculated simplequestion 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
8 * @package questionbank
9 * @subpackage questiontypes
10 */
11
12/**
13 * calculatedsimple editing form definition.
14 */
15class question_edit_calculatedsimple_form extends question_edit_form {
16 /**
17 * Handle to the question type for this question.
18 *
19 * @var question_calculatedsimple_qtype
20 */
21 var $qtypeobj;
0735b509 22
83a15d02 23 var $wildcarddisplay ;
0735b509 24
83a15d02 25 var $questiondisplay ;
26
27 public $datasetdefs;
28
29 public $reload = false ;
aeb15530 30
83a15d02 31 public $maxnumber = -1;
32
33 public $regenerate = true;
34
35 public $noofitems;
aeb15530 36
83a15d02 37 public $outsidelimit = false ;
aeb15530
PS
38
39 public $commentanswer = array();
40
83a15d02 41 public $answer = array();
42
43 public $nonemptyanswer = array();
aeb15530 44
a31697ba 45 public $numbererrors = array();
46
aeb15530
PS
47 public $formdata = array();
48
a31697ba 49
83a15d02 50
51 function question_edit_calculatedsimple_form(&$submiturl, &$question, &$category, &$contexts, $formeditable = true){
52 global $QTYPES, $SESSION, $CFG, $DB;
83a15d02 53 $this->regenerate = true;
54 $this->question = $question;
b003b818 55
83a15d02 56 $this->qtypeobj =& $QTYPES[$this->question->qtype];
57 //get the dataset definitions for this question
58 //coming here everytime even when using a NoSubmitButton
59 //so this will only set the values to the actual question database content which is not what we want
60 //so this should be removed from here
61 // get priority to paramdatasets
aeb15530 62
83a15d02 63 if ( "1" == optional_param('reload','', PARAM_INT )) {
83a15d02 64 $this->reload = true ;
65 }else {
66 $this->reload = false ;
67 }
aeb15530 68 if(!$this->reload ){ // use database data as this is first pass
0735b509 69 // question->id == 0 so no stored datasets
aeb15530 70 // else get datasets
83a15d02 71 if ( !empty($question->id)) {
72 if (empty($question->options)) {
73 $this->get_question_options($question);
74 }
75 $this->datasetdefs = $this->qtypeobj->get_dataset_definitions($question->id, array());
aeb15530 76
83a15d02 77 if(!empty($this->datasetdefs)){
1d1f5784 78 foreach ($this->datasetdefs as $defid => $datasetdef) {
aeb15530 79 // first get the items in case their number does not correspond to itemcount
1d1f5784 80 if (isset($datasetdef->id)) {
0735b509 81 $this->datasetdefs[$defid]->items = $this->qtypeobj->get_database_dataset_items($datasetdef->id);
82 if ( $this->datasetdefs[$defid]->items != '') {
83 $datasetdef->itemcount = count($this->datasetdefs[$defid]->items);
84 } else {
85 $datasetdef->itemcount = 0 ;
86 }
1d1f5784 87 }
83a15d02 88 // Get maxnumber
89 if ($this->maxnumber == -1 || $datasetdef->itemcount < $this->maxnumber) {
90 $this->maxnumber = $datasetdef->itemcount;
91 }
92 }
83a15d02 93 }
1d1f5784 94
83a15d02 95 $i = 0 ;
96 foreach($this->question->options->answers as $answer){
97 $this->answer[$i] = $answer ;
98 $i++;
aeb15530 99 }
83a15d02 100 $this->nonemptyanswer = $this->answer ;
aeb15530 101 }
83a15d02 102 $datasettoremove = false;
aeb15530
PS
103 $newdatasetvalues = false ;
104 $newdataset = false ;
105 }else {
83a15d02 106 // handle reload to get values from the form-elements
107 // answers, datasetdefs and data_items
aeb15530
PS
108 // In any case the validation step will warn the user of any error in settings the values.
109 // Verification for the specific dataset values as the other parameters
83a15d02 110 // unints, feeedback etc are handled elsewhere
111 // handle request buttons :
aeb15530 112 // 'analyzequestion' (Identify the wild cards {x..} present in answers)
83a15d02 113 // 'addbutton' (create new set of datatitems)
114 // 'updatedatasets' is handled automatically on each reload
aeb15530 115 // The analyzequestion is done every time on reload
83a15d02 116 // to detect any new wild cards so that the current display reflects
117 // the mandatory (i.e. in answers) datasets
118 // to implement : don't do any changes if the question is used in a quiz.
aeb15530
PS
119 // If new datadef, new properties should erase items.
120 // Most of the data
06f80c6c 121 $datasettoremove = false;
aeb15530
PS
122 $newdatasetvalues = false ;
123 $newdataset = false ;
0735b509 124 $dummyform = new stdClass();
125 $mandatorydatasets = array();
aeb15530 126 // should not test on adding a new answer
06f80c6c 127 // should test if there are already olddatasets or if the 'analyzequestion' submit button has been clicked
aeb15530
PS
128 if ('' != optional_param('datasetdef', '', PARAM_RAW) || '' != optional_param('analyzequestion', '', PARAM_RAW)){
129
130 if ( $dummyform->answer = optional_param('answer', '', PARAM_NOTAGS)) { // there is always at least one answer...
131 $tolerance = optional_param('tolerance', '', PARAM_NUMBER);
132 $tolerancetype = optional_param('tolerancetype', '', PARAM_NUMBER);
133 $correctanswerlength = optional_param('correctanswerlength', '', PARAM_INT);
134 $correctanswerformat = optional_param('correctanswerformat', '', PARAM_INT);
135
06f80c6c 136 foreach( $dummyform->answer as $key => $answer ) {
aeb15530 137 if(trim($answer) != ''){ // just look for non-empty
06f80c6c 138 $this->answer[$key]=new stdClass();
139 $this->answer[$key]->answer = $answer;
b003b818 140 $this->answer[$key]->fraction = $fraction[$key];
06f80c6c 141 $this->answer[$key]->tolerance = $tolerance[$key];
142 $this->answer[$key]->tolerancetype = $tolerancetype[$key];
143 $this->answer[$key]->correctanswerlength = $correctanswerlength[$key];
144 $this->answer[$key]->correctanswerformat = $correctanswerformat[$key];
145 $this->nonemptyanswer[]= $this->answer[$key];
146 $mandatorydatasets +=$this->qtypeobj->find_dataset_names($answer);
147 }
0735b509 148 }
83a15d02 149 }
06f80c6c 150 $this->datasetdefs = array();
151 // rebuild datasetdefs from old values
aeb15530
PS
152 if ($olddef = optional_param('datasetdef', '', PARAM_RAW)){
153 $calcmin = optional_param('calcmin', '', PARAM_NUMBER);
154 $calclength = optional_param('calclength', '', PARAM_INT);
b003b818 155 $calcmax = optional_param('calcmax', '', PARAM_NUMBER);
aeb15530
PS
156 $oldoptions = optional_param('defoptions', '', PARAM_RAW);
157 $newdatasetvalues = false ;
06f80c6c 158 for($key = 1 ; $key <= sizeof($olddef) ; $key++) {
159 $def = $olddef[$key] ;
160 $this->datasetdefs[$def]= new stdClass ;
161 $this->datasetdefs[$def]->type = 1;
162 $this->datasetdefs[$def]->category = 0;
163 // $this->datasets[$key]->name = $datasetname;
b003b818 164 $this->datasetdefs[$def]->options = $oldoptions[$key] ;
06f80c6c 165 $this->datasetdefs[$def]->calcmin = $calcmin[$key] ;
166 $this->datasetdefs[$def]->calcmax = $calcmax[$key] ;
167 $this->datasetdefs[$def]->calclength = $calclength[$key] ;
168 //then compare with new values
169 if (preg_match('~^(uniform|loguniform):([^:]*):([^:]*):([0-9]*)$~', $this->datasetdefs[$def]->options, $regs)) {
170 if( $this->datasetdefs[$def]->calcmin != $regs[2]||
171 $this->datasetdefs[$def]->calcmax != $regs[3] ||
172 $this->datasetdefs[$def]->calclength != $regs[4]){
173 $newdatasetvalues = true ;
aeb15530 174 }
06f80c6c 175 }
176 $this->datasetdefs[$def]->options="uniform:".$this->datasetdefs[$def]->calcmin.":".$this->datasetdefs[$def]->calcmax.":".$this->datasetdefs[$def]->calclength;
177 }
178 }// if (olddef...
aeb15530
PS
179 // detect new datasets
180 $newdataset = false ;
83a15d02 181 foreach ($mandatorydatasets as $datasetname) {
182 if (!isset($this->datasetdefs["1-0-$datasetname"])) {
83a15d02 183 $key = "1-0-$datasetname";
184 $this->datasetdefs[$key]=new stdClass ;//"1-0-$datasetname";
185 $this->datasetdefs[$key]->type = 1;
186 $this->datasetdefs[$key]->category = 0;
187 $this->datasetdefs[$key]->name = $datasetname;
188 $this->datasetdefs[$key]->options = "uniform:1.0:10.0:1";
aeb15530 189 $newdataset = true ;
83a15d02 190 }else {
191 $this->datasetdefs["1-0-$datasetname"]->name = $datasetname ;
192 }
193 }
aeb15530 194 // remove obsolete datasets
83a15d02 195 $datasettoremove = false;
196 foreach ($this->datasetdefs as $defkey => $datasetdef){
197 if(!isset($datasetdef->name )){
83a15d02 198 $datasettoremove = true;
199 unset($this->datasetdefs[$defkey]);
200 }
06f80c6c 201 }
aeb15530 202 }
83a15d02 203 } // handle reload
204 // create items if $newdataset and noofitems > 0 and !$newdatasetvalues
205 // eliminate any items if $newdatasetvalues
206 // eliminate any items if $datasettoremove, $newdataset, $newdatasetvalues
207 if ($datasettoremove ||$newdataset ||$newdatasetvalues ) {
208 foreach ($this->datasetdefs as $defkey => $datasetdef){
209 $datasetdef->itemcount = 0;
210 unset($datasetdef->items);
211 }
212 }
213 $maxnumber = -1 ;
214 if ( "" !=optional_param('addbutton')){
06f80c6c 215 $maxnumber = optional_param('selectadd', '', PARAM_INT); //FIXME: sloppy coding
83a15d02 216 foreach ($this->datasetdefs as $defid => $datasetdef) {
217 $datasetdef->itemcount = $maxnumber;
218 unset($datasetdef->items);
219 for ($numberadded =1 ; $numberadded <= $maxnumber; $numberadded++){
220 $datasetitem = new stdClass;
83a15d02 221 $datasetitem->itemnumber = $numberadded;
222 $datasetitem->id = 0;
223 $datasetitem->value = $this->qtypeobj->generate_dataset_item($datasetdef->options);
224 $this->datasetdefs[$defid]->items[$numberadded]=$datasetitem ;
83a15d02 225 }//for number added
226 }// datasetsdefs end
227 $this->maxnumber = $maxnumber ;
83a15d02 228 }else {
0735b509 229 // Handle reload dataset items
aeb15530 230 if ( "" !=optional_param('definition')&& !($datasettoremove ||$newdataset ||$newdatasetvalues )){
83a15d02 231 $i = 1;
aeb15530
PS
232 $fromformdefinition = optional_param('definition', '', PARAM_NOTAGS);
233 $fromformnumber = optional_param('number', '', PARAM_INT);
234 $fromformitemid = optional_param('itemid', '', PARAM_INT);
83a15d02 235 ksort($fromformdefinition);
aeb15530 236
83a15d02 237 foreach($fromformdefinition as $key => $defid) {
238 $addeditem = new stdClass();
239 $addeditem->id = $fromformitemid[$i] ;
240 $addeditem->value = $fromformnumber[$i];
241 $addeditem->itemnumber = ceil($i / count($this->datasetdefs));
242 $this->datasetdefs[$defid]->items[$addeditem->itemnumber]=$addeditem ;
243 $this->datasetdefs[$defid]->itemcount = $i ;
244 $i++;
245 }
246 }
247 if (isset($addeditem->itemnumber) && $this->maxnumber < $addeditem->itemnumber){
248 $this->maxnumber = $addeditem->itemnumber;
aeb15530 249 if(!empty($this->datasetdefs)){
83a15d02 250 foreach ($this->datasetdefs as $datasetdef) {
251 $datasetdef->itemcount = $this->maxnumber ;
252 }
253 }
254 }
255 }
256
83a15d02 257 parent::question_edit_form($submiturl, $question, $category, $contexts, $formeditable);
258 }
259
260 function get_per_answer_fields(&$mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) {
aeab3f8d 261 $repeated = parent::get_per_answer_fields($mform, $label, $gradeoptions, $repeatedoptions, $answersoption);
83a15d02 262 $mform->setType('answer', PARAM_NOTAGS);
263 $addrepeated = array();
264 $addrepeated[] =& $mform->createElement('text', 'tolerance', get_string('tolerance', 'qtype_calculated'));
265 $repeatedoptions['tolerance']['type'] = PARAM_NUMBER;
266 $repeatedoptions['tolerance']['default'] = 0.01;
267 $addrepeated[] =& $mform->createElement('select', 'tolerancetype', get_string('tolerancetype', 'quiz'), $this->qtypeobj->tolerance_types());
268 $addrepeated[] =& $mform->createElement('select', 'correctanswerlength', get_string('correctanswershows', 'qtype_calculated'), range(0, 9));
269 $repeatedoptions['correctanswerlength']['default'] = 2;
270
271 $answerlengthformats = array('1' => get_string('decimalformat', 'quiz'), '2' => get_string('significantfiguresformat', 'quiz'));
272 $addrepeated[] =& $mform->createElement('select', 'correctanswerformat', get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
273 array_splice($repeated, 3, 0, $addrepeated);
274 $repeated[1]->setLabel(get_string('correctanswerformula', 'quiz').'=');
275
276 return $repeated;
277 }
278
279 /**
280 * Add question-type specific form fields.
281 *
282 * @param MoodleQuickForm $mform the form being built.
283 */
284 function definition_inner(&$mform) {
285 global $QTYPES;
286 $this->qtypeobj =& $QTYPES[$this->qtype()];
287 $strquestionlabel = $this->qtypeobj->comment_header($this->nonemptyanswer);
a31697ba 288 $label = get_string("sharedwildcards", "qtype_datasetdependent");
b003b818 289 $mform->addElement('hidden', 'synchronize', 0);
83a15d02 290 $mform->addElement('hidden', 'initialcategory', 1);
d18e0fe6 291 $mform->setType('initialcategory', PARAM_INT);
83a15d02 292 $mform->addElement('hidden', 'reload', 1);
d18e0fe6 293 $mform->setType('reload', PARAM_INT);
a31697ba 294 $addfieldsname='updatequestion value';
83a15d02 295 $addstring=get_string("updatecategory", "qtype_calculated");
a31697ba 296 $mform->registerNoSubmitButton($addfieldsname);
0735b509 297//put a submit button to stop supplementary answers on update answers parameters
83a15d02 298// $mform->insertElementBefore( $mform->createElement('submit', $addfieldsname, $addstring),'listcategory');
299
300 $creategrades = get_grade_options();
301 $this->add_per_answer_fields($mform, get_string('answerhdr', 'qtype_calculated', '{no}'),
302 $creategrades->gradeoptions, 1, 1);
303
b003b818 304 $QTYPES['numerical']->edit_numerical_options($mform,$this);
aeb15530 305
83a15d02 306 $repeated = array();
307 $repeated[] =& $mform->createElement('header', 'unithdr', get_string('unithdr', 'qtype_numerical', '{no}'));
308
309 $repeated[] =& $mform->createElement('text', 'unit', get_string('unit', 'quiz'));
310 $mform->setType('unit', PARAM_NOTAGS);
311
312 $repeated[] =& $mform->createElement('text', 'multiplier', get_string('multiplier', 'quiz'));
313 $mform->setType('multiplier', PARAM_NUMBER);
314
315 if (isset($this->question->options)){
316 $countunits = count($this->question->options->units);
317 } else {
318 $countunits = 0;
319 }
320 if ($this->question->formoptions->repeatelements){
321 $repeatsatstart = $countunits + 1;
322 } else {
323 $repeatsatstart = $countunits;
324 }
325 $this->repeat_elements($repeated, $repeatsatstart, array(), 'nounits', 'addunits', 2, get_string('addmoreunitblanks', 'qtype_calculated', '{no}'));
326
327 if ($mform->elementExists('multiplier[0]')){
328 $firstunit =& $mform->getElement('multiplier[0]');
329 $firstunit->freeze();
330 $firstunit->setValue('1.0');
331 $firstunit->setPersistantFreeze(true);
332 }
b003b818 333
83a15d02 334 //hidden elements
335 // $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
336 // $mform->setType('wizard', PARAM_ALPHA);
337 // $mform->addElement('header', '', '');
338 $label = "<div class='mdl-align'></div><div class='mdl-align'>".get_string('wildcardrole', 'qtype_calculatedsimple')."</div>";
339 $mform->addElement('html', "<div class='mdl-align'>&nbsp;</div>");
340 $mform->addElement('html', $label);// explaining the role of datasets so other strings can be shortened
341
342 $mform->addElement('submit', 'analyzequestion', get_string('findwildcards','qtype_calculatedsimple'));
343 $mform->registerNoSubmitButton('analyzequestion');
344 $mform->closeHeaderBefore('analyzequestion');
345 if ( "" != optional_param('analyzequestion','', PARAM_RAW)) {
346
347 $this->wizarddisplay = true;
83a15d02 348
349 }else {
350 $this->wizwarddisplay = false;
351 }
352 if ($this->maxnumber != -1){
353 $this->noofitems = $this->maxnumber;
354 } else {
355 $this->noofitems = 0;
356 }
a31697ba 357 if(!empty($this->datasetdefs)){//So there are some datadefs
358 // we put them on the page
0735b509 359 $key = 0;
360 $mform->addElement('header', 'additemhdr', get_string('wildcardparam', 'qtype_calculatedsimple'));
361 $idx = 1;
362 if(!empty($this->datasetdefs)){// unnecessary test
363 $j = (($this->noofitems) * count($this->datasetdefs))+1;//
364 foreach ($this->datasetdefs as $defkey => $datasetdef){
365 $mform->addElement('static', "na[$j]", get_string('param', 'qtype_datasetdependent', $datasetdef->name));
366 $this->qtypeobj->custom_generator_tools_part($mform, $idx, $j);
367 $mform->addElement('hidden', "datasetdef[$idx]");
368 $mform->setType("datasetdef[$idx]", PARAM_RAW);
b003b818 369 $mform->addElement('hidden', "defoptions[$idx]");
aeb15530 370 $mform->setType("defoptions[$idx]", PARAM_RAW);
0735b509 371 $idx++;
372 $mform->addElement('static', "divider[$j]", '', '<hr />');
373 $j++;
374 }
375 }
376 //this should be done before the elements are created and stored as $this->formdata ;
377 //fill out all data sets and also the fields for the next item to add.
aeb15530 378 /*Here we do already the values error analysis so that
0735b509 379 * we could force all wild cards values display if there is an error in values.
380 * as using a , in a number */
381 $this->numbererrors = array();
382 if(!empty($this->datasetdefs)){
383 $j = $this->noofitems * count($this->datasetdefs);
384 for ($itemnumber = $this->noofitems; $itemnumber >= 1; $itemnumber--){
385 $data = array();
386 $numbererrors = array() ;
387 $comment = new stdClass;
388 $comment->stranswers = array();
389 $comment->outsidelimit = false ;
390 $comment->answers = array();
391
392 foreach ($this->datasetdefs as $defid => $datasetdef){
393 if (isset($datasetdef->items[$itemnumber])){
394 $this->formdata["definition[$j]"] = $defid;
395 $this->formdata["itemid[$j]"] = $datasetdef->items[$itemnumber]->id;
396 $data[$datasetdef->name] = $datasetdef->items[$itemnumber]->value;
397 $this->formdata["number[$j]"] = $number = $datasetdef->items[$itemnumber]->value;
398 if(! is_numeric($number)){
399 $a = new stdClass;
400 $a->name = '{'.$datasetdef->name.'}' ;
401 $a->value = $datasetdef->items[$itemnumber]->value ;
a31697ba 402 if (stristr($number,',')){
0735b509 403 $this->numbererrors["number[$j]"]=get_string('nocommaallowed', 'qtype_datasetdependent');
404 $numbererrors .= $this->numbererrors['number['.$j.']']."<br />";
aeb15530 405
a31697ba 406 }else {
0735b509 407 $this->numbererrors["number[$j]"]= get_string('notvalidnumber','qtype_datasetdependent',$a);
408 $numbererrors .= $this->numbererrors['number['.$j.']']."<br />";
409 //$comment->outsidelimit = false ;
410 }
aeb15530 411 }else if( stristr($number,'x')){ // hexa will pass the test
a31697ba 412 $a = new stdClass;
413 $a->name = '{'.$datasetdef->name.'}' ;
414 $a->value = $datasetdef->items[$itemnumber]->value ;
415 $this->numbererrors['number['.$j.']']= get_string('hexanotallowed','qtype_datasetdependent',$a);
0735b509 416 $numbererrors .= $this->numbererrors['number['.$j.']']."<br />";
417 } else if( is_nan($number)){
418 $a = new stdClass;
419 $a->name = '{'.$datasetdef->name.'}' ;
420 $a->value = $datasetdef->items[$itemnumber]->value ;
421 $this->numbererrors["number[$j]"]= get_string('notvalidnumber','qtype_datasetdependent',$a);
422 $numbererrors .= $this->numbererrors['number['.$j.']']."<br />";
423 // $val = 1.0 ;
aeb15530 424 }
0735b509 425 }
426 $j--;
427 }
428 if($this->noofitems != 0 ) {
429 if (empty($numbererrors )){
430 if(!isset($question->id)) $question->id = 0 ;
ab8b5142 431 $comment = $this->qtypeobj->comment_on_datasetitems($question->id,$question->questiontext,$this->nonemptyanswer, $data, $itemnumber);//$this->
0735b509 432 if ($comment->outsidelimit) {
433 $this->outsidelimit=$comment->outsidelimit ;
434 }
435 $totalcomment='';
aeb15530 436
0735b509 437 foreach ($this->nonemptyanswer as $key => $answer) {
438 $totalcomment .= $comment->stranswers[$key].'<br/>';
439 }
aeb15530 440
0735b509 441 $this->formdata['answercomment['.$itemnumber.']'] = $totalcomment ;
442 }
443 }
444 }
445 $this->formdata['selectdelete'] = '1';
446 $this->formdata['selectadd'] = '1';
447 $j = $this->noofitems * count($this->datasetdefs)+1;
448 $data = array(); // data for comment_on_datasetitems later
449 $idx =1 ;
450 foreach ($this->datasetdefs as $defid => $datasetdef){
451 $this->formdata["datasetdef[$idx]"] = $defid;
452 $idx++;
453 }
454 $this->formdata = $this->qtypeobj->custom_generator_set_data($this->datasetdefs, $this->formdata);
455 }
456
aeb15530 457
83a15d02 458 $addoptions = Array();
459 $addoptions['1']='1';
460 for ($i=10; $i<=100 ; $i+=10){
461 $addoptions["$i"]="$i";
462 }
a31697ba 463 $showoptions = Array();
464 $showoptions['1']='1';
465 $showoptions['2']='2';
466 $showoptions['5']='5';
467 for ($i=10; $i<=100 ; $i+=10){
468 $showoptions["$i"]="$i";
469 }
83a15d02 470 $mform->closeHeaderBefore('additemhdr');
471 $addgrp = array();
472 $addgrp[] =& $mform->createElement('submit', 'addbutton', get_string('generatenewitemsset', 'qtype_calculatedsimple'));
1d1f5784 473 $addgrp[] =& $mform->createElement('select', "selectadd", '', $addoptions);
474 $addgrp[] = & $mform->createElement('static',"stat",'',get_string('newsetwildcardvalues', 'qtype_calculatedsimple'));
83a15d02 475 $mform->addGroup($addgrp, 'addgrp', '', ' ', false);
476 $mform->registerNoSubmitButton('addbutton');
477 $mform->closeHeaderBefore('addgrp');
a31697ba 478 $addgrp1 = array();
479 $addgrp1[] =& $mform->createElement('submit', 'showbutton', get_string('showitems', 'qtype_calculatedsimple'));
480 $addgrp1[] =& $mform->createElement('select', "selectshow",'' , $showoptions);
1d1f5784 481 $addgrp1[] = & $mform->createElement('static',"stat",'',get_string('setwildcardvalues', 'qtype_calculatedsimple'));
a31697ba 482 $mform->addGroup($addgrp1, 'addgrp1', '', ' ', false);
483 $mform->registerNoSubmitButton('showbutton');
484 $mform->closeHeaderBefore('addgrp1');
83a15d02 485 $mform->addElement('static', "divideradd", '', '');
486 if ($this->noofitems == 0) {
a31697ba 487 $mform->addElement('static','warningnoitems','','<span class="error">'.get_string('youmustaddatleastonevalue', 'qtype_calculatedsimple').'</span>');
0735b509 488 $mform->closeHeaderBefore('warningnoitems');
83a15d02 489 }else {
0735b509 490 $mform->addElement('header', 'additemhdr1', get_string('wildcardvalues', 'qtype_calculatedsimple'));
491 $mform->closeHeaderBefore('additemhdr1');
83a15d02 492 // $mform->addElement('header', '', get_string('itemno', 'qtype_datasetdependent', ""));
a31697ba 493 if( !empty($this->numbererrors) || $this->outsidelimit) {
494 $mform->addElement('static', "alert", '', '<span class="error">'.get_string('useadvance', 'qtype_calculatedsimple').'</span>');
495 }
aeb15530 496
a31697ba 497 $mform->addElement('submit', 'updatedatasets', get_string('updatewildcardvalues', 'qtype_calculatedsimple'));
498 $mform->registerNoSubmitButton('updatedatasets');
499 $mform->setAdvanced("updatedatasets",true);
83a15d02 500
501//------------------------------------------------------------------------------------------------------------------------------
502 $j = $this->noofitems * count($this->datasetdefs);
a31697ba 503 $k = 1 ;
504 if ("" != optional_param('selectshow')){
aeb15530 505 $k = optional_param('selectshow', '', PARAM_INT);
53e8c830 506 }
a31697ba 507
83a15d02 508 for ($i = $this->noofitems; $i >= 1 ; $i--){
509 foreach ($this->datasetdefs as $defkey => $datasetdef){
a31697ba 510 if($k > 0 || $this->outsidelimit || !empty($this->numbererrors ) ){
511 $mform->addElement('text',"number[$j]" , get_string('wildcard', 'qtype_calculatedsimple', $datasetdef->name));
83a15d02 512 $mform->setAdvanced("number[$j]",true);
aeb15530 513 if(!empty($this->numbererrors['number['.$j.']']) ){
0735b509 514 $mform->addElement('static', "numbercomment[$j]",'','<span class="error">'.$this->numbererrors['number['.$j.']'].'</span>');
a31697ba 515 $mform->setAdvanced("numbercomment[$j]",true);
516 }
517 }else {
518 $mform->addElement('hidden',"number[$j]" , get_string('wildcard', 'qtype_calculatedsimple', $datasetdef->name));
519 }
520 $mform->setType("number[$j]", PARAM_NUMBER);
aeb15530 521
83a15d02 522 $mform->addElement('hidden', "itemid[$j]");
523 $mform->setType("itemid[$j]", PARAM_INT);
524
525 $mform->addElement('hidden', "definition[$j]");
526 $mform->setType("definition[$j]", PARAM_NOTAGS);
527
528 $j--;
529 }
a31697ba 530 if (!empty( $strquestionlabel) && ($k > 0 || $this->outsidelimit || !empty($this->numbererrors ) ) ){
531 // $repeated[] =& $mform->addElement('static', "answercomment[$i]", $strquestionlabel);
0735b509 532 $mform->addElement('static', "answercomment[$i]", "<b>".get_string('setno', 'qtype_calculatedsimple', $i)."</b>&nbsp;&nbsp;".$strquestionlabel);
aeb15530 533
83a15d02 534 }
aeb15530 535 if($k > 0 || $this->outsidelimit || !empty($this->numbererrors )){
0735b509 536 $mform->addElement('static', "divider1[$j]", '', '<hr />');
aeb15530 537
a31697ba 538 }
0735b509 539 $k-- ;
83a15d02 540 }
541 }
542 // if ($this->outsidelimit){
543 // $mform->addElement('static','outsidelimit','','');
544 // }
545 }else {
546 $mform->addElement('static','warningnowildcards','','<span class="error">'.get_string('atleastonewildcard', 'qtype_calculatedsimple').'</span>');
547 $mform->closeHeaderBefore('warningnowildcards');
548 }
549
b003b818 550
83a15d02 551//------------------------------------------------------------------------------------------------------------------------------
552 //non standard name for button element needed so not using add_action_buttons
553 //hidden elements
554
555 $mform->addElement('hidden', 'id');
556 $mform->setType('id', PARAM_INT);
557
558 $mform->addElement('hidden', 'courseid');
559 $mform->setType('courseid', PARAM_INT);
560 $mform->setDefault('courseid', 0);
561
562 $mform->addElement('hidden', 'cmid');
563 $mform->setType('cmid', PARAM_INT);
564 $mform->setDefault('cmid', 0);
565 if (!empty($this->question->id)){
566 if ($this->question->formoptions->cansaveasnew){
567 $mform->addElement('header', 'additemhdr', get_string('converttocalculated', 'qtype_calculatedsimple'));
568 $mform->closeHeaderBefore('additemhdr');
aeb15530 569
83a15d02 570 $mform->addElement('checkbox', 'convert','' ,get_string('willconverttocalculated', 'qtype_calculatedsimple'));
571 $mform->setDefault('convert', 0);
572
573 }
574 }
575 // $mform->addElement('hidden', 'wizard', 'edit_calculatedsimple');
576 // $mform->setType('wizard', PARAM_ALPHA);
577/*
578 $mform->addElement('hidden', 'returnurl');
579 $mform->setType('returnurl', PARAM_LOCALURL);
580 $mform->setDefault('returnurl', 0);
581
582*/
583 }
584
585 function set_data($question) {
586 $answer = $this->answer;
587 $default_values = array();
b003b818 588 if (count($answer)) {
83a15d02 589 $key = 0;
590 foreach ($answer as $answer){
591 $default_values['answer['.$key.']'] = $answer->answer;
aeb15530 592 // echo "<p> $answer->fraction </p>";
83a15d02 593 $default_values['fraction['.$key.']'] = $answer->fraction;
594 $default_values['tolerance['.$key.']'] = $answer->tolerance;
595 $default_values['tolerancetype['.$key.']'] = $answer->tolerancetype;
596 $default_values['correctanswerlength['.$key.']'] = $answer->correctanswerlength;
597 $default_values['correctanswerformat['.$key.']'] = $answer->correctanswerformat;
598 $default_values['feedback['.$key.']'] = $answer->feedback;
599 $key++;
600 }
b003b818 601 }
b003b818 602 $default_values['synchronize'] = 0 ;
83a15d02 603 if (isset($question->options)){
b003b818 604 $default_values['unitgradingtype'] = $question->options->unitgradingtype ;
605 $default_values['unitpenalty'] = $question->options->unitpenalty ;
606 $default_values['showunits'] = $question->options->showunits ;
607 $default_values['unitsleft'] = $question->options->unitsleft ;
608 $default_values['instructions'] = $question->options->instructions ;
609
83a15d02 610 $units = array_values($question->options->units);
611 // make sure the default unit is at index 0
612 usort($units, create_function('$a, $b',
613 'if (1.0 === (float)$a->multiplier) { return -1; } else '.
614 'if (1.0 === (float)$b->multiplier) { return 1; } else { return 0; }'));
615 if (count($units)) {
616 $key = 0;
617 foreach ($units as $unit){
618 $default_values['unit['.$key.']'] = $unit->unit;
619 $default_values['multiplier['.$key.']'] = $unit->multiplier;
620 $key++;
621 }
622 }
623 }
624 $key = 0 ;
83a15d02 625
626 $formdata = array();
627 $fromform = new stdClass();
a31697ba 628 //this should be done before the elements are created and stored as $this->formdata ;
83a15d02 629 //fill out all data sets and also the fields for the next item to add.
a31697ba 630 /* if(!empty($this->datasetdefs)){
83a15d02 631 $j = $this->noofitems * count($this->datasetdefs);
632 for ($itemnumber = $this->noofitems; $itemnumber >= 1; $itemnumber--){
633 $data = array();
634 foreach ($this->datasetdefs as $defid => $datasetdef){
635 if (isset($datasetdef->items[$itemnumber])){
636 $formdata["number[$j]"] = $datasetdef->items[$itemnumber]->value;
637 $formdata["definition[$j]"] = $defid;
638 $formdata["itemid[$j]"] = $datasetdef->items[$itemnumber]->id;
639 $data[$datasetdef->name] = $datasetdef->items[$itemnumber]->value;
640 }
641 $j--;
642 }
643 // echo "<p>answers avant comment <pre>";print_r($answer);echo"</pre></p>";
644 // echo "<p>data avant comment <pre>";print_r($data);echo"</pre></p>";
aeb15530 645
83a15d02 646 if($this->noofitems != 0 ) {
647 if(!isset($question->id)) $question->id = 0 ;
648 $comment = $this->qtypeobj->comment_on_datasetitems($question->id,$this->nonemptyanswer, $data, $itemnumber);//$this->
649 if ($comment->outsidelimit) {
650 $this->outsidelimit=$comment->outsidelimit ;
651 }
652 $totalcomment='';
653 // echo "<p> comment <pre>";print_r($comment);echo"</pre></p>";
654
655 foreach ($this->nonemptyanswer as $key => $answer) {
656 $totalcomment .= $comment->stranswers[$key].'<br/>';
657 }
658
659 $formdata['answercomment['.$itemnumber.']'] = $totalcomment ;
660 }
661 }
662 // $formdata['reload'] = '1';
663 // $formdata['nextpageparam[forceregeneration]'] = $this->regenerate;
664 $formdata['selectdelete'] = '1';
665 $formdata['selectadd'] = '1';
666 $j = $this->noofitems * count($this->datasetdefs)+1;
667 $data = array(); // data for comment_on_datasetitems later
668 $idx =1 ;
669 foreach ($this->datasetdefs as $defid => $datasetdef){
670 $formdata["datasetdef[$idx]"] = $defid;
671 $idx++;
672 }
673 $formdata = $this->qtypeobj->custom_generator_set_data($this->datasetdefs, $formdata);
a31697ba 674 }*/
675 $question = (object)((array)$question + $default_values+$this->formdata );
83a15d02 676
677 parent::set_data($question);
678 }
679
680 function qtype() {
681 return 'calculatedsimple';
682 }
683
684 function validation($data, $files) {
685 $errors = parent::validation($data, $files);
686 //verifying for errors in {=...} in question text;
687 $qtext = "";
688 $qtextremaining = $data['questiontext'] ;
689 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']);
06f80c6c 690 foreach ($possibledatasets as $name => $value) {
83a15d02 691 $qtextremaining = str_replace('{'.$name.'}', '1', $qtextremaining);
692 }
6dbcacee 693 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
83a15d02 694 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
695 $qtext =$qtext.$qtextsplits[0];
696 $qtextremaining = $qtextsplits[1];
697 if (!empty($regs1[1]) && $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])) {
698 if(!isset($errors['questiontext'])){
699 $errors['questiontext'] = $formulaerrors.':'.$regs1[1] ;
700 }else {
701 $errors['questiontext'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
702 }
703 }
704 }
705 $answers = $data['answer'];
706 $answercount = 0;
707 $maxgrade = false;
708 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']);
709 $mandatorydatasets = array();
710 foreach ($answers as $key => $answer){
711 $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
712 }
713 if ( count($mandatorydatasets )==0){
a31697ba 714 foreach ($answers as $key => $answer){
83a15d02 715 $errors['answer['.$key.']'] = get_string('atleastonewildcard', 'qtype_datasetdependent');
716 }
717 }
718 foreach ($answers as $key => $answer){
719 //check no of choices
720 // the * for everykind of answer not actually implemented
721 $trimmedanswer = trim($answer);
722 if (($trimmedanswer!='')||$answercount==0){
723 $eqerror = qtype_calculated_find_formula_errors($trimmedanswer);
724 if (FALSE !== $eqerror){
725 $errors['answer['.$key.']'] = $eqerror;
726 }
727 }
728 if ($trimmedanswer!=''){
729 if ('2' == $data['correctanswerformat'][$key]
730 && '0' == $data['correctanswerlength'][$key]) {
731 $errors['correctanswerlength['.$key.']'] = get_string('zerosignificantfiguresnotallowed','quiz');
732 }
733 if (!is_numeric($data['tolerance'][$key])){
734 $errors['tolerance['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
735 }
736 if ($data['fraction'][$key] == 1) {
737 $maxgrade = true;
738 }
739
740 $answercount++;
741 }
742 //check grades
743
744 //TODO how should grade checking work here??
745 /*if ($answer != '') {
746 if ($data['fraction'][$key] > 0) {
747 $totalfraction += $data['fraction'][$key];
748 }
749 if ($data['fraction'][$key] > $maxfraction) {
750 $maxfraction = $data['fraction'][$key];
751 }
752 }*/
753 }
754 //grade checking :
755 /// Perform sanity checks on fractional grades
756 /*if ( ) {
757 if ($maxfraction != 1) {
758 $maxfraction = $maxfraction * 100;
759 $errors['fraction[0]'] = get_string('errfractionsnomax', 'qtype_multichoice', $maxfraction);
760 }
761 } else {
762 $totalfraction = round($totalfraction,2);
763 if ($totalfraction != 1) {
764 $totalfraction = $totalfraction * 100;
765 $errors['fraction[0]'] = get_string('errfractionsaddwrong', 'qtype_multichoice', $totalfraction);
766 }
767 }*/
768 $units = $data['unit'];
769 if (count($units)) {
770 foreach ($units as $key => $unit){
771 if (is_numeric($unit)){
772 $errors['unit['.$key.']'] = get_string('mustnotbenumeric', 'qtype_calculated');
773 }
774 $trimmedunit = trim($unit);
775 $trimmedmultiplier = trim($data['multiplier'][$key]);
776 if (!empty($trimmedunit)){
777 if (empty($trimmedmultiplier)){
778 $errors['multiplier['.$key.']'] = get_string('youmustenteramultiplierhere', 'qtype_calculated');
779 }
780 if (!is_numeric($trimmedmultiplier)){
781 $errors['multiplier['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
782 }
783
784 }
785 }
786 }
787 if ($answercount==0){
788 $errors['answer[0]'] = get_string('atleastoneanswer', 'qtype_calculated');
789 }
790 if ($maxgrade == false) {
791 $errors['fraction[0]'] = get_string('fractionsnomax', 'question');
792 }
793 if (isset($data['backtoquiz']) && ($this->noofitems==0) ){
794 $errors['warning'] = get_string('warning', 'mnet');
aeb15530 795 }
83a15d02 796 if ($this->outsidelimit){
797 // if(!isset($errors['warning'])) $errors['warning']=' ';
798 $errors['outsidelimits'] = get_string('oneanswertrueansweroutsidelimits','qtype_calculated');
799 }
aeb15530 800 /*Here we use the already done the error analysis so that
0735b509 801 * we could force all wild cards values display if there is an error in values.
b003b818 802 * as using a , in a number *//*
83a15d02 803 $numbers = $data['number'];
804 foreach ($numbers as $key => $number){
805 if(! is_numeric($number)){
806 if (stristr($number,',')){
a31697ba 807 $errors['number['.$key.']'] = get_string('notvalidnumber', 'qtype_datasetdependent');
aeb15530 808 }else {
a31697ba 809 $errors['number['.$key.']'] = get_string('notvalidnumber', 'qtype_datasetdependent');
83a15d02 810 }
811 }else if( stristr($number,'x')){
a31697ba 812 $errors['number['.$key.']'] = get_string('notvalidnumber', 'qtype_datasetdependent');
83a15d02 813 } else if( is_nan($number)){
a31697ba 814 $errors['number['.$key.']'] = get_string('notvalidnumber', 'qtype_datasetdependent');
aeb15530 815 }
83a15d02 816 }
b003b818 817 */
83a15d02 818 if ( $this->noofitems==0 ){
819 $errors['warning'] = get_string('warning', 'mnet');
820 }
821
822 return $errors;
823 }
824}
aeb15530 825