SpreadQuiz/testmgr.php
2024-03-05 16:07:47 +01:00

93 lines
2.8 KiB
PHP

<?php
require_once "globals.php";
require_once "common_func.php";
require_once "gamemgr.php";
require_once "usermgr.php";
$testdb = new \SleekDB\Store(TESTDB, DATADIR, ["timeout" => false]);
const TEST_ONGOING = "ongoing";
const TEST_CONCLUDED = "concluded";
function create_or_continue_test(string $gameid, string $nickname): string
{
global $testdb;
// get game and user data
$game_data = get_game($gameid);
$user_data = get_user($nickname);
if ((count($game_data) === 0) || (count($user_data) === 0)) {
return "";
}
// check if this user has permission to take this test
// if the intersection of user's groups and game's assigned groups is zero, then the user has no access to this game
if (count(array_intersect($game_data["groups"], $user_data["groups"])) === 0) {
return "";
}
// check if the user had taken this test before
$fetch_criteria = [["gameid", "=", $gameid], "AND", ["nickname", "=", $nickname]];
$previous_tests = $testdb->findBy($fetch_criteria);
if (count($previous_tests) > 0) { // if there are previous attempts, then...
// update timed tests to see if they had expired
update_timed_tests($previous_tests);
// re-fetch tests, look only for ongoing
$ongoing_tests = $testdb->findBy([$fetch_criteria, "AND", ["state", "=", TEST_ONGOING]]);
if (count($ongoing_tests) !== 0) { // if there's an ongoing test
return $ongoing_tests[0]["_id"];
} else { // there's no ongoing test
if ($game_data["properties"]["repeatable"]) { // test is repeatable...
return create_test($game_data, $user_data);
} else { // test is non-repeatable, cannot be attempted more times
return "";
}
}
} else { // there were no previous attempts
return create_test($game_data, $user_data);
}
}
function create_test(array $game_data, array $user_data) : string
{
$gameid = $game_data["_id"];
// fill basic data
$game_data = [
"gameid" => $gameid,
"nickname" => $user_data["nickname"],
];
// fill challenges
$challenges = load_challenges($gameid);
// shuffle answers
foreach ($challenges as &$ch) {
shuffle($ch["answers"]);
}
$game_data["challenges"] = $challenges;
// involve properties
}
function update_timed_tests(array $test_data_array)
{
$now = time();
foreach ($test_data_array as $test_data) {
// look for unprocessed expired tests
if (($test_data["state"] === TEST_ONGOING) && ($test_data["end_limit_time"] < $now)) {
$test_data["state"] = TEST_CONCLUDED;
update_test($test_data);
}
}
}
function update_test(array $test_data)
{
global $testdb;
$testdb->update($test_data);
}