Housekeeping

This commit is contained in:
William 2022-04-14 20:59:42 +00:00
parent 35f0270d00
commit 149c43b889
24 changed files with 120 additions and 125 deletions

View File

@ -12,10 +12,18 @@
* Tread carefully
*/
$php_version = '8';
if (version_compare(PHP_VERSION, $php_version, '<'))
{
echo 'This app requires a minimum of PHP ' . $php_version . ' current being: ' . PHP_VERSION . "\n";
die();
}
unset($php_version);
// PSR-4 like autoloader
spl_autoload_register(
function ($className) {
$path = __DIR__ . '/lib/' . str_replace('\\', '/', $className) . '.php';
function ($class_name) {
$path = __DIR__ . '/lib/' . str_replace('\\', '/', $class_name) . '.php';
require $path;
}
);
@ -32,15 +40,11 @@ use App\Core\ {
new ErrorHandler();
$config = (new Config(__DIR__ . '/config.php'))->config;
$config = (new Config(__DIR__ . '/config.php'))->config;
$database = new Database($config['database']);
$session = new Session();
$user = new User($session, $database);
$app = new App(__DIR__, $config, $database, $session, $user);
$session = new Session();
$user = new User($session, $database);
$app = new App(__DIR__, $config, $database, $session, $user);
// we will use $app instead
unset($config, $database, $session, $user);

View File

@ -13,7 +13,7 @@ class AccessControl
public App $app;
private array $acl;
private string $currentPage;
private string $current_page;
public function __construct(App $app)
{
@ -34,7 +34,7 @@ class AccessControl
// routes that dont need any auth
[
"routes" => [
"*"
"*" // this is dumb but security is not that important :D
],
"catcher" => [
"name" => "nothing",
@ -42,7 +42,7 @@ class AccessControl
]
];
$this->currentPage = substr(
$this->current_page = substr(
$_SERVER["SCRIPT_NAME"],
strlen($this->app->config["root_url"])
);
@ -61,13 +61,13 @@ class AccessControl
// remove asterisk
$value = substr($value, 0, -1);
// check if string starts with
if (strncmp($this->currentPage, $value, strlen($value)) !== 0)
if (strncmp($this->current_page, $value, strlen($value)) !== 0)
{
continue;
}
} else {
// end is not an asterisk, match full string
if ($value !== $this->currentPage)
if ($value !== $this->current_page)
{
continue;
}
@ -87,9 +87,9 @@ class AccessControl
throw new Exception("Could not find current page in access control list, did you add it?");
}
private function page(int $powerLevel): void
private function page(int $power_level): void
{
if (!$this->app->user->loggedIn || !($this->app->user->powerLevel >= $powerLevel))
if (!$this->app->user->logged_in || !($this->app->user->power_level >= $power_level))
{
http_response_code(401);
$this->app->view("template/header", ["title" => "Ingen tilgang!"]);

View File

@ -36,7 +36,7 @@ class App
* TODO: have a look to see if this might name conflict with anything and
* maybe also throw an exception if the model class is not found within the file
*/
public function model(string $model, $injection = NULL): object
public function model(string $model, mixed $injection = NULL): object
{
// require model file
$path = $this->dir . '/model/' . $model . '.php';
@ -70,7 +70,7 @@ class App
}
/**
* Convert data into json response
* Convert data into JSON response
*/
public function api(mixed $data, int $status_code = 200): void
{
@ -83,7 +83,7 @@ class App
}
/**
* Redirect to given url
* Redirect to given URL
*/
public function redirect(string $url): void
{

View File

@ -8,10 +8,7 @@ namespace App\Core;
*/
class ErrorHandler
{
/**
* Holds error messages
*/
public array $errors;
public array $error_messages;
public function __construct()
{
@ -20,23 +17,23 @@ class ErrorHandler
set_error_handler([$this, 'error']);
set_exception_handler([$this, 'exception']);
$this->errors = [];
$this->error_messages = [];
}
public function error($errno, $errstr, $errfile, $errline): void
{
$errstr = htmlspecialchars($errstr);
$this->errors[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
$this->error_messages[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
}
public function exception($exception): void
{
$this->errors[] = "<b>Uncaught Exception:</b> " . $exception;
$this->error_messages[] = "<b>Uncaught Exception:</b> " . $exception;
}
public function __destruct()
{
if (!$this->errors) {
if (!$this->error_messages) {
return;
}
@ -64,8 +61,8 @@ class ErrorHandler
echo '<h1>Error!!1 (✖﹏✖)</h1>';
echo '<p>Oisann! Dette var ikke ment å skje. Dersom det vedvarer, vennligst kontakt nettadministratoren.</p>';
foreach ($this->errors as $error) {
echo "<div id=\"error\">$error</div>";
foreach ($this->error_messages as $error_message) {
echo "<div id=\"error\">$error_message</div>";
}
}
}

View File

@ -24,10 +24,7 @@ class Session
return array_key_exists($key, $_SESSION);
}
/**
* Returns mixed but php 7.4 DOES NOT SUPPORT THAT TYPE HINT >:((
*/
public function get(string $key)
public function get(string $key): mixed
{
if ($this->has($key))
{
@ -36,7 +33,7 @@ class Session
return NULL;
}
public function set(string $key, $value): void
public function set(string $key, mixed $value): void
{
$_SESSION[$key] = $value;
}

View File

@ -15,12 +15,12 @@ class User
private Database $database;
// always initialized
public bool $loggedIn;
public bool $logged_in;
// initialized only if logged in
public string $username;
public string $password;
public int $powerLevel;
public int $power_level;
public function __construct(Session $session, Database $database)
{
@ -32,24 +32,24 @@ class User
// check if user session has been set
if (!$user)
{
$this->loggedIn = FALSE;
$this->logged_in = FALSE;
return;
}
// check if username and password match
if (!$this->authenticate($user['username'], $user['password']))
{
$this->loggedIn = FALSE;
$this->logged_in = FALSE;
$this->logout();
$this->session->flash('Kontodetaljer er blitt endret, vennligst logg inn igjen', 'warning');
return;
}
// all is good, we should be logged in now! (hopefully)
$this->loggedIn = TRUE;
$this->username = $user['username'];
$this->password = $user['password'];
$this->powerLevel = $this->getPowerLevel();
$this->logged_in = TRUE;
$this->username = $user['username'];
$this->password = $user['password'];
$this->power_level = $this->getPowerLevel();
}
/**
@ -57,7 +57,7 @@ class User
*/
private function getPowerLevel(): int
{
if (!$this->loggedIn)
if (!$this->logged_in)
{
throw new Exception("Can't get power level without being logged in!");
}

View File

@ -9,11 +9,10 @@ namespace App\SSE;
*/
class EventLoop
{
public int $interval = 3;
public int $heartbeat = 5; // send heartbeat every num seconds to ensure connection is still alive
public int $timeLimit = 3600;
public int $execLimit = 30;
public int $interval = 3;
public int $heartbeat = 5; // send heartbeat every num seconds to ensure connection is still alive
public int $time_limit = 3600;
public int $exec_limit = 30;
public function start(callable $callback): void
{
@ -34,19 +33,19 @@ class EventLoop
ob_end_flush();
flush();
$expirationTime = time() + $this->timeLimit;
$expiration_time = time() + $this->time_limit;
$lastHeartbeat = time();
$last_heartbeat = time();
while (!connection_aborted() && time() < $expirationTime)
while (!connection_aborted() && time() < $expiration_time)
{
set_time_limit($this->execLimit);
set_time_limit($this->exec_limit);
try {
$data = call_user_func($callback);
if ($data !== NULL)
{
$this->send($data);
$lastHeartbeat = time();
$last_heartbeat = time();
}
} catch (StopEventLoopException $th) {
break;
@ -55,12 +54,12 @@ class EventLoop
// sleep and perform heartbeat to ensure connection is still alive
for ($i = 0; $i < $this->interval; $i++)
{
if (time() >= $lastHeartbeat + $this->heartbeat)
if (time() >= $last_heartbeat + $this->heartbeat)
{
echo ": \n\n";
ob_end_flush();
flush();
$lastHeartbeat = time();
$last_heartbeat = time();
}
sleep(1);
}
@ -68,9 +67,9 @@ class EventLoop
}
/**
* Send data to client encoded as json
* Send data to client encoded as JSON
*/
private function send($data): void
private function send(mixed $data): void
{
echo "data: " . json_encode($data);
echo "\n\n";

View File

@ -9,15 +9,15 @@ use \InvalidArgumentException;
*/
class Team
{
public int $id;
public string $name = 'NN';
public string $company = 'NN';
public string $cardnumber = 'NN';
public string $leader = 'NN';
public string $phone = 'NN';
public int $participants = 0;
public int $rounds = 0;
public ?int $bestTime = NULL;
public int $id;
public string $name = 'NN';
public string $company = 'NN';
public string $cardnumber = 'NN';
public string $leader = 'NN';
public string $phone = 'NN';
public int $participants = 0;
public int $rounds = 0;
public ?int $best_time = NULL;
/**
* PHP by default does not include multi byte functions. Therefore we use this

View File

@ -29,7 +29,7 @@ class TeamMapper
$team->setPhone($row['Telefon']);
$team->setParticipants($row['Deltagere']);
$team->setRounds($row['Runder']);
$team->bestTime = $row['Bestetid'];
$team->best_time = $row['Bestetid'];
return $team;
}
@ -95,7 +95,7 @@ class TeamMapper
$team->phone,
$team->participants,
$team->rounds,
$team->bestTime
$team->best_time
]);
$lastId = $this->dbh->lastInsertId();
return $this->get($lastId);
@ -119,7 +119,7 @@ class TeamMapper
$team->phone,
$team->participants,
$team->rounds,
$team->bestTime,
$team->best_time,
$team->id
]);
return $this->get($team->id);

View File

@ -10,12 +10,12 @@ use \DateTime;
class Time
{
public int $id;
public int $teamId;
public int $team_id;
public DateTime $date;
public function setTeamId(int $teamId): Self
public function setTeamId(int $team_id): Self
{
$this->teamId = $teamId;
$this->team_id = $team_id;
return $this;
}

View File

@ -48,10 +48,10 @@ class TimeMapper
return NULL;
}
public function getLatestByTeamId(int $teamId): ?Time
public function getLatestByTeamId(int $team_id): ?Time
{
$sth = $this->dbh->prepare('SELECT * FROM tidtabell WHERE LagID = ? ORDER BY Tidspunkt DESC LIMIT 1');
$sth->execute([$teamId]);
$sth->execute([$team_id]);
$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row)
{
@ -75,7 +75,7 @@ class TimeMapper
public function create(Time $time): Time
{
$sth = $this->dbh->prepare('INSERT INTO tidtabell (LagID) VALUES (?)');
$sth->execute([$time->teamId]);
$sth->execute([$time->team_id]);
$lastId = $this->dbh->lastInsertId();
return $this->get($lastId);
}

View File

@ -10,15 +10,14 @@ class BatonReader
{
public PDO $dbh;
public TeamMapper $teamMapper;
public TimeMapper $timeMapper;
public TeamMapper $team_mapper;
public TimeMapper $time_mapper;
public function __construct(Database $database)
{
$this->dbh = $database->conn;
$this->teamMapper = new TeamMapper($this->dbh);
$this->timeMapper = new TimeMapper($this->dbh);
$this->team_mapper = new TeamMapper($this->dbh);
$this->time_mapper = new TimeMapper($this->dbh);
}
/**
@ -31,22 +30,22 @@ class BatonReader
*/
public function receive(string $cardnumber, int $timeout): int
{
$team = $this->teamMapper->getByCardnumber($cardnumber);
$team = $this->team_mapper->getByCardnumber($cardnumber);
if (!$team)
{
// team does not exist, lets create it
$team = new Team;
$team->setCardnumber($cardnumber);
$this->teamMapper->create($team);
$this->team_mapper->create($team);
return 0;
}
// team exists, insert into time table
// and update team best time
$prev_time = $this->timeMapper->getLatestByTeamId($team->id);
$prev_time = $this->time_mapper->getLatestByTeamId($team->id);
$new_time = new Time;
$new_time->setTeamId($team->id);
$new_time = $this->timeMapper->create($new_time);
$new_time = $this->time_mapper->create($new_time);
if ($prev_time === NULL)
{
@ -57,23 +56,23 @@ class BatonReader
$diff = $new_time->date->getTimestamp() - $prev_time->date->getTimestamp();
if ($diff <= $timeout)
{
$this->timeMapper->delete($new_time->id); // i mean... it works?
$this->time_mapper->delete($new_time->id); // i mean... it works?
return 2;
}
$team->rounds += 1;
$this->teamMapper->update($team);
$this->team_mapper->update($team);
if ($team->bestTime === NULL)
if ($team->best_time === NULL)
{
$team->bestTime = $diff;
$this->teamMapper->update($team);
$team->best_time = $diff;
$this->team_mapper->update($team);
}
if ($diff < $team->bestTime)
if ($diff < $team->best_time)
{
$team->bestTime = $diff;
$this->teamMapper->update($team);
$team->best_time = $diff;
$this->team_mapper->update($team);
return 4;
}
return 3;

View File

@ -28,7 +28,7 @@
echo "<td>" . htmlspecialchars($team->phone) . "</td>";
echo "<td>" . htmlspecialchars($team->participants) . "</td>";
echo "<td>" . htmlspecialchars($team->rounds) . "</td>";
echo "<td>" . htmlspecialchars(($team->bestTime === NULL) ? "Ukjent" : $team->bestTime) . "</td>";
echo "<td>" . htmlspecialchars(($team->best_time === NULL) ? "Ukjent" : $team->best_time) . "</td>";
echo "<td>";
echo "<span>[&nbsp;<a class='danger' href='delete.php?item={$team->id}'>Slett</a>&nbsp;]&nbsp;</span>";
echo "<span>[&nbsp;<a class='info' href='update.php?item={$team->id}'>Endre</a>&nbsp;]</span>";

View File

@ -31,7 +31,7 @@ async function loop()
async function updateTable()
{
let response = await fetch("sync.php?h=" + hash);
let response = await fetch("../api/v1/race/sync.php?h=" + hash);
if (response.status === 204)
{

View File

@ -19,7 +19,7 @@
<div id="menu">
<small>
<?php if ($this->user->loggedIn): ?>
<?php if ($this->user->logged_in): ?>
<span><?=htmlspecialchars($this->user->username)?></span>
<a href="<?=$this->config['root_url']?>logout.php">Logg ut</a>
<?php else: ?>
@ -41,8 +41,8 @@
<li><a href="<?=$this->config['root_url']?>race/live.php">Resultater</a></li>
</ul>
<?php if ($this->user->loggedIn): ?>
<?php if ($this->user->powerLevel > 0): ?>
<?php if ($this->user->logged_in): ?>
<?php if ($this->user->power_level > 0): ?>
<h4>Tillatelser</h4>
<ul>
<li><a href="<?=$this->config['root_url']?>race/simulator.php">Simulator</a></li>

View File

@ -1,4 +1,4 @@
<?php $app = require '../../app/inc.php';
<?php $app = require '../../../../app/inc.php';
/**
* We originally wanted to use SSE for this, but the hosting provider
* did not support that so we resorted to simple polling instead
@ -10,17 +10,17 @@
use App\Teamtable\TeamMapper;
use App\Timetable\TimeMapper;
$teamMapper = new TeamMapper($app->database->conn);
$timeMapper = new TimeMapper($app->database->conn);
$team_mapper = new TeamMapper($app->database->conn);
$time_mapper = new TimeMapper($app->database->conn);
$prev_hash = (int)filter_input(INPUT_GET, 'h');
$data = [];
$times = $timeMapper->getAll();
$times = $time_mapper->getAll();
foreach ($times as $time)
{
$team = $teamMapper->get($time->teamId);
$team = $team_mapper->get($time->team_id);
if (!$team)
{

View File

@ -1,5 +1,4 @@
<?php
$app = require '../app/inc.php';
<?php $app = require '../app/inc.php';
$app->view('template/header', ["title" => "Forside"]);
$app->view('pages/index');

View File

@ -1,6 +1,6 @@
<?php $app = require '../app/inc.php';
if ($app->user->loggedIn)
if ($app->user->logged_in)
{
$app->redirect('index.php');
}

View File

@ -1,7 +1,7 @@
<?php
$app = require '../app/inc.php';
if (!$app->user->loggedIn)
if (!$app->user->logged_in)
{
$app->redirect('login.php');
}

View File

@ -18,25 +18,25 @@ if (!$confirm)
die();
}
$teamMapper = new TeamMapper($app->database->conn);
$timeMapper = new TimeMapper($app->database->conn);
$team_mapper = new TeamMapper($app->database->conn);
$time_mapper = new TimeMapper($app->database->conn);
// reset counters for all teams
$teams = $teamMapper->getAll();
$teams = $team_mapper->getAll();
foreach ($teams as $key => $team)
{
$team->setRounds(0);
$team->bestTime = NULL;
$teamMapper->update($team);
$team->best_time = NULL;
$team_mapper->update($team);
}
// delete all time records
$times = $timeMapper->getAll();
$times = $time_mapper->getAll();
foreach ($times as $key => $time)
{
$timeMapper->delete($time->id);
$time_mapper->delete($time->id);
}
$app->session->flash("Runder er nullstilt", "success");

View File

@ -6,7 +6,7 @@ use App\Teamtable\TeamMapper;
$item = filter_input(INPUT_GET, 'item', FILTER_VALIDATE_INT);
$confirm = filter_input(INPUT_GET, 'confirm', FILTER_VALIDATE_BOOLEAN);
$teamMapper = new TeamMapper($app->database->conn);
$team_mapper = new TeamMapper($app->database->conn);
// item is NULL if not set
if ($item === NULL)
@ -15,7 +15,7 @@ if ($item === NULL)
$app->redirect('index.php');
}
$team = $teamMapper->get($item);
$team = $team_mapper->get($item);
if (!$team)
{
// team does not exist
@ -33,6 +33,6 @@ if (!$confirm)
}
// all is good, lets delete the team
$teamMapper->delete($team->id);
$team_mapper->delete($team->id);
$app->session->flash("Slettet lag: {$team->name}", "success");
$app->redirect('index.php');

View File

@ -2,9 +2,9 @@
use App\Teamtable\TeamMapper;
$teamMapper = new TeamMapper($app->database->conn);
$team_mapper = new TeamMapper($app->database->conn);
$teams = $teamMapper->getAll();
$teams = $team_mapper->getAll();
$app->view('template/header', ['title' => 'Endre lagtabell']);
$app->view('pages/race/configure/teams/index', ["teams" => $teams]);

View File

@ -8,12 +8,12 @@ use App\Teamtable\TeamMapper;
$item = filter_input(INPUT_GET, 'item', FILTER_VALIDATE_INT);
$teamMapper = new TeamMapper($app->database->conn);
$team_mapper = new TeamMapper($app->database->conn);
$team;
if ($item !== NULL)
{
$team = $teamMapper->get($item);
$team = $team_mapper->get($item);
if (!$team)
{
// team does not exist
@ -51,12 +51,12 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// team exists, lets update it
$team->id = $item;
$teamMapper->update($team);
$team_mapper->update($team);
$app->session->flash('Oppdaterte lag', 'success');
$app->redirect('index.php');
}
// no team was specified, lets create one
$teamMapper->create($team);
$team_mapper->create($team);
$app->session->flash('Opprettet nytt lag', 'success');
$app->redirect('index.php');
}

View File

@ -2,7 +2,7 @@
// uh oh.. stinky
$batonReader = $app->model('BatonReader');
$baton_reader = $app->model('BatonReader');
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
@ -11,7 +11,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST')
$cardnumber = (string)$_POST['cardnumber'];
try {
$code = $batonReader->receive($cardnumber, 0);
$code = $baton_reader->receive($cardnumber, 0);
switch ($code) {
case 0:
$app->session->flash('Opprettet nytt lag', 'success');