Merge branch 'MDL-59081-master' of git://github.com/abgreeve/moodle
[moodle.git] / mod / lesson / pagetypes / numerical.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Numerical
20  *
21  * @package mod_lesson
22  * @copyright  2009 Sam Hemelryk
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  **/
26 defined('MOODLE_INTERNAL') || die();
28 /** Numerical question type */
29 define("LESSON_PAGE_NUMERICAL",     "8");
31 class lesson_page_type_numerical extends lesson_page {
33     protected $type = lesson_page::TYPE_QUESTION;
34     protected $typeidstring = 'numerical';
35     protected $typeid = LESSON_PAGE_NUMERICAL;
36     protected $string = null;
38     public function get_typeid() {
39         return $this->typeid;
40     }
41     public function get_typestring() {
42         if ($this->string===null) {
43             $this->string = get_string($this->typeidstring, 'lesson');
44         }
45         return $this->string;
46     }
47     public function get_idstring() {
48         return $this->typeidstring;
49     }
50     public function display($renderer, $attempt) {
51         global $USER, $CFG, $PAGE;
52         $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents(), 'lessonid'=>$this->lesson->id));
53         $data = new stdClass;
54         $data->id = $PAGE->cm->id;
55         $data->pageid = $this->properties->id;
56         if (isset($USER->modattempts[$this->lesson->id])) {
57             $data->answer = s($attempt->useranswer);
58         }
59         $mform->set_data($data);
61         // Trigger an event question viewed.
62         $eventparams = array(
63             'context' => context_module::instance($PAGE->cm->id),
64             'objectid' => $this->properties->id,
65             'other' => array(
66                     'pagetype' => $this->get_typestring()
67                 )
68             );
70         $event = \mod_lesson\event\question_viewed::create($eventparams);
71         $event->trigger();
72         return $mform->display();
73     }
75     /**
76      * Creates answers for this page type.
77      *
78      * @param  object $properties The answer properties.
79      */
80     public function create_answers($properties) {
81         if (isset($properties->enableotheranswers) && $properties->enableotheranswers) {
82             $properties->response_editor = array_values($properties->response_editor);
83             $properties->jumpto = array_values($properties->jumpto);
84             $properties->score = array_values($properties->score);
85             $wrongresponse = end($properties->response_editor);
86             $wrongkey = key($properties->response_editor);
87             $properties->answer_editor[$wrongkey] = LESSON_OTHER_ANSWERS;
88         }
89         parent::create_answers($properties);
90     }
92     /**
93      * Update the answers for this page type.
94      *
95      * @param  object $properties The answer properties.
96      * @param  context $context The context for this module.
97      * @param  int $maxbytes The maximum bytes for any uploades.
98      */
99     public function update($properties, $context = null, $maxbytes = null) {
100         if ($properties->enableotheranswers) {
101             $properties->response_editor = array_values($properties->response_editor);
102             $properties->jumpto = array_values($properties->jumpto);
103             $properties->score = array_values($properties->score);
104             $wrongresponse = end($properties->response_editor);
105             $wrongkey = key($properties->response_editor);
106             $properties->answer_editor[$wrongkey] = LESSON_OTHER_ANSWERS;
107         }
108         parent::update($properties, $context, $maxbytes);
109     }
111     public function check_answer() {
112         global $CFG;
113         $result = parent::check_answer();
115         $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents()));
116         $data = $mform->get_data();
117         require_sesskey();
119         $formattextdefoptions = new stdClass();
120         $formattextdefoptions->noclean = true;
121         $formattextdefoptions->para = false;
123         // set defaults
124         $result->response = '';
125         $result->newpageid = 0;
127         if (!isset($data->answer) || !is_numeric($data->answer)) {
128             $result->noanswer = true;
129             return $result;
130         } else {
131             // Just doing default PARAM_RAW, not doing PARAM_INT because it could be a float.
132             $result->useranswer = (float)$data->answer;
133         }
134         $result->studentanswer = $result->userresponse = $result->useranswer;
135         $answers = $this->get_answers();
136         foreach ($answers as $answer) {
137             $answer = parent::rewrite_answers_urls($answer);
138             if (strpos($answer->answer, ':')) {
139                 // there's a pairs of values
140                 list($min, $max) = explode(':', $answer->answer);
141                 $minimum = (float) $min;
142                 $maximum = (float) $max;
143             } else {
144                 // there's only one value
145                 $minimum = (float) $answer->answer;
146                 $maximum = $minimum;
147             }
148             if (($result->useranswer >= $minimum) && ($result->useranswer <= $maximum)) {
149                 $result->newpageid = $answer->jumpto;
150                 $result->response = format_text($answer->response, $answer->responseformat, $formattextdefoptions);
151                 if ($this->lesson->jumpto_is_correct($this->properties->id, $result->newpageid)) {
152                     $result->correctanswer = true;
153                 }
154                 if ($this->lesson->custom) {
155                     if ($answer->score > 0) {
156                         $result->correctanswer = true;
157                     } else {
158                         $result->correctanswer = false;
159                     }
160                 }
161                 $result->answerid = $answer->id;
162                 return $result;
163             }
164         }
165         // We could check here to see if we have a wrong answer jump to use.
166         if ($result->answerid == 0) {
167             // Use the all other answers jump details if it is set up.
168             $lastanswer = end($answers);
169             // Double check that this is the @#wronganswer#@ answer.
170             if (strpos($lastanswer->answer, LESSON_OTHER_ANSWERS) !== false) {
171                 $otheranswers = end($answers);
172                 $result->newpageid = $otheranswers->jumpto;
173                 $result->response = format_text($otheranswers->response, $otheranswers->responseformat, $formattextdefoptions);
174                 // Does this also need to do the jumpto_is_correct?
175                 if ($this->lesson->custom) {
176                     $result->correctanswer = ($otheranswers->score > 0);
177                 }
178                 $result->answerid = $otheranswers->id;
179             }
180         }
181         return $result;
182     }
184     public function display_answers(html_table $table) {
185         $answers = $this->get_answers();
186         $options = new stdClass;
187         $options->noclean = true;
188         $options->para = false;
189         $i = 1;
190         foreach ($answers as $answer) {
191             $answer = parent::rewrite_answers_urls($answer, false);
192             $cells = array();
193             if ($this->lesson->custom && $answer->score > 0) {
194                 // if the score is > 0, then it is correct
195                 $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
196             } else if ($this->lesson->custom) {
197                 $cells[] = '<label>' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
198             } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
199                 // underline correct answers
200                 $cells[] = '<span class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</span>:' . "\n";
201             } else {
202                 $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . ' ' . $i . '</label>:';
203             }
204             $cells[] = format_text($answer->answer, $answer->answerformat, $options);
205             $table->data[] = new html_table_row($cells);
207             $cells = array();
208             $cells[] = '<label>' . get_string('response', 'lesson') . ' ' . $i . '</label>:';
209             $cells[] = format_text($answer->response, $answer->responseformat, $options);
210             $table->data[] = new html_table_row($cells);
212             $cells = array();
213             $cells[] = '<label>' . get_string('score', 'lesson') . '</label>:';
214             $cells[] = $answer->score;
215             $table->data[] = new html_table_row($cells);
217             $cells = array();
218             $cells[] = '<label>' . get_string('jump', 'lesson') . '</label>:';
219             $cells[] = $this->get_jump_name($answer->jumpto);
220             $table->data[] = new html_table_row($cells);
221             if ($i === 1){
222                 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
223             }
224             $i++;
225         }
226         return $table;
227     }
228     public function stats(array &$pagestats, $tries) {
229         if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
230             $temp = $tries[$this->lesson->maxattempts - 1];
231         } else {
232             // else, user attempted the question less than the max, so grab the last one
233             $temp = end($tries);
234         }
235         if (isset($pagestats[$temp->pageid][$temp->useranswer])) {
236             $pagestats[$temp->pageid][$temp->useranswer]++;
237         } else {
238             $pagestats[$temp->pageid][$temp->useranswer] = 1;
239         }
240         if (isset($pagestats[$temp->pageid]["total"])) {
241             $pagestats[$temp->pageid]["total"]++;
242         } else {
243             $pagestats[$temp->pageid]["total"] = 1;
244         }
245         return true;
246     }
248     public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
249         $answers = $this->get_answers();
250         $formattextdefoptions = new stdClass;
251         $formattextdefoptions->para = false;  //I'll use it widely in this page
252         foreach ($answers as $answer) {
253             if ($useranswer == null && $i == 0) {
254                 // I have the $i == 0 because it is easier to blast through it all at once.
255                 if (isset($pagestats[$this->properties->id])) {
256                     $stats = $pagestats[$this->properties->id];
257                     $total = $stats["total"];
258                     unset($stats["total"]);
259                     foreach ($stats as $valentered => $ntimes) {
260                         $data = '<input class="form-control" type="text" size="50" ' .
261                                 'disabled="disabled" readonly="readonly" value="'.s($valentered).'" />';
262                         $percent = $ntimes / $total * 100;
263                         $percent = round($percent, 2);
264                         $percent .= "% ".get_string("enteredthis", "lesson");
265                         $answerdata->answers[] = array($data, $percent);
266                     }
267                 } else {
268                     $answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " ");
269                 }
270                 $i++;
271             } else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) &&
272                     empty($answerdata->answers)))) {
273                 // Get in here when the user answered or for the last answer.
274                 $data = '<input class="form-control" type="text" size="50" ' .
275                         'disabled="disabled" readonly="readonly" value="'.s($useranswer->useranswer).'">';
276                 if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) {
277                     $percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100;
278                     $percent = round($percent, 2);
279                     $percent .= "% ".get_string("enteredthis", "lesson");
280                 } else {
281                     $percent = get_string("nooneenteredthis", "lesson");
282                 }
283                 $answerdata->answers[] = array($data, $percent);
285                 if ($answer->id == $useranswer->answerid) {
286                     if ($answer->response == null) {
287                         if ($useranswer->correct) {
288                             $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
289                         } else {
290                             $answerdata->response = get_string("thatsthewronganswer", "lesson");
291                         }
292                     } else {
293                         $answerdata->response = $answer->response;
294                     }
295                     if ($this->lesson->custom) {
296                         $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
297                     } elseif ($useranswer->correct) {
298                         $answerdata->score = get_string("receivedcredit", "lesson");
299                     } else {
300                         $answerdata->score = get_string("didnotreceivecredit", "lesson");
301                     }
302                 } else {
303                     $answerdata->response = get_string("thatsthewronganswer", "lesson");
304                     if ($this->lesson->custom) {
305                         $answerdata->score = get_string("pointsearned", "lesson").": 0";
306                     } else {
307                         $answerdata->score = get_string("didnotreceivecredit", "lesson");
308                     }
309                 }
310             }
311             $answerpage->answerdata = $answerdata;
312         }
313         return $answerpage;
314     }
316     /**
317      * Make updates to the form data if required. In this case to put the all other answer data into the write section of the form.
318      *
319      * @param stdClass $data The form data to update.
320      * @return stdClass The updated fom data.
321      */
322     public function update_form_data(stdClass $data) : stdClass {
323         $answercount = count($this->get_answers());
324         // Check for other answer entry.
325         $lastanswer = $data->{'answer_editor[' . ($answercount - 1) . ']'};
326         if (strpos($lastanswer, LESSON_OTHER_ANSWERS) !== false) {
327             $data->{'answer_editor[' . ($this->lesson->maxanswers + 1) . ']'} =
328                     $data->{'answer_editor[' . ($answercount - 1) . ']'};
329             $data->{'response_editor[' . ($this->lesson->maxanswers + 1) . ']'} =
330                     $data->{'response_editor[' . ($answercount - 1) . ']'};
331             $data->{'jumpto[' . ($this->lesson->maxanswers + 1) . ']'} = $data->{'jumpto[' . ($answercount - 1) . ']'};
332             $data->{'score[' . ($this->lesson->maxanswers + 1) . ']'} = $data->{'score[' . ($answercount - 1) . ']'};
333             $data->enableotheranswers = true;
335             // Unset the old values.
336             unset($data->{'answer_editor[' . ($answercount - 1) . ']'});
337             unset($data->{'response_editor[' . ($answercount - 1) . ']'});
338             unset($data->{'jumpto['. ($answercount - 1) . ']'});
339             unset($data->{'score[' . ($answercount - 1) . ']'});
340         }
342         return $data;
343     }
346 class lesson_add_page_form_numerical extends lesson_add_page_form_base {
348     public $qtype = 'numerical';
349     public $qtypestring = 'numerical';
350     protected $answerformat = '';
351     protected $responseformat = LESSON_ANSWER_HTML;
353     public function custom_definition() {
354         $answercount = $this->_customdata['lesson']->maxanswers;
355         for ($i = 0; $i < $answercount; $i++) {
356             $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1));
357             $this->add_answer($i, null, ($i < 1));
358             $this->add_response($i);
359             $this->add_jumpto($i, null, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE));
360             $this->add_score($i, null, ($i===0)?1:0);
361         }
362         // Wrong answer jump.
363         $this->_form->addElement('header', 'wronganswer', get_string('allotheranswers', 'lesson'));
364         $newcount = $answercount + 1;
365         $this->_form->addElement('advcheckbox', 'enableotheranswers', get_string('enabled', 'lesson'));
366         $this->add_response($newcount);
367         $this->add_jumpto($newcount, get_string('allotheranswersjump', 'lesson'), LESSON_NEXTPAGE);
368         $this->add_score($newcount, get_string('allotheranswersscore', 'lesson'), 0);
369     }
372 class lesson_display_answer_form_numerical extends moodleform {
374     public function definition() {
375         global $USER, $OUTPUT;
376         $mform = $this->_form;
377         $contents = $this->_customdata['contents'];
379         // Disable shortforms.
380         $mform->setDisableShortforms();
382         $mform->addElement('header', 'pageheader');
384         $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
386         $hasattempt = false;
387         $attrs = array('size'=>'50', 'maxlength'=>'200');
388         if (isset($this->_customdata['lessonid'])) {
389             $lessonid = $this->_customdata['lessonid'];
390             if (isset($USER->modattempts[$lessonid]->useranswer)) {
391                 $attrs['readonly'] = 'readonly';
392                 $hasattempt = true;
393             }
394         }
395         $options = new stdClass;
396         $options->para = false;
397         $options->noclean = true;
399         $mform->addElement('hidden', 'id');
400         $mform->setType('id', PARAM_INT);
402         $mform->addElement('hidden', 'pageid');
403         $mform->setType('pageid', PARAM_INT);
405         $mform->addElement('text', 'answer', get_string('youranswer', 'lesson'), $attrs);
406         $mform->setType('answer', PARAM_FLOAT);
408         if ($hasattempt) {
409             $this->add_action_buttons(null, get_string("nextpage", "lesson"));
410         } else {
411             $this->add_action_buttons(null, get_string("submit", "lesson"));
412         }
413     }