answerChecker2.php 18 KB

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