answerChecker2.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Checks submitted answers, updates the score and writes the report row.
  4. *
  5. * Changes from the current repo version:
  6. * - one correctness decision ($correct, from isCorrect()) now drives the
  7. * on-screen message, the score/minutes AND the report row. Before, the
  8. * message and score used a strict === comparison while the report used
  9. * isCorrect(), so "1.1" vs "1.10" showed as wrong but was logged correct
  10. * - anagrams: the old retrieve('tk_wordList','word') returned a single value
  11. * so findInList() looped over a string and never matched. Now an answer is
  12. * accepted if it uses exactly the same letters AND is in the word list
  13. * - 'rounding' had no case in the switch, so every rounding question hit
  14. * "An error has been detected"; added with its messages
  15. * - user-typed text is escaped before being shown
  16. * - updateScore(): a brand-new user (retrieve() returns false) no longer
  17. * increments keys on false or decrements null; user escaped in SQL
  18. * - getDifficulty(): MPREFIX instead of `e107.`, user escaped, no null result
  19. * - removed the broken, unused shortCode() and findInList()
  20. * - a wrong answer takes a minute off but never below zero
  21. */
  22. class answerChecker2 {
  23. private $user;
  24. private $messages = [
  25. 'numbers' => ['Find the missing number. {QUESTION}', "Congratulations '{USER_ANSWER}' was correct for Find the missing number '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Find the missing number in {QUESTION}'"],
  26. 'addition' => ['Solve the following equation. {QUESTION}.', "Congratulations '{USER_ANSWER}' was correct for Solve the following equation. '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Solve the following equation in {QUESTION}'"],
  27. 'subtraction' => ['Solve the following equation. {QUESTION}.', "Congratulations '{USER_ANSWER}' was correct for Solve the following equation. '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Solve the following equation in {QUESTION}'"],
  28. 'multiplication' => ['Solve the following equation. {QUESTION}.', "Congratulations '{USER_ANSWER}' was correct for Solve the following equation. '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Solve the following equation in {QUESTION}'"],
  29. 'division' => ['Solve the following equation. {QUESTION}.', "Congratulations '{USER_ANSWER}' was correct for Solve the following equation. '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Solve the following equation in {QUESTION}'"],
  30. 'rounding' => ['Round to the nearest 5 cents. {QUESTION}', "Congratulations '{USER_ANSWER}' was correct for rounding to the nearest 5 cents '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Round {QUESTION} to the nearest 5 cents'"],
  31. 'worded_add' => [],
  32. 'worded_sub' => [],
  33. 'worded_mult' => [],
  34. 'worded_devi' => [],
  35. 'anagrams' => ['Unjumble the letters to find the word. {QUESTION}.', "Congratulations '{USER_ANSWER}' was correct for Unjumble the letters '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Unjumble the letters in {QUESTION}'"],
  36. 'generalKnowledge' => [],
  37. 'elements' => ['Fill in the missing element information. {QUESTION}', "Congratulations '{USER_ANSWER}' was correct for Fill in the missing element information '{ANSWER}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for 'Fill in the missing element information in {QUESTION}'"],
  38. 'continents' => [],
  39. 'countries' => [],
  40. 'flags' => [],
  41. 'capitalCities' => [],
  42. 'artists' => [],
  43. 'malaySpelling' => [],
  44. 'nameBodyParts' => [],
  45. 'nameBodyOrgans' => [],
  46. 'basicFirstAid' => []
  47. ];
  48. /**
  49. * Get the right answer checker for the subject
  50. */
  51. public function checkQuestionSubject($subject, $user) {
  52. $this->user = $user;
  53. switch ($subject) {
  54. case 'numbers':
  55. case 'addition':
  56. case 'subtraction':
  57. case 'multiplication':
  58. case 'division':
  59. case 'rounding':
  60. $this->checkGeneric($subject);
  61. break;
  62. case 'worded_add':
  63. case 'worded_sub':
  64. case 'worded_mult':
  65. case 'worded_devi':
  66. case 'spelling':
  67. $this->checkSpelling(); //Custom checker
  68. break;
  69. case 'anagrams':
  70. $this->checkAnagrams();
  71. break;
  72. case 'generalKnowledge':
  73. case 'elements':
  74. $this->checkGeneric('elements');
  75. break;
  76. case 'continents':
  77. case 'countries':
  78. case 'flags':
  79. case 'capitalCities':
  80. case 'artists':
  81. case 'malaySpelling':
  82. case 'nameBodyParts':
  83. case 'nameBodyOrgans':
  84. case 'basicFirstAid':
  85. default:
  86. print_a('An error has been detected in the answer checker. Please report this and refresh the page.');
  87. break;
  88. }
  89. }
  90. /**
  91. * Check the answer for anything basic
  92. */
  93. private function checkGeneric($subject) {
  94. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  95. $answer = $this->loadPending();
  96. if ($answer === null) {
  97. return;
  98. }
  99. $correct = $this->isCorrect($answer['answer1'], $usersAnswer);
  100. $this->finishCheck($subject, $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, $subject));
  101. }
  102. /**
  103. * Check an anagram answer: the exact word, or any other real word made
  104. * from the same letters.
  105. */
  106. private function checkAnagrams() {
  107. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  108. $answer = $this->loadPending();
  109. if ($answer === null) {
  110. return;
  111. }
  112. $correct = $this->isCorrect($answer['answer1'], $usersAnswer)
  113. || $this->isValidAnagram($usersAnswer, $answer['answer1']);
  114. $this->finishCheck('anagrams', $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, 'anagrams'));
  115. }
  116. /**
  117. * Check the answer for spelling
  118. */
  119. private function checkSpelling() {
  120. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  121. $answer = $this->loadPending();
  122. if ($answer === null) {
  123. return;
  124. }
  125. $word = (string) $answer['word'];
  126. $correct = $this->isCorrect($word, $usersAnswer);
  127. $safeAnswer = htmlspecialchars($usersAnswer);
  128. $safeWord = htmlspecialchars($word);
  129. if ($correct) {
  130. $text = "Congratulations '" . $safeAnswer . "' was correct for 'spell the word " . $safeWord . "'<br/>";
  131. } else {
  132. $text = "Sorry but '" . $safeAnswer . "' was incorrect it should have been '" . $safeWord . "' for 'spell the word " . $safeWord . "'<br/>";
  133. }
  134. $this->updateScore($correct);
  135. $this->addToReport($word, $usersAnswer, 'spelling', "Spell the word " . $word, $correct);
  136. e107::getRender()->tablerender('Spelling answer check', $text);
  137. }
  138. /**
  139. * Shared tail of the generic and anagram checks: build the message, update
  140. * the score, write the report row, render the result. $correct is the one
  141. * decision used for all three.
  142. */
  143. private function finishCheck($subject, $correct, $expected, $usersAnswer, $question) {
  144. $expected = (string) $expected;
  145. $messages = $this->messages[$subject];
  146. $safe = [
  147. '{ANSWER}' => htmlspecialchars($expected),
  148. '{USER_ANSWER}' => htmlspecialchars($usersAnswer),
  149. '{QUESTION}' => htmlspecialchars($question),
  150. ];
  151. $text = strtr($correct ? $messages[1] : $messages[2], $safe) . "<br/>";
  152. $this->updateScore($correct);
  153. $questionString = strtr($messages[0], ['{ANSWER}' => $expected, '{QUESTION}' => $question]);
  154. $this->addToReport($expected, $usersAnswer, $subject, $questionString, $correct);
  155. e107::getRender()->tablerender(ucfirst($subject) . ' answer check', $text);
  156. }
  157. /**
  158. * Question text for messages. Array questions (equations, number
  159. * sequences, scrambled letters) are joined; a rounding question is just
  160. * the amount.
  161. */
  162. private function questionText($answer, $subject) {
  163. $question = isset($answer['question']) ? $answer['question'] : '';
  164. if (is_array($question)) {
  165. if ($subject === 'rounding') {
  166. $question = array_slice($question, 0, 1);
  167. }
  168. $question = implode('', $question);
  169. }
  170. return (string) $question;
  171. }
  172. /**
  173. * Numbers compare numerically ("1.1" == "1.10"), everything else
  174. * case-insensitively, after trimming.
  175. */
  176. private function isCorrect($expected, $given): bool {
  177. $expected = trim((string) $expected);
  178. $given = trim((string) $given);
  179. if (is_numeric($expected) && is_numeric($given)) {
  180. return abs((float) $expected - (float) $given) < 1e-9;
  181. }
  182. return mb_strtolower($expected) === mb_strtolower($given);
  183. }
  184. /**
  185. * An alternative anagram answer is valid when it uses exactly the same
  186. * letters as the original word and is itself in the word list.
  187. */
  188. private function isValidAnagram($given, $original) {
  189. $given = trim((string) $given);
  190. if ($given === '' || !$this->sameLetters($given, (string) $original)) {
  191. return false;
  192. }
  193. $db = e107::getDb();
  194. return $db->count('tk_wordList', '(*)', "word = '" . $db->escape($given) . "'") > 0;
  195. }
  196. private function sameLetters($a, $b) {
  197. $a = preg_split('//u', mb_strtolower($a), -1, PREG_SPLIT_NO_EMPTY);
  198. $b = preg_split('//u', mb_strtolower($b), -1, PREG_SPLIT_NO_EMPTY);
  199. sort($a);
  200. sort($b);
  201. return $a === $b;
  202. }
  203. /**
  204. * Add or minus the score
  205. */
  206. private function updateScore($scorePoint) {
  207. $db = e107::getDb();
  208. $user = $db->escape($this->user);
  209. $currentScore = $db->retrieve('timekeeperScore', 'timekeeper_lifetimecorrect, timekeeper_lifetimequestions, timekeeper_minutes', 'timekeeper_username="' . $user . '"');
  210. $isNew = !is_array($currentScore);
  211. if ($isNew) {
  212. $currentScore = ['timekeeper_lifetimecorrect' => 0, 'timekeeper_lifetimequestions' => 0, 'timekeeper_minutes' => 0];
  213. }
  214. if ($scorePoint) {
  215. $currentScore['timekeeper_lifetimecorrect']++;
  216. $currentScore['timekeeper_minutes'] = $currentScore['timekeeper_minutes'] + $this->scaleTimeAddition();
  217. } else {
  218. // Never below zero: the column is signed now, and a negative balance would
  219. // otherwise have to be earned back before any play time counts.
  220. $currentScore['timekeeper_minutes'] = max(0, $currentScore['timekeeper_minutes'] - 1);
  221. }
  222. $currentScore['timekeeper_lifetimequestions']++;
  223. if ($isNew) {
  224. $currentScore['timekeeper_lastquestiondatestamp'] = time();
  225. $currentScore['timekeeper_yearlevel'] = 0;
  226. $currentScore['timekeeper_username'] = $this->user;
  227. $db->insert('timekeeperScore', $currentScore);
  228. } else {
  229. $currentScore['WHERE'] = 'timekeeper_username="' . $user . '"';
  230. $db->update('timekeeperScore', $currentScore);
  231. }
  232. }
  233. /**
  234. * Return how many minutes play time to award scaled by difficulty
  235. */
  236. private function scaleTimeAddition() {
  237. //TODO look at this and fix it.
  238. $difficulty = $this->getDifficulty($this->user); //replace with db call
  239. $returnMinutes = (int) $difficulty / 10;
  240. $returnMinutes = round($returnMinutes);
  241. if ($returnMinutes <= 1) {
  242. $returnMinutes = 1;
  243. }
  244. return round($returnMinutes);
  245. }
  246. /**
  247. * Return users overall accuracy (percent) for the last month.
  248. */
  249. private function getDifficulty($user) {
  250. $db = e107::getDb();
  251. $db->gen("SELECT CAST((SUM(correct)/COUNT(id)*100) AS DECIMAL(5,2)) AS percent
  252. FROM `" . MPREFIX . "tkReport` WHERE username = '" . $db->escape($user) . "'
  253. AND answereddatestamp >= UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 1 MONTH)
  254. AND answereddatestamp <= UNIX_TIMESTAMP(CURRENT_DATE() + INTERVAL 1 DAY)");
  255. $row = $db->fetch();
  256. return is_array($row) ? (float) $row['percent'] : 0;
  257. }
  258. /**
  259. * Add the last answered question to the report DB table.
  260. */
  261. private function addToReport($answer, $usersAnswer, $subject, $questionString, $isCorrect) {
  262. $insert = [
  263. 'username' => $this->user,
  264. 'question' => $questionString,
  265. 'answereddatestamp' => time(),
  266. 'userAnswer' => trim($usersAnswer),
  267. 'answer' => trim($answer),
  268. 'subject' => $subject,
  269. 'correct' => $isCorrect ? 1 : 0
  270. ];
  271. e107::getDb()->insert('tkReport', $insert);
  272. }
  273. /**
  274. * Load the expected answer for this user's open question. Single use:
  275. * a stale tab, a tampered token or a double-submit gets the message below.
  276. */
  277. private function loadPending(): ?array {
  278. $token = filter_input(INPUT_POST, 'checkerData');
  279. $answer = TkAnswerStore::consume($this->user, is_string($token) ? $token : null);
  280. if ($answer === null) {
  281. e107::getRender()->tablerender('Answer check',
  282. 'That question has expired or was already answered. Please answer the new question.');
  283. }
  284. return $answer;
  285. }
  286. }