add autoloaded "Modules" directory

This commit is contained in:
Thomas Rubini 2023-01-22 22:26:20 +01:00
parent d716f15fe7
commit 5ee8c4c753
No known key found for this signature in database
GPG Key ID: C7D287C8C1CAC373
4 changed files with 35 additions and 84 deletions

View File

@ -14,6 +14,8 @@ final class Constants
const CONTROLLERS_DIR = '/Controllers/';
const MODULES_DIR = '/Modules/';
public static function rootDir() {
return realpath(__DIR__ . '/../');
@ -39,4 +41,8 @@ final class Constants
return self::rootDir() . self::CONTROLLERS_DIR;
}
public static function modulesDir() {
return self::rootDir() . self::MODULES_DIR;
}
}

View File

@ -1,84 +0,0 @@
<?php
final class Session
{
public static function start_session()
{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
public static function resume_session()
{
if(self::has_session_cookie()){
self::start_session();
return true;
}
return false;
}
public static function destroy_session()
{
self::start_session();
session_destroy();
}
/*
Reason: start_session() automatically sets a cookie,
we want a way to know if the user have a session without setting a cookie
(e.g to not set a cookie on every page to set the header, which change if you are logged-in)
*/
public static function has_session_cookie()
{
return isset($_COOKIE[session_name()]);
}
public static function is_login()
{
if (!self::resume_session()) {
return false;
}
if (!isset($_SESSION)) {
return false;
}
if (!isset($_SESSION["ID"])) {
return False;
}
// ensure account has not been deleted/disabled in the meantime
$O_userModel = new UserModel();
$B_userActive = $O_userModel->isUserActive($_SESSION["ID"]);
return $B_userActive;
}
public static function set_login($I_id){
self::start_session();
$_SESSION["ID"] = $I_id;
}
public static function login_or_die()
{
if (!self::is_login()) {
header("Location: /user/login?return_uri=".$_SERVER["REQUEST_URI"]);
die();
}
}
public static function is_admin(){
if (!self::is_login()) return false;
$O_userModel = new UserModel();
return $O_userModel->isUserAdmin($_SESSION["ID"]);
}
public static function admin_or_die(){
Session::login_or_die();
if (!self::is_admin()) {
header("Location: /");
die();
}
}
}

28
Modules/AutoLoad.php Normal file
View File

@ -0,0 +1,28 @@
<?php
class ModulesAutoLoad
{
public static function loadModuleClass($S_className)
{
$dir = Constants::modulesDir();
foreach (scandir($dir) as $path) {
if($path === ".." || $path === ".") continue;
$subdir = "$dir/$path";
if (is_dir($subdir)) {
static::_load("$subdir/$S_className.php");
}
}
}
private static function _load($S_path)
{
if (is_readable($S_path))
{
require $S_path;
}
}
}
spl_autoload_register('ModulesAutoLoad::loadModuleClass');

View File

@ -3,6 +3,7 @@
require 'vendor/autoload.php';
require 'Kernel/AutoLoad.php';
require 'Modules/AutoLoad.php';
$dotenv = Dotenv\Dotenv::createImmutable(Constants::rootDir());
$dotenv->load();