MDL-34050 Lesson Module: Fixed spacing and removed array_unique() for responses
[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[$answer->id] = trim($answer->response);
76             }
77         }
79         $responseoptions = array(''=>get_string('choosedots'));
80         if (!empty($responses)) {
81             $shuffleresponses = $responses;
82             shuffle($shuffleresponses);
83             foreach ($shuffleresponses as  $response) {
84                 $key = array_search($response, $responses);
85                 $responseoptions[$key] = $response;
86             }
87         }
88         if (isset($USER->modattempts[$this->lesson->id]) && !empty($attempt->useranswer)) {
89             $useranswers = explode(',', $attempt->useranswer);
90             $t = 0;
91         } else {
92             $useranswers = array();
93         }
95         $action = $CFG->wwwroot.'/mod/lesson/continue.php';
96         $params = array('answers'=>$answers, 'useranswers'=>$useranswers, 'responseoptions'=>$responseoptions, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents());
97         $mform = new lesson_display_answer_form_matching($action, $params);
98         return $mform;
99     }
101     public function create_answers($properties) {
102         global $DB;
103         // now add the answers
104         $newanswer = new stdClass;
105         $newanswer->lessonid = $this->lesson->id;
106         $newanswer->pageid = $this->properties->id;
107         $newanswer->timecreated = $this->properties->timecreated;
109         $answers = array();
111         // need to add two to offset correct response and wrong response
112         $this->lesson->maxanswers = $this->lesson->maxanswers + 2;
113         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
114             $answer = clone($newanswer);
115             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
116                 $answer->answer = $properties->answer_editor[$i]['text'];
117                 $answer->answerformat = $properties->answer_editor[$i]['format'];
118             }
119             if (!empty($properties->response_editor[$i])) {
120                 $answer->response = $properties->response_editor[$i];
121                 $answer->responseformat = 0;
122             }
124             if (isset($properties->jumpto[$i])) {
125                 $answer->jumpto = $properties->jumpto[$i];
126             }
127             if ($this->lesson->custom && isset($properties->score[$i])) {
128                 $answer->score = $properties->score[$i];
129             }
131             if (isset($answer->answer) && $answer->answer != '') {
132                 $answer->id = $DB->insert_record("lesson_answers", $answer);
133                 $answers[$answer->id] = new lesson_page_answer($answer);
134             } else if ($i < 2) {
135                 $answer->id = $DB->insert_record("lesson_answers", $answer);
136                 $answers[$answer->id] = new lesson_page_answer($answer);
137             } else {
138                 break;
139             }
140         }
141         $this->answers = $answers;
142         return $answers;
143     }
145     public function check_answer() {
146         global $CFG, $PAGE;
148         $formattextdefoptions = new stdClass();
149         $formattextdefoptions->noclean = true;
150         $formattextdefoptions->para = false;
152         $result = parent::check_answer();
154         $mform = $this->make_answer_form();
156         $data = $mform->get_data();
157         require_sesskey();
159         if (!$data) {
160             redirect(new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id, 'pageid'=>$this->properties->id)));
161         }
163         $response = $data->response;
164         if (!is_array($response)) {
165             $result->noanswer = true;
166             return $result;
167         }
169         $answers = $this->get_answers();
171         $correct = array_shift($answers);
172         $wrong   = array_shift($answers);
174         foreach ($answers as $key=>$answer) {
175             if ($answer->answer !== '' or $answer->response !== '') {
176                 $answers[$answer->id] = $answer;
177             }
178             unset($answers[$key]);
179         }
180         // get he users exact responses for record keeping
181         $hits = 0;
182         $userresponse = array();
183         foreach ($response as $id => $value) {
184             $userresponse[] = $value;
185             // Make sure the user's answer is exist in question's answer
186             if (array_key_exists($id, $answers)) {
187                 $answer = $answers[$id];
188                 $result->studentanswer .= '<br />'.format_text($answer->answer, $answer->answerformat, $formattextdefoptions).' = '.$answers[$value]->response;
189                 if ($id == $value) {
190                     $hits++;
191                 }
192             }
193         }
195         $result->userresponse = implode(",", $userresponse);
197         if ($hits == count($answers)) {
198             $result->correctanswer = true;
199             $result->response      = format_text($correct->answer, $correct->answerformat, $formattextdefoptions);
200             $result->answerid      = $correct->id;
201             $result->newpageid     = $correct->jumpto;
202         } else {
203             $result->correctanswer = false;
204             $result->response      = format_text($wrong->answer, $wrong->answerformat, $formattextdefoptions);
205             $result->answerid      = $wrong->id;
206             $result->newpageid     = $wrong->jumpto;
207         }
209         return $result;
210     }
212     public function option_description_string() {
213         return get_string("firstanswershould", "lesson");
214     }
216     public function display_answers(html_table $table) {
217         $answers = $this->get_answers();
218         $options = new stdClass;
219         $options->noclean = true;
220         $options->para = false;
221         $i = 1;
222         $n = 0;
224         foreach ($answers as $answer) {
225             if ($n < 2) {
226                 if ($answer->answer != NULL) {
227                     $cells = array();
228                     if ($n == 0) {
229                         $cells[] = "<span class=\"label\">".get_string("correctresponse", "lesson").'</span>';
230                     } else {
231                         $cells[] = "<span class=\"label\">".get_string("wrongresponse", "lesson").'</span>';
232                     }
233                     $cells[] = format_text($answer->answer, $answer->answerformat, $options);
234                     $table->data[] = new html_table_row($cells);
235                 }
237                 if ($n == 0) {
238                     $cells = array();
239                     $cells[] = '<span class="label">'.get_string("correctanswerscore", "lesson")."</span>: ";
240                     $cells[] = $answer->score;
241                     $table->data[] = new html_table_row($cells);
243                     $cells = array();
244                     $cells[] = '<span class="label">'.get_string("correctanswerjump", "lesson")."</span>: ";
245                     $cells[] = $this->get_jump_name($answer->jumpto);
246                     $table->data[] = new html_table_row($cells);
247                 } elseif ($n == 1) {
248                     $cells = array();
249                     $cells[] = '<span class="label">'.get_string("wronganswerscore", "lesson")."</span>: ";
250                     $cells[] = $answer->score;
251                     $table->data[] = new html_table_row($cells);
253                     $cells = array();
254                     $cells[] = '<span class="label">'.get_string("wronganswerjump", "lesson")."</span>: ";
255                     $cells[] = $this->get_jump_name($answer->jumpto);
256                     $table->data[] = new html_table_row($cells);
257                 }
259                 if ($n === 0){
260                     $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
261                 }
262                 $n++;
263                 $i--;
264             } else {
265                 $cells = array();
266                 if ($this->lesson->custom && $answer->score > 0) {
267                     // if the score is > 0, then it is correct
268                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
269                 } else if ($this->lesson->custom) {
270                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
271                 } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
272                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
273                 } else {
274                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
275                 }
276                 $cells[] = format_text($answer->answer, $answer->answerformat, $options);
277                 $table->data[] = new html_table_row($cells);
279                 $cells = array();
280                 $cells[] = '<span class="label">'.get_string("matchesanswer", "lesson")." $i</span>: ";
281                 $cells[] = format_text($answer->response, $answer->responseformat, $options);
282                 $table->data[] = new html_table_row($cells);
283             }
284             $i++;
285         }
286         return $table;
287     }
288     /**
289      * Updates the page and its answers
290      *
291      * @global moodle_database $DB
292      * @global moodle_page $PAGE
293      * @param stdClass $properties
294      * @return bool
295      */
296     public function update($properties, $context = null, $maxbytes = null) {
297         global $DB, $PAGE;
298         $answers  = $this->get_answers();
299         $properties->id = $this->properties->id;
300         $properties->lessonid = $this->lesson->id;
301         $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$PAGE->course->maxbytes), context_module::instance($PAGE->cm->id), 'mod_lesson', 'page_contents', $properties->id);
302         $DB->update_record("lesson_pages", $properties);
304         // need to add two to offset correct response and wrong response
305         $this->lesson->maxanswers += 2;
306         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
307             if (!array_key_exists($i, $this->answers)) {
308                 $this->answers[$i] = new stdClass;
309                 $this->answers[$i]->lessonid = $this->lesson->id;
310                 $this->answers[$i]->pageid = $this->id;
311                 $this->answers[$i]->timecreated = $this->timecreated;
312             }
314             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
315                 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
316                 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
317             }
318             if (!empty($properties->response_editor[$i])) {
319                 $this->answers[$i]->response = $properties->response_editor[$i];
320                 $this->answers[$i]->responseformat = 0;
321             }
323             if (isset($properties->jumpto[$i])) {
324                 $this->answers[$i]->jumpto = $properties->jumpto[$i];
325             }
326             if ($this->lesson->custom && isset($properties->score[$i])) {
327                 $this->answers[$i]->score = $properties->score[$i];
328             }
330             // we don't need to check for isset here because properties called it's own isset method.
331             if ($this->answers[$i]->answer != '') {
332                 if (!isset($this->answers[$i]->id)) {
333                     $this->answers[$i]->id =  $DB->insert_record("lesson_answers", $this->answers[$i]);
334                 } else {
335                     $DB->update_record("lesson_answers", $this->answers[$i]->properties());
336                 }
337             } else if ($i < 2) {
338                 if (!isset($this->answers[$i]->id)) {
339                     $this->answers[$i]->id =  $DB->insert_record("lesson_answers", $this->answers[$i]);
340                 } else {
341                     $DB->update_record("lesson_answers", $this->answers[$i]->properties());
342                 }
344             } else if (isset($this->answers[$i]->id)) {
345                 $DB->delete_records('lesson_answers', array('id'=>$this->answers[$i]->id));
346                 unset($this->answers[$i]);
347             }
348         }
349         return true;
350     }
351     public function stats(array &$pagestats, $tries) {
352         if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
353             $temp = $tries[$this->lesson->maxattempts - 1];
354         } else {
355             // else, user attempted the question less than the max, so grab the last one
356             $temp = end($tries);
357         }
358         if ($temp->correct) {
359             if (isset($pagestats[$temp->pageid]["correct"])) {
360                 $pagestats[$temp->pageid]["correct"]++;
361             } else {
362                 $pagestats[$temp->pageid]["correct"] = 1;
363             }
364         }
365         if (isset($pagestats[$temp->pageid]["total"])) {
366             $pagestats[$temp->pageid]["total"]++;
367         } else {
368             $pagestats[$temp->pageid]["total"] = 1;
369         }
370         return true;
371     }
372     public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
373         $answers = array();
374         foreach ($this->get_answers() as $answer) {
375             $answers[$answer->id] = $answer;
376         }
377         $formattextdefoptions = new stdClass;
378         $formattextdefoptions->para = false;  //I'll use it widely in this page
379         foreach ($answers as $answer) {
380             if ($n == 0 && $useranswer != NULL && $useranswer->correct) {
381                 if ($answer->response == NULL && $useranswer != NULL) {
382                     $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
383                 } else {
384                     $answerdata->response = $answer->response;
385                 }
386                 if ($this->lesson->custom) {
387                     $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
388                 } else {
389                     $answerdata->score = get_string("receivedcredit", "lesson");
390                 }
391             } elseif ($n == 1 && $useranswer != NULL && !$useranswer->correct) {
392                 if ($answer->response == NULL && $useranswer != NULL) {
393                     $answerdata->response = get_string("thatsthewronganswer", "lesson");
394                 } else {
395                     $answerdata->response = $answer->response;
396                 }
397                 if ($this->lesson->custom) {
398                     $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
399                 } else {
400                     $answerdata->score = get_string("didnotreceivecredit", "lesson");
401                 }
402             } elseif ($n > 1) {
403                 $data = '<label class="accesshide" for="answer_' . $n . '">' . get_string('answer', 'lesson') . '</label>';
404                 $data .= "<select id=\"answer_". $n ."\" disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->answer))."</option></select>";
405                 if ($useranswer != NULL) {
406                     $userresponse = explode(",", $useranswer->useranswer);
407                     $data .= '<label class="accesshide" for="stu_answer_response_' . $n . '">' . get_string('matchesanswer', 'lesson') . '</label>';
408                     $data .= "<select id=\"stu_answer_response_" . $n . "\" disabled=\"disabled\"><option selected=\"selected\">";
409                     if (array_key_exists($i, $userresponse)) {
410                         $data .= strip_tags(format_string($answers[$userresponse[$i]]->response));
411                     }
412                     $data .= "</option></select>";
413                 } else {
414                     $data .= '<label class="accesshide" for="answer_response_' . $n . '">' . get_string('matchesanswer', 'lesson') . '</label>';
415                     $data .= "<select id=\"answer_response_" . $n . "\" disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->response))."</option></select>";
416                 }
418                 if ($n == 2) {
419                     if (isset($pagestats[$this->properties->id])) {
420                         if (!array_key_exists('correct', $pagestats[$this->properties->id])) {
421                             $pagestats[$this->properties->id]["correct"] = 0;
422                         }
423                         $percent = $pagestats[$this->properties->id]["correct"] / $pagestats[$this->properties->id]["total"] * 100;
424                         $percent = round($percent, 2);
425                         $percent .= "% ".get_string("answeredcorrectly", "lesson");
426                     } else {
427                         $percent = get_string("nooneansweredthisquestion", "lesson");
428                     }
429                 } else {
430                     $percent = '';
431                 }
433                 $answerdata->answers[] = array($data, $percent);
434                 $i++;
435             }
436             $n++;
437             $answerpage->answerdata = $answerdata;
438         }
439         return $answerpage;
440     }
441     public function get_jumps() {
442         global $DB;
443         // The jumps for matching question type are stored in the 1st and 2nd answer record.
444         $jumps = array();
445         if ($answers = $DB->get_records("lesson_answers", array("lessonid" => $this->lesson->id, "pageid" => $this->properties->id), 'id', '*', 0, 2)) {
446             foreach ($answers as $answer) {
447                 $jumps[] = $this->get_jump_name($answer->jumpto);
448             }
449         } else {
450             $jumps[] = $this->get_jump_name($this->properties->nextpageid);
451         }
452         return $jumps;
453     }
456 class lesson_add_page_form_matching extends lesson_add_page_form_base {
458     public $qtype = 'matching';
459     public $qtypestring = 'matching';
461     public function custom_definition() {
463         $this->_form->addElement('header', 'correctresponse', get_string('correctresponse', 'lesson'));
464         $this->_form->addElement('editor', 'answer_editor[0]', get_string('correctresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
465         $this->add_jumpto(0, get_string('correctanswerjump','lesson'), LESSON_NEXTPAGE);
466         $this->add_score(0, get_string("correctanswerscore", "lesson"), 1);
468         $this->_form->addElement('header', 'wrongresponse', get_string('wrongresponse', 'lesson'));
469         $this->_form->addElement('editor', 'answer_editor[1]', get_string('wrongresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
470         $this->add_jumpto(1, get_string('wronganswerjump','lesson'), LESSON_THISPAGE);
471         $this->add_score(1, get_string("wronganswerscore", "lesson"), 0);
473         for ($i = 2; $i < $this->_customdata['lesson']->maxanswers+2; $i++) {
474             $this->_form->addElement('header', 'matchingpair'.($i-1), get_string('matchingpair', 'lesson', $i-1));
475             $this->add_answer($i, NULL, ($i < 4));
476             $required = ($i < 4);
477             $label = get_string('matchesanswer','lesson');
478             $count = $i;
479             $this->_form->addElement('text', 'response_editor['.$count.']', $label, array('size'=>'50'));
480             $this->_form->setDefault('response_editor['.$count.']', '');
481             if ($required) {
482                 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
483             }
484         }
485     }
488 class lesson_display_answer_form_matching extends moodleform {
490     public function definition() {
491         global $USER, $OUTPUT;
492         $mform = $this->_form;
493         $answers = $this->_customdata['answers'];
494         $useranswers = $this->_customdata['useranswers'];
495         $responseoptions = $this->_customdata['responseoptions'];
496         $lessonid = $this->_customdata['lessonid'];
497         $contents = $this->_customdata['contents'];
499         $mform->addElement('header', 'pageheader');
501         $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
503         $hasattempt = false;
504         $disabled = '';
505         if (isset($useranswers) && !empty($useranswers)) {
506             $hasattempt = true;
507             $disabled = array('disabled' => 'disabled');
508         }
510         $options = new stdClass;
511         $options->para = false;
512         $options->noclean = true;
514         $mform->addElement('hidden', 'id');
515         $mform->setType('id', PARAM_INT);
517         $mform->addElement('hidden', 'pageid');
518         $mform->setType('pageid', PARAM_INT);
520         $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(trim($answers[$useranswers[$i]]->response)));
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($answers[$useranswers[$i]]->response))); //TODO: this is suspicious
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     }