TK2.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /**
  3. * TimeKeeper front page controller: shows the student's stats, checks a
  4. * submitted answer, and asks a question generator for the next question.
  5. *
  6. * Changes from the current repo version:
  7. * - removed adminDev(): for every Main Admin it ran on every page load,
  8. * printed debug dumps (the students' settings and stats, test numbers),
  9. * hard-coded two students' user names, set the time zone, and generated a
  10. * question from the unfinished "continents" generator
  11. * - checkAnswer() called delete(..., true): the third argument is e107's
  12. * debug flag, so the SQL was printed on the page after every answer.
  13. * It's gone, and the user name is escaped
  14. * - generators are loaded with require_once and an absolute path (include
  15. * plus ./relative paths depended on the working directory and could
  16. * redeclare a class)
  17. * - getQuestion(): generalKnowledge fell through into elements (no break);
  18. * countries/flags/capitalCities built an elements2 object after including
  19. * continents.php (class not found). Subjects that aren't built yet now
  20. * show a plain message instead
  21. * - getScores()/getLastQuestion(): MPREFIX instead of `e107.e107_...`, user
  22. * escaped, and a student with no answers this month gets zeros (not
  23. * null) for the stats
  24. * - showMessage(): user name escaped
  25. * - someone with neither the student nor the teacher class now sees a
  26. * message instead of an empty page
  27. */
  28. require_once __DIR__ . '/TkAnswerStore.php';
  29. class TK2 {
  30. private $data = [];
  31. private $subjectsList = [
  32. // Math
  33. [['numbers', 1, 0], // number sequences
  34. ['addition', 1, 10000], // Numeracy adding
  35. ['subtraction', 1, 20000], // Numeracy minus'
  36. ['multiplication', 1, 200000], // Numeracy times'
  37. ['division', 0, 0], // Numeracy deviding
  38. ['rounding', 0, 0], // Numeracy rounding
  39. ['worded_add', 0, 0], // Numeracy worded adding
  40. ['worded_sub', 0, 0], // Numeracy worded minusing
  41. ['worded_mult', 0, 0], // Numeracy worded timesing
  42. ['worded_devi', 0, 0], // Numeracy worded deviding
  43. ],
  44. // English
  45. [['spelling', 1, 0], // Plain spelling
  46. ['anagrams', 1, 4000000], // Shuffle letters in a word
  47. ],
  48. // General knowledge
  49. [['generalKnowledge', 0, 0], // Name kinda says it all
  50. ],
  51. // Science
  52. [['elements', 1, 150000], // Periodic table of elements
  53. ],
  54. // Geography
  55. [['continents', 0, 0], // Point to the continent
  56. ['countries', 0, 0], // Point to the country
  57. ['flags', 0, 0], // Name the country by the flag picture
  58. ['capitalCities', 0, 0], // Name the capital for a country
  59. ],
  60. // History
  61. // Art
  62. [['artists', 0, 0], // Name the artist for famous paintings
  63. ],
  64. // Technology
  65. // language
  66. [['malaySpelling', 0, 0], // This could be interesting
  67. ],
  68. // Health - Health and Physical Education
  69. [['nameBodyParts', 0, 0], // Name the body parts from the images or point to the part
  70. ['nameBodyOrgans', 0, 0], // Name the organs or what they do
  71. ['basicFirstAid', 0, 0], // Some BASIC things to know for first aid
  72. ],
  73. ];
  74. /**
  75. * Run the timekeeper functionality
  76. */
  77. public function run(): void {
  78. $isStudent = check_class("TIMEKEEPER_STUDENT");
  79. $isTeacher = check_class("TIMEKEEPER_TEACHER");
  80. if ($isStudent) {
  81. $this->student();
  82. }
  83. if ($isTeacher) {
  84. $this->teacher();
  85. }
  86. if (!$isStudent && !$isTeacher) {
  87. e107::getRender()->tablerender('TimeKeeper', USER ? 'Your account has no TimeKeeper role (student or teacher).' : 'Please log in to use TimeKeeper.');
  88. }
  89. }
  90. /**
  91. * Run the sequence for teachers
  92. */
  93. private function teacher(): void {
  94. }
  95. /**
  96. * Run the sequence for students
  97. */
  98. private function student(): void {
  99. $user = e107::getUser()->getLoginName();
  100. $this->checkAnswer($user);
  101. $this->getScores($user);
  102. $this->showMessage();
  103. // If the last question has not been answered ask again.
  104. if ($this->getLastQuestion()) {
  105. return;
  106. }
  107. $this->getSubject();
  108. $this->getQuestion();
  109. }
  110. /**
  111. * Check if the last question was answered and check the answer
  112. * @param string $user
  113. */
  114. private function checkAnswer($user): void {
  115. $subject = filter_input(INPUT_POST, 'subject');
  116. if (is_string($subject) && $subject !== '') {
  117. require_once __DIR__ . '/answerChecker2.php';
  118. $ac = new answerChecker2();
  119. $ac->checkQuestionSubject($subject, $user);
  120. $db = e107::getDb();
  121. $db->delete('tkLastQuestion', "user = '" . $db->escape($user) . "'");
  122. }
  123. }
  124. /**
  125. * Show the last question asked if it hasn't been answered.
  126. * @return bool True when a question was shown.
  127. */
  128. private function getLastQuestion(): bool {
  129. $db = e107::getDb();
  130. $lastQuestion = $db->retrieve("SELECT LastQuestionHtml FROM `" . MPREFIX . "tkLastQuestion` WHERE user = '" . $db->escape($this->data['user']) . "' ORDER BY id DESC LIMIT 1");
  131. if (!empty($lastQuestion)) {
  132. e107::getRender()->tablerender('Last Question', base64_decode($lastQuestion));
  133. return true;
  134. }
  135. return false;
  136. }
  137. /**
  138. * Get the question based on selected subject
  139. * @return void
  140. */
  141. private function getQuestion(): void {
  142. switch ($this->data['selectedSubject']) {
  143. case 'numbers':
  144. require_once __DIR__ . '/questionGenerators/math/numbers2.php';
  145. $questionGen = new numbers2($this->data['user']);
  146. $questionGen->getNumbers();
  147. break;
  148. case 'addition':
  149. case 'subtraction':
  150. case 'multiplication':
  151. case 'division':
  152. case 'rounding':
  153. require_once __DIR__ . '/questionGenerators/math/numeracy2.php';
  154. $questionGen = new numeracy2($this->data['user'], $this->data['selectedSubject']);
  155. $questionGen->getNumeracy();
  156. break;
  157. case 'worded_add':
  158. case 'worded_sub':
  159. case 'worded_mult':
  160. case 'worded_devi':
  161. case 'spelling':
  162. require_once __DIR__ . '/questionGenerators/english/spelling2.php';
  163. $questionGen = new spelling2($this->data['user']);
  164. $questionGen->getSpellingWord();
  165. break;
  166. case 'anagrams':
  167. require_once __DIR__ . '/questionGenerators/english/anagrams.php';
  168. $questionGen = new anagrams($this->data['user']);
  169. $questionGen->getanagram();
  170. break;
  171. case 'elements':
  172. require_once __DIR__ . '/questionGenerators/science/elements2.php';
  173. $questionGen = new elements2($this->data['user']);
  174. $questionGen->getElements();
  175. break;
  176. case 'generalKnowledge':
  177. case 'continents':
  178. case 'countries':
  179. case 'flags':
  180. case 'capitalCities':
  181. case 'artists':
  182. case 'malaySpelling':
  183. case 'nameBodyParts':
  184. case 'nameBodyOrgans':
  185. case 'basicFirstAid':
  186. default:
  187. // Not built yet (or unknown): none of these are in the random pool.
  188. e107::getRender()->tablerender('TimeKeeper', 'This subject is not available yet. Please refresh the page.');
  189. break;
  190. }
  191. }
  192. /**
  193. * Get the list of available subjects and select a random one.
  194. * @return void
  195. */
  196. private function getSubject(): void {
  197. $usableSubjects = [];
  198. foreach ($this->subjectsList as $subjects) {
  199. foreach ($subjects as $subject) {
  200. if ($subject[1] === 1 && $this->data['difficulty'] >= $subject[2]) {
  201. $usableSubjects[] = $subject[0];
  202. }
  203. }
  204. }
  205. if (empty($usableSubjects)) {
  206. $usableSubjects[] = 'numbers';
  207. }
  208. $this->data['selectedSubject'] = $usableSubjects[mt_rand(0, count($usableSubjects) - 1)];
  209. }
  210. /**
  211. * Show an initial stats message to the user.
  212. * @return void
  213. */
  214. private function showMessage(): void {
  215. $text = "You have answered " . (int) $this->data['cntr'] . " questions this month.<br/>"
  216. . "Your accuacy for the month is " . htmlspecialchars((string) $this->data['percent']) . "%.<br/>"
  217. . "Your difficulty is set at " . htmlspecialchars((string) $this->data['difficulty']) . ".<br/><br/>";
  218. e107::getRender()->tablerender('Your stats ' . htmlspecialchars(ucfirst($this->data['user'])), $text);
  219. }
  220. /**
  221. * Get the initial values needed to generate a sane question.
  222. * @param string $user
  223. * @return void
  224. */
  225. private function getScores($user): void {
  226. $db = e107::getDb();
  227. $u = $db->escape($user);
  228. $returnArray = [];
  229. $returnArray['totalQuestionCount'] = (int) $db->count('tkReport', '(id)', "username = '{$u}'");
  230. $db->gen("SELECT COUNT(id) AS cntr, CAST((SUM(correct)/COUNT(id)*100) AS DECIMAL(5,2)) AS percent
  231. FROM `" . MPREFIX . "tkReport` WHERE username = '{$u}'
  232. AND answereddatestamp >= UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 1 MONTH)
  233. AND answereddatestamp <= UNIX_TIMESTAMP(CURRENT_DATE() + INTERVAL 1 DAY)");
  234. $row = $db->fetch();
  235. $returnArray['cntr'] = is_array($row) ? (int) $row['cntr'] : 0;
  236. $returnArray['percent'] = (is_array($row) && $row['percent'] !== null) ? (float) $row['percent'] : 0;
  237. $returnArray['user'] = $user;
  238. $returnArray['difficulty'] = $returnArray['totalQuestionCount'] * $returnArray['percent'];
  239. $this->data = $returnArray;
  240. }
  241. }