52b6ad6ca8b219fad515b2625a8bd0324a1b1fcc
[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     }
74     public function check_answer() {
75         global $CFG;
76         $result = parent::check_answer();
78         $mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents()));
79         $data = $mform->get_data();
80         require_sesskey();
82         // set defaults
83         $result->response = '';
84         $result->newpageid = 0;
86         if (isset($data->answer)) {
87             // just doing default PARAM_RAW, not doing PARAM_INT because it could be a float
88             $result->useranswer = (float)$data->answer;
89         } else {
90             $result->noanswer = true;
91             return $result;
92         }
93         $result->studentanswer = $result->userresponse = $result->useranswer;
94         $answers = $this->get_answers();
95         foreach ($answers as $answer) {
96             if (strpos($answer->answer, ':')) {
97                 // there's a pairs of values
98                 list($min, $max) = explode(':', $answer->answer);
99                 $minimum = (float) $min;
100                 $maximum = (float) $max;
101             } else {
102                 // there's only one value
103                 $minimum = (float) $answer->answer;
104                 $maximum = $minimum;
105             }
106             if (($result->useranswer >= $minimum) && ($result->useranswer <= $maximum)) {
107                 $result->newpageid = $answer->jumpto;
108                 $result->response = trim($answer->response);
109                 if ($this->lesson->jumpto_is_correct($this->properties->id, $result->newpageid)) {
110                     $result->correctanswer = true;
111                 }
112                 if ($this->lesson->custom) {
113                     if ($answer->score > 0) {
114                         $result->correctanswer = true;
115                     } else {
116                         $result->correctanswer = false;
117                     }
118                 }
119                 $result->answerid = $answer->id;
120                 return $result;
121             }
122         }
123         return $result;
124     }
126     public function display_answers(html_table $table) {
127         $answers = $this->get_answers();
128         $options = new stdClass;
129         $options->noclean = true;
130         $options->para = false;
131         $i = 1;
132         foreach ($answers as $answer) {
133             $answer = parent::rewrite_answers_urls($answer, false);
134             $cells = array();
135             if ($this->lesson->custom && $answer->score > 0) {
136                 // if the score is > 0, then it is correct
137                 $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
138             } else if ($this->lesson->custom) {
139                 $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
140             } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
141                 // underline correct answers
142                 $cells[] = '<span class="correct">'.get_string("answer", "lesson")." $i</span>: \n";
143             } else {
144                 $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
145             }
146             $cells[] = format_text($answer->answer, $answer->answerformat, $options);
147             $table->data[] = new html_table_row($cells);
149             $cells = array();
150             $cells[] = "<span class=\"label\">".get_string("response", "lesson")." $i</span>";
151             $cells[] = format_text($answer->response, $answer->responseformat, $options);
152             $table->data[] = new html_table_row($cells);
154             $cells = array();
155             $cells[] = "<span class=\"label\">".get_string("score", "lesson").'</span>';
156             $cells[] = $answer->score;
157             $table->data[] = new html_table_row($cells);
159             $cells = array();
160             $cells[] = "<span class=\"label\">".get_string("jump", "lesson").'</span>';
161             $cells[] = $this->get_jump_name($answer->jumpto);
162             $table->data[] = new html_table_row($cells);
163             if ($i === 1){
164                 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
165             }
166             $i++;
167         }
168         return $table;
169     }
170     public function stats(array &$pagestats, $tries) {
171         if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
172             $temp = $tries[$this->lesson->maxattempts - 1];
173         } else {
174             // else, user attempted the question less than the max, so grab the last one
175             $temp = end($tries);
176         }
177         if (isset($pagestats[$temp->pageid][$temp->useranswer])) {
178             $pagestats[$temp->pageid][$temp->useranswer]++;
179         } else {
180             $pagestats[$temp->pageid][$temp->useranswer] = 1;
181         }
182         if (isset($pagestats[$temp->pageid]["total"])) {
183             $pagestats[$temp->pageid]["total"]++;
184         } else {
185             $pagestats[$temp->pageid]["total"] = 1;
186         }
187         return true;
188     }
190     public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
191         $answers = $this->get_answers();
192         $formattextdefoptions = new stdClass;
193         $formattextdefoptions->para = false;  //I'll use it widely in this page
194         foreach ($answers as $answer) {
195             if ($useranswer == null && $i == 0) {
196                 // I have the $i == 0 because it is easier to blast through it all at once.
197                 if (isset($pagestats[$this->properties->id])) {
198                     $stats = $pagestats[$this->properties->id];
199                     $total = $stats["total"];
200                     unset($stats["total"]);
201                     foreach ($stats as $valentered => $ntimes) {
202                         $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($valentered).'" />';
203                         $percent = $ntimes / $total * 100;
204                         $percent = round($percent, 2);
205                         $percent .= "% ".get_string("enteredthis", "lesson");
206                         $answerdata->answers[] = array($data, $percent);
207                     }
208                 } else {
209                     $answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " ");
210                 }
211                 $i++;
212             } else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) && empty($answerdata)))) {
213                  // get in here when what the user entered is not one of the answers
214                 $data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($useranswer->useranswer).'">';
215                 if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) {
216                     $percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100;
217                     $percent = round($percent, 2);
218                     $percent .= "% ".get_string("enteredthis", "lesson");
219                 } else {
220                     $percent = get_string("nooneenteredthis", "lesson");
221                 }
222                 $answerdata->answers[] = array($data, $percent);
224                 if ($answer->id == $useranswer->answerid) {
225                     if ($answer->response == null) {
226                         if ($useranswer->correct) {
227                             $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
228                         } else {
229                             $answerdata->response = get_string("thatsthewronganswer", "lesson");
230                         }
231                     } else {
232                         $answerdata->response = $answer->response;
233                     }
234                     if ($this->lesson->custom) {
235                         $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
236                     } elseif ($useranswer->correct) {
237                         $answerdata->score = get_string("receivedcredit", "lesson");
238                     } else {
239                         $answerdata->score = get_string("didnotreceivecredit", "lesson");
240                     }
241                 } else {
242                     $answerdata->response = get_string("thatsthewronganswer", "lesson");
243                     if ($this->lesson->custom) {
244                         $answerdata->score = get_string("pointsearned", "lesson").": 0";
245                     } else {
246                         $answerdata->score = get_string("didnotreceivecredit", "lesson");
247                     }
248                 }
249             }
250             $answerpage->answerdata = $answerdata;
251         }
252         return $answerpage;
253     }
256 class lesson_add_page_form_numerical extends lesson_add_page_form_base {
258     public $qtype = 'numerical';
259     public $qtypestring = 'numerical';
260     protected $answerformat = '';
261     protected $responseformat = LESSON_ANSWER_HTML;
263     public function custom_definition() {
264         for ($i = 0; $i < $this->_customdata['lesson']->maxanswers; $i++) {
265             $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1));
266             $this->add_answer($i, null, ($i < 1));
267             $this->add_response($i);
268             $this->add_jumpto($i, null, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE));
269             $this->add_score($i, null, ($i===0)?1:0);
270         }
271     }
274 class lesson_display_answer_form_numerical extends moodleform {
276     public function definition() {
277         global $USER, $OUTPUT;
278         $mform = $this->_form;
279         $contents = $this->_customdata['contents'];
281         // Disable shortforms.
282         $mform->setDisableShortforms();
284         $mform->addElement('header', 'pageheader');
286         $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
288         $hasattempt = false;
289         $attrs = array('size'=>'50', 'maxlength'=>'200');
290         if (isset($this->_customdata['lessonid'])) {
291             $lessonid = $this->_customdata['lessonid'];
292             if (isset($USER->modattempts[$lessonid]->useranswer)) {
293                 $attrs['readonly'] = 'readonly';
294                 $hasattempt = true;
295             }
296         }
297         $options = new stdClass;
298         $options->para = false;
299         $options->noclean = true;
301         $mform->addElement('hidden', 'id');
302         $mform->setType('id', PARAM_INT);
304         $mform->addElement('hidden', 'pageid');
305         $mform->setType('pageid', PARAM_INT);
307         $mform->addElement('text', 'answer', get_string('youranswer', 'lesson'), $attrs);
308         $mform->setType('answer', PARAM_FLOAT);
310         if ($hasattempt) {
311             $this->add_action_buttons(null, get_string("nextpage", "lesson"));
312         } else {
313             $this->add_action_buttons(null, get_string("submit", "lesson"));
314         }
315     }