-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpsychologistMode.php
More file actions
320 lines (298 loc) · 17.9 KB
/
psychologistMode.php
File metadata and controls
320 lines (298 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<?php # Doing some password/session checking and declarations before sending the page
#error_reporting(E_ALL); # debugging stuff, comment it out for production
#ini_set('display_errors', '1');
include 'serverScripts/sessionManagement.php';
$pw_checked = false;
$pw_valid = false;
$session_valid = false;
$testingEnabled = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') $pw_input = $_POST["password"];
if (isset($_COOKIE["session"])) { $pw_input = $_COOKIE["password"]; setcookie ("password", "", -1, "/"); } # remove this unsafe piece of garbage cookie storage
try {
$db = getDB();
$testingEnabled = (intval($db->querySingle("select \"Value\" from Settings where \"Key\" = 'testing_enabled'")) == 1);
if (isset($_COOKIE["session_id"])) $session_valid = verifySession();
else if (isset($pw_input)) { # password check routine
$pw_checked = true;
$pw_valid = verifyPassword($pw_input);
if ($pw_valid) { # create a new session for this one
createSession();
$session_valid = true; # we just created a new valid session and linked to it in cookies
} else $db->close(); # password invalid, won't need the DB connection until next request
}
} catch (SQLite3Exception $e) { # error out if we get a DB exception
echo "<b>Ошибка базы данных:</b> ".$e->getMessage();
die();
}
function defaultPsychologistMode($db, $testingEnabled){
echo "<a class=\"button\" href=\"/\" style=\"position: fixed\"><img alt=\"На главную\" src=\"/icons/home.svg\" height=\"32px\"/></a>";
echo "<a class=\"button\" id=\"exitButton\" href=\"/serverScripts/exit.php\"><img alt=\"Выход\" src=\"/icons/exit.svg\" height=\"32px\"/></a>";
echo "<table class=\"centerADiv\">";
echo "<tr><td colspan=\"2\"><h1>Режим психолога</h1></td>";
echo "<tr><td><a class='button' style='width: 95%; text-align: center;' href='/psychologistMode.php?action=changePassword'>Сменить пароль</a></td><td><button id='testingToggleButton'>";
echo "Тестирование:<span style='text-shadow: none; font-weight: bold; color: ".(($testingEnabled) ? "green;'>Вкл." : "red;'>Выкл."); # testing toggle button
echo "</span></button><tr><td colspan=\"2\"><h3>Просмотр результатов тестирования</h3></td></tr>";
$results = $db->query("SELECT tr.\"ID\", (tr.\"LastName\" || ' ' || tr.\"FirstName\" || ', ' || tr.\"Group\") as \"FullName\", tr.\"TestDate\", t.\"ReadableName\" FROM \"TestResults\" tr INNER JOIN \"Tests\" t ON tr.\"TestID\" = t.\"ID\";");
# setting up t h e t a b l e
echo "<tr><td colspan=\"2\"><table class='sortable'>";
echo "<tr>";
echo "<th>Студент</th>";
echo "<th>Дата</th>";
echo "<th>Тест (щёлкните для показа результатов)</th>";
echo "<th></th>";
echo "</tr>";
while ($row = $results->fetchArray()) { # adding rows and whatnot
echo "<tr id=\"entry$row[0]\">";
echo "<td>$row[1]</td>";
echo "<td><time class=\"date\" datetime=\"".DateTime::createFromFormat("U", $row[2])->format("Y-m-d H:i:s")."\"></time></td>";
echo "<td><a href='psychologistMode.php?action=viewResult&id=".$row[0]."'>".$row[3]."</a></td>";
echo "<td><button onClick=\"delEntry($row[0])\" style=\"padding: 0;\"><img alt=\"Удалить\" src=\"/icons/trash.svg\" height=\"32px\"/></button></td>";
echo "</tr>";
} echo "</table></td></tr>";
echo "<tr><td>"; # footer buttons or something idk
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php?action=testManagement\">Управление тестами</a>";
echo "</td><td>";
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php?action=about\">О программе</a>";
echo "</td></tr>\n</table>";
}
function changePasswordForm($db){
$setupMode = isset($_GET["setup_key"]);
if ($setupMode){
$setupKey = $_GET["setup_key"];
$setupMode = ($db->querySingle("SELECT \"Value\" FROM Settings WHERE \"Key\" = 'setup_key'") == $setupKey);
}
echo "<a class=\"button\" href=\"/\" style=\"position: fixed\"><img alt=\"На главную\" src=\"/icons/home.svg\" height=\"32px\"/></a>";
echo "<a class=\"button\" id=\"exitButton\" href=\"/serverScripts/exit.php\"><img alt=\"Выход\" src=\"/icons/exit.svg\" height=\"32px\"/></a>";
echo "<form id=\"changePassword\">";
echo "<table class=\"centerADiv\">";
echo ($setupMode)
? "<tr><td colspan=\"2\"><h1>Satori - Первоначальная настройка</h1></td>"
."<tr><td colspan=\"2\"><h3>Установка пароля</h3></td></tr>"
: "<tr><td colspan=\"2\"><h1>Режим психолога</h1></td>"
."<tr><td colspan=\"2\"><h3>Смена пароля</h3></td></tr>";
echo "<tr><td colspan=\"2\" class='error' id='error'></td></tr>";
echo ($setupMode)
? "<tr><td colspan=\"2\"><input type='hidden' id='setupKey' name='setupKey' value='".$setupKey."'/></td></tr>"
: "<tr><td><label for='oldPassword'>Старый пароль</label></td><td><input class='textbox' type='password' id='oldPassword' name='password'/></td></tr>";
echo "<tr><td><label for='newPassword'>Новый пароль</label></td><td><input class='textbox' type='password' id='newPassword' name='password'/></td></tr>";
echo "<tr><td><label for='passwordConfirmation'>Подтверждение пароля</label></td><td><input class='textbox' type='password' id='passwordConfirmation' name='password'/></td></tr>";
echo "<tr><td colspan=2><input class='button' type='submit' value='Подтвердить' id='bConfirm'/></td></tr>";
echo "</table></form>";
}
function resultView($db){
$readableName = $db->querySingle("select t.ReadableName from Tests t inner join TestResults tr on t.ID = tr.TestID where tr.ID = ".intval($_GET["id"]).";");
$resultPresenter = $db->querySingle("select t.ResultPresenter from Tests t inner join TestResults tr on t.ID = tr.TestID where tr.ID = ".intval($_GET["id"]).";");
echo "<a class=\"button\" href=\"/psychologistMode.php\" style=\"position: fixed\">Назад</a>";
echo "<div class=\"centerADiv\">";
echo "<h1>Satori - Режим психолога</h1>";
echo "<h3>$readableName - просмотр результатов</h3>\n";
echo "<p>Студент: ".$db->querySingle("select (\"LastName\" || ' ' || \"FirstName\" || ', гр. ' || \"Group\") as \"FullName\" from \"TestResults\" where \"ID\" = ".intval($_GET["id"]).";")."</p>"; # from integer to string and back - so no SQL injection will occur
echo $resultPresenter;
echo "</div>";
}
function passwordEntryForm($pw_checked){
echo "<a class=\"button\" href=\"/\" style=\"position: fixed\"><img alt=\"На главную\" src=\"/icons/home.svg\" height=\"32px\"/></a>";
echo "<form class=\"centerADiv\" action='/psychologistMode.php' method='post'>";
echo "<table>";
echo "<tr><td colspan=\"2\"><h1>";
echo "Введите пароль";
echo "</h1></td></tr>";
if ($pw_checked) echo "<tr><td colspan=\"2\" class='error'>Неверный пароль.</td></tr>";
echo "<tr><td><label for='password'>Пароль</label></td><td><input class='textbox' type='password' id='password' name='password'/></td></tr>";
echo "<tr><td colspan=\"2\"><input class='button' type='submit' value='Войти'/></td></tr>";
echo "</table>";
echo "</form>";
}
function testManagement($db, $testingEnabled){
echo "<a class=\"button\" href=\"/\" style=\"position: fixed\"><img alt=\"На главную\" src=\"/icons/home.svg\" height=\"32px\"/></a>";
echo "<a class=\"button\" id=\"exitButton\" href=\"/serverScripts/exit.php\"><img alt=\"Выход\" src=\"/icons/exit.svg\" height=\"32px\"/></a>";
echo "<table class=\"centerADiv\">";
echo "<tr><td colspan=\"2\"><h1>Режим психолога</h1></td>";
echo "<tr><td><a class='button' style='width: 95%; text-align: center;' href='/psychologistMode.php?action=changePassword'>Сменить пароль</a></td><td><button id='testingToggleButton'>";
echo "Тестирование:<span style='text-shadow: none; font-weight: bold; color: ".(($testingEnabled) ? "green;'>Вкл." : "red;'>Выкл."); # ternary statements
echo "</span></button><tr><td colspan=\"2\"><h3>Управление тестами</h3></td></tr>";
$results = $db->query("SELECT t.\"ID\", t.\"ReadableName\", count(tq.TestID), t.TestEnabled FROM \"TestQuestions\" tq INNER JOIN \"Tests\" t ON tq.\"TestID\" = t.\"ID\" GROUP BY t.\"ID\";");
# setting up t h e t a b l e
echo "<tr><td colspan=\"2\"><table class='sortable'>";
echo "<tr>";
echo "<th>Тест</th>";
echo "<th>Количество вопросов</th>";
echo "<th></th>";
echo "<th></th>";
echo "</tr>";
while ($row = $results->fetchArray()) { # adding rows and whatnot
echo "<tr id=\"test$row[0]\">";
echo "<td style='text-align: center'>$row[1]</td>";
echo "<td style='text-align: center'>$row[2]</td>";
echo "<td><button onClick=\"toggleTest($row[0])\" id=\"test$row[0]ToggleButton\" style=\"height: 100%;\"><span style='text-shadow: none; font-weight: bold; color: ".(($row[3] == 1) ? "green;'>Вкл." : "red;'>Выкл.")."</button></td>";
echo "<td><button onClick=\"delEntry($row[0])\" style=\"padding: 0;\"><img alt=\"Удалить\" src=\"/icons/trash.svg\" alt=\"Удалить\" height=\"32px\"/></button></td>";
echo "</tr>";
}
echo "<tr><td colspan=\"4\"><input type=\"file\" accept=\"text\" onchange=\"addTest(event)\" id=\"testFile\" hidden/><button onclick=\"$('#testFile').click();\">Добавить тест</button></td></tr>";
echo "</table></td></tr>";
echo "<tr><td>"; # footer buttons or something idk
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php\">Просмотр результатов</a>";
echo "</td><td>";
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php?action=about\">О программе</a>";
echo "</td></tr>\n</table>";
}
function aboutPage(){
echo "<a class=\"button\" href=\"/\" style=\"position: fixed\"><img alt=\"На главную\" src=\"/icons/home.svg\" height=\"32px\"/></a>";
echo "<a class=\"button\" id=\"exitButton\" href=\"/serverScripts/exit.php\"><img alt=\"Выход\" src=\"/icons/exit.svg\" height=\"32px\"/></a>";
echo "<table class=\"centerADiv\">";
echo "<tr><td colspan=\"2\"><h1>Режим психолога</h1></td>";
echo "</span></button><tr><td colspan=\"2\"><h3>О программе</h3></td></tr>";
echo "<tr><td>";
echo "<img alt=\"古明地 さとり\" src=\"/2hu_reference.png\"/ style=\"margin: 0px\">";
echo "</td><td>";
echo "<p style=\"text-align: center\">Автоматизированное рабочее место педагога-психолога образовательного учреждения <b style=\"margin: 0px;font-size: x-large;\">«Satori»</b> v0.01</p>";
echo "<p>ПО для автоматизации психодиагностики.</p>";
echo "<p>Распространяется по <a href=\"/LICENSE\" style=\"margin: 0px\">лицензии MIT.</a></p>";
echo "<p>© GhostNoise, 2024</p>";
echo "</td></tr>";
echo "<tr><td>"; # footer buttons or something idk
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php\">Просмотр результатов</a>";
echo "</td><td>";
echo "<a class=\"button\" style='width: 95%; text-align: center;' href=\"/psychologistMode.php?action=testManagement\">Управление тестами</a>";
echo "</td></tr><tr><td colspan=\"2\">";
echo "<a class=\"button\" style='width: 98%; text-align: center;' href=\"https://software.ghostnoise.ru\">На сайт разработчика</a>";
echo "</td></tr>\n</table>";
}
$resultsScript = '
<script src="/clientScripts/sorttable.js"></script>
<script>
$(function(){
$(".date").each(function(){
$(this).text(new Date($(this).attr("datetime")).toLocaleDateString(window.navigator.language, {
year: "numeric",
month: "numeric",
day: "numeric",
}));
});
$("#testingToggleButton").click(function(e){
$.post("/serverScripts/toggleTesting.php", {}, function(text){
if (text !== "true" && text !== "false"){ alert("Ошибка! \n" + text); return; }
$("#testingToggleButton").html(
"Тестирование:<span style=\'text-shadow: none; font-weight: bold; color: " + ((text === "true") ? "green;\'>Вкл." : "red;\'>Выкл.")
);
});
});
});
function delEntry(id) {
if (confirm("Вы точно хотите удалить эту запись?"))
$.post("serverScripts/removeResultFromDB.php", {
id: id
}, function (text) {
if (text.length !== 0) alert("Ошибка: \n" + text);
else $("#entry" + id).remove();
}
);
}
</script>';
$testsScript = '
<script src="/clientScripts/sorttable.js"></script>
<script>
$(function(){
$("#testingToggleButton").click(function(e){
$.post("/serverScripts/toggleTesting.php", {}, function(text){
if (text !== "true" && text !== "false"){ alert("Ошибка! \n" + text); return; }
$("#testingToggleButton").html(
"Тестирование:<span style=\'text-shadow: none; font-weight: bold; color: " + ((text === "true") ? "green;\'>Вкл." : "red;\'>Выкл.")
);
});
});
});
function toggleTest(id) {
$.post("/serverScripts/toggleTest.php", { testID: id }, function(text){
if (text !== "true" && text !== "false"){ alert("Ошибка! \n" + text); return; }
$("#test" + id + "ToggleButton").html("<span style=\'text-shadow: none; font-weight: bold; color: "
+ ((text === "true")
? "green;\'>Вкл."
: "red;\'>Выкл."
));
});
}
function delEntry(id) {
if (confirm("Вы уверены, что хотите удалить этот тест?\nУдаление теста приведёт к удалению результатов.")
&& confirm("Вы ТОЧНО уверены, что хотите удалить этот тест СО ВСЕМИ СВЯЗАННЫМИ РЕЗУЛЬТАТАМИ?"))
$.post("serverScripts/removeTestFromDB.php", {
id: id
}, function (text) {
if (text.length !== 0) alert("Ошибка: \n" + text);
else $("#test" + id).remove();
}
);
}
function addTest(event){
fr = new FileReader();
fr.onload = function(){
test = JSON.parse(fr.result);
if (confirm("Вы хотите загрузить тест \\"" + test.readableName + "\\" с " + test.questions.length + " вопросами на сервер?"))
$.post("serverScripts/addTestToDB.php", {
guide: test.guide,
readableName: test.readableName,
questions: JSON.stringify(test.questions),
answerForm: test.answerForm,
pageScript: test.pageScript,
answerHandlingScript: test.answerHandlingScript,
resultCalculatingScript: test.resultCalculatingScript,
resultPresenter: test.resultPresenter,
}, function(text){
if (text !== "") alert ("Ошибка:\n" + text);
else alert ("Тест успешно загружен на сервер.");
});
}; fr.readAsText(event.target.files[0]);
}
</script>';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title><?php
echo ($session_valid) ? "Режим психолога" : "Введите пароль"; # ok ternary statements exist in this god forsaken language
?></title>
<script src="/clientScripts/jquery.js"></script>
<script src="/clientScripts/cookieManagement.js"></script>
<?php
if (isset($_GET["action"])) switch($_GET["action"]) {
case "changePassword": echo " <script src=\"/clientScripts/ajaxPasswordChanger.js\"></script>"; break;
case "viewResult":
if (!isset($_GET["id"])) defaultPsychologistMode($db, $testingEnabled);
else {
echo "<script>";
echo "\t\t\tfirstName = \"".$db->querySingle("select \"FirstName\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";")."\";\n";
echo "\t\t\tlastName = \"".$db->querySingle("select \"LastName\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";")."\";\n";
echo "\t\t\tgroup = \"".$db->querySingle("select \"Group\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";")."\";\n";
echo "\t\t\ttestName = \"".$db->querySingle("select \"TestName\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";")."\";\n";
echo "\t\t\ttestDate = new Date(\"".DateTime::createFromFormat("U", $db->querySingle("select \"TestDate\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";"))->format("Y-m-d H:i:s")."\");\n";
echo "\t\t\tanswers = JSON.parse(\"".$db->querySingle("select \"TestResult\" from \"TestResults\" where \"ID\" = ".$_GET["id"].";")."\");\n\n";
echo $db->querySingle("select t.ResultCalculatingScript from Tests t inner join TestResults tr on t.ID = tr.TestID where tr.ID = ".intval($_GET["id"]).";");
echo "\t\t</script>";
} break;
case "testManagement": echo $testsScript; break;
case "about": break;
case "results":
default: echo $resultsScript; break;
} else echo $resultsScript;
?>
<link rel="stylesheet" type="text/css" href="/styles/main.css"/>
</head>
<body>
<div class="bg"></div>
<?php # ok the fun part (torture) begins
if ($session_valid) {
if (!isset($_GET["action"])) defaultPsychologistMode($db, $testingEnabled);
else switch($_GET["action"]) {
case "changePassword": changePasswordForm($db); break;
case "viewResult": resultView($db); break;
case "testManagement": testManagement($db, $testingEnabled); break;
case "about": aboutPage(); break;
case "results":
default: defaultPsychologistMode($db, $testingEnabled); break;
}
} else passwordEntryForm($pw_checked);
?>
</body>
</html>
<?php if (isset($db)) $db->close(); ?>