answerChecker2.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. * - a correct answer gets a friendlier, randomised message: a cheer, the answer
  22. * worked out, the play minutes earned, and a streak of correct answers (the
  23. * old "Congratulations" strings at messages[...][1] are no longer used)
  24. */
  25. class answerChecker2 {
  26. private $user;
  27. private $messages = [
  28. '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}'"],
  29. '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}'"],
  30. '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}'"],
  31. '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}'"],
  32. '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}'"],
  33. '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'"],
  34. 'word_problems' => ['{QUESTION}', "Congratulations '{USER_ANSWER}' was correct for '{QUESTION}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for '{QUESTION}'"],
  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. case 'word_problems':
  61. $this->checkGeneric($subject);
  62. break;
  63. case 'spelling':
  64. $this->checkSpelling(); //Custom checker
  65. break;
  66. case 'anagrams':
  67. $this->checkAnagrams();
  68. break;
  69. case 'generalKnowledge':
  70. case 'elements':
  71. $this->checkGeneric('elements');
  72. break;
  73. case 'continents':
  74. case 'countries':
  75. case 'flags':
  76. case 'capitalCities':
  77. case 'artists':
  78. case 'malaySpelling':
  79. case 'nameBodyParts':
  80. case 'nameBodyOrgans':
  81. case 'basicFirstAid':
  82. default:
  83. print_a('An error has been detected in the answer checker. Please report this and refresh the page.');
  84. break;
  85. }
  86. }
  87. /**
  88. * Check the answer for anything basic
  89. */
  90. private function checkGeneric($subject) {
  91. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  92. $answer = $this->loadPending();
  93. if ($answer === null) {
  94. return;
  95. }
  96. $correct = $this->isCorrect($answer['answer1'], $usersAnswer);
  97. $this->finishCheck($subject, $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, $subject));
  98. }
  99. /**
  100. * Check an anagram answer: the exact word, or any other real word made
  101. * from the same letters.
  102. */
  103. private function checkAnagrams() {
  104. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  105. $answer = $this->loadPending();
  106. if ($answer === null) {
  107. return;
  108. }
  109. $correct = $this->isCorrect($answer['answer1'], $usersAnswer)
  110. || $this->isValidAnagram($usersAnswer, $answer['answer1']);
  111. $this->finishCheck('anagrams', $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, 'anagrams'));
  112. }
  113. /**
  114. * Check the answer for spelling
  115. */
  116. private function checkSpelling() {
  117. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  118. $answer = $this->loadPending();
  119. if ($answer === null) {
  120. return;
  121. }
  122. $word = (string) $answer['word'];
  123. $correct = $this->isCorrect($word, $usersAnswer);
  124. $minutes = $this->updateScore($correct);
  125. $this->addToReport($word, $usersAnswer, 'spelling', "Spell the word " . $word, $correct);
  126. if ($correct) {
  127. $text = $this->correctText('spelling', $word, $usersAnswer, $word, $minutes);
  128. $title = 'Correct!';
  129. } else {
  130. $safeAnswer = htmlspecialchars($usersAnswer);
  131. $safeWord = htmlspecialchars($word);
  132. $text = "Sorry but '" . $safeAnswer . "' was incorrect it should have been '" . $safeWord . "' for 'spell the word " . $safeWord . "'<br/>";
  133. $title = 'Spelling answer check';
  134. }
  135. e107::getRender()->tablerender($title, $text);
  136. }
  137. /**
  138. * Shared tail of the generic and anagram checks: build the message, update
  139. * the score, write the report row, render the result. $correct is the one
  140. * decision used for all three.
  141. */
  142. private function finishCheck($subject, $correct, $expected, $usersAnswer, $question) {
  143. $expected = (string) $expected;
  144. $messages = $this->messages[$subject];
  145. $minutes = $this->updateScore($correct);
  146. $questionString = strtr($messages[0], ['{ANSWER}' => $expected, '{QUESTION}' => $question]);
  147. $this->addToReport($expected, $usersAnswer, $subject, $questionString, $correct);
  148. if ($correct) {
  149. $text = $this->correctText($subject, $expected, $usersAnswer, $question, $minutes);
  150. $title = 'Correct!';
  151. } else {
  152. $safe = [
  153. '{ANSWER}' => htmlspecialchars($expected),
  154. '{USER_ANSWER}' => htmlspecialchars($usersAnswer),
  155. '{QUESTION}' => htmlspecialchars($question),
  156. ];
  157. $text = strtr($messages[2], $safe) . "<br/>";
  158. $title = ucfirst($subject) . ' answer check';
  159. }
  160. e107::getRender()->tablerender($title, $text);
  161. }
  162. private $cheers = [
  163. "🎉 Woohoo! You got it!",
  164. "⭐ Brilliant!",
  165. "🚀 Boom! Nailed it!",
  166. "💪 Spot on!",
  167. "🙌 High five! That's right!",
  168. "🧠 Big brain move!",
  169. "🌟 You're a star!",
  170. "😎 Too easy for you!",
  171. "🏆 Champion answer!",
  172. "✨ Yes! Exactly right!",
  173. "🎯 Bullseye!",
  174. "🦄 Magical! Correct!",
  175. ];
  176. /**
  177. * The message for a correct answer: a cheer, the answer, minutes earned,
  178. * and a streak when there is one. Everything typed by the student is escaped.
  179. */
  180. private function correctText($subject, $expected, $usersAnswer, $question, $minutes) {
  181. $text = '<div style="font-size:160%;font-weight:bold;">' . $this->cheers[array_rand($this->cheers)] . '</div>';
  182. $text .= '<p>' . $this->correctDetail($subject, $expected, $usersAnswer, $question) . '</p>';
  183. if ($minutes > 0) {
  184. $text .= '<p>🎮 <b>+' . (int) $minutes . ((int) $minutes === 1 ? ' minute' : ' minutes') . '</b> of play time earned!</p>';
  185. }
  186. $streak = $this->correctStreak();
  187. if ($streak >= 25) {
  188. $text .= '<p>🚀 25 or more correct in a row. Unstoppable!</p>';
  189. } elseif ($streak >= 10) {
  190. $text .= '<p>🚀 ' . $streak . ' correct in a row. Unstoppable!</p>';
  191. } elseif ($streak >= 5) {
  192. $text .= '<p>🔥 ' . $streak . ' correct in a row. You\'re on fire!</p>';
  193. } elseif ($streak >= 3) {
  194. $text .= '<p>🔥 ' . $streak . ' correct in a row!</p>';
  195. }
  196. return $text;
  197. }
  198. /**
  199. * The line that says what the right answer was, for this kind of question.
  200. */
  201. private function correctDetail($subject, $expected, $usersAnswer, $question) {
  202. $e = htmlspecialchars($expected);
  203. switch ($subject) {
  204. case 'numbers':
  205. return 'The missing number was <b>' . $e . '</b>.';
  206. case 'addition':
  207. case 'subtraction':
  208. case 'multiplication':
  209. case 'division':
  210. $sum = strtr($question, ['x' => ' × ', '/' => ' ÷ ', '+' => ' + ', '-' => ' − ']);
  211. return '<b>' . htmlspecialchars($sum) . ' = ' . $e . '</b>';
  212. case 'rounding':
  213. return '<b>' . htmlspecialchars($question) . '</b> rounds to <b>' . $e . '</b> (the nearest 5 cents).';
  214. case 'anagrams':
  215. if (mb_strtolower(trim($usersAnswer)) !== mb_strtolower($expected)) {
  216. return 'You found <b>' . htmlspecialchars($usersAnswer) . '</b>. I was thinking of <b>' . $e . '</b>, but that is a real word too!';
  217. }
  218. return 'You unjumbled it: <b>' . $e . '</b>!';
  219. case 'word_problems':
  220. return 'The answer was <b>' . $e . '</b>.';
  221. case 'spelling':
  222. return 'You spelled <b>' . $e . '</b> perfectly!';
  223. default:
  224. return '<b>' . $e . '</b> was exactly right.';
  225. }
  226. }
  227. /**
  228. * How many of the student's latest answers in a row were correct (up to 25).
  229. * Called after the current answer has been written to the report.
  230. */
  231. private function correctStreak() {
  232. $db = e107::getDb();
  233. $db->gen("SELECT `correct` FROM `" . MPREFIX . "tkReport` WHERE `username` = '" . $db->escape($this->user) . "' ORDER BY `id` DESC LIMIT 25");
  234. $recent = [];
  235. while ($row = $db->fetch()) {
  236. $recent[] = (int) $row['correct'];
  237. }
  238. $streak = 0;
  239. foreach ($recent as $correct) {
  240. if ($correct !== 1) {
  241. break;
  242. }
  243. $streak++;
  244. }
  245. return $streak;
  246. }
  247. /**
  248. * Question text for messages. Array questions (equations, number
  249. * sequences, scrambled letters) are joined; a rounding question is just
  250. * the amount.
  251. */
  252. private function questionText($answer, $subject) {
  253. $question = isset($answer['question']) ? $answer['question'] : '';
  254. if (is_array($question)) {
  255. if ($subject === 'rounding') {
  256. $question = array_slice($question, 0, 1);
  257. }
  258. $question = implode('', $question);
  259. }
  260. return (string) $question;
  261. }
  262. /**
  263. * Numbers compare numerically ("1.1" == "1.10"), everything else
  264. * case-insensitively, after trimming.
  265. */
  266. private function isCorrect($expected, $given): bool {
  267. $expected = trim((string) $expected);
  268. $given = trim((string) $given);
  269. if (is_numeric($expected) && is_numeric($given)) {
  270. return abs((float) $expected - (float) $given) < 1e-9;
  271. }
  272. return mb_strtolower($expected) === mb_strtolower($given);
  273. }
  274. /**
  275. * An alternative anagram answer is valid when it uses exactly the same
  276. * letters as the original word and is itself in the word list.
  277. */
  278. private function isValidAnagram($given, $original) {
  279. $given = trim((string) $given);
  280. if ($given === '' || !$this->sameLetters($given, (string) $original)) {
  281. return false;
  282. }
  283. $db = e107::getDb();
  284. return $db->count('tk_wordList', '(*)', "word = '" . $db->escape($given) . "'") > 0;
  285. }
  286. private function sameLetters($a, $b) {
  287. $a = preg_split('//u', mb_strtolower($a), -1, PREG_SPLIT_NO_EMPTY);
  288. $b = preg_split('//u', mb_strtolower($b), -1, PREG_SPLIT_NO_EMPTY);
  289. sort($a);
  290. sort($b);
  291. return $a === $b;
  292. }
  293. /**
  294. * Add or minus the score.
  295. *
  296. * @return int The play minutes awarded for a correct answer (0 otherwise).
  297. */
  298. private function updateScore($scorePoint) {
  299. $db = e107::getDb();
  300. $user = $db->escape($this->user);
  301. $currentScore = $db->retrieve('timekeeperScore', 'timekeeper_lifetimecorrect, timekeeper_lifetimequestions, timekeeper_minutes', 'timekeeper_username="' . $user . '"');
  302. $isNew = !is_array($currentScore);
  303. if ($isNew) {
  304. $currentScore = ['timekeeper_lifetimecorrect' => 0, 'timekeeper_lifetimequestions' => 0, 'timekeeper_minutes' => 0];
  305. }
  306. $awarded = 0;
  307. if ($scorePoint) {
  308. $currentScore['timekeeper_lifetimecorrect']++;
  309. $awarded = (int) $this->scaleTimeAddition();
  310. $currentScore['timekeeper_minutes'] = $currentScore['timekeeper_minutes'] + $awarded;
  311. } else {
  312. // Never below zero: the column is signed now, and a negative balance would
  313. // otherwise have to be earned back before any play time counts.
  314. $currentScore['timekeeper_minutes'] = max(0, $currentScore['timekeeper_minutes'] - 1);
  315. }
  316. $currentScore['timekeeper_lifetimequestions']++;
  317. if ($isNew) {
  318. $currentScore['timekeeper_lastquestiondatestamp'] = time();
  319. $currentScore['timekeeper_yearlevel'] = 0;
  320. $currentScore['timekeeper_username'] = $this->user;
  321. $db->insert('timekeeperScore', $currentScore);
  322. } else {
  323. $currentScore['WHERE'] = 'timekeeper_username="' . $user . '"';
  324. $db->update('timekeeperScore', $currentScore);
  325. }
  326. return $awarded;
  327. }
  328. /**
  329. * Return how many minutes play time to award scaled by difficulty
  330. */
  331. private function scaleTimeAddition() {
  332. //TODO look at this and fix it.
  333. $difficulty = $this->getDifficulty($this->user); //replace with db call
  334. $returnMinutes = (int) $difficulty / 10;
  335. $returnMinutes = round($returnMinutes);
  336. if ($returnMinutes <= 1) {
  337. $returnMinutes = 1;
  338. }
  339. return round($returnMinutes);
  340. }
  341. /**
  342. * Return users overall accuracy (percent) for the last month.
  343. */
  344. private function getDifficulty($user) {
  345. $db = e107::getDb();
  346. $db->gen("SELECT CAST((SUM(correct)/COUNT(id)*100) AS DECIMAL(5,2)) AS percent
  347. FROM `" . MPREFIX . "tkReport` WHERE username = '" . $db->escape($user) . "'
  348. AND answereddatestamp >= UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 1 MONTH)
  349. AND answereddatestamp <= UNIX_TIMESTAMP(CURRENT_DATE() + INTERVAL 1 DAY)");
  350. $row = $db->fetch();
  351. return is_array($row) ? (float) $row['percent'] : 0;
  352. }
  353. /**
  354. * Add the last answered question to the report DB table.
  355. */
  356. private function addToReport($answer, $usersAnswer, $subject, $questionString, $isCorrect) {
  357. $insert = [
  358. 'username' => $this->user,
  359. 'question' => $questionString,
  360. 'answereddatestamp' => time(),
  361. 'userAnswer' => trim($usersAnswer),
  362. 'answer' => trim($answer),
  363. 'subject' => $subject,
  364. 'correct' => $isCorrect ? 1 : 0
  365. ];
  366. e107::getDb()->insert('tkReport', $insert);
  367. }
  368. /**
  369. * Load the expected answer for this user's open question. Single use:
  370. * a stale tab, a tampered token or a double-submit gets the message below.
  371. */
  372. private function loadPending(): ?array {
  373. $token = filter_input(INPUT_POST, 'checkerData');
  374. $answer = TkAnswerStore::consume($this->user, is_string($token) ? $token : null);
  375. if ($answer === null) {
  376. e107::getRender()->tablerender('Answer check',
  377. 'That question has expired or was already answered. Please answer the new question.');
  378. }
  379. return $answer;
  380. }
  381. }