answerChecker2.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. /*
  3. * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
  4. * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/EmptyPHP.php to edit this template
  5. */
  6. class answerChecker2 {
  7. private $user;
  8. private $messages = [
  9. '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}'"],
  10. '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}'"],
  11. '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}'"],
  12. '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}'"],
  13. '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}'"],
  14. 'rounding' => [],
  15. 'worded_add' => [],
  16. 'worded_sub' => [],
  17. 'worded_mult' => [],
  18. 'worded_devi' => [],
  19. '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}'"],
  20. 'generalKnowledge' => [],
  21. '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}'"],
  22. 'continents' => [],
  23. 'countries' => [],
  24. 'flags' => [],
  25. 'capitalCities' => [],
  26. 'artists' => [],
  27. 'malaySpelling' => [],
  28. 'nameBodyParts' => [],
  29. 'nameBodyOrgans' => [],
  30. 'basicFirstAid' => []
  31. ];
  32. /**
  33. * Get the right answer checker for the subject
  34. */
  35. public function checkQuestionSubject($subject, $user) {
  36. $this->user = $user;
  37. switch ($subject) {
  38. case 'numbers':
  39. case 'addition':
  40. case 'subtraction':
  41. case 'multiplication':
  42. case 'division':
  43. $this->checkGeneric($subject);
  44. break;
  45. case 'worded_add':
  46. case 'worded_sub':
  47. case 'worded_mult':
  48. case 'worded_devi':
  49. case 'spelling':
  50. $this->checkSpelling(); //Custom checker
  51. break;
  52. case 'anagrams':
  53. $this->checkAnagrams();
  54. break;
  55. case 'generalKnowledge':
  56. case 'elements':
  57. $this->checkGeneric('elements');
  58. break;
  59. case 'continents':
  60. case 'countries':
  61. case 'flags':
  62. case 'capitalCities':
  63. case 'artists':
  64. case 'malaySpelling':
  65. case 'nameBodyParts':
  66. case 'nameBodyOrgans':
  67. case 'basicFirstAid':
  68. default:
  69. print_a('An error has been detected in the answer checker. Please report this and refresh the page.');
  70. break;
  71. }
  72. }
  73. /**
  74. * Check the answer for anything basic
  75. */
  76. private function checkGeneric($subject) {
  77. $usersAnswer = (string) filter_input(INPUT_POST, 'a1');
  78. $answer = $this->loadPending();
  79. if ($answer === null) {
  80. return;
  81. }
  82. if (is_array($answer['question'])) {
  83. $answer['question'] = implode('', $answer['question']);
  84. }
  85. if (trim($usersAnswer) === trim((string) $answer['answer1'])) {
  86. $text = str_replace(['{ANSWER}', '{USER_ANSWER}'], [$answer['answer1'], trim($usersAnswer)], $this->messages[$subject][1]) . "<br/>";
  87. $this->updateScore(true);
  88. } else {
  89. $text = str_replace(['{ANSWER}', '{USER_ANSWER}', '{QUESTION}'], [$answer['answer1'], trim($usersAnswer), $answer['question']], $this->messages[$subject][2]) . "<br/>";
  90. $this->updateScore(false);
  91. }
  92. $this->addToReport($answer['answer1'], $usersAnswer, $subject, str_replace('{ANSWER}', $answer['answer1'], str_replace('{QUESTION}', $answer['question'], $this->messages[$subject][0])));
  93. e107::getRender()->tablerender(ucfirst($subject) . ' answer check', $text);
  94. }
  95. /**
  96. * Check the answer for anything basic
  97. */
  98. private function checkAnagrams() {
  99. $usersAnswer = (string) filter_input(INPUT_POST, 'a1');
  100. $answer = $this->loadPending();
  101. if ($answer === null) {
  102. return;
  103. }
  104. if (is_array($answer['question'])) {
  105. $answer['question'] = implode('', $answer['question']);
  106. }
  107. $words = e107::getDb()->retrieve('tk_wordList', 'word');
  108. if (trim($usersAnswer) === trim((string) $answer['answer1']) || $this->findInList($words, $usersAnswer)) {
  109. $text = str_replace(['{ANSWER}', '{USER_ANSWER}'], [$answer['answer1'], trim($usersAnswer)], $this->messages['anagrams'][1]) . "<br/>";
  110. $this->updateScore(true);
  111. } else {
  112. $text = str_replace(['{ANSWER}', '{USER_ANSWER}', '{QUESTION}'], [$answer['answer1'], trim($usersAnswer), $answer['question']], $this->messages['anagrams'][2]) . "<br/>";
  113. $this->updateScore(false);
  114. }
  115. $this->addToReport($answer['answer1'], $usersAnswer, 'anagrams', str_replace('{ANSWER}', $answer['answer1'], str_replace('{QUESTION}', $answer['question'], $this->messages['anagrams'][0])));
  116. e107::getRender()->tablerender(ucfirst('anagrams') . ' answer check', $text);
  117. }
  118. private function findInList($list, $needle) {
  119. foreach ($list as $listItem) {
  120. if ($listItem == $needle) {
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. /**
  127. * Check the answer for spelling
  128. */
  129. private function checkSpelling() {
  130. $usersAnswer = (string) filter_input(INPUT_POST, 'a1');
  131. $answer = $this->loadPending();
  132. if ($answer === null) {
  133. return;
  134. }
  135. if (trim($usersAnswer) === trim((string) $answer['word'])) {
  136. $text = "Congratulations '" . trim($usersAnswer) . "' was correct for 'spell the word " . $answer['word'] . "'<br/>";
  137. $this->updateScore(true);
  138. //file_put_contents('debug_Spelling_data.txt','<->'.$answer['word'].'<->'.$usersAnswer.'<->True'."\n",FILE_APPEND);//=================================
  139. } else {
  140. $text = "Sorry but '" . trim($usersAnswer) . "' was incorrect it should have been '" . trim($answer['word']) . "' for 'spell the word " . $answer['word'] . "'<br/>";
  141. $this->updateScore(false);
  142. //file_put_contents('debug_Spelling_data.txt','<->'.$answer['word'].'<->'.$usersAnswer.'<->False'."\n",FILE_APPEND);//=================================
  143. }
  144. $this->addToReport($answer['word'], $usersAnswer, 'spelling', "Spell the word " . $answer['word']);
  145. e107::getRender()->tablerender('Spelling answer check', $text);
  146. }
  147. /**
  148. * Add or minus the score
  149. */
  150. private function updateScore($scorePoint) {
  151. $currentScore = e107::getDb()->retrieve('timekeeperScore', 'timekeeper_lifetimecorrect, timekeeper_lifetimequestions, timekeeper_minutes', 'timekeeper_username="' . $this->user . '"');
  152. if ($scorePoint) {
  153. $currentScore['timekeeper_lifetimecorrect']++;
  154. $currentScore['timekeeper_minutes'] = $currentScore['timekeeper_minutes'] + $this->scaleTimeAddition();
  155. } else {
  156. $currentScore['timekeeper_minutes']--;
  157. }
  158. $currentScore['timekeeper_lifetimequestions']++;
  159. if ($currentScore['timekeeper_lifetimequestions'] == 1) {
  160. $currentScore['timekeeper_lastquestiondatestamp'] = time();
  161. $currentScore['timekeeper_yearlevel'] = 0;
  162. $currentScore['timekeeper_username'] = $this->user;
  163. e107::getDb()->insert('timekeeperScore', $currentScore);
  164. } else {
  165. $currentScore['WHERE'] = 'timekeeper_username="' . $this->user . '"';
  166. e107::getDb()->update('timekeeperScore', $currentScore);
  167. }
  168. }
  169. /**
  170. * Return how many minutes play time to award scaled by difficulty
  171. */
  172. private function scaleTimeAddition() {
  173. //TODO look at this and fix it.
  174. $difficulty = $this->getDifficulty($this->user); //replace with db call
  175. $maxDifficulty = 5000000; // 5 mil is max here
  176. //$returnMinutes = 10 - ($difficulty / $maxDifficulty * 100) / 10;
  177. $returnMinutes = (int) $difficulty / 10;
  178. //print_a(['diffi'=>$difficulty,'fprint'=> round($difficulty),'retmins'=>round($returnMinutes)]);
  179. $returnMinutes = round($returnMinutes);
  180. if ($returnMinutes <= 1) {
  181. $returnMinutes = 1;
  182. }
  183. return round($returnMinutes);
  184. }
  185. /**
  186. * Return users overall difficulty.
  187. */
  188. private function getDifficulty($user) {
  189. $returnArray = [];
  190. //$returnArray['totalQuestionCount'] = e107::getDb()->count("tkReport", "(id)", "username = '" . $user . "'");
  191. e107::getDb()->gen("SELECT COUNT(id) as cntr, CAST((SUM(correct)/COUNT(id)*100) as DECIMAL(5,2)) as percent
  192. FROM e107.`e107_tkReport` WHERE username = '" . $user . "'
  193. AND answereddatestamp >= unix_timestamp(CURRENT_DATE() - INTERVAL 1 MONTH)
  194. AND answereddatestamp <= unix_timestamp(CURRENT_DATE() + INTERVAL 1 DAY)");
  195. while ($row = e107::getDb()->fetch()) {
  196. $returnArray = array_merge($returnArray, $row);
  197. }
  198. return $returnArray['percent']; //($returnArray['totalQuestionCount']*$returnArray['percent']);
  199. }
  200. /**
  201. * Add the last answered question to the report DB table.
  202. */
  203. private function addToReport($answer, $usersAnswer, $subject, $questionString) {
  204. if ($answer == $usersAnswer) {
  205. $correct = 1;
  206. } else {
  207. $correct = 0;
  208. }
  209. $insert = [
  210. 'username' => $this->user,
  211. 'question' => $questionString,
  212. 'answereddatestamp' => time(),
  213. 'userAnswer' => trim($usersAnswer),
  214. 'answer' => trim($answer),
  215. 'subject' => $subject,
  216. 'correct' => $correct
  217. ];
  218. e107::getDb()->insert('tkReport', $insert);
  219. }
  220. /**
  221. * ShortCode engine
  222. */
  223. private function shortCode($keys, $message) {
  224. $returnMessage = $message;
  225. foreach ($keys as $key => $value) {
  226. $returnMessage = $str;
  227. }
  228. }
  229. private function loadPending(): ?array {
  230. $token = filter_input(INPUT_POST, 'checkerData');
  231. $answer = TkAnswerStore::consume($this->user, is_string($token) ? $token : null);
  232. if ($answer === null) {
  233. e107::getRender()->tablerender('Answer check',
  234. 'That question has expired or was already answered. Please answer the new question.');
  235. }
  236. return $answer;
  237. }
  238. }