From 149c43b8890e0aef09101ce7ec689cd38847bc5d Mon Sep 17 00:00:00 2001 From: William Date: Thu, 14 Apr 2022 20:59:42 +0000 Subject: [PATCH] Housekeeping --- app/inc.php | 24 ++++++++------ app/lib/App/Core/AccessControl.php | 14 ++++---- app/lib/App/Core/App.php | 6 ++-- app/lib/App/Core/ErrorHandler.php | 17 ++++------ app/lib/App/Core/Session.php | 7 ++-- app/lib/App/Core/User.php | 18 +++++----- app/lib/App/SSE/EventLoop.php | 27 ++++++++------- app/lib/App/Teamtable/Team.php | 18 +++++----- app/lib/App/Teamtable/TeamMapper.php | 6 ++-- app/lib/App/Timetable/Time.php | 6 ++-- app/lib/App/Timetable/TimeMapper.php | 6 ++-- app/model/BatonReader.php | 33 +++++++++---------- app/view/pages/race/configure/teams/index.php | 2 +- app/view/pages/race/live.php | 2 +- app/view/template/header.php | 6 ++-- public/{ => api/v1}/race/sync.php | 10 +++--- public/index.php | 3 +- public/login.php | 2 +- public/logout.php | 2 +- public/race/configure/reset.php | 14 ++++---- public/race/configure/teams/delete.php | 6 ++-- public/race/configure/teams/index.php | 4 +-- public/race/configure/teams/update.php | 8 ++--- public/race/simulator.php | 4 +-- 24 files changed, 120 insertions(+), 125 deletions(-) rename public/{ => api/v1}/race/sync.php (74%) diff --git a/app/inc.php b/app/inc.php index 84eda46..559e965 100644 --- a/app/inc.php +++ b/app/inc.php @@ -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); diff --git a/app/lib/App/Core/AccessControl.php b/app/lib/App/Core/AccessControl.php index b447aea..cb46d87 100644 --- a/app/lib/App/Core/AccessControl.php +++ b/app/lib/App/Core/AccessControl.php @@ -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!"]); diff --git a/app/lib/App/Core/App.php b/app/lib/App/Core/App.php index 87cc510..1b41c9e 100644 --- a/app/lib/App/Core/App.php +++ b/app/lib/App/Core/App.php @@ -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 { diff --git a/app/lib/App/Core/ErrorHandler.php b/app/lib/App/Core/ErrorHandler.php index a7c88cd..9bebc0f 100644 --- a/app/lib/App/Core/ErrorHandler.php +++ b/app/lib/App/Core/ErrorHandler.php @@ -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[] = "Error[$errno]: $errstr in $errfile at line $errline"; + $this->error_messages[] = "Error[$errno]: $errstr in $errfile at line $errline"; } public function exception($exception): void { - $this->errors[] = "Uncaught Exception: " . $exception; + $this->error_messages[] = "Uncaught Exception: " . $exception; } public function __destruct() { - if (!$this->errors) { + if (!$this->error_messages) { return; } @@ -64,8 +61,8 @@ class ErrorHandler echo '

Error!!1 (✖﹏✖)

'; echo '

Oisann! Dette var ikke ment å skje. Dersom det vedvarer, vennligst kontakt nettadministratoren.

'; - foreach ($this->errors as $error) { - echo "
$error
"; + foreach ($this->error_messages as $error_message) { + echo "
$error_message
"; } } } \ No newline at end of file diff --git a/app/lib/App/Core/Session.php b/app/lib/App/Core/Session.php index 85e34df..c4fe698 100644 --- a/app/lib/App/Core/Session.php +++ b/app/lib/App/Core/Session.php @@ -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; } diff --git a/app/lib/App/Core/User.php b/app/lib/App/Core/User.php index f4add72..25d0ef6 100644 --- a/app/lib/App/Core/User.php +++ b/app/lib/App/Core/User.php @@ -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!"); } diff --git a/app/lib/App/SSE/EventLoop.php b/app/lib/App/SSE/EventLoop.php index 84f3b58..ebe15be 100644 --- a/app/lib/App/SSE/EventLoop.php +++ b/app/lib/App/SSE/EventLoop.php @@ -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"; diff --git a/app/lib/App/Teamtable/Team.php b/app/lib/App/Teamtable/Team.php index 077bd8c..b63362a 100644 --- a/app/lib/App/Teamtable/Team.php +++ b/app/lib/App/Teamtable/Team.php @@ -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 diff --git a/app/lib/App/Teamtable/TeamMapper.php b/app/lib/App/Teamtable/TeamMapper.php index 621bca6..5b9cc43 100644 --- a/app/lib/App/Teamtable/TeamMapper.php +++ b/app/lib/App/Teamtable/TeamMapper.php @@ -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); diff --git a/app/lib/App/Timetable/Time.php b/app/lib/App/Timetable/Time.php index 51c7a2d..0e8dd58 100644 --- a/app/lib/App/Timetable/Time.php +++ b/app/lib/App/Timetable/Time.php @@ -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; } diff --git a/app/lib/App/Timetable/TimeMapper.php b/app/lib/App/Timetable/TimeMapper.php index 2c7624e..fe1923d 100644 --- a/app/lib/App/Timetable/TimeMapper.php +++ b/app/lib/App/Timetable/TimeMapper.php @@ -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); } diff --git a/app/model/BatonReader.php b/app/model/BatonReader.php index 1e440cf..b0b48b8 100644 --- a/app/model/BatonReader.php +++ b/app/model/BatonReader.php @@ -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; diff --git a/app/view/pages/race/configure/teams/index.php b/app/view/pages/race/configure/teams/index.php index 93438af..9dd5c18 100644 --- a/app/view/pages/race/configure/teams/index.php +++ b/app/view/pages/race/configure/teams/index.php @@ -28,7 +28,7 @@ echo "" . htmlspecialchars($team->phone) . ""; echo "" . htmlspecialchars($team->participants) . ""; echo "" . htmlspecialchars($team->rounds) . ""; - echo "" . htmlspecialchars(($team->bestTime === NULL) ? "Ukjent" : $team->bestTime) . ""; + echo "" . htmlspecialchars(($team->best_time === NULL) ? "Ukjent" : $team->best_time) . ""; echo ""; echo "Slett ] "; echo "Endre ]"; diff --git a/app/view/pages/race/live.php b/app/view/pages/race/live.php index 0b8753a..669db9a 100644 --- a/app/view/pages/race/live.php +++ b/app/view/pages/race/live.php @@ -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) { diff --git a/app/view/template/header.php b/app/view/template/header.php index 21b6c79..f1b61e4 100644 --- a/app/view/template/header.php +++ b/app/view/template/header.php @@ -19,7 +19,7 @@