MDL-39546 Lesson module: removed duplicate to decode special characters
[moodle.git] / mod / lesson / pagetypes / matching.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  * Matching
20  *
21  * @package    mod
22  * @subpackage lesson
23  * @copyright  2009 Sam Hemelryk
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  **/
27 defined('MOODLE_INTERNAL') || die();
29 /** Matching question type */
30 define("LESSON_PAGE_MATCHING",      "5");
32 class lesson_page_type_matching extends lesson_page {
34     protected $type = lesson_page::TYPE_QUESTION;
35     protected $typeid = LESSON_PAGE_MATCHING;
36     protected $typeidstring = 'matching';
37     protected $string = null;
39     public function get_typeid() {
40         return $this->typeid;
41     }
42     public function get_typestring() {
43         if ($this->string===null) {
44             $this->string = get_string($this->typeidstring, 'lesson');
45         }
46         return $this->string;
47     }
48     public function get_idstring() {
49         return $this->typeidstring;
50     }
51     public function display($renderer, $attempt) {
52         global $USER, $CFG, $PAGE;
53         $mform = $this->make_answer_form($attempt);
54         $data = new stdClass;
55         $data->id = $PAGE->cm->id;
56         $data->pageid = $this->properties->id;
57         $mform->set_data($data);
58         return $mform->display();
59     }
61     protected function make_answer_form($attempt=null) {
62         global $USER, $CFG;
63         // don't shuffle answers (could be an option??)
64         $getanswers = array_slice($this->get_answers(), 2);
66         $answers = array();
67         foreach ($getanswers as $getanswer) {
68             $answers[$getanswer->id] = $getanswer;
69         }
71         $responses = array();
72         foreach ($answers as $answer) {
73             // get all the response
74             if ($answer->response != null) {
75                 $responses[] = trim($answer->response);
76             }
77         }
79         $responseoptions = array(''=>get_string('choosedots'));
80         if (!empty($responses)) {
81             shuffle($responses);
82             foreach ($responses as  $response) {
83                 $responseoptions[htmlspecialchars($response)] = $response;
84             }
85         }
86         if (isset($USER->modattempts[$this->lesson->id]) && !empty($attempt->useranswer)) {
87             $useranswers = explode(',', $attempt->useranswer);
88             $t = 0;
89         } else {
90             $useranswers = array();
91         }
93         $action = $CFG->wwwroot.'/mod/lesson/continue.php';
94         $params = array('answers'=>$answers, 'useranswers'=>$useranswers, 'responseoptions'=>$responseoptions, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents());
95         $mform = new lesson_display_answer_form_matching($action, $params);
96         return $mform;
97     }
99     public function create_answers($properties) {
100         global $DB;
101         // now add the answers
102         $newanswer = new stdClass;
103         $newanswer->lessonid = $this->lesson->id;
104         $newanswer->pageid = $this->properties->id;
105         $newanswer->timecreated = $this->properties->timecreated;
107         $answers = array();
109         // need to add two to offset correct response and wrong response
110         $this->lesson->maxanswers = $this->lesson->maxanswers + 2;
111         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
112             $answer = clone($newanswer);
113             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
114                 $answer->answer = $properties->answer_editor[$i]['text'];
115                 $answer->answerformat = $properties->answer_editor[$i]['format'];
116             }
117             if (!empty($properties->response_editor[$i])) {
118                 $answer->response = $properties->response_editor[$i];
119                 $answer->responseformat = 0;
120             }
122             if (isset($properties->jumpto[$i])) {
123                 $answer->jumpto = $properties->jumpto[$i];
124             }
125             if ($this->lesson->custom && isset($properties->score[$i])) {
126                 $answer->score = $properties->score[$i];
127             }
129             if (isset($answer->answer) && $answer->answer != '') {
130                 $answer->id = $DB->insert_record("lesson_answers", $answer);
131                 $answers[$answer->id] = new lesson_page_answer($answer);
132             } else if ($i < 2) {
133                 $answer->id = $DB->insert_record("lesson_answers", $answer);
134                 $answers[$answer->id] = new lesson_page_answer($answer);
135             } else {
136                 break;
137             }
138         }
139         $this->answers = $answers;
140         return $answers;
141     }
143     public function check_answer() {
144         global $CFG, $PAGE;
146         $formattextdefoptions = new stdClass();
147         $formattextdefoptions->noclean = true;
148         $formattextdefoptions->para = false;
150         $result = parent::check_answer();
152         $mform = $this->make_answer_form();
154         $data = $mform->get_data();
155         require_sesskey();
157         if (!$data) {
158             redirect(new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id, 'pageid'=>$this->properties->id)));
159         }
161         $response = $data->response;
162         $getanswers = $this->get_answers();
164         $correct = array_shift($getanswers);
165         $wrong   = array_shift($getanswers);
167         $answers = array();
168         foreach ($getanswers as $key => $answer) {
169             if ($answer->answer !== '' or $answer->response !== '') {
170                 $answers[$answer->id] = $answer;
171             }
172         }
174         // get the user's exact responses for record keeping
175         $hits = 0;
176         $userresponse = array();
177         foreach ($response as $id => $value) {
178             if ($value == '') {
179                 $result->noanswer = true;
180                 return $result;
181             }
182             $value = htmlspecialchars_decode($value);
183             $userresponse[] = $value;
184             // Make sure the user's answer exists in question's answer
185             if (array_key_exists($id, $answers)) {
186                 $answer = $answers[$id];
187                 $result->studentanswer .= '<br />'.format_text($answer->answer, $answer->answerformat, $formattextdefoptions).' = '.$value;
188                 if (trim($answer->response) == trim($value)) {
189                     $hits++;
190                 }
191             }
192         }
194         $result->userresponse = implode(",", $userresponse);
196         if ($hits == count($answers)) {
197             $result->correctanswer = true;
198             $result->response      = format_text($correct->answer, $correct->answerformat, $formattextdefoptions);
199             $result->answerid      = $correct->id;
200             $result->newpageid     = $correct->jumpto;
201         } else {
202             $result->correctanswer = false;
203             $result->response      = format_text($wrong->answer, $wrong->answerformat, $formattextdefoptions);
204             $result->answerid      = $wrong->id;
205             $result->newpageid     = $wrong->jumpto;
206         }
208         return $result;
209     }
211     public function option_description_string() {
212         return get_string("firstanswershould", "lesson");
213     }
215     public function display_answers(html_table $table) {
216         $answers = $this->get_answers();
217         $options = new stdClass;
218         $options->noclean = true;
219         $options->para = false;
220         $i = 1;
221         $n = 0;
223         foreach ($answers as $answer) {
224             if ($n < 2) {
225                 if ($answer->answer != NULL) {
226                     $cells = array();
227                     if ($n == 0) {
228                         $cells[] = "<span class=\"label\">".get_string("correctresponse", "lesson").'</span>';
229                     } else {
230                         $cells[] = "<span class=\"label\">".get_string("wrongresponse", "lesson").'</span>';
231                     }
232                     $cells[] = format_text($answer->answer, $answer->answerformat, $options);
233                     $table->data[] = new html_table_row($cells);
234                 }
236                 if ($n == 0) {
237                     $cells = array();
238                     $cells[] = '<span class="label">'.get_string("correctanswerscore", "lesson")."</span>: ";
239                     $cells[] = $answer->score;
240                     $table->data[] = new html_table_row($cells);
242                     $cells = array();
243                     $cells[] = '<span class="label">'.get_string("correctanswerjump", "lesson")."</span>: ";
244                     $cells[] = $this->get_jump_name($answer->jumpto);
245                     $table->data[] = new html_table_row($cells);
246                 } elseif ($n == 1) {
247                     $cells = array();
248                     $cells[] = '<span class="label">'.get_string("wronganswerscore", "lesson")."</span>: ";
249                     $cells[] = $answer->score;
250                     $table->data[] = new html_table_row($cells);
252                     $cells = array();
253                     $cells[] = '<span class="label">'.get_string("wronganswerjump", "lesson")."</span>: ";
254                     $cells[] = $this->get_jump_name($answer->jumpto);
255                     $table->data[] = new html_table_row($cells);
256                 }
258                 if ($n === 0){
259                     $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
260                 }
261                 $n++;
262                 $i--;
263             } else {
264                 $cells = array();
265                 if ($this->lesson->custom && $answer->score > 0) {
266                     // if the score is > 0, then it is correct
267                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
268                 } else if ($this->lesson->custom) {
269                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
270                 } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
271                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
272                 } else {
273                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
274                 }
275                 $cells[] = format_text($answer->answer, $answer->answerformat, $options);
276                 $table->data[] = new html_table_row($cells);
278                 $cells = array();
279                 $cells[] = '<span class="label">'.get_string("matchesanswer", "lesson")." $i</span>: ";
280                 $cells[] = format_text($answer->response, $answer->responseformat, $options);
281                 $table->data[] = new html_table_row($cells);
282             }
283             $i++;
284         }
285         return $table;
286     }
287     /**
288      * Updates the page and its answers
289      *
290      * @global moodle_database $DB
291      * @global moodle_page $PAGE
292      * @param stdClass $properties
293      * @return bool
294      */
295     public function update($properties, $context = null, $maxbytes = null) {
296         global $DB, $PAGE;
297         $answers  = $this->get_answers();
298         $properties->id = $this->properties->id;
299         $properties->lessonid = $this->lesson->id;
300         $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), get_context_instance(CONTEXT_MODULE, $PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id);
301         $DB->update_record("lesson_pages", $properties);
303         // need to add two to offset correct response and wrong response
304         $this->lesson->maxanswers += 2;
305         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
306             if (!array_key_exists($i, $this->answers)) {
307                 $this->answers[$i] = new stdClass;
308                 $this->answers[$i]->lessonid = $this->lesson->id;
309                 $this->answers[$i]->pageid = $this->id;
310                 $this->answers[$i]->timecreated = $this->timecreated;
311             }
313             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
314                 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
315                 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
316             }
317             if (!empty($properties->response_editor[$i])) {
318                 $this->answers[$i]->response = $properties->response_editor[$i];
319                 $this->answers[$i]->responseformat = 0;
320             }
322             if (isset($properties->jumpto[$i])) {
323                 $this->answers[$i]->jumpto = $properties->jumpto[$i];
324             }
325             if ($this->lesson->custom && isset($properties->score[$i])) {
326                 $this->answers[$i]->score = $properties->score[$i];
327             }
329             // we don't need to check for isset here because properties called it's own isset method.
330             if ($this->answers[$i]->answer != '') {
331                 if (!isset($this->answers[$i]->id)) {
332                     $this->answers[$i]->id =  $DB->insert_record("lesson_answers", $this->answers[$i]);
333                 } else {
334                     $DB->update_record("lesson_answers", $this->answers[$i]->properties());
335                 }
336             } else if ($i < 2) {
337                 if (!isset($this->answers[$i]->id)) {
338                     $this->answers[$i]->id =  $DB->insert_record("lesson_answers", $this->answers[$i]);
339                 } else {
340                     $DB->update_record("lesson_answers", $this->answers[$i]->properties());
341                 }
343             } else if (isset($this->answers[$i]->id)) {
344                 $DB->delete_records('lesson_answers', array('id'=>$this->answers[$i]->id));
345                 unset($this->answers[$i]);
346             }
347         }
348         return true;
349     }
350     public function stats(array &$pagestats, $tries) {
351         if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
352             $temp = $tries[$this->lesson->maxattempts - 1];
353         } else {
354             // else, user attempted the question less than the max, so grab the last one
355             $temp = end($tries);
356         }
357         if ($temp->correct) {
358             if (isset($pagestats[$temp->pageid]["correct"])) {
359                 $pagestats[$temp->pageid]["correct"]++;
360             } else {
361                 $pagestats[$temp->pageid]["correct"] = 1;
362             }
363         }
364         if (isset($pagestats[$temp->pageid]["total"])) {
365             $pagestats[$temp->pageid]["total"]++;
366         } else {
367             $pagestats[$temp->pageid]["total"] = 1;
368         }
369         return true;
370     }
371     public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
372         $answers = array();
373         foreach ($this->get_answers() as $answer) {
374             $answers[$answer->id] = $answer;
375         }
376         $formattextdefoptions = new stdClass;
377         $formattextdefoptions->para = false;  //I'll use it widely in this page
378         foreach ($answers as $answer) {
379             if ($n == 0 && $useranswer != NULL && $useranswer->correct) {
380                 if ($answer->response == NULL && $useranswer != NULL) {
381                     $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
382                 } else {
383                     $answerdata->response = $answer->response;
384                 }
385                 if ($this->lesson->custom) {
386                     $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
387                 } else {
388                     $answerdata->score = get_string("receivedcredit", "lesson");
389                 }
390             } elseif ($n == 1 && $useranswer != NULL && !$useranswer->correct) {
391                 if ($answer->response == NULL && $useranswer != NULL) {
392                     $answerdata->response = get_string("thatsthewronganswer", "lesson");
393                 } else {
394                     $answerdata->response = $answer->response;
395                 }
396                 if ($this->lesson->custom) {
397                     $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
398                 } else {
399                     $answerdata->score = get_string("didnotreceivecredit", "lesson");
400                 }
401             } elseif ($n > 1) {
402                 $data = '<label class="accesshide" for="answer_' . $n . '">' . get_string('answer', 'lesson') . '</label>';
403                 $data .= strip_tags(format_string($answer->answer)) . ' ';
404                 if ($useranswer != null) {
405                     $userresponse = explode(",", $useranswer->useranswer);
406                     $data .= '<label class="accesshide" for="stu_answer_response_' . $n . '">' . get_string('matchesanswer', 'lesson') . '</label>';
407                     $data .= "<select id=\"stu_answer_response_" . $n . "\" disabled=\"disabled\"><option selected=\"selected\">";
408                     if (array_key_exists($i, $userresponse)) {
409                         $data .= $userresponse[$i];
410                     }
411                     $data .= "</option></select>";
412                 } else {
413                     $data .= '<label class="accesshide" for="answer_response_' . $n . '">' . get_string('matchesanswer', 'lesson') . '</label>';
414                     $data .= "<select id=\"answer_response_" . $n . "\" disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->response))."</option></select>";
415                 }
417                 if ($n == 2) {
418                     if (isset($pagestats[$this->properties->id])) {
419                         if (!array_key_exists('correct', $pagestats[$this->properties->id])) {
420                             $pagestats[$this->properties->id]["correct"] = 0;
421                         }
422                         $percent = $pagestats[$this->properties->id]["correct"] / $pagestats[$this->properties->id]["total"] * 100;
423                         $percent = round($percent, 2);
424                         $percent .= "% ".get_string("answeredcorrectly", "lesson");
425                     } else {
426                         $percent = get_string("nooneansweredthisquestion", "lesson");
427                     }
428                 } else {
429                     $percent = '';
430                 }
432                 $answerdata->answers[] = array($data, $percent);
433                 $i++;
434             }
435             $n++;
436             $answerpage->answerdata = $answerdata;
437         }
438         return $answerpage;
439     }
440     public function get_jumps() {
441         global $DB;
442         // The jumps for matching question type are stored in the 1st and 2nd answer record.
443         $jumps = array();
444         if ($answers = $DB->get_records("lesson_answers", array("lessonid" => $this->lesson->id, "pageid" => $this->properties->id), 'id', '*', 0, 2)) {
445             foreach ($answers as $answer) {
446                 $jumps[] = $this->get_jump_name($answer->jumpto);
447             }
448         } else {
449             $jumps[] = $this->get_jump_name($this->properties->nextpageid);
450         }
451         return $jumps;
452     }
455 class lesson_add_page_form_matching extends lesson_add_page_form_base {
457     public $qtype = 'matching';
458     public $qtypestring = 'matching';
460     public function custom_definition() {
462         $this->_form->addElement('header', 'correctresponse', get_string('correctresponse', 'lesson'));
463         $this->_form->addElement('editor', 'answer_editor[0]', get_string('correctresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
464         $this->add_jumpto(0, get_string('correctanswerjump','lesson'), LESSON_NEXTPAGE);
465         $this->add_score(0, get_string("correctanswerscore", "lesson"), 1);
467         $this->_form->addElement('header', 'wrongresponse', get_string('wrongresponse', 'lesson'));
468         $this->_form->addElement('editor', 'answer_editor[1]', get_string('wrongresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
469         $this->add_jumpto(1, get_string('wronganswerjump','lesson'), LESSON_THISPAGE);
470         $this->add_score(1, get_string("wronganswerscore", "lesson"), 0);
472         for ($i = 2; $i < $this->_customdata['lesson']->maxanswers+2; $i++) {
473             $this->_form->addElement('header', 'matchingpair'.($i-1), get_string('matchingpair', 'lesson', $i-1));
474             $this->add_answer($i, NULL, ($i < 4));
475             $required = ($i < 4);
476             $label = get_string('matchesanswer','lesson');
477             $count = $i;
478             $this->_form->addElement('text', 'response_editor['.$count.']', $label, array('size'=>'50'));
479             $this->_form->setDefault('response_editor['.$count.']', '');
480             if ($required) {
481                 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
482             }
483         }
484     }
487 class lesson_display_answer_form_matching extends moodleform {
489     public function definition() {
490         global $USER, $OUTPUT;
491         $mform = $this->_form;
492         $answers = $this->_customdata['answers'];
493         $useranswers = $this->_customdata['useranswers'];
494         $responseoptions = $this->_customdata['responseoptions'];
495         $lessonid = $this->_customdata['lessonid'];
496         $contents = $this->_customdata['contents'];
498         $mform->addElement('header', 'pageheader');
500         $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
502         $hasattempt = false;
503         $disabled = '';
504         if (isset($useranswers) && !empty($useranswers)) {
505             $hasattempt = true;
506             $disabled = array('disabled' => 'disabled');
507         }
509         $options = new stdClass;
510         $options->para = false;
511         $options->noclean = true;
513         $mform->addElement('hidden', 'id');
514         $mform->setType('id', PARAM_INT);
516         $mform->addElement('hidden', 'pageid');
517         $mform->setType('pageid', PARAM_INT);
519         $i = 0;
521         foreach ($answers as $answer) {
522             $mform->addElement('html', '<div class="answeroption">');
523             if ($answer->response != null) {
524                 $responseid = 'response['.$answer->id.']';
525                 if ($hasattempt) {
526                     $responseid = 'response_'.$answer->id;
527                     $mform->addElement('hidden', 'response['.$answer->id.']', htmlspecialchars($useranswers[$i]));
528                     $mform->setType('response['.$answer->id.']', PARAM_TEXT);
529                 }
530                 $mform->addElement('select', $responseid, format_text($answer->answer,$answer->answerformat,$options), $responseoptions, $disabled);
531                 $mform->setType($responseid, PARAM_TEXT);
532                 if ($hasattempt) {
533                     $mform->setDefault($responseid, htmlspecialchars(trim($useranswers[$i])));
534                 } else {
535                     $mform->setDefault($responseid, 'answeroption');
536                 }
537             }
538             $mform->addElement('html', '</div>');
539             $i++;
540         }
541         if ($hasattempt) {
542             $this->add_action_buttons(null, get_string("nextpage", "lesson"));
543         } else {
544             $this->add_action_buttons(null, get_string("submit", "lesson"));
545         }
546     }