MDL-25122 Quiz review page does not check and enforce separate groups mode.
[moodle.git] / question / type / calculatedmulti / edit_calculatedmulti_form.php
CommitLineData
2d279432
PP
1<?php
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
8 * @package questionbank
9 * @subpackage questiontypes
10 */
11
12/**
13 * calculated editing form definition.
14 */
15class question_edit_calculatedmulti_form extends question_edit_form {
16 /**
17 * Handle to the question type for this question.
18 *
19 * @var question_calculatedmulti_qtype
20 */
fe6ce234 21 public $qtypeobj;
d90b016b
PP
22 public $questiondisplay ;
23 public $initialname = '';
24 public $reload = false ;
fe6ce234 25 function question_edit_calculatedmulti_form(&$submiturl, &$question, &$category, &$contexts, $formeditable = true) {
2d279432 26 global $QTYPES, $SESSION, $CFG, $DB;
2d279432
PP
27 $this->question = $question;
28 $this->qtypeobj =& $QTYPES[$this->question->qtype];
d90b016b
PP
29 if ( "1" == optional_param('reload','', PARAM_INT )) {
30 $this->reload = true ;
31 }else {
32 $this->reload = false ;
33 }
34 if(!$this->reload ){ // use database data as this is first pass
35 if(isset($this->question->id )){
36 // remove prefix #{..}# if exists
37 $this->initialname = $question->name ;
38 $regs= array();
39 if(preg_match('~#\{([^[:space:]]*)#~',$question->name , $regs)){
40 $question->name = str_replace($regs[0], '', $question->name);
fe6ce234 41 };
d90b016b
PP
42 }
43 }else {
fe6ce234 44 }
2d279432
PP
45 parent::question_edit_form($submiturl, $question, $category, $contexts, $formeditable);
46 }
47
2d279432 48 function get_per_answer_fields(&$mform, $label, $gradeoptions, &$repeatedoptions, &$answersoption) {
fe6ce234
DC
49 // $repeated = parent::get_per_answer_fields($mform, $label, $gradeoptions, $repeatedoptions, $answersoption);
50 $repeated = array();
2d279432 51 $repeated[] =& $mform->createElement('header', 'answerhdr', $label);
fe6ce234 52 // if ($this->editasmultichoice == 1){
2d279432
PP
53 $repeated[] =& $mform->createElement('text', 'answer', get_string('answer', 'quiz'), array('size' => 50));
54 $repeated[] =& $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions);
fe6ce234 55 $repeated[] =& $mform->createElement('editor', 'feedback', get_string('feedback', 'quiz'), null, $this->editoroptions);
2d279432
PP
56 $repeatedoptions['answer']['type'] = PARAM_RAW;
57 $repeatedoptions['fraction']['default'] = 0;
58 $answersoption = 'answers';
59
60 $mform->setType('answer', PARAM_NOTAGS);
61
62 $addrepeated = array();
fe6ce234
DC
63 $addrepeated[] =& $mform->createElement('hidden', 'tolerance');
64 $addrepeated[] =& $mform->createElement('hidden', 'tolerancetype',1);
2d279432
PP
65 $repeatedoptions['tolerance']['type'] = PARAM_NUMBER;
66 $repeatedoptions['tolerance']['default'] = 0.01;
67
68 $addrepeated[] =& $mform->createElement('select', 'correctanswerlength', get_string('correctanswershows', 'qtype_calculated'), range(0, 9));
69 $repeatedoptions['correctanswerlength']['default'] = 2;
70
71 $answerlengthformats = array('1' => get_string('decimalformat', 'quiz'), '2' => get_string('significantfiguresformat', 'quiz'));
72 $addrepeated[] =& $mform->createElement('select', 'correctanswerformat', get_string('correctanswershowsformat', 'qtype_calculated'), $answerlengthformats);
73 array_splice($repeated, 3, 0, $addrepeated);
fe6ce234 74 $repeated[1]->setLabel('...<strong>{={x}+..}</strong>...');
2d279432
PP
75
76 return $repeated;
77 }
78
79 /**
80 * Add question-type specific form fields.
81 *
82 * @param MoodleQuickForm $mform the form being built.
83 */
84 function definition_inner(&$mform) {
85 global $QTYPES;
86 $this->qtypeobj =& $QTYPES[$this->qtype()];
fe6ce234
DC
87 // echo code left for testing period
88 // echo "<p>question ".optional_param('multichoice', '', PARAM_RAW)." optional<pre>";print_r($this->question);echo "</pre></p>";
d7be65a3 89 $label = get_string("sharedwildcards", "qtype_calculated");
2d279432 90 $mform->addElement('hidden', 'initialcategory', 1);
d90b016b 91 $mform->addElement('hidden', 'reload', 1);
2d279432
PP
92 $mform->setType('initialcategory', PARAM_INT);
93
fe6ce234
DC
94 // $html2 = $this->qtypeobj->print_dataset_definitions_category($this->question);
95 $html2 ="";
2d279432 96 $mform->insertElementBefore($mform->createElement('static','listcategory',$label,$html2),'name');
d90b016b
PP
97 if(isset($this->question->id )){
98 $mform->insertElementBefore($mform->createElement('static','initialname',get_string('questionstoredname','qtype_calculated'),$this->initialname),'name');
99 };
2d279432
PP
100 $addfieldsname='updatecategory';
101 $addstring=get_string("updatecategory", "qtype_calculated");
fe6ce234 102 $mform->registerNoSubmitButton($addfieldsname);
2d279432 103 $this->editasmultichoice = 1 ;
fe6ce234 104
2d279432
PP
105
106 $mform->insertElementBefore( $mform->createElement('submit', $addfieldsname, $addstring),'listcategory');
107 $mform->registerNoSubmitButton('createoptionbutton');
fe6ce234
DC
108 $mform->addElement('hidden', 'multichoice',$this->editasmultichoice);
109 $mform->setType('multichoice', PARAM_INT);
2d279432 110
fe6ce234
DC
111
112 // $mform->addElement('header', 'choicehdr',get_string('multichoicecalculatedquestion', 'qtype_calculated'));
113 $menu = array(get_string('answersingleno', 'qtype_multichoice'), get_string('answersingleyes', 'qtype_multichoice'));
114 $mform->addElement('select', 'single', get_string('answerhowmany', 'qtype_multichoice'), $menu);
115 $mform->setDefault('single', 1);
116
117 $mform->addElement('advcheckbox', 'shuffleanswers', get_string('shuffleanswers', 'qtype_multichoice'), null, null, array(0,1));
ed14ad02 118 $mform->addHelpButton('shuffleanswers', 'shuffleanswers', 'qtype_multichoice');
fe6ce234
DC
119 $mform->setDefault('shuffleanswers', 1);
120
121 $numberingoptions = $QTYPES['multichoice']->get_numbering_styles();
122 $menu = array();
123 foreach ($numberingoptions as $numberingoption) {
124 $menu[$numberingoption] = get_string('answernumbering' . $numberingoption, 'qtype_multichoice');
125 }
126 $mform->addElement('select', 'answernumbering', get_string('answernumbering', 'qtype_multichoice'), $menu);
127 $mform->setDefault('answernumbering', 'abc');
2d279432
PP
128
129 $creategrades = get_grade_options();
fe6ce234
DC
130 $this->add_per_answer_fields($mform, get_string('choiceno', 'qtype_multichoice', '{no}'),
131 $creategrades->gradeoptionsfull, max(5, QUESTION_NUMANS_START));
132
2d279432
PP
133
134 $repeated = array();
fe6ce234
DC
135 // if ($this->editasmultichoice == 1){
136 $nounits = optional_param('nounits', 1, PARAM_INT);
137 $mform->addElement('hidden', 'nounits', $nounits);
138 $mform->setType('nounits', PARAM_INT);
139 $mform->setConstants(array('nounits'=>$nounits));
140 for ($i=0; $i< $nounits; $i++) {
141 $mform->addElement('hidden','unit'."[$i]", optional_param('unit'."[$i]", '', PARAM_NOTAGS));
142 $mform->setType('unit'."[$i]", PARAM_NOTAGS);
143 $mform->addElement('hidden', 'multiplier'."[$i]", optional_param('multiplier'."[$i]", '', PARAM_NUMBER));
144 $mform->setType('multiplier'."[$i]", PARAM_NUMBER);
145 }
2d279432 146
fe6ce234
DC
147 $mform->setType('addunits','hidden');
148 $mform->addElement('header', 'overallfeedbackhdr', get_string('overallfeedback', 'qtype_multichoice'));
2d279432 149
fe6ce234
DC
150 foreach (array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback') as $feedbackname) {
151 $mform->addElement('editor', $feedbackname, get_string($feedbackname, 'qtype_multichoice'), null, $this->editoroptions);
152 $mform->setType($feedbackname, PARAM_RAW);
153 }
2d279432
PP
154 //hidden elements
155 $mform->addElement('hidden', 'synchronize', '');
156 $mform->setType('synchronize', PARAM_INT);
157 if (isset($this->question->options)&& isset($this->question->options->synchronize) ){
158 $mform->setDefault("synchronize", $this->question->options->synchronize);
159 } else {
160 $mform->setDefault("synchronize", 0 );
161 }
162 $mform->addElement('hidden', 'wizard', 'datasetdefinitions');
163 $mform->setType('wizard', PARAM_ALPHA);
2d279432
PP
164 }
165
fe6ce234
DC
166 function data_preprocessing($question) {
167 $default_values['multichoice']= $this->editasmultichoice ; //$this->editasmultichoice ;
2d279432
PP
168 if (isset($question->options)){
169 $answers = $question->options->answers;
170 if (count($answers)) {
171 $key = 0;
172 foreach ($answers as $answer){
fe6ce234 173 $draftid = file_get_submitted_draft_itemid('feedback['.$key.']');
2d279432
PP
174 $default_values['answer['.$key.']'] = $answer->answer;
175 $default_values['fraction['.$key.']'] = $answer->fraction;
176 $default_values['tolerance['.$key.']'] = $answer->tolerance;
177 $default_values['tolerancetype['.$key.']'] = $answer->tolerancetype;
178 $default_values['correctanswerlength['.$key.']'] = $answer->correctanswerlength;
179 $default_values['correctanswerformat['.$key.']'] = $answer->correctanswerformat;
fe6ce234
DC
180 $default_values['feedback['.$key.']'] = array();
181 // prepare draftarea
41dcc2a5 182 $default_values['feedback['.$key.']']['text'] = file_prepare_draft_area($draftid, $this->context->id, 'question', 'answerfeedback', empty($answer->id)?null:(int)$answer->id, $this->fileoptions, $answer->feedback);
fe6ce234
DC
183 $default_values['feedback['.$key.']']['format'] = $answer->feedbackformat;
184 $default_values['feedback['.$key.']']['itemid'] = $draftid;
2d279432
PP
185 $key++;
186 }
187 }
fe6ce234 188 $default_values['synchronize'] = $question->options->synchronize ;
2d279432
PP
189
190 if (isset($question->options->units)){
191 $units = array_values($question->options->units);
192 // make sure the default unit is at index 0
193 usort($units, create_function('$a, $b',
fe6ce234
DC
194 'if (1.0 === (float)$a->multiplier) { return -1; } else '.
195 'if (1.0 === (float)$b->multiplier) { return 1; } else { return 0; }'));
2d279432
PP
196 if (count($units)) {
197 $key = 0;
198 foreach ($units as $unit){
199 $default_values['unit['.$key.']'] = $unit->unit;
200 $default_values['multiplier['.$key.']'] = $unit->multiplier;
201 $key++;
202 }
203 }
204 }
205 }
206 if (isset($question->options->single)){
fe6ce234
DC
207 $default_values['single'] = $question->options->single;
208 $default_values['answernumbering'] = $question->options->answernumbering;
209 $default_values['shuffleanswers'] = $question->options->shuffleanswers;
210 }
2d279432
PP
211 $default_values['submitbutton'] = get_string('nextpage', 'qtype_calculated');
212 $default_values['makecopy'] = get_string('makecopynextpage', 'qtype_calculated');
fe6ce234
DC
213
214 // prepare draft files
215 foreach (array('correctfeedback', 'partiallycorrectfeedback', 'incorrectfeedback') as $feedbackname) {
216 if (!isset($question->options->$feedbackname)) {
217 continue;
218 }
219 $text = $question->options->$feedbackname;
220 $draftid = file_get_submitted_draft_itemid($feedbackname);
221 $feedbackformat = $feedbackname . 'format';
222 $format = $question->options->$feedbackformat;
223 $default_values[$feedbackname] = array();
224 $default_values[$feedbackname]['text'] = file_prepare_draft_area(
225 $draftid, // draftid
226 $this->context->id, // context
227 'qtype_calculatedmulti', // component
228 $feedbackname, // filarea
229 !empty($question->id)?(int)$question->id:null, // itemid
230 $this->fileoptions, // options
231 $text // text
232 );
233 $default_values[$feedbackname]['format'] = $format;
234 $default_values[$feedbackname]['itemid'] = $draftid;
235 }
236 /**
237 * set the wild cards category display given that on loading the category element is
238 * unselected when processing this function but have a valid value when processing the
239 * update category button. The value can be obtain by
240 * $qu->category =$this->_form->_elements[$this->_form->_elementIndex['category']]->_values[0];
241 * but is coded using existing functions
242 */
243 $qu = new stdClass;
244 $el = new stdClass;
245 /* no need to call elementExists() here */
246 if ($this->_form->elementExists('category')){
2d279432 247 $el=$this->_form->getElement('category');
fe6ce234 248 } else {
2d279432 249 $el=$this->_form->getElement('categorymoveto');
fe6ce234
DC
250 }
251 if($value =$el->getSelected()) {
2d279432
PP
252 $qu->category =$value[0];
253 }else {
254 $qu->category=$question->category;// on load $question->category is set by question.php
255 }
256 $html2 = $this->qtypeobj->print_dataset_definitions_category($qu);
257 $this->_form->_elements[$this->_form->_elementIndex['listcategory']]->_text = $html2 ;
258 $question = (object)((array)$question + $default_values);
fe6ce234 259 return $question;
2d279432
PP
260 }
261
262 function qtype() {
263 return 'calculatedmulti';
264 }
265
266 function validation($data, $files) {
fe6ce234
DC
267 // echo code left for testing period
268 // echo "<p>question <pre>";print_r($this->question);echo "</pre></p>";
269 // echo "<p>data <pre>";print_r($data);echo "</pre></p>";
2d279432
PP
270
271 $errors = parent::validation($data, $files);
272 //verifying for errors in {=...} in question text;
273 $qtext = "";
fe6ce234
DC
274 $qtextremaining = $data['questiontext']['text'];
275 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
276 foreach ($possibledatasets as $name => $value) {
2d279432
PP
277 $qtextremaining = str_replace('{'.$name.'}', '1', $qtextremaining);
278 }
fe6ce234
DC
279 // echo "numericalquestion qtextremaining <pre>";print_r($possibledatasets);
280 while (preg_match('~\{=([^[:space:]}]*)}~', $qtextremaining, $regs1)) {
2d279432
PP
281 $qtextsplits = explode($regs1[0], $qtextremaining, 2);
282 $qtext =$qtext.$qtextsplits[0];
283 $qtextremaining = $qtextsplits[1];
284 if (!empty($regs1[1]) && $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])) {
285 if(!isset($errors['questiontext'])){
286 $errors['questiontext'] = $formulaerrors.':'.$regs1[1] ;
287 }else {
288 $errors['questiontext'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
289 }
290 }
291 }
292 $answers = $data['answer'];
293 $answercount = 0;
294 $maxgrade = false;
fe6ce234 295 $possibledatasets = $this->qtypeobj->find_dataset_names($data['questiontext']['text']);
2d279432
PP
296 $mandatorydatasets = array();
297 foreach ($answers as $key => $answer){
298 $mandatorydatasets += $this->qtypeobj->find_dataset_names($answer);
299 }
300 if ( count($mandatorydatasets )==0){
fe6ce234 301 // $errors['questiontext']=get_string('atleastonewildcard', 'qtype_datasetdependent');
2d279432
PP
302 foreach ($answers as $key => $answer){
303 $errors['answer['.$key.']'] = get_string('atleastonewildcard', 'qtype_datasetdependent');
304 }
305 }
306 if ($data['multichoice']== 1 ){
307 foreach ($answers as $key => $answer){
308 $trimmedanswer = trim($answer);
fe6ce234 309 if (($trimmedanswer!='')||$answercount==0){
2d279432
PP
310 //verifying for errors in {=...} in answer text;
311 $qanswer = "";
312 $qanswerremaining = $trimmedanswer ;
313 $possibledatasets = $this->qtypeobj->find_dataset_names($trimmedanswer);
fe6ce234 314 foreach ($possibledatasets as $name => $value) {
2d279432
PP
315 $qanswerremaining = str_replace('{'.$name.'}', '1', $qanswerremaining);
316 }
fe6ce234 317 // echo "numericalquestion qanswerremaining <pre>";print_r($possibledatasets);
2d279432
PP
318 while (preg_match('~\{=([^[:space:]}]*)}~', $qanswerremaining, $regs1)) {
319 $qanswersplits = explode($regs1[0], $qanswerremaining, 2);
320 $qanswer =$qanswer.$qanswersplits[0];
321 $qanswerremaining = $qanswersplits[1];
322 if (!empty($regs1[1]) && $formulaerrors = qtype_calculated_find_formula_errors($regs1[1])) {
323 if(!isset($errors['answer['.$key.']'])){
324 $errors['answer['.$key.']'] = $formulaerrors.':'.$regs1[1] ;
325 }else {
326 $errors['answer['.$key.']'] .= '<br/>'.$formulaerrors.':'.$regs1[1];
327 }
328 }
329 }
330 }
331 if ($trimmedanswer!=''){
332 if ('2' == $data['correctanswerformat'][$key]
fe6ce234
DC
333 && '0' == $data['correctanswerlength'][$key]) {
334 $errors['correctanswerlength['.$key.']'] = get_string('zerosignificantfiguresnotallowed','quiz');
335 }
2d279432
PP
336 if (!is_numeric($data['tolerance'][$key])){
337 $errors['tolerance['.$key.']'] = get_string('mustbenumeric', 'qtype_calculated');
338 }
339 if ($data['fraction'][$key] == 1) {
fe6ce234 340 $maxgrade = true;
2d279432 341 }
fe6ce234 342
2d279432
PP
343 $answercount++;
344 }
345 //check grades
346 $totalfraction = 0 ;
347 $maxfraction = 0 ;
348 if ($answer != '') {
349 if ($data['fraction'][$key] > 0) {
350 $totalfraction += $data['fraction'][$key];
351 }
352 if ($data['fraction'][$key] > $maxfraction) {
353 $maxfraction = $data['fraction'][$key];
354 }
fe6ce234 355 }
2d279432
PP
356 }
357 if ($answercount==0){
358 $errors['answer[0]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
359 $errors['answer[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
360 } elseif ($answercount==1){
361 $errors['answer[1]'] = get_string('notenoughanswers', 'qtype_multichoice', 2);
fe6ce234 362
2d279432
PP
363 }
364
365 /// Perform sanity checks on fractional grades
366 if ($data['single']) {
367 if ($maxfraction > 0.999 ) {
368 $maxfraction = $maxfraction * 100;
369 $errors['fraction[0]'] = get_string('errfractionsnomax', 'qtype_multichoice', $maxfraction);
370 }
371 } else {
372 $totalfraction = round($totalfraction,2);
373 if ($totalfraction != 1) {
374 $totalfraction = $totalfraction * 100;
375 $errors['fraction[0]'] = get_string('errfractionsaddwrong', 'qtype_multichoice', $totalfraction);
376 }
377 }
fe6ce234 378
2d279432
PP
379 if ($answercount==0){
380 $errors['answer[0]'] = get_string('atleastoneanswer', 'qtype_calculated');
381 }
382 if ($maxgrade == false) {
383 $errors['fraction[0]'] = get_string('fractionsnomax', 'question');
384 }
fe6ce234 385
2d279432
PP
386 }
387 return $errors;
388 }
389}