answerChecker2.php 27 KB

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