94d98867bee863aa82ca32f90d9b8fb0ba689a88
[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         $answers = array_slice($this->get_answers(), 2);
65         $responses = array();
66         foreach ($answers as $answer) {
67             // get all the response
68             if ($answer->response != NULL) {
69                 $responses[] = trim($answer->response);
70             }
71         }
73         $responseoptions = array(''=>get_string('choosedots'));
74         if (!empty($responses)) {
75             shuffle($responses);
76             $responses = array_unique($responses);
77             foreach ($responses as $response) {
78                 $responseoptions[htmlspecialchars(trim($response))] = $response;
79             }
80         }
81         if (isset($USER->modattempts[$this->lesson->id]) && !empty($attempt->useranswer)) {
82             $useranswers = explode(',', $attempt->useranswer);
83             $t = 0;
84         } else {
85             $useranswers = array();
86         }
88         $action = $CFG->wwwroot.'/mod/lesson/continue.php';
89         $params = array('answers'=>$answers, 'useranswers'=>$useranswers, 'responseoptions'=>$responseoptions, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents());
90         $mform = new lesson_display_answer_form_matching($action, $params);
91         return $mform;
92     }
94     public function create_answers($properties) {
95         global $DB;
96         // now add the answers
97         $newanswer = new stdClass;
98         $newanswer->lessonid = $this->lesson->id;
99         $newanswer->pageid = $this->properties->id;
100         $newanswer->timecreated = $this->properties->timecreated;
102         $answers = array();
104         // need to add two to offset correct response and wrong response
105         $this->lesson->maxanswers = $this->lesson->maxanswers + 2;
106         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
107             $answer = clone($newanswer);
108             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
109                 $answer->answer = $properties->answer_editor[$i]['text'];
110                 $answer->answerformat = $properties->answer_editor[$i]['format'];
111             }
112             if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
113                 $answer->response = $properties->response_editor[$i]['text'];
114                 $answer->responseformat = $properties->response_editor[$i]['format'];
115             }
117             if (!empty($answer->answer)) {
118                 if (isset($properties->jumpto[$i])) {
119                     $answer->jumpto = $properties->jumpto[$i];
120                 }
121                 if ($this->lesson->custom && isset($properties->score[$i])) {
122                     $answer->score = $properties->score[$i];
123                 }
124                 $answer->id = $DB->insert_record("lesson_answers", $answer);
125                 $answers[$answer->id] = new lesson_page_answer($answer);
126             } else if ($i < 2) {
127                 $answer->id = $DB->insert_record("lesson_answers", $answer);
128                 $answers[$answer->id] = new lesson_page_answer($answer);
129             } else {
130                 break;
131             }
132         }
133         $this->answers = $answers;
134         return $answers;
135     }
137     public function check_answer() {
138         global $CFG, $PAGE;
140         $formattextdefoptions = new stdClass();
141         $formattextdefoptions->noclean = true;
142         $formattextdefoptions->para = false;
144         $result = parent::check_answer();
146         $mform = $this->make_answer_form();
148         $data = $mform->get_data();
149         require_sesskey();
151         if (!$data) {
152             redirect(new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id, 'pageid'=>$this->properties->id)));
153         }
155         $response = $data->response;
156         if (!is_array($response)) {
157             $result->noanswer = true;
158             return $result;
159         }
161         $answers = $this->get_answers();
163         $correct = array_shift($answers);
164         $wrong   = array_shift($answers);
166         foreach ($answers as $key=>$answer) {
167             if ($answer->answer === '' or $answer->response === '') {
168                 // incomplete option!
169                 unset($answers[$key]);
170             }
171         }
172         // get he users exact responses for record keeping
173         $hits = 0;
174         $userresponse = array();
175         foreach ($response as $key => $value) {
176             foreach($answers as $answer) {
177                 if ($value === $answer->response) {
178                     $userresponse[] = $answer->id;
179                 }
180                 if ((int)$answer->id === (int)$key) {
181                     $result->studentanswer .= '<br />'.format_text($answer->answer, $answer->answerformat, $formattextdefoptions).' = '.$value;
182                 }
183                 if ((int)$answer->id === (int)$key and $value === $answer->response) {
184                     $hits++;
185                 }
186             }
187         }
188         $result->userresponse = implode(",", $userresponse);
190         if ($hits == count($answers)) {
191             $result->correctanswer = true;
192             $result->response      = format_text($correct->answer, $correct->answerformat, $formattextdefoptions);
193             $result->answerid      = $correct->id;
194             $result->newpageid     = $correct->jumpto;
195         } else {
196             $result->correctanswer = false;
197             $result->response      = format_text($wrong->answer, $wrong->answerformat, $formattextdefoptions);
198             $result->answerid      = $wrong->id;
199             $result->newpageid     = $wrong->jumpto;
200         }
202         return $result;
203     }
205     public function option_description_string() {
206         return get_string("firstanswershould", "lesson");
207     }
209     public function display_answers(html_table $table) {
210         $answers = $this->get_answers();
211         $options = new stdClass;
212         $options->noclean = true;
213         $options->para = false;
214         $i = 1;
215         $n = 0;
217         foreach ($answers as $answer) {
218             if ($n < 2) {
219                 if ($answer->answer != NULL) {
220                     $cells = array();
221                     if ($n == 0) {
222                         $cells[] = "<span class=\"label\">".get_string("correctresponse", "lesson").'</span>';
223                     } else {
224                         $cells[] = "<span class=\"label\">".get_string("wrongresponse", "lesson").'</span>';
225                     }
226                     $cells[] = format_text($answer->answer, $answer->answerformat, $options);
227                     $table->data[] = new html_table_row($cells);
228                 }
229                 $n++;
230                 $i--;
231             } else {
232                 $cells = array();
233                 if ($this->lesson->custom && $answer->score > 0) {
234                     // if the score is > 0, then it is correct
235                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
236                 } else if ($this->lesson->custom) {
237                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
238                 } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
239                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
240                 } else {
241                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
242                 }
243                 $cells[] = format_text($answer->answer, $answer->answerformat, $options);
244                 $table->data[] = new html_table_row($cells);
246                 $cells = array();
247                 $cells[] = '<span class="label">'.get_string("matchesanswer", "lesson")." $i</span>: ";
248                 $cells[] = format_text($answer->response, $answer->responseformat, $options);
249                 $table->data[] = new html_table_row($cells);
250             }
252             if ($i == 1) {
253                 $cells = array();
254                 $cells[] = '<span class="label">'.get_string("correctanswerscore", "lesson")." $i</span>: ";
255                 $cells[] = $answer->score;
256                 $table->data[] = new html_table_row($cells);
258                 $cells = array();
259                 $cells[] = '<span class="label">'.get_string("correctanswerjump", "lesson")." $i</span>: ";
260                 $cells[] = $this->get_jump_name($answer->jumpto);
261                 $table->data[] = new html_table_row($cells);
262             } elseif ($i == 2) {
263                 $cells = array();
264                 $cells[] = '<span class="label">'.get_string("wronganswerscore", "lesson")." $i</span>: ";
265                 $cells[] = $answer->score;
266                 $table->data[] = new html_table_row($cells);
268                 $cells = array();
269                 $cells[] = '<span class="label">'.get_string("wronganswerjump", "lesson")." $i</span>: ";
270                 $cells[] = $this->get_jump_name($answer->jumpto);
271                 $table->data[] = new html_table_row($cells);
272             }
274             if ($i === 1){
275                 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
276             }
278             $i++;
279         }
280         return $table;
281     }
282     /**
283      * Updates the page and its answers
284      *
285      * @global moodle_database $DB
286      * @global moodle_page $PAGE
287      * @param stdClass $properties
288      * @return bool
289      */
290     public function update($properties) {
291         global $DB, $PAGE;
292         $answers  = $this->get_answers();
293         $properties->id = $this->properties->id;
294         $properties->lessonid = $this->lesson->id;
295         $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);
296         $DB->update_record("lesson_pages", $properties);
298         // need to add two to offset correct response and wrong response
299         $this->lesson->maxanswers += 2;
300         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
301             if (!array_key_exists($i, $this->answers)) {
302                 $this->answers[$i] = new stdClass;
303                 $this->answers[$i]->lessonid = $this->lesson->id;
304                 $this->answers[$i]->pageid = $this->id;
305                 $this->answers[$i]->timecreated = $this->timecreated;
306             }
308             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
309                 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
310                 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
311             }
312             if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
313                 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
314                 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
315             }
317             if (!empty($this->answers[$i]->answer)) {
318                 if (isset($properties->jumpto[$i])) {
319                     $this->answers[$i]->jumpto = $properties->jumpto[$i];
320                 }
321                 if ($this->lesson->custom && isset($properties->score[$i])) {
322                     $this->answers[$i]->score = $properties->score[$i];
323                 }
324                 if (!isset($this->answers[$i]->id)) {
325                     $this->answers[$i]->id =  $DB->insert_record("lesson_answers", $this->answers[$i]);
326                 } else {
327                     $DB->update_record("lesson_answers", $this->answers[$i]->properties());
328                 }
330             } else if ($i < 2) {
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                 }
337             } else if (isset($this->answers[$i]->id)) {
338                 $DB->delete_records('lesson_answers', array('id'=>$this->answers[$i]->id));
339                 unset($this->answers[$i]);
340             }
341         }
342         return true;
343     }
344     public function stats(array &$pagestats, $tries) {
345         if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
346             $temp = $tries[$this->lesson->maxattempts - 1];
347         } else {
348             // else, user attempted the question less than the max, so grab the last one
349             $temp = end($tries);
350         }
351         if ($temp->correct) {
352             if (isset($pagestats[$temp->pageid]["correct"])) {
353                 $pagestats[$temp->pageid]["correct"]++;
354             } else {
355                 $pagestats[$temp->pageid]["correct"] = 1;
356             }
357         }
358         if (isset($pagestats[$temp->pageid]["total"])) {
359             $pagestats[$temp->pageid]["total"]++;
360         } else {
361             $pagestats[$temp->pageid]["total"] = 1;
362         }
363         return true;
364     }
365     public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
366         $answers = array();
367         foreach ($this->get_answers() as $answer) {
368             $answers[$answer->id] = $answer;
369         }
370         $formattextdefoptions = new stdClass;
371         $formattextdefoptions->para = false;  //I'll use it widely in this page
372         foreach ($answers as $answer) {
373             if ($n == 0 && $useranswer != NULL && $useranswer->correct) {
374                 if ($answer->response == NULL && $useranswer != NULL) {
375                     $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
376                 } else {
377                     $answerdata->response = $answer->response;
378                 }
379             } elseif ($n == 1 && $useranswer != NULL && !$useranswer->correct) {
380                 if ($answer->response == NULL && $useranswer != NULL) {
381                     $answerdata->response = get_string("thatsthewronganswer", "lesson");
382                 } else {
383                     $answerdata->response = $answer->response;
384                 }
385             } elseif ($n > 1) {
386                 if ($n == 2 && $useranswer != NULL && $useranswer->correct) {
387                     if ($this->lesson->custom) {
388                         $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
389                     } else {
390                         $answerdata->score = get_string("receivedcredit", "lesson");
391                     }
392                 } elseif ($n == 3 && $useranswer != NULL && !$useranswer->correct) {
393                     if ($this->lesson->custom) {
394                         $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
395                     } else {
396                         $answerdata->score = get_string("didnotreceivecredit", "lesson");
397                     }
398                 }
399                 $data = "<select disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->answer))."</option></select>";
400                 if ($useranswer != NULL) {
401                     $userresponse = explode(",", $useranswer->useranswer);
402                     $data .= "<select disabled=\"disabled\"><option selected=\"selected\">";
403                     if (array_key_exists($i, $userresponse)) {
404                         $data .= strip_tags(format_string($answers[$userresponse[$i]]->response));
405                     }
406                     $data .= "</option></select>";
407                 } else {
408                     $data .= "<select disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->response))."</option></select>";
409                 }
411                 if ($n == 2) {
412                     if (isset($pagestats[$this->properties->id])) {
413                         if (!array_key_exists('correct', $pagestats[$this->properties->id])) {
414                             $pagestats[$this->properties->id]["correct"] = 0;
415                         }
416                         $percent = $pagestats[$this->properties->id]["correct"] / $pagestats[$this->properties->id]["total"] * 100;
417                         $percent = round($percent, 2);
418                         $percent .= "% ".get_string("answeredcorrectly", "lesson");
419                     } else {
420                         $percent = get_string("nooneansweredthisquestion", "lesson");
421                     }
422                 } else {
423                     $percent = "";
424                 }
426                 $answerdata->answers[] = array($data, $percent);
427                 $i++;
428             }
429             $n++;
430             $answerpage->answerdata = $answerdata;
431         }
432         return $answerpage;
433     }
434     public function get_jumps() {
435         global $DB;
436         // The jumps for matching question type is stored
437         // in the 3rd and 4rth answer record.
438         $jumps = array();
439         if ($answers = $DB->get_records("lesson_answers", array("lessonid" => $this->lesson->id, "pageid" => $this->properties->id), 'id', '*', 0, 2)) {
440             foreach ($answers as $answer) {
441                 $jumps[] = $this->get_jump_name($answer->jumpto);
442             }
443         } else {
444             $jumps[] = $this->get_jump_name($this->properties->nextpageid);
445         }
446         return $jumps;
447     }
450 class lesson_add_page_form_matching extends lesson_add_page_form_base {
452     public $qtype = 'matching';
453     public $qtypestring = 'matching';
455     public function custom_definition() {
457         $this->_form->addElement('header', 'correctresponse', get_string('correctresponse', 'lesson'));
458         $this->_form->addElement('editor', 'answer_editor[0]', get_string('correctresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
459         $this->add_jumpto(0, get_string('correctanswerjump','lesson'), LESSON_NEXTPAGE);
460         $this->add_score(0, get_string("correctanswerscore", "lesson"));
462         $this->_form->addElement('header', 'wrongresponse', get_string('wrongresponse', 'lesson'));
463         $this->_form->addElement('editor', 'answer_editor[1]', get_string('wrongresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
464         $this->add_jumpto(1, get_string('wronganswerjump','lesson'), LESSON_THISPAGE);
465         $this->add_score(1, get_string("wronganswerscore", "lesson"));
467         for ($i = 2; $i < $this->_customdata['lesson']->maxanswers+2; $i++) {
468             $this->_form->addElement('header', 'matchingpair'.($i-1), get_string('matchingpair', 'lesson', $i-1));
469             $this->add_answer($i, NULL, ($i < 4));
470             $this->add_response($i, get_string('matchesanswer','lesson'), ($i < 4));
471         }
472     }
476 class lesson_display_answer_form_matching extends moodleform {
478     public function definition() {
479         global $USER, $OUTPUT;
480         $mform = $this->_form;
481         $answers = $this->_customdata['answers'];
482         $useranswers = $this->_customdata['useranswers'];
483         $responseoptions = $this->_customdata['responseoptions'];
484         $lessonid = $this->_customdata['lessonid'];
485         $contents = $this->_customdata['contents'];
487         $mform->addElement('header', 'pageheader', $OUTPUT->box($contents, 'contents'));
489         $options = new stdClass;
490         $options->para = false;
491         $options->noclean = true;
493         $mform->addElement('hidden', 'id');
494         $mform->setType('id', PARAM_INT);
496         $mform->addElement('hidden', 'pageid');
497         $mform->setType('pageid', PARAM_INT);
499         $i = 0;
500         foreach ($answers as $answer) {
501             $mform->addElement('html', '<div class="answeroption">');
502             if ($answer->response != NULL) {
503                 $mform->addElement('select', 'response['.$answer->id.']', format_text($answer->answer,$answer->answerformat,$options), $responseoptions);
504                 $mform->setType('response['.$answer->id.']', PARAM_TEXT);
505                 if (isset($USER->modattempts[$lessonid])) {
506                     $mform->setDefault('response['.$answer->id.']', htmlspecialchars(trim($answers[$useranswers[$i]]->response))); //TODO: this is suspicious
507                 } else {
508                     $mform->setDefault('response['.$answer->id.']', 'answeroption');
509                 }
510             }
511             $mform->addElement('html', '</div>');
512             $i++;
513         }
515         $this->add_action_buttons(null, get_string("pleasematchtheabovepairs", "lesson"));
516     }