answerChecker2.php 25 KB

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