answerChecker2.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. * - fractions: the answer may be typed as 3/4, a mixed number (1 1/2), a whole number
  22. * or an exact decimal (0.75); it must be in its simplest form, and a right value that
  23. * isn't simplified (or isn't a mixed number when one was asked for) is marked wrong
  24. * with a hint
  25. * - a correct answer gets a friendlier, randomised message: a cheer, the answer
  26. * worked out, the play minutes earned, and a streak of correct answers (the
  27. * old "Congratulations" strings at messages[...][1] are no longer used)
  28. */
  29. class answerChecker2 {
  30. private $user;
  31. private $messages = [
  32. '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}'"],
  33. '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}'"],
  34. '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}'"],
  35. '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}'"],
  36. '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}'"],
  37. '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'"],
  38. 'fractions' => ['Fractions: {QUESTION}', "Congratulations '{USER_ANSWER}' was correct for '{QUESTION}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for '{QUESTION}'"],
  39. 'word_problems' => ['{QUESTION}', "Congratulations '{USER_ANSWER}' was correct for '{QUESTION}'", "Sorry but '{USER_ANSWER}' was incorrect it should have been '{ANSWER}' for '{QUESTION}'"],
  40. '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}'"],
  41. 'generalKnowledge' => [],
  42. '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}'"],
  43. 'continents' => [],
  44. 'countries' => [],
  45. 'flags' => [],
  46. 'capitalCities' => [],
  47. 'artists' => [],
  48. 'malaySpelling' => [],
  49. 'nameBodyParts' => [],
  50. 'nameBodyOrgans' => [],
  51. 'basicFirstAid' => []
  52. ];
  53. /**
  54. * Get the right answer checker for the subject
  55. */
  56. public function checkQuestionSubject($subject, $user) {
  57. $this->user = $user;
  58. switch ($subject) {
  59. case 'numbers':
  60. case 'addition':
  61. case 'subtraction':
  62. case 'multiplication':
  63. case 'division':
  64. case 'rounding':
  65. case 'word_problems':
  66. $this->checkGeneric($subject);
  67. break;
  68. case 'spelling':
  69. $this->checkSpelling(); //Custom checker
  70. break;
  71. case 'anagrams':
  72. $this->checkAnagrams();
  73. break;
  74. case 'fractions':
  75. $this->checkFractions();
  76. break;
  77. case 'generalKnowledge':
  78. case 'elements':
  79. $this->checkGeneric('elements');
  80. break;
  81. case 'continents':
  82. case 'countries':
  83. case 'flags':
  84. case 'capitalCities':
  85. case 'artists':
  86. case 'malaySpelling':
  87. case 'nameBodyParts':
  88. case 'nameBodyOrgans':
  89. case 'basicFirstAid':
  90. default:
  91. print_a('An error has been detected in the answer checker. Please report this and refresh the page.');
  92. break;
  93. }
  94. }
  95. /**
  96. * Check the answer for anything basic
  97. */
  98. private function checkGeneric($subject) {
  99. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  100. $answer = $this->loadPending();
  101. if ($answer === null) {
  102. return;
  103. }
  104. $correct = $this->isCorrect($answer['answer1'], $usersAnswer);
  105. $this->finishCheck($subject, $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, $subject));
  106. }
  107. /**
  108. * Check an anagram answer: the exact word, or any other real word made
  109. * from the same letters.
  110. */
  111. private function checkAnagrams() {
  112. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  113. $answer = $this->loadPending();
  114. if ($answer === null) {
  115. return;
  116. }
  117. $correct = $this->isCorrect($answer['answer1'], $usersAnswer)
  118. || $this->isValidAnagram($usersAnswer, $answer['answer1']);
  119. $this->finishCheck('anagrams', $correct, $answer['answer1'], $usersAnswer, $this->questionText($answer, 'anagrams'));
  120. }
  121. /**
  122. * Check a fractions answer. Any correct form is accepted (3/4, a mixed
  123. * number like 1 1/2, a whole number, an exact decimal like 0.75) but it has
  124. * to be in its simplest form, and a mixed number if one was asked for.
  125. */
  126. private function checkFractions() {
  127. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  128. $answer = $this->loadPending();
  129. if ($answer === null) {
  130. return;
  131. }
  132. $format = isset($answer['format']) ? $answer['format'] : 'simplest';
  133. $verdict = $this->fractionVerdict((string) $answer['answer1'], $format, $usersAnswer);
  134. $hint = '';
  135. if ($verdict === 'unsimplified') {
  136. $hint = "That's the right value, but it can be written more simply. ";
  137. } elseif ($verdict === 'wrongform') {
  138. $hint = "That's the right value, but write it as a mixed number, like 2 1/3. ";
  139. }
  140. $this->finishCheck('fractions', $verdict === 'correct', $answer['answer1'], $usersAnswer, $this->questionText($answer, 'fractions'), $hint);
  141. }
  142. /**
  143. * @param string $expectedText The right answer in its simplest form ("3/4", "1 1/2", "7").
  144. * @param string $format 'simplest', or 'mixed' when a mixed number was asked for.
  145. * @param string $given What the student typed.
  146. * @return string 'correct', 'unsimplified', 'wrongform' or 'wrong'
  147. */
  148. private function fractionVerdict($expectedText, $format, $given) {
  149. require_once __DIR__ . '/fraction/src/Fraction.php';
  150. $typed = $this->parseFractionAnswer($given);
  151. if ($typed === null) {
  152. return 'wrong';
  153. }
  154. try {
  155. $expected = Fraction::fromString($expectedText);
  156. } catch (InvalidArgumentException $e) {
  157. return 'wrong';
  158. }
  159. if (!$typed['value']->isSameValueAs($expected)) {
  160. return 'wrong';
  161. }
  162. if ($format === 'mixed' && $typed['form'] !== 'mixed') {
  163. return 'wrongform';
  164. }
  165. if (!$typed['lowest']) {
  166. return 'unsimplified';
  167. }
  168. return 'correct';
  169. }
  170. /**
  171. * Read what the student typed as a fraction.
  172. *
  173. * @return array|null ['value' => Fraction, 'form' => whole|fraction|mixed|decimal,
  174. * 'lowest' => bool (in simplest form)], or null if it isn't a number
  175. */
  176. private function parseFractionAnswer($text) {
  177. $text = trim(preg_replace('/\s+/', ' ', (string) $text));
  178. try {
  179. if (preg_match('#^(\d{1,9})$#', $text, $m)) {
  180. return ['value' => new Fraction((int) $m[1]), 'form' => 'whole', 'lowest' => true];
  181. }
  182. if (preg_match('#^(\d{1,9}) ?/ ?(\d{1,9})$#', $text, $m)) {
  183. $n = (int) $m[1];
  184. $d = (int) $m[2];
  185. if ($d < 1) {
  186. return null;
  187. }
  188. return ['value' => new Fraction($n, $d), 'form' => 'fraction', 'lowest' => ($n > 0 && $this->gcdInt($n, $d) === 1)];
  189. }
  190. if (preg_match('#^(\d{1,9}) (\d{1,9}) ?/ ?(\d{1,9})$#', $text, $m)) {
  191. $w = (int) $m[1];
  192. $n = (int) $m[2];
  193. $d = (int) $m[3];
  194. if ($d < 1) {
  195. return null;
  196. }
  197. $value = (new Fraction($w))->add(new Fraction($n, $d));
  198. return ['value' => $value, 'form' => 'mixed', 'lowest' => ($n > 0 && $n < $d && $this->gcdInt($n, $d) === 1)];
  199. }
  200. if (preg_match('#^(\d{0,9})\.(\d{1,8})$#', $text, $m)) {
  201. // Exact: 0.29 is 29/100. (Fraction::fromFloat() goes through floating point.)
  202. $digits = ($m[1] === '' ? '0' : $m[1]) . $m[2];
  203. return ['value' => new Fraction((int) $digits, (int) pow(10, strlen($m[2]))), 'form' => 'decimal', 'lowest' => true];
  204. }
  205. } catch (InvalidArgumentException $e) {
  206. return null;
  207. }
  208. return null;
  209. }
  210. private function gcdInt($a, $b) {
  211. $a = abs($a);
  212. $b = abs($b);
  213. while ($b > 0) {
  214. $t = $a % $b;
  215. $a = $b;
  216. $b = $t;
  217. }
  218. return $a;
  219. }
  220. /**
  221. * Check the answer for spelling
  222. */
  223. private function checkSpelling() {
  224. $usersAnswer = trim((string) filter_input(INPUT_POST, 'a1'));
  225. $answer = $this->loadPending();
  226. if ($answer === null) {
  227. return;
  228. }
  229. $word = (string) $answer['word'];
  230. $correct = $this->isCorrect($word, $usersAnswer);
  231. $minutes = $this->updateScore($correct);
  232. $this->addToReport($word, $usersAnswer, 'spelling', "Spell the word " . $word, $correct);
  233. if ($correct) {
  234. $text = $this->correctText('spelling', $word, $usersAnswer, $word, $minutes);
  235. $title = 'Correct!';
  236. } else {
  237. $safeAnswer = htmlspecialchars($usersAnswer);
  238. $safeWord = htmlspecialchars($word);
  239. $text = "Sorry but '" . $safeAnswer . "' was incorrect it should have been '" . $safeWord . "' for 'spell the word " . $safeWord . "'<br/>";
  240. $title = 'Spelling answer check';
  241. }
  242. e107::getRender()->tablerender($title, $text);
  243. }
  244. /**
  245. * Shared tail of the generic and anagram checks: build the message, update
  246. * the score, write the report row, render the result. $correct is the one
  247. * decision used for all three.
  248. */
  249. private function finishCheck($subject, $correct, $expected, $usersAnswer, $question, $hint = '') {
  250. $expected = (string) $expected;
  251. $messages = $this->messages[$subject];
  252. $minutes = $this->updateScore($correct);
  253. $questionString = strtr($messages[0], ['{ANSWER}' => $expected, '{QUESTION}' => $question]);
  254. $this->addToReport($expected, $usersAnswer, $subject, $questionString, $correct);
  255. if ($correct) {
  256. $text = $this->correctText($subject, $expected, $usersAnswer, $question, $minutes);
  257. $title = 'Correct!';
  258. } else {
  259. $safe = [
  260. '{ANSWER}' => htmlspecialchars($expected),
  261. '{USER_ANSWER}' => htmlspecialchars($usersAnswer),
  262. '{QUESTION}' => htmlspecialchars($question),
  263. ];
  264. $text = $hint . strtr($messages[2], $safe) . "<br/>";
  265. $title = ucfirst($subject) . ' answer check';
  266. }
  267. e107::getRender()->tablerender($title, $text);
  268. }
  269. private $cheers = [
  270. "🎉 Woohoo! You got it!",
  271. "⭐ Brilliant!",
  272. "🚀 Boom! Nailed it!",
  273. "💪 Spot on!",
  274. "🙌 High five! That's right!",
  275. "🧠 Big brain move!",
  276. "🌟 You're a star!",
  277. "😎 Too easy for you!",
  278. "🏆 Champion answer!",
  279. "✨ Yes! Exactly right!",
  280. "🎯 Bullseye!",
  281. "🦄 Magical! Correct!",
  282. ];
  283. /**
  284. * The message for a correct answer: a cheer, the answer, minutes earned,
  285. * and a streak when there is one. Everything typed by the student is escaped.
  286. */
  287. private function correctText($subject, $expected, $usersAnswer, $question, $minutes) {
  288. $text = '<div style="font-size:160%;font-weight:bold;">' . $this->cheers[array_rand($this->cheers)] . '</div>';
  289. $text .= '<p>' . $this->correctDetail($subject, $expected, $usersAnswer, $question) . '</p>';
  290. if ($minutes > 0) {
  291. $text .= '<p>🎮 <b>+' . (int) $minutes . ((int) $minutes === 1 ? ' minute' : ' minutes') . '</b> of play time earned!</p>';
  292. }
  293. $streak = $this->correctStreak();
  294. if ($streak >= 25) {
  295. $text .= '<p>🚀 25 or more correct in a row. Unstoppable!</p>';
  296. } elseif ($streak >= 10) {
  297. $text .= '<p>🚀 ' . $streak . ' correct in a row. Unstoppable!</p>';
  298. } elseif ($streak >= 5) {
  299. $text .= '<p>🔥 ' . $streak . ' correct in a row. You\'re on fire!</p>';
  300. } elseif ($streak >= 3) {
  301. $text .= '<p>🔥 ' . $streak . ' correct in a row!</p>';
  302. }
  303. return $text;
  304. }
  305. /**
  306. * The line that says what the right answer was, for this kind of question.
  307. */
  308. private function correctDetail($subject, $expected, $usersAnswer, $question) {
  309. $e = htmlspecialchars($expected);
  310. switch ($subject) {
  311. case 'numbers':
  312. return 'The missing number was <b>' . $e . '</b>.';
  313. case 'addition':
  314. case 'subtraction':
  315. case 'multiplication':
  316. case 'division':
  317. $sum = strtr($question, ['x' => ' × ', '/' => ' ÷ ', '+' => ' + ', '-' => ' − ']);
  318. return '<b>' . htmlspecialchars($sum) . ' = ' . $e . '</b>';
  319. case 'rounding':
  320. return '<b>' . htmlspecialchars($question) . '</b> rounds to <b>' . $e . '</b> (the nearest 5 cents).';
  321. case 'anagrams':
  322. if (mb_strtolower(trim($usersAnswer)) !== mb_strtolower($expected)) {
  323. return 'You found <b>' . htmlspecialchars($usersAnswer) . '</b>. I was thinking of <b>' . $e . '</b>, but that is a real word too!';
  324. }
  325. return 'You unjumbled it: <b>' . $e . '</b>!';
  326. case 'fractions':
  327. return '<b>' . htmlspecialchars($question) . ' = ' . $e . '</b>';
  328. case 'word_problems':
  329. return 'The answer was <b>' . $e . '</b>.';
  330. case 'spelling':
  331. return 'You spelled <b>' . $e . '</b> perfectly!';
  332. default:
  333. return '<b>' . $e . '</b> was exactly right.';
  334. }
  335. }
  336. /**
  337. * How many of the student's latest answers in a row were correct (up to 25).
  338. * Called after the current answer has been written to the report.
  339. */
  340. private function correctStreak() {
  341. $db = e107::getDb();
  342. $db->gen("SELECT `correct` FROM `" . MPREFIX . "tkReport` WHERE `username` = '" . $db->escape($this->user) . "' ORDER BY `id` DESC LIMIT 25");
  343. $recent = [];
  344. while ($row = $db->fetch()) {
  345. $recent[] = (int) $row['correct'];
  346. }
  347. $streak = 0;
  348. foreach ($recent as $correct) {
  349. if ($correct !== 1) {
  350. break;
  351. }
  352. $streak++;
  353. }
  354. return $streak;
  355. }
  356. /**
  357. * Question text for messages. Array questions (equations, number
  358. * sequences, scrambled letters) are joined; a rounding question is just
  359. * the amount.
  360. */
  361. private function questionText($answer, $subject) {
  362. $question = isset($answer['question']) ? $answer['question'] : '';
  363. if (is_array($question)) {
  364. if ($subject === 'rounding') {
  365. $question = array_slice($question, 0, 1);
  366. }
  367. $question = implode('', $question);
  368. }
  369. return (string) $question;
  370. }
  371. /**
  372. * Numbers compare numerically ("1.1" == "1.10"), everything else
  373. * case-insensitively, after trimming.
  374. */
  375. private function isCorrect($expected, $given): bool {
  376. $expected = trim((string) $expected);
  377. $given = trim((string) $given);
  378. if (is_numeric($expected) && is_numeric($given)) {
  379. return abs((float) $expected - (float) $given) < 1e-9;
  380. }
  381. return mb_strtolower($expected) === mb_strtolower($given);
  382. }
  383. /**
  384. * An alternative anagram answer is valid when it uses exactly the same
  385. * letters as the original word and is itself in the word list.
  386. */
  387. private function isValidAnagram($given, $original) {
  388. $given = trim((string) $given);
  389. if ($given === '' || !$this->sameLetters($given, (string) $original)) {
  390. return false;
  391. }
  392. $db = e107::getDb();
  393. return $db->count('tk_wordList', '(*)', "word = '" . $db->escape($given) . "'") > 0;
  394. }
  395. private function sameLetters($a, $b) {
  396. $a = preg_split('//u', mb_strtolower($a), -1, PREG_SPLIT_NO_EMPTY);
  397. $b = preg_split('//u', mb_strtolower($b), -1, PREG_SPLIT_NO_EMPTY);
  398. sort($a);
  399. sort($b);
  400. return $a === $b;
  401. }
  402. /**
  403. * Add or minus the score.
  404. *
  405. * @return int The play minutes awarded for a correct answer (0 otherwise).
  406. */
  407. private function updateScore($scorePoint) {
  408. $db = e107::getDb();
  409. $user = $db->escape($this->user);
  410. $currentScore = $db->retrieve('timekeeperScore', 'timekeeper_lifetimecorrect, timekeeper_lifetimequestions, timekeeper_minutes', 'timekeeper_username="' . $user . '"');
  411. $isNew = !is_array($currentScore);
  412. if ($isNew) {
  413. $currentScore = ['timekeeper_lifetimecorrect' => 0, 'timekeeper_lifetimequestions' => 0, 'timekeeper_minutes' => 0];
  414. }
  415. $awarded = 0;
  416. if ($scorePoint) {
  417. $currentScore['timekeeper_lifetimecorrect']++;
  418. $awarded = (int) $this->scaleTimeAddition();
  419. $currentScore['timekeeper_minutes'] = $currentScore['timekeeper_minutes'] + $awarded;
  420. } else {
  421. // Never below zero: the column is signed now, and a negative balance would
  422. // otherwise have to be earned back before any play time counts.
  423. $currentScore['timekeeper_minutes'] = max(0, $currentScore['timekeeper_minutes'] - 1);
  424. }
  425. $currentScore['timekeeper_lifetimequestions']++;
  426. if ($isNew) {
  427. $currentScore['timekeeper_lastquestiondatestamp'] = time();
  428. $currentScore['timekeeper_yearlevel'] = 0;
  429. $currentScore['timekeeper_username'] = $this->user;
  430. $db->insert('timekeeperScore', $currentScore);
  431. } else {
  432. $currentScore['WHERE'] = 'timekeeper_username="' . $user . '"';
  433. $db->update('timekeeperScore', $currentScore);
  434. }
  435. return $awarded;
  436. }
  437. /**
  438. * Return how many minutes play time to award scaled by difficulty
  439. */
  440. private function scaleTimeAddition() {
  441. //TODO look at this and fix it.
  442. $difficulty = $this->getDifficulty($this->user); //replace with db call
  443. $returnMinutes = (int) $difficulty / 10;
  444. $returnMinutes = round($returnMinutes);
  445. if ($returnMinutes <= 1) {
  446. $returnMinutes = 1;
  447. }
  448. return round($returnMinutes);
  449. }
  450. /**
  451. * Return users overall accuracy (percent) for the last month.
  452. */
  453. private function getDifficulty($user) {
  454. $db = e107::getDb();
  455. $db->gen("SELECT CAST((SUM(correct)/COUNT(id)*100) AS DECIMAL(5,2)) AS percent
  456. FROM `" . MPREFIX . "tkReport` WHERE username = '" . $db->escape($user) . "'
  457. AND answereddatestamp >= UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 1 MONTH)
  458. AND answereddatestamp <= UNIX_TIMESTAMP(CURRENT_DATE() + INTERVAL 1 DAY)");
  459. $row = $db->fetch();
  460. return is_array($row) ? (float) $row['percent'] : 0;
  461. }
  462. /**
  463. * Add the last answered question to the report DB table.
  464. */
  465. private function addToReport($answer, $usersAnswer, $subject, $questionString, $isCorrect) {
  466. $insert = [
  467. 'username' => $this->user,
  468. 'question' => $questionString,
  469. 'answereddatestamp' => time(),
  470. 'userAnswer' => trim($usersAnswer),
  471. 'answer' => trim($answer),
  472. 'subject' => $subject,
  473. 'correct' => $isCorrect ? 1 : 0
  474. ];
  475. e107::getDb()->insert('tkReport', $insert);
  476. }
  477. /**
  478. * Load the expected answer for this user's open question. Single use:
  479. * a stale tab, a tampered token or a double-submit gets the message below.
  480. */
  481. private function loadPending(): ?array {
  482. $token = filter_input(INPUT_POST, 'checkerData');
  483. $answer = TkAnswerStore::consume($this->user, is_string($token) ? $token : null);
  484. if ($answer === null) {
  485. e107::getRender()->tablerender('Answer check',
  486. 'That question has expired or was already answered. Please answer the new question.');
  487. }
  488. return $answer;
  489. }
  490. }