PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/lesson/pagetypes/multichoice.php

https://bitbucket.org/moodle/moodle
PHP | 579 lines | 460 code | 66 blank | 53 comment | 116 complexity | 58924b375e0a65f75b94019c84badea7 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Multichoice
  18. *
  19. * @package mod_lesson
  20. * @copyright 2009 Sam Hemelryk
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. **/
  23. defined('MOODLE_INTERNAL') || die();
  24. /** Multichoice question type */
  25. define("LESSON_PAGE_MULTICHOICE", "3");
  26. class lesson_page_type_multichoice extends lesson_page {
  27. protected $type = lesson_page::TYPE_QUESTION;
  28. protected $typeidstring = 'multichoice';
  29. protected $typeid = LESSON_PAGE_MULTICHOICE;
  30. protected $string = null;
  31. public function get_typeid() {
  32. return $this->typeid;
  33. }
  34. public function get_typestring() {
  35. if ($this->string===null) {
  36. $this->string = get_string($this->typeidstring, 'lesson');
  37. }
  38. return $this->string;
  39. }
  40. public function get_idstring() {
  41. return $this->typeidstring;
  42. }
  43. /**
  44. * Gets an array of the jumps used by the answers of this page
  45. *
  46. * @return array
  47. */
  48. public function get_jumps() {
  49. global $DB;
  50. $jumps = array();
  51. if ($answers = $this->get_answers()) {
  52. foreach ($answers as $answer) {
  53. if ($answer->answer === '') {
  54. // show only jumps for real branches (==have description)
  55. continue;
  56. }
  57. $jumps[] = $this->get_jump_name($answer->jumpto);
  58. }
  59. } else {
  60. // We get here is the lesson was created on a Moodle 1.9 site and
  61. // the lesson contains question pages without any answers.
  62. $jumps[] = $this->get_jump_name($this->properties->nextpageid);
  63. }
  64. return $jumps;
  65. }
  66. public function get_used_answers() {
  67. $answers = $this->get_answers();
  68. foreach ($answers as $key=>$answer) {
  69. if ($answer->answer === '') {
  70. unset($answers[$key]);
  71. } else {
  72. $answers[$key] = parent::rewrite_answers_urls($answer);
  73. }
  74. }
  75. return $answers;
  76. }
  77. public function display($renderer, $attempt) {
  78. global $CFG, $PAGE;
  79. $answers = $this->get_used_answers();
  80. shuffle($answers);
  81. $action = $CFG->wwwroot.'/mod/lesson/continue.php';
  82. $params = array('answers'=>$answers, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents(), 'attempt'=>$attempt);
  83. if ($this->properties->qoption) {
  84. $mform = new lesson_display_answer_form_multichoice_multianswer($action, $params);
  85. } else {
  86. $mform = new lesson_display_answer_form_multichoice_singleanswer($action, $params);
  87. }
  88. $data = new stdClass;
  89. $data->id = $PAGE->cm->id;
  90. $data->pageid = $this->properties->id;
  91. $mform->set_data($data);
  92. // Trigger an event question viewed.
  93. $eventparams = array(
  94. 'context' => context_module::instance($PAGE->cm->id),
  95. 'objectid' => $this->properties->id,
  96. 'other' => array(
  97. 'pagetype' => $this->get_typestring()
  98. )
  99. );
  100. $event = \mod_lesson\event\question_viewed::create($eventparams);
  101. $event->trigger();
  102. return $mform->display();
  103. }
  104. public function check_answer() {
  105. global $DB, $CFG, $PAGE;
  106. $result = parent::check_answer();
  107. $formattextdefoptions = new stdClass();
  108. $formattextdefoptions->noclean = true;
  109. $formattextdefoptions->para = false;
  110. $answers = $this->get_used_answers();
  111. shuffle($answers);
  112. $action = $CFG->wwwroot.'/mod/lesson/continue.php';
  113. $params = array('answers'=>$answers, 'lessonid'=>$this->lesson->id, 'contents'=>$this->get_contents());
  114. if ($this->properties->qoption) {
  115. $mform = new lesson_display_answer_form_multichoice_multianswer($action, $params);
  116. } else {
  117. $mform = new lesson_display_answer_form_multichoice_singleanswer($action, $params);
  118. }
  119. $data = $mform->get_data();
  120. require_sesskey();
  121. if (!$data) {
  122. $result->inmediatejump = true;
  123. $result->newpageid = $this->properties->id;
  124. return $result;
  125. }
  126. if ($this->properties->qoption) {
  127. // Multianswer allowed, user's answer is an array
  128. if (empty($data->answer) || !is_array($data->answer)) {
  129. $result->noanswer = true;
  130. return $result;
  131. }
  132. $studentanswers = array();
  133. foreach ($data->answer as $key=>$value) {
  134. $studentanswers[] = (int)$key;
  135. }
  136. // get what the user answered
  137. $result->userresponse = implode(",", $studentanswers);
  138. // get the answers in a set order, the id order
  139. $answers = $this->get_used_answers();
  140. $ncorrect = 0;
  141. $nhits = 0;
  142. $responses = array();
  143. $correctanswerid = 0;
  144. $wronganswerid = 0;
  145. // store student's answers for displaying on feedback page
  146. $result->studentanswer = '';
  147. $result->studentanswerformat = FORMAT_HTML;
  148. foreach ($answers as $answer) {
  149. foreach ($studentanswers as $answerid) {
  150. if ($answerid == $answer->id) {
  151. $studentanswerarray[] = format_text($answer->answer, $answer->answerformat, $formattextdefoptions);
  152. $responses[$answerid] = format_text($answer->response, $answer->responseformat, $formattextdefoptions);
  153. }
  154. }
  155. }
  156. $result->studentanswer = implode(self::MULTIANSWER_DELIMITER, $studentanswerarray);
  157. $correctpageid = null;
  158. $wrongpageid = null;
  159. // Iterate over all the possible answers.
  160. foreach ($answers as $answer) {
  161. if ($this->lesson->custom) {
  162. $iscorrectanswer = $answer->score > 0;
  163. } else {
  164. $iscorrectanswer = $this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto);
  165. }
  166. // Iterate over all the student answers to check if he selected the current possible answer.
  167. foreach ($studentanswers as $answerid) {
  168. if ($answerid == $answer->id) {
  169. if ($iscorrectanswer) {
  170. $nhits++;
  171. } else {
  172. // Always jump to the page related to the student's first wrong answer.
  173. if (!isset($wrongpageid)) {
  174. // Leave in its "raw" state - will be converted into a proper page id later.
  175. $wrongpageid = $answer->jumpto;
  176. }
  177. // Save the answer id for scoring.
  178. if ($wronganswerid == 0) {
  179. $wronganswerid = $answer->id;
  180. }
  181. }
  182. }
  183. }
  184. if ($iscorrectanswer) {
  185. $ncorrect++;
  186. // Save the first jumpto page id, may be needed!
  187. if (!isset($correctpageid)) {
  188. // Leave in its "raw" state - will be converted into a proper page id later.
  189. $correctpageid = $answer->jumpto;
  190. }
  191. // Save the answer id for scoring.
  192. if ($correctanswerid == 0) {
  193. $correctanswerid = $answer->id;
  194. }
  195. }
  196. }
  197. if ((count($studentanswers) == $ncorrect) and ($nhits == $ncorrect)) {
  198. $result->correctanswer = true;
  199. $result->response = implode(self::MULTIANSWER_DELIMITER, $responses);
  200. $result->newpageid = $correctpageid;
  201. $result->answerid = $correctanswerid;
  202. } else {
  203. $result->response = implode(self::MULTIANSWER_DELIMITER, $responses);
  204. $result->newpageid = $wrongpageid;
  205. $result->answerid = $wronganswerid;
  206. }
  207. } else {
  208. // only one answer allowed
  209. if (!isset($data->answerid) || (empty($data->answerid) && !is_int($data->answerid))) {
  210. $result->noanswer = true;
  211. return $result;
  212. }
  213. $result->answerid = $data->answerid;
  214. if (!$answer = $DB->get_record("lesson_answers", array("id" => $result->answerid))) {
  215. print_error("Continue: answer record not found");
  216. }
  217. $answer = parent::rewrite_answers_urls($answer);
  218. if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
  219. $result->correctanswer = true;
  220. }
  221. if ($this->lesson->custom) {
  222. if ($answer->score > 0) {
  223. $result->correctanswer = true;
  224. } else {
  225. $result->correctanswer = false;
  226. }
  227. }
  228. $result->newpageid = $answer->jumpto;
  229. $result->response = format_text($answer->response, $answer->responseformat, $formattextdefoptions);
  230. $result->userresponse = format_text($answer->answer, $answer->answerformat, $formattextdefoptions);
  231. $result->studentanswer = $result->userresponse;
  232. }
  233. return $result;
  234. }
  235. public function option_description_string() {
  236. if ($this->properties->qoption) {
  237. return " - ".get_string("multianswer", "lesson");
  238. }
  239. return parent::option_description_string();
  240. }
  241. public function display_answers(html_table $table) {
  242. $answers = $this->get_used_answers();
  243. $options = new stdClass;
  244. $options->noclean = true;
  245. $options->para = false;
  246. $i = 1;
  247. foreach ($answers as $answer) {
  248. $answer = parent::rewrite_answers_urls($answer);
  249. $cells = array();
  250. if ($this->lesson->custom && $answer->score > 0) {
  251. // if the score is > 0, then it is correct
  252. $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . " {$i}</label>: \n";
  253. } else if ($this->lesson->custom) {
  254. $cells[] = '<label>' . get_string('answer', 'lesson') . " {$i}</label>: \n";
  255. } else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
  256. // underline correct answers
  257. $cells[] = '<span class="correct">' . get_string('answer', 'lesson') . " {$i}</span>: \n";
  258. } else {
  259. $cells[] = '<label class="correct">' . get_string('answer', 'lesson') . " {$i}</label>: \n";
  260. }
  261. $cells[] = format_text($answer->answer, $answer->answerformat, $options);
  262. $table->data[] = new html_table_row($cells);
  263. $cells = array();
  264. $cells[] = '<label>' . get_string('response', 'lesson') . " {$i} </label>:\n";
  265. $cells[] = format_text($answer->response, $answer->responseformat, $options);
  266. $table->data[] = new html_table_row($cells);
  267. $cells = array();
  268. $cells[] = '<label>' . get_string('score', 'lesson') . '</label>:';
  269. $cells[] = $answer->score;
  270. $table->data[] = new html_table_row($cells);
  271. $cells = array();
  272. $cells[] = '<label>' . get_string('jump', 'lesson') . '</label>:';
  273. $cells[] = $this->get_jump_name($answer->jumpto);
  274. $table->data[] = new html_table_row($cells);
  275. if ($i === 1){
  276. $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
  277. }
  278. $i++;
  279. }
  280. return $table;
  281. }
  282. public function stats(array &$pagestats, $tries) {
  283. $temp = $this->lesson->get_last_attempt($tries);
  284. if ($this->properties->qoption) {
  285. $userresponse = explode(",", $temp->useranswer);
  286. foreach ($userresponse as $response) {
  287. if (isset($pagestats[$temp->pageid][$response])) {
  288. $pagestats[$temp->pageid][$response]++;
  289. } else {
  290. $pagestats[$temp->pageid][$response] = 1;
  291. }
  292. }
  293. } else {
  294. if (isset($pagestats[$temp->pageid][$temp->answerid])) {
  295. $pagestats[$temp->pageid][$temp->answerid]++;
  296. } else {
  297. $pagestats[$temp->pageid][$temp->answerid] = 1;
  298. }
  299. }
  300. if (isset($pagestats[$temp->pageid]["total"])) {
  301. $pagestats[$temp->pageid]["total"]++;
  302. } else {
  303. $pagestats[$temp->pageid]["total"] = 1;
  304. }
  305. return true;
  306. }
  307. public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
  308. $answers = $this->get_used_answers();
  309. $formattextdefoptions = new stdClass;
  310. $formattextdefoptions->para = false; //I'll use it widely in this page
  311. $formattextdefoptions->context = $answerpage->context;
  312. foreach ($answers as $answer) {
  313. $answertext = format_text($answer->answer,$answer->answerformat,$formattextdefoptions);
  314. $correctresponsetext = html_writer::div(get_string('correctresponse', 'lesson'), 'badge badge-success');
  315. if ($this->properties->qoption) {
  316. if ($useranswer == null) {
  317. $userresponse = array();
  318. } else {
  319. $userresponse = explode(",", $useranswer->useranswer);
  320. }
  321. if (in_array($answer->id, $userresponse)) {
  322. // make checked
  323. $checkboxelement = "<input readonly=\"readonly\" disabled=\"disabled\" name=\"answer[$i]\" checked=\"checked\" type=\"checkbox\" value=\"1\" />";
  324. if (!isset($answerdata->response)) {
  325. if ($answer->response == null) {
  326. if ($useranswer->correct) {
  327. $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
  328. } else {
  329. $answerdata->response = get_string("thatsthewronganswer", "lesson");
  330. }
  331. } else {
  332. $answerdata->response = $answer->response;
  333. }
  334. }
  335. if (!isset($answerdata->score)) {
  336. if ($this->lesson->custom) {
  337. $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
  338. } elseif ($useranswer->correct) {
  339. $answerdata->score = get_string("receivedcredit", "lesson");
  340. } else {
  341. $answerdata->score = get_string("didnotreceivecredit", "lesson");
  342. }
  343. }
  344. } else {
  345. // unchecked
  346. $checkboxelement = "<input type=\"checkbox\" readonly=\"readonly\" name=\"answer[$i]\" value=\"0\" disabled=\"disabled\" />";
  347. }
  348. $answercontent = html_writer::label($checkboxelement . ' ' . $answertext, null);
  349. if (($answer->score > 0 && $this->lesson->custom) || ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto) && !$this->lesson->custom)) {
  350. $data = html_writer::div($answercontent, 'text-success') . $correctresponsetext;
  351. } else {
  352. $data = $answercontent;
  353. }
  354. } else {
  355. if ($useranswer != null and $answer->id == $useranswer->answerid) {
  356. // make checked
  357. $checkboxelement = "<input readonly=\"readonly\" disabled=\"disabled\" name=\"answer[$i]\" checked=\"checked\" type=\"checkbox\" value=\"1\" />";
  358. if ($answer->response == null) {
  359. if ($useranswer->correct) {
  360. $answerdata->response = get_string("thatsthecorrectanswer", "lesson");
  361. } else {
  362. $answerdata->response = get_string("thatsthewronganswer", "lesson");
  363. }
  364. } else {
  365. $answerdata->response = $answer->response;
  366. }
  367. if ($this->lesson->custom) {
  368. $answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
  369. } elseif ($useranswer->correct) {
  370. $answerdata->score = get_string("receivedcredit", "lesson");
  371. } else {
  372. $answerdata->score = get_string("didnotreceivecredit", "lesson");
  373. }
  374. } else {
  375. // unchecked
  376. $checkboxelement = "<input type=\"checkbox\" readonly=\"readonly\" name=\"answer[$i]\" value=\"0\" disabled=\"disabled\" />";
  377. }
  378. $answercontent = html_writer::label($checkboxelement . ' ' . $answertext, null);
  379. if (($answer->score > 0 && $this->lesson->custom) || ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto) && !$this->lesson->custom)) {
  380. $data = html_writer::div($answercontent, 'text-success') . $correctresponsetext;
  381. } else {
  382. $data = $answercontent;
  383. }
  384. }
  385. if (isset($pagestats[$this->properties->id][$answer->id])) {
  386. $percent = $pagestats[$this->properties->id][$answer->id] / $pagestats[$this->properties->id]["total"] * 100;
  387. $percent = round($percent, 2);
  388. $percent .= "% ".get_string("checkedthisone", "lesson");
  389. } else {
  390. $percent = get_string("noonecheckedthis", "lesson");
  391. }
  392. $answerdata->answers[] = array($data, $percent);
  393. $answerpage->answerdata = $answerdata;
  394. }
  395. return $answerpage;
  396. }
  397. }
  398. class lesson_add_page_form_multichoice extends lesson_add_page_form_base {
  399. public $qtype = 'multichoice';
  400. public $qtypestring = 'multichoice';
  401. protected $answerformat = LESSON_ANSWER_HTML;
  402. protected $responseformat = LESSON_ANSWER_HTML;
  403. public function custom_definition() {
  404. $this->_form->addElement('checkbox', 'qoption', get_string('options', 'lesson'), get_string('multianswer', 'lesson'));
  405. $this->_form->setDefault('qoption', 0);
  406. $this->_form->addHelpButton('qoption', 'multianswer', 'lesson');
  407. for ($i = 0; $i < $this->_customdata['lesson']->maxanswers; $i++) {
  408. $this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1));
  409. $this->add_answer($i, null, ($i<2), $this->get_answer_format());
  410. $this->add_response($i);
  411. $this->add_jumpto($i, null, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE));
  412. $this->add_score($i, null, ($i===0)?1:0);
  413. }
  414. }
  415. }
  416. class lesson_display_answer_form_multichoice_singleanswer extends moodleform {
  417. public function definition() {
  418. global $USER, $OUTPUT;
  419. $mform = $this->_form;
  420. $answers = $this->_customdata['answers'];
  421. $lessonid = $this->_customdata['lessonid'];
  422. $contents = $this->_customdata['contents'];
  423. if (array_key_exists('attempt', $this->_customdata)) {
  424. $attempt = $this->_customdata['attempt'];
  425. } else {
  426. $attempt = new stdClass();
  427. $attempt->answerid = null;
  428. }
  429. // Disable shortforms.
  430. $mform->setDisableShortforms();
  431. $mform->addElement('header', 'pageheader');
  432. $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
  433. $hasattempt = false;
  434. $disabled = '';
  435. if (isset($USER->modattempts[$lessonid]) && !empty($USER->modattempts[$lessonid])) {
  436. $hasattempt = true;
  437. $disabled = array('disabled' => 'disabled');
  438. }
  439. $options = new stdClass;
  440. $options->para = false;
  441. $options->noclean = true;
  442. $mform->addElement('hidden', 'id');
  443. $mform->setType('id', PARAM_INT);
  444. $mform->addElement('hidden', 'pageid');
  445. $mform->setType('pageid', PARAM_INT);
  446. $i = 0;
  447. foreach ($answers as $answer) {
  448. $mform->addElement('html', '<div class="answeroption">');
  449. $answer->answer = preg_replace('#>$#', '> ', $answer->answer);
  450. $mform->addElement('radio','answerid',null,format_text($answer->answer, $answer->answerformat, $options),$answer->id, $disabled);
  451. $mform->setType('answer'.$i, PARAM_INT);
  452. if ($hasattempt && $answer->id == $USER->modattempts[$lessonid]->answerid) {
  453. $mform->setDefault('answerid', $USER->modattempts[$lessonid]->answerid);
  454. }
  455. $mform->addElement('html', '</div>');
  456. $i++;
  457. }
  458. if ($hasattempt) {
  459. $this->add_action_buttons(null, get_string("nextpage", "lesson"));
  460. } else {
  461. $this->add_action_buttons(null, get_string("submit", "lesson"));
  462. }
  463. }
  464. }
  465. class lesson_display_answer_form_multichoice_multianswer extends moodleform {
  466. public function definition() {
  467. global $USER, $OUTPUT;
  468. $mform = $this->_form;
  469. $answers = $this->_customdata['answers'];
  470. $lessonid = $this->_customdata['lessonid'];
  471. $contents = $this->_customdata['contents'];
  472. // Disable shortforms.
  473. $mform->setDisableShortforms();
  474. $mform->addElement('header', 'pageheader');
  475. $mform->addElement('html', $OUTPUT->container($contents, 'contents'));
  476. $hasattempt = false;
  477. $disabled = '';
  478. $useranswers = array();
  479. if (isset($USER->modattempts[$lessonid]) && !empty($USER->modattempts[$lessonid])) {
  480. $hasattempt = true;
  481. $disabled = array('disabled' => 'disabled');
  482. $useranswers = explode(',', $USER->modattempts[$lessonid]->useranswer);
  483. }
  484. $options = new stdClass;
  485. $options->para = false;
  486. $options->noclean = true;
  487. $mform->addElement('hidden', 'id');
  488. $mform->setType('id', PARAM_INT);
  489. $mform->addElement('hidden', 'pageid');
  490. $mform->setType('pageid', PARAM_INT);
  491. foreach ($answers as $answer) {
  492. $mform->addElement('html', '<div class="answeroption">');
  493. $answerid = 'answer['.$answer->id.']';
  494. if ($hasattempt && in_array($answer->id, $useranswers)) {
  495. $answerid = 'answer_'.$answer->id;
  496. $mform->addElement('hidden', 'answer['.$answer->id.']', $answer->answer);
  497. $mform->setType('answer['.$answer->id.']', PARAM_NOTAGS);
  498. $mform->setDefault($answerid, true);
  499. $mform->setDefault('answer['.$answer->id.']', true);
  500. }
  501. // NOTE: our silly checkbox supports only value '1' - we can not use it like the radiobox above!!!!!!
  502. $answer->answer = preg_replace('#>$#', '> ', $answer->answer);
  503. $mform->addElement('checkbox', $answerid, null, format_text($answer->answer, $answer->answerformat, $options), $disabled);
  504. $mform->setType($answerid, PARAM_INT);
  505. $mform->addElement('html', '</div>');
  506. }
  507. if ($hasattempt) {
  508. $this->add_action_buttons(null, get_string("nextpage", "lesson"));
  509. } else {
  510. $this->add_action_buttons(null, get_string("submit", "lesson"));
  511. }
  512. }
  513. }