Merge branch 'wip-MDL-40136-m26' of git://github.com/samhemelryk/moodle
[moodle.git] / question / type / calculated / datasetitems_form.php
1 <?php
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/>.
17 /**
18  * Defines the editing form for the calculated question data set items.
19  *
20  * @package    qtype
21  * @subpackage calculated
22  * @copyright  2007 Jamie Pratt me@jamiep.org
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->dirroot . '/question/type/edit_question_form.php');
32 /**
33  * Calculated question data set items editing form definition.
34  *
35  * @copyright  2007 Jamie Pratt me@jamiep.org
36  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37  */
38 class question_dataset_dependent_items_form extends question_wizard_form {
39     /**
40      * Question object with options and answers already loaded by get_question_options
41      * Be careful how you use this it is needed sometimes to set up the structure of the
42      * form in definition_inner but data is always loaded into the form with set_defaults.
43      *
44      * @var object
45      */
46     public $question;
47     /**
48      * Reference to question type object
49      *
50      * @var question_dataset_dependent_questiontype
51      */
52     public $qtypeobj;
54     public $datasetdefs;
56     public $maxnumber = -1;
58     public $regenerate;
60     public $noofitems;
62     public $outsidelimit = false;
64     public $commentanswers = array();
66     /**
67      * Add question-type specific form fields.
68      *
69      * @param MoodleQuickForm $mform the form being built.
70      */
71     public function __construct($submiturl, $question, $regenerate) {
72         global $SESSION, $CFG, $DB;
73         $this->regenerate = $regenerate;
74         $this->question = $question;
75         $this->qtypeobj = question_bank::get_qtype($this->question->qtype);
76         // Validate the question category.
77         if (!$category = $DB->get_record('question_categories',
78                 array('id' => $question->category))) {
79             print_error('categorydoesnotexist', 'question', $returnurl);
80         }
81         $this->category = $category;
82         $this->categorycontext = context::instance_by_id($category->contextid);
83         // Get the dataset defintions for this question.
84         if (empty($question->id)) {
85             $this->datasetdefs = $this->qtypeobj->get_dataset_definitions(
86                     $question->id, $SESSION->calculated->definitionform->dataset);
87         } else {
88             if (empty($question->options)) {
89                 $this->get_question_options($question);
90             }
91             $this->datasetdefs = $this->qtypeobj->get_dataset_definitions(
92                     $question->id, array());
93         }
95         foreach ($this->datasetdefs as $datasetdef) {
96             // Get maxnumber.
97             if ($this->maxnumber == -1 || $datasetdef->itemcount < $this->maxnumber) {
98                 $this->maxnumber = $datasetdef->itemcount;
99             }
100         }
101         foreach ($this->datasetdefs as $defid => $datasetdef) {
102             if (isset($datasetdef->id)) {
103                 $this->datasetdefs[$defid]->items =
104                         $this->qtypeobj->get_database_dataset_items($datasetdef->id);
105             }
106         }
107         parent::__construct($submiturl);
108     }
110     protected function definition() {
111         $labelsharedwildcard = get_string("sharedwildcard", "qtype_calculated");
112         $mform =& $this->_form;
113         $mform->setDisableShortforms();
115         $strquestionlabel = $this->qtypeobj->comment_header($this->question);
116         if ($this->maxnumber != -1 ) {
117             $this->noofitems = $this->maxnumber;
118         } else {
119             $this->noofitems = 0;
120         }
121         $label = get_string("sharedwildcards", "qtype_calculated");
123         $html2 = $this->qtypeobj->print_dataset_definitions_category_shared(
124                 $this->question, $this->datasetdefs);
125         $mform->addElement('static', 'listcategory', $label, $html2);
126         // ...----------------------------------------------------------------------.
127         $mform->addElement('submit', 'updatedatasets',
128                 get_string('updatedatasetparam', 'qtype_calculated'));
129         $mform->registerNoSubmitButton('updatedatasets');
130         $mform->addElement('header', 'additemhdr',
131                 get_string('itemtoadd', 'qtype_calculated'));
132         $idx = 1;
133         $data = array();
134         $j = (($this->noofitems) * count($this->datasetdefs))+1;
135         foreach ($this->datasetdefs as $defkey => $datasetdef) {
136             if ($datasetdef->category |= 0 ) {
137                 $name = get_string('sharedwildcard', 'qtype_calculated', $datasetdef->name);
138             } else {
139                 $name = get_string('wildcard', 'qtype_calculated', $datasetdef->name);
140             }
141             $mform->addElement('text', "number[$j]", $name);
142             $mform->setType("number[$j]", PARAM_FLOAT);
143             $this->qtypeobj->custom_generator_tools_part($mform, $idx, $j);
144             $idx++;
145             $mform->addElement('hidden', "definition[$j]");
146             $mform->setType("definition[$j]", PARAM_RAW);
147             $mform->addElement('hidden', "itemid[$j]");
148             $mform->setType("itemid[$j]", PARAM_RAW);
149             $mform->addElement('static', "divider[$j]", '', '<hr />');
150             $mform->setType("divider[$j]", PARAM_RAW);
151             $j++;
152         }
154         $mform->addElement('header', 'updateanswershdr',
155                 get_string('answerstoleranceparam', 'qtype_calculated'));
156         $mform->addElement('submit', 'updateanswers',
157                 get_string('updatetolerancesparam', 'qtype_calculated'));
158         $mform->setAdvanced('updateanswers', true);
159         $mform->registerNoSubmitButton('updateanswers');
161         $answers = fullclone($this->question->options->answers);
162         $key1 =1;
163         foreach ($answers as $key => $answer) {
164             if ('' === $answer->answer) {
165                 // Do nothing.
166             } else if ('*' === $answer->answer) {
167                 $mform->addElement('static',
168                         'answercomment[' . ($this->noofitems+$key1) . ']', $answer->answer);
169                 $mform->addElement('hidden', 'tolerance['.$key.']', '');
170                 $mform->setType('tolerance['.$key.']', PARAM_RAW);
171                 $mform->setAdvanced('tolerance['.$key.']', true);
172                 $mform->addElement('hidden', 'tolerancetype['.$key.']', '');
173                 $mform->setType('tolerancetype['.$key.']', PARAM_RAW);
174                 $mform->setAdvanced('tolerancetype['.$key.']', true);
175                 $mform->addElement('hidden', 'correctanswerlength['.$key.']', '');
176                 $mform->setType('correctanswerlength['.$key.']', PARAM_RAW);
177                 $mform->setAdvanced('correctanswerlength['.$key.']', true);
178                 $mform->addElement('hidden', 'correctanswerformat['.$key.']', '');
179                 $mform->setType('correctanswerformat['.$key.']', PARAM_RAW);
180                 $mform->setAdvanced('correctanswerformat['.$key.']', true);
181             } else {
182                 $mform->addElement('static', 'answercomment[' . ($this->noofitems+$key1) . ']',
183                         $answer->answer);
184                 $mform->addElement('text', 'tolerance['.$key.']',
185                         get_string('tolerance', 'qtype_calculated'));
186                 $mform->setType('tolerance['.$key.']', PARAM_RAW);
187                 $mform->setAdvanced('tolerance['.$key.']', true);
188                 $mform->addElement('select', 'tolerancetype['.$key.']',
189                         get_string('tolerancetype', 'qtype_numerical'),
190                         $this->qtypeobj->tolerance_types());
191                 $mform->setAdvanced('tolerancetype['.$key.']', true);
193                 $mform->addElement('select', 'correctanswerlength['.$key.']',
194                         get_string('correctanswershows', 'qtype_calculated'), range(0, 9));
195                 $mform->setAdvanced('correctanswerlength['.$key.']', true);
197                 $answerlengthformats = array(
198                     '1' => get_string('decimalformat', 'qtype_numerical'),
199                     '2' => get_string('significantfiguresformat', 'qtype_calculated')
200                 );
201                 $mform->addElement('select', 'correctanswerformat['.$key.']',
202                         get_string('correctanswershowsformat', 'qtype_calculated'),
203                         $answerlengthformats);
204                 $mform->setAdvanced('correctanswerformat['.$key.']', true);
205                 $mform->addElement('static', 'dividertolerance', '', '<hr />');
206                 $mform->setAdvanced('dividertolerance', true);
207             }
208             $key1++;
209         }
211         $addremoveoptions = array();
212         $addremoveoptions['1']='1';
213         for ($i=10; $i<=100; $i+=10) {
214              $addremoveoptions["$i"]="$i";
215         }
216         $showoptions = Array();
217         $showoptions['1']='1';
218         $showoptions['2']='2';
219         $showoptions['5']='5';
220         for ($i=10; $i<=100; $i+=10) {
221              $showoptions["$i"]="$i";
222         }
223         $mform->addElement('header', 'addhdr', get_string('add', 'moodle'));
224         $mform->closeHeaderBefore('addhdr');
226         if ($this->qtypeobj->supports_dataset_item_generation()) {
227             $radiogrp = array();
228             $radiogrp[] =& $mform->createElement('radio', 'nextpageparam[forceregeneration]',
229                     null, get_string('reuseifpossible', 'qtype_calculated'), 0);
230             $radiogrp[] =& $mform->createElement('radio', 'nextpageparam[forceregeneration]',
231                     null, get_string('forceregenerationshared', 'qtype_calculated'), 1);
232             $radiogrp[] =& $mform->createElement('radio', 'nextpageparam[forceregeneration]',
233                     null, get_string('forceregenerationall', 'qtype_calculated'), 2);
234             $mform->addGroup($radiogrp, 'forceregenerationgrp',
235                     get_string('nextitemtoadd', 'qtype_calculated'), "<br/>", false);
236         }
238         $mform->addElement('submit', 'getnextbutton', get_string('getnextnow', 'qtype_calculated'));
239         $mform->addElement('static', "dividera", '', '<hr />');
240         $addgrp = array();
241         $addgrp[] =& $mform->createElement('submit', 'addbutton', get_string('add', 'moodle'));
242         $addgrp[] =& $mform->createElement('select', "selectadd",
243                 get_string('additem', 'qtype_calculated'), $addremoveoptions);
244         $addgrp[] = & $mform->createElement('static', "stat", "Items",
245                 get_string('newsetwildcardvalues', 'qtype_calculatedsimple'));
246         $mform->addGroup($addgrp, 'addgrp', get_string('additem', 'qtype_calculated'), ' ', false);
247         $mform->addElement('static', "divideradd", '', '');
248         if ($this->noofitems > 0) {
249             $mform->addElement('header', 'deleteitemhdr', get_string('delete', 'moodle'));
250             $deletegrp = array();
251             $deletegrp[] = $mform->createElement('submit', 'deletebutton',
252                     get_string('delete', 'moodle'));
253             $deletegrp[] = $mform->createElement('select', 'selectdelete',
254                     get_string('deleteitem', 'qtype_calculated')."1", $addremoveoptions);
255             $deletegrp[] = $mform->createElement('static', "stat", "Items",
256                     get_string('setwildcardvalues', 'qtype_calculatedsimple'));
257             $mform->addGroup($deletegrp, 'deletegrp', '', '   ', false);
258         } else {
259             $mform->addElement('static', 'warning', '', '<span class="error">' .
260                     get_string('youmustaddatleastoneitem', 'qtype_calculated').'</span>');
261         }
263         $addgrp1 = array();
264         $addgrp1[] = $mform->createElement('submit', 'showbutton',
265                 get_string('showitems', 'qtype_calculated'));
266         $addgrp1[] = $mform->createElement('select', "selectshow", '' , $showoptions);
267         $addgrp1[] = $mform->createElement('static', "stat", '',
268                 get_string('setwildcardvalues', 'qtype_calculated'));
269         $mform->addGroup($addgrp1, 'addgrp1', '', '   ', false);
270         $mform->registerNoSubmitButton('showbutton');
271         $mform->closeHeaderBefore('addgrp1');
272         // ...----------------------------------------------------------------------.
273         $j = $this->noofitems * count($this->datasetdefs);
274         $k = optional_param('selectshow', 1, PARAM_INT);
275         for ($i = $this->noofitems; $i >= 1; $i--) {
276             if ($k > 0) {
277                 $mform->addElement('header', 'setnoheader' . $i, "<b>" .
278                         get_string('setno', 'qtype_calculated', $i)."</b>&nbsp;&nbsp;");
279             }
280             foreach ($this->datasetdefs as $defkey => $datasetdef) {
281                 if ($k > 0) {
282                     if ($datasetdef->category == 0 ) {
283                         $mform->addElement('text', "number[$j]",
284                                 get_string('wildcard', 'qtype_calculated', $datasetdef->name));
285                     } else {
286                         $mform->addElement('text', "number[$j]", get_string(
287                                 'sharedwildcard', 'qtype_calculated', $datasetdef->name));
288                     }
290                 } else {
291                     $mform->addElement('hidden', "number[$j]" , '');
292                 }
293                 $mform->setType("number[$j]", PARAM_FLOAT);
294                 $mform->addElement('hidden', "itemid[$j]");
295                 $mform->setType("itemid[$j]", PARAM_INT);
297                 $mform->addElement('hidden', "definition[$j]");
298                 $mform->setType("definition[$j]", PARAM_NOTAGS);
299                 $data[$datasetdef->name] =$datasetdef->items[$i]->value;
301                 $j--;
302             }
303             if ('' != $strquestionlabel && ($k > 0 )) {
304                 // ... $this->outsidelimit || !empty($this->numbererrors ).
305                 $repeated[] = $mform->addElement('static', "answercomment[$i]", $strquestionlabel);
306                 // Decode equations in question text.
307                 $qtext = $this->qtypeobj->substitute_variables(
308                         $this->question->questiontext, $data);
309                 $textequations = $this->qtypeobj->find_math_equations($qtext);
310                 if ($textequations != '' && count($textequations) > 0 ) {
311                     $mform->addElement('static', "divider1[$j]", '',
312                             'Formulas {=..} in question text');
313                     foreach ($textequations as $key => $equation) {
314                         if ($formulaerrors = qtype_calculated_find_formula_errors($equation)) {
315                             $str=$formulaerrors;
316                         } else {
317                             eval('$str = '.$equation.';');
318                         }
320                         $mform->addElement('static', "textequation", "{=$equation}", "=".$str);
321                     }
322                 }
324             }
325             $k--;
327         }
328         $mform->addElement('static', 'outsidelimit', '', '');
329         // ...----------------------------------------------------------------------
330         // Non standard name for button element needed so not using add_action_buttons.
331         if (!($this->noofitems==0) ) {
332             $mform->addElement('submit', 'savechanges', get_string('savechanges'));
333             $mform->closeHeaderBefore('savechanges');
334         }
336         $this->add_hidden_fields();
338         $mform->addElement('hidden', 'category');
339         $mform->setType('category', PARAM_SEQUENCE);
341         $mform->addElement('hidden', 'wizard', 'datasetitems');
342         $mform->setType('wizard', PARAM_ALPHA);
343     }
345     public function set_data($question) {
346         $formdata = array();
347         $fromform = new stdClass();
348         if (isset($question->options)) {
349             $answers = $question->options->answers;
350             if (count($answers)) {
351                 if (optional_param('updateanswers', false, PARAM_BOOL) ||
352                         optional_param('updatedatasets', false, PARAM_BOOL)) {
353                     foreach ($answers as $key => $answer) {
354                         $fromform->tolerance[$key]= $this->_form->getElementValue(
355                                 'tolerance['.$key.']');
356                         $answer->tolerance = $fromform->tolerance[$key];
357                         $fromform->tolerancetype[$key]= $this->_form->getElementValue(
358                                 'tolerancetype['.$key.']');
359                         if (is_array($fromform->tolerancetype[$key])) {
360                             $fromform->tolerancetype[$key]= $fromform->tolerancetype[$key][0];
361                         }
362                         $answer->tolerancetype = $fromform->tolerancetype[$key];
363                         $fromform->correctanswerlength[$key]= $this->_form->getElementValue(
364                                 'correctanswerlength['.$key.']');
365                         if (is_array($fromform->correctanswerlength[$key])) {
366                             $fromform->correctanswerlength[$key] =
367                                     $fromform->correctanswerlength[$key][0];
368                         }
369                         $answer->correctanswerlength = $fromform->correctanswerlength[$key];
370                         $fromform->correctanswerformat[$key] = $this->_form->getElementValue(
371                                 'correctanswerformat['.$key.']');
372                         if (is_array($fromform->correctanswerformat[$key])) {
373                             $fromform->correctanswerformat[$key] =
374                                     $fromform->correctanswerformat[$key][0];
375                         }
376                         $answer->correctanswerformat = $fromform->correctanswerformat[$key];
377                     }
378                     $this->qtypeobj->save_question_calculated($question, $fromform);
380                 } else {
381                     foreach ($answers as $key => $answer) {
382                         $formdata['tolerance['.$key.']'] = $answer->tolerance;
383                         $formdata['tolerancetype['.$key.']'] = $answer->tolerancetype;
384                         $formdata['correctanswerlength['.$key.']'] = $answer->correctanswerlength;
385                         $formdata['correctanswerformat['.$key.']'] = $answer->correctanswerformat;
386                     }
387                 }
388             }
389         }
390         // Fill out all data sets and also the fields for the next item to add.
391         $j = $this->noofitems * count($this->datasetdefs);
392         for ($itemnumber = $this->noofitems; $itemnumber >= 1; $itemnumber--) {
393             $data = array();
394             foreach ($this->datasetdefs as $defid => $datasetdef) {
395                 if (isset($datasetdef->items[$itemnumber])) {
396                     $formdata["number[$j]"] = $datasetdef->items[$itemnumber]->value;
397                     $formdata["definition[$j]"] = $defid;
398                     $formdata["itemid[$j]"] = $datasetdef->items[$itemnumber]->id;
399                     $data[$datasetdef->name] = $datasetdef->items[$itemnumber]->value;
400                 }
401                 $j--;
402             }
403             $comment = $this->qtypeobj->comment_on_datasetitems($this->qtypeobj, $question->id,
404                     $question->questiontext, $answers, $data, $itemnumber);
405             if ($comment->outsidelimit) {
406                 $this->outsidelimit=$comment->outsidelimit;
407             }
408             $totalcomment='';
409             foreach ($question->options->answers as $key => $answer) {
410                 $totalcomment .= $comment->stranswers[$key].'<br/>';
411             }
412             $formdata['answercomment['.$itemnumber.']'] = $totalcomment;
413         }
415         $formdata['nextpageparam[forceregeneration]'] = $this->regenerate;
416         $formdata['selectdelete'] = '1';
417         $formdata['selectadd'] = '1';
418         $j = $this->noofitems * count($this->datasetdefs)+1;
419         $data = array(); // Data for comment_on_datasetitems later.
420         // Dataset generation defaults.
421         if ($this->qtypeobj->supports_dataset_item_generation()) {
422             $itemnumber = $this->noofitems+1;
423             foreach ($this->datasetdefs as $defid => $datasetdef) {
424                 if (!optional_param('updatedatasets', false, PARAM_BOOL) &&
425                         !optional_param('updateanswers', false, PARAM_BOOL)) {
426                     $formdata["number[$j]"] = $this->qtypeobj->generate_dataset_item(
427                             $datasetdef->options);
428                 } else {
429                     $formdata["number[$j]"] = $this->_form->getElementValue("number[$j]");
430                 }
431                 $formdata["definition[$j]"] = $defid;
432                 $formdata["itemid[$j]"] = isset($datasetdef->items[$itemnumber]) ?
433                         $datasetdef->items[$itemnumber]->id : 0;
434                 $data[$datasetdef->name] = $formdata["number[$j]"];
435                 $j++;
436             }
437         }
439         // Existing records override generated data depending on radio element.
440         $j = $this->noofitems * count($this->datasetdefs) + 1;
441         if (!$this->regenerate && !optional_param('updatedatasets', false, PARAM_BOOL) &&
442                 !optional_param('updateanswers', false, PARAM_BOOL)) {
443             $idx = 1;
444             $itemnumber = $this->noofitems + 1;
445             foreach ($this->datasetdefs as $defid => $datasetdef) {
446                 if (isset($datasetdef->items[$itemnumber])) {
447                     $formdata["number[$j]"] = $datasetdef->items[$itemnumber]->value;
448                     $formdata["definition[$j]"] = $defid;
449                     $formdata["itemid[$j]"] = $datasetdef->items[$itemnumber]->id;
450                     $data[$datasetdef->name] = $datasetdef->items[$itemnumber]->value;
451                 }
452                 $j++;
453             }
454         }
456         $comment = $this->qtypeobj->comment_on_datasetitems($this->qtypeobj, $question->id,
457                 $question->questiontext, $answers, $data, ($this->noofitems + 1));
458         if (isset($comment->outsidelimit) && $comment->outsidelimit) {
459             $this->outsidelimit=$comment->outsidelimit;
460         }
461         $key1 = 1;
462         foreach ($question->options->answers as $key => $answer) {
463             $formdata['answercomment['.($this->noofitems+$key1).']'] = $comment->stranswers[$key];
464             $key1++;
465         }
467         if ($this->outsidelimit) {
468             $formdata['outsidelimit']= '<span class="error">' .
469                     get_string('oneanswertrueansweroutsidelimits', 'qtype_calculated') . '</span>';
470         }
471         $formdata = $this->qtypeobj->custom_generator_set_data($this->datasetdefs, $formdata);
473         parent::set_data((object)($formdata + (array)$question));
474     }
476     public function validation($data, $files) {
477         $errors = array();
478         if (isset($data['savechanges']) && ($this->noofitems==0) ) {
479             $errors['warning'] = get_string('warning', 'mnet');
480         }
481         if ($this->outsidelimit) {
482             $errors['outsidelimits'] =
483                     get_string('oneanswertrueansweroutsidelimits', 'qtype_calculated');
484         }
485         $numbers = $data['number'];
486         foreach ($numbers as $key => $number) {
487             if (! is_numeric($number)) {
488                 if (stristr($number, ', ')) {
489                     $errors['number['.$key.']'] = get_string(
490                         'The , cannot be used, use . as in 0.013 or 1.3e-2', 'qtype_calculated');
491                 } else {
492                     $errors['number['.$key.']'] = get_string(
493                             'This is not a valid number', 'qtype_calculated');
494                 }
495             } else if (stristr($number, 'x')) {
496                 $errors['number['.$key.']'] = get_string(
497                         'Hexadecimal format (i.e. 0X12d) is not allowed', 'qtype_calculated');
498             } else if (is_nan($number)) {
499                 $errors['number['.$key.']'] = get_string(
500                         'is a NAN number', 'qtype_calculated');
501             }
502         }
503         return $errors;
504     }