MDL-26486 Lesson : fixed whitespace
[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             $responses = array_unique($responses);
83             foreach ($responses as $response) {
84                 $responseoptions[htmlspecialchars(trim($response))] = $response;
85             }
86         }
87         if (isset($USER->modattempts[$this->lesson->id]) && !empty($attempt->useranswer)) {
88             $useranswers = explode(',', $attempt->useranswer);
89             $t = 0;
90         } else {
91             $useranswers = array();
92         }
94         $action = $CFG->wwwroot.'/mod/lesson/continue.php';
95         $params = array('answers'=>$answers, 'useranswers'=>$useranswers, 'responseoptions'=>$responseoptions, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents());
96         $mform = new lesson_display_answer_form_matching($action, $params);
97         return $mform;
98     }
100     public function create_answers($properties) {
101         global $DB;
102         // now add the answers
103         $newanswer = new stdClass;
104         $newanswer->lessonid = $this->lesson->id;
105         $newanswer->pageid = $this->properties->id;
106         $newanswer->timecreated = $this->properties->timecreated;
108         $answers = array();
110         // need to add two to offset correct response and wrong response
111         $this->lesson->maxanswers = $this->lesson->maxanswers + 2;
112         for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
113             $answer = clone($newanswer);
114             if (!empty($properties->answer_editor[$i]) && is_array($properties->answer_editor[$i])) {
115                 $answer->answer = $properties->answer_editor[$i]['text'];
116                 $answer->answerformat = $properties->answer_editor[$i]['format'];
117             }
118             if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
119                 $answer->response = $properties->response_editor[$i]['text'];
120                 $answer->responseformat = $properties->response_editor[$i]['format'];
121             }
123             if (isset($answer->answer) && $answer->answer != '') {
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                 }
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         if (!is_array($response)) {
163             $result->noanswer = true;
164             return $result;
165         }
167         $answers = $this->get_answers();
169         $correct = array_shift($answers);
170         $wrong   = array_shift($answers);
172         foreach ($answers as $key=>$answer) {
173             if ($answer->answer === '' or $answer->response === '') {
174                 // incomplete option!
175                 unset($answers[$key]);
176             }
177         }
178         // get he users exact responses for record keeping
179         $hits = 0;
180         $userresponse = array();
181         foreach ($response as $key => $value) {
182             foreach($answers as $answer) {
183                 if ($value === $answer->response) {
184                     $userresponse[] = $answer->id;
185                 }
186                 if ((int)$answer->id === (int)$key) {
187                     $result->studentanswer .= '<br />'.format_text($answer->answer, $answer->answerformat, $formattextdefoptions).' = '.$value;
188                 }
189                 if ((int)$answer->id === (int)$key and $value === $answer->response) {
190                     $hits++;
191                 }
192             }
193         }
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                 }
235                 $n++;
236                 $i--;
237             } else {
238                 $cells = array();
239                 if ($this->lesson->custom && $answer->score > 0) {
240                     // if the score is > 0, then it is correct
241                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
242                 } else if ($this->lesson->custom) {
243                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
244                 } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
245                     $cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
246                 } else {
247                     $cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
248                 }
249                 $cells[] = format_text($answer->answer, $answer->answerformat, $options);
250                 $table->data[] = new html_table_row($cells);
252                 $cells = array();
253                 $cells[] = '<span class="label">'.get_string("matchesanswer", "lesson")." $i</span>: ";
254                 $cells[] = format_text($answer->response, $answer->responseformat, $options);
255                 $table->data[] = new html_table_row($cells);
256             }
258             if ($i == 1) {
259                 $cells = array();
260                 $cells[] = '<span class="label">'.get_string("correctanswerscore", "lesson")." $i</span>: ";
261                 $cells[] = $answer->score;
262                 $table->data[] = new html_table_row($cells);
264                 $cells = array();
265                 $cells[] = '<span class="label">'.get_string("correctanswerjump", "lesson")." $i</span>: ";
266                 $cells[] = $this->get_jump_name($answer->jumpto);
267                 $table->data[] = new html_table_row($cells);
268             } elseif ($i == 2) {
269                 $cells = array();
270                 $cells[] = '<span class="label">'.get_string("wronganswerscore", "lesson")." $i</span>: ";
271                 $cells[] = $answer->score;
272                 $table->data[] = new html_table_row($cells);
274                 $cells = array();
275                 $cells[] = '<span class="label">'.get_string("wronganswerjump", "lesson")." $i</span>: ";
276                 $cells[] = $this->get_jump_name($answer->jumpto);
277                 $table->data[] = new html_table_row($cells);
278             }
280             if ($i === 1){
281                 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
282             }
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) {
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), get_context_instance(CONTEXT_MODULE, $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]) && is_array($properties->response_editor[$i])) {
319                 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
320                 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
321             }
323             // we don't need to check for isset here because properties called it's own isset method.
324             if ($this->answers[$i]->answer != '') {
325                 if (isset($properties->jumpto[$i])) {
326                     $this->answers[$i]->jumpto = $properties->jumpto[$i];
327                 }
328                 if ($this->lesson->custom && isset($properties->score[$i])) {
329                     $this->answers[$i]->score = $properties->score[$i];
330                 }
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 ($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 = "<select disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->answer))."</option></select>";
404                 if ($useranswer != NULL) {
405                     $userresponse = explode(",", $useranswer->useranswer);
406                     $data .= "<select disabled=\"disabled\"><option selected=\"selected\">";
407                     if (array_key_exists($i, $userresponse)) {
408                         $data .= strip_tags(format_string($answers[$userresponse[$i]]->response));
409                     }
410                     $data .= "</option></select>";
411                 } else {
412                     $data .= "<select disabled=\"disabled\"><option selected=\"selected\">".strip_tags(format_string($answer->response))."</option></select>";
413                 }
415                 if ($n == 2) {
416                     if (isset($pagestats[$this->properties->id])) {
417                         if (!array_key_exists('correct', $pagestats[$this->properties->id])) {
418                             $pagestats[$this->properties->id]["correct"] = 0;
419                         }
420                         $percent = $pagestats[$this->properties->id]["correct"] / $pagestats[$this->properties->id]["total"] * 100;
421                         $percent = round($percent, 2);
422                         $percent .= "% ".get_string("answeredcorrectly", "lesson");
423                     } else {
424                         $percent = get_string("nooneansweredthisquestion", "lesson");
425                     }
426                 } else {
427                     $percent = '';
428                 }
430                 $answerdata->answers[] = array($data, $percent);
431                 $i++;
432             }
433             $n++;
434             $answerpage->answerdata = $answerdata;
435         }
436         return $answerpage;
437     }
438     public function get_jumps() {
439         global $DB;
440         // The jumps for matching question type are stored in the 1st and 2nd answer record.
441         $jumps = array();
442         if ($answers = $DB->get_records("lesson_answers", array("lessonid" => $this->lesson->id, "pageid" => $this->properties->id), 'id', '*', 0, 2)) {
443             foreach ($answers as $answer) {
444                 $jumps[] = $this->get_jump_name($answer->jumpto);
445             }
446         } else {
447             $jumps[] = $this->get_jump_name($this->properties->nextpageid);
448         }
449         return $jumps;
450     }
453 class lesson_add_page_form_matching extends lesson_add_page_form_base {
455     public $qtype = 'matching';
456     public $qtypestring = 'matching';
458     public function custom_definition() {
460         $this->_form->addElement('header', 'correctresponse', get_string('correctresponse', 'lesson'));
461         $this->_form->addElement('editor', 'answer_editor[0]', get_string('correctresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
462         $this->add_jumpto(0, get_string('correctanswerjump','lesson'), LESSON_NEXTPAGE);
463         $this->add_score(0, get_string("correctanswerscore", "lesson"));
465         $this->_form->addElement('header', 'wrongresponse', get_string('wrongresponse', 'lesson'));
466         $this->_form->addElement('editor', 'answer_editor[1]', get_string('wrongresponse', 'lesson'), array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
467         $this->add_jumpto(1, get_string('wronganswerjump','lesson'), LESSON_THISPAGE);
468         $this->add_score(1, get_string("wronganswerscore", "lesson"));
470         for ($i = 2; $i < $this->_customdata['lesson']->maxanswers+2; $i++) {
471             $this->_form->addElement('header', 'matchingpair'.($i-1), get_string('matchingpair', 'lesson', $i-1));
472             $this->add_answer($i, NULL, ($i < 4));
473             $this->add_response($i, get_string('matchesanswer','lesson'), ($i < 4));
474         }
475     }
479 class lesson_display_answer_form_matching extends moodleform {
481     public function definition() {
482         global $USER, $OUTPUT;
483         $mform = $this->_form;
484         $answers = $this->_customdata['answers'];
485         $useranswers = $this->_customdata['useranswers'];
486         $responseoptions = $this->_customdata['responseoptions'];
487         $lessonid = $this->_customdata['lessonid'];
488         $contents = $this->_customdata['contents'];
490         $mform->addElement('header', 'pageheader');
492         $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
494         $hasattempt = false;
495         $disabled = '';
496         if (isset($useranswers) && !empty($useranswers)) {
497             $hasattempt = true;
498             $disabled = array('disabled' => 'disabled');
499         }
501         $options = new stdClass;
502         $options->para = false;
503         $options->noclean = true;
505         $mform->addElement('hidden', 'id');
506         $mform->setType('id', PARAM_INT);
508         $mform->addElement('hidden', 'pageid');
509         $mform->setType('pageid', PARAM_INT);
511         $i = 0;
512         foreach ($answers as $answer) {
513             $mform->addElement('html', '<div class="answeroption">');
514             if ($answer->response != NULL) {
515                 $responseid = 'response['.$answer->id.']';
516                 if ($hasattempt) {
517                     $responseid = 'response_'.$answer->id;
518                     $mform->addElement('hidden', 'response['.$answer->id.']', htmlspecialchars(trim($answers[$useranswers[$i]]->response)));
519                     $mform->setType('response['.$answer->id.']', PARAM_TEXT);
520                 }
521                 $mform->addElement('select', $responseid, format_text($answer->answer,$answer->answerformat,$options), $responseoptions, $disabled);
522                 $mform->setType($responseid, PARAM_TEXT);
523                 if ($hasattempt) {
524                     $mform->setDefault($responseid, htmlspecialchars(trim($answers[$useranswers[$i]]->response))); //TODO: this is suspicious
525                 } else {
526                     $mform->setDefault($responseid, 'answeroption');
527                 }
528             }
529             $mform->addElement('html', '</div>');
530             $i++;
531         }
532         if ($hasattempt) {
533             $this->add_action_buttons(null, get_string("nextpage", "lesson"));
534         } else {
535             $this->add_action_buttons(null, get_string("submit", "lesson"));
536         }
537     }