Compare commits

..

14 Commits

Author SHA1 Message Date
tracer b60d9481ab added 404 support 2022-10-23 18:04:03 +02:00
tracer 582698a8d0 initial commit 2022-10-23 14:49:41 +02:00
tracer 06c9b9443d initial commit 2022-10-23 14:27:54 +02:00
tracer 74381857f2 initial commit 2022-10-23 14:27:40 +02:00
tracer f652132911 shut down after rendering the page 2022-10-23 14:22:18 +02:00
tracer b4ab876463 added getters & setters 2022-10-23 12:46:00 +02:00
tracer 5447a7dbad added getters & setters 2022-10-23 12:44:55 +02:00
tracer a3b2bf27f1 added getters & setters 2022-10-23 12:43:50 +02:00
tracer 4a85f45e3a initial commit 2022-10-23 12:41:14 +02:00
tracer 9a485b5424 added orderBy to findAll() 2022-10-23 12:40:40 +02:00
tracer d19e7d5b25 fixed a typo 2022-10-23 12:36:24 +02:00
tracer cbbfe45c1b added a side note 2022-10-23 12:32:53 +02:00
tracer 9cacf9ced9 fixed some typos 2022-10-23 12:30:09 +02:00
tracer 8a7a4a2253 added copyright 2022-10-23 12:26:30 +02:00
12 changed files with 278 additions and 176 deletions

View File

@ -1,2 +1,3 @@
# addressbook As I was not allowed to use any framework, respectively no foreign code, most of the timme was spent, well creating some kind of framework myself. :-)
The address book itself was than done in a few hours.

View File

@ -1,4 +1,11 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Entity; namespace App\Entity;
@ -13,4 +20,44 @@ class AddressBookEntry
{ {
// empty body // empty body
} }
public function getUserid(): int
{
return $this->userid;
}
public function setUserid(int $userid): void
{
$this->userid = $userid;
}
public function getFirst(): string
{
return $this->first;
}
public function setFirst(string $first): void
{
$this->first = $first;
}
public function getLast(): string
{
return $this->last;
}
public function setLast(string $last): void
{
$this->last = $last;
}
public function getNick(): string
{
return $this->nick;
}
public function setNick(string $nick): void
{
$this->nick = $nick;
}
} }

View File

@ -1,4 +1,11 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Entity; namespace App\Entity;
@ -17,81 +24,51 @@ class Route
// empty body // empty body
} }
/**
* @return string
*/
public function getName(): string public function getName(): string
{ {
return $this->name; return $this->name;
} }
/**
* @param string $name
*/
public function setName(string $name): void public function setName(string $name): void
{ {
$this->name = $name; $this->name = $name;
} }
/**
* @return string
*/
public function getRoute(): string public function getRoute(): string
{ {
return $this->route; return $this->route;
} }
/**
* @param string $route
*/
public function setRoute(string $route): void public function setRoute(string $route): void
{ {
$this->route = $route; $this->route = $route;
} }
/**
* @return string
*/
public function getRegEx(): string public function getRegEx(): string
{ {
return $this->regEx; return $this->regEx;
} }
/**
* @param string $regEx
*/
public function setRegEx(string $regEx): void public function setRegEx(string $regEx): void
{ {
$this->regEx = $regEx; $this->regEx = $regEx;
} }
/**
* @return array
*/
public function getParameters(): array public function getParameters(): array
{ {
return $this->parameters; return $this->parameters;
} }
/**
* @param array $parameters
*/
public function setParameters(array $parameters): void public function setParameters(array $parameters): void
{ {
$this->parameters = $parameters; $this->parameters = $parameters;
} }
/**
* @return Closure
*/
public function getCallback(): Closure public function getCallback(): Closure
{ {
return $this->callback; return $this->callback;
} }
/**
* @param Closure $callback
*/
public function setCallback(Closure $callback): void public function setCallback(Closure $callback): void
{ {
$this->callback = $callback; $this->callback = $callback;

View File

@ -1,18 +1,99 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Entity; namespace App\Entity;
use App\Enums\UserAuth;
class User class User
{ {
public function __construct( public function __construct(
private string $nick, private string $nick = '',
private string $password, private string $password = '',
private string $first = '', private string $first = '',
private string $last = '', private string $last = '',
private int $id = 0, private int $id = 0,
private bool $isAdmin = false private bool $isAdmin = false,
private UserAuth $userAuth = UserAuth::AUTH_ANONYMOUS
) )
{ {
// empty body // empty body
} }
public function getNick(): string
{
return $this->nick;
}
public function setNick(string $nick): void
{
$this->nick = $nick;
}
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): void
{
$this->password = $password;
}
public function getFirst(): string
{
return $this->first;
}
public function setFirst(string $first): void
{
$this->first = $first;
}
public function getLast(): string
{
return $this->last;
}
public function setLast(string $last): void
{
$this->last = $last;
}
public function getId(): int
{
return $this->id;
}
public function setId(int $id): void
{
$this->id = $id;
}
public function isAdmin(): bool
{
return $this->isAdmin;
}
public function setIsAdmin(bool $isAdmin): void
{
$this->isAdmin = $isAdmin;
}
public function getAuth()
{
return UserAuth::AUTH_ANONYMOUS;
}
public function setAuth(UserAuth $userAuth)
{
$this->userAuth = $userAuth;
}
} }

17
src/Enums/UserAuth.php Normal file
View File

@ -0,0 +1,17 @@
<?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Enums;
enum UserAuth
{
case AUTH_ANONYMOUS;
case AUTH_USER;
case AUTH_ADMIN;
}

View File

@ -1,21 +1,25 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Repository; namespace App\Repository;
use App\Service\Config;
use App\Service\DatabaseConnection; use App\Service\DatabaseConnection;
use App\Entity\User; use App\Entity\User;
use PDO; use PDO;
use PDOException; use PDOException;
/** /**
* * Handles CRUD od User class.
*/ */
class DomainRepository class UserRepository
{ {
public function __construct( public function __construct(private readonly DatabaseConnection $databaseConnection)
private readonly DatabaseConnection $databaseConnection,
private readonly Config $configController)
{ {
// empty body // empty body
} }
@ -24,40 +28,35 @@ class DomainRepository
/** /**
* @return array * @return array
*/ */
public function findAll(): array public function findAll(string $orderBy = 'nick'): array
{ {
$users = []; $users = [];
$sql = " $sql = "
SELECT id, nick, first, last, is_admin SELECT id, nick, first, last, is_admin
FROM " . DatabaseConnection::TABLE_USERS . " FROM " . DatabaseConnection::TABLE_USERS . "
ORDER BY name"; ORDER BY :order";
try { try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':order', var: $order);
$statement->execute(); $statement->execute();
while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) { while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
$domain = new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']); $user = new User(nick: $result['nick'], first: $result['first'], last: $result['last'], id: $result['id']);
$domains[] = $domain; $users[] = $user;
} }
return $domains; return $users;
} catch (PDOException $e) { } catch (PDOException $e) {
exit($e->getMessage()); exit($e->getMessage());
} }
} }
/** public function findByID(int $id): ?User
* @param int $id
*
* @return bool|\App\Entity\Domain
*/
public function findByID(int $id): bool|Domain
{ {
$this->logger->debug(message: "findById($id)");
$sql = " $sql = "
SELECT id, name, panel SELECT id, nick, first, last, is_admin
FROM . " . DatabaseConnection::TABLE_DOMAINS . " FROM " . DatabaseConnection::TABLE_USERS . "
WHERE id = :id"; WHERE id = :id";
try { try {
@ -65,85 +64,41 @@ class DomainRepository
$statement->bindParam(param: ':id', var: $id); $statement->bindParam(param: ':id', var: $id);
$statement->execute(); $statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) { if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new User(nick: $result['nick'], first: $result['first'], last: $result['last'], id: $result['id']);
return new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
} else { } else {
return false; return null;
} }
} catch (PDOException $e) { } catch (PDOException $e) {
exit($e->getMessage()); exit($e->getMessage());
} }
} }
public function findByNick(string $nick): ?User
/**
* @param String $name
*
* @return \App\Entity\Domain|bool
*/
public function findByName(string $name): Domain|bool
{ {
$this->logger->debug(message: "findByName($name)");
$sql = " $sql = "
SELECT id, name, panel SELECT id, nick, first, last, is_admin
FROM " . DatabaseConnection::TABLE_DOMAINS . " FROM " . DatabaseConnection::TABLE_USERS . "
WHERE name = :name"; WHERE nick = :nick";
try { try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name); $statement->bindParam(param: ':nick', var: $nick);
$statement->execute(); $statement->execute();
if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) { if ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
return new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']); return new User(nick: $result['nick'], first: $result['first'], last: $result['last'], id: $result['id']);
} else { } else {
return false; return null;
} }
} catch (PDOException $e) { } catch (PDOException $e) {
exit($e->getMessage()); exit($e->getMessage());
} }
} }
public function insert(User $user): bool|string
/**
* @param string $host
*
* @return \App\Entity\Domain|bool
*/
public function findByHost(string $host): Domain|bool
{ {
$this->logger->debug(message: "findByHost($host)"); /*
$host = strtolower(string: trim(string: $host));
$count = substr_count(haystack: $host, needle: '.');
if ($count == 2) {
if (strlen(string: explode(separator: '.', string: $host)[1]) > 3) {
$host = explode(separator: '.', string: $host, limit: 2)[1];
}
} elseif ($count > 2) {
$host = $this->findByHost(host: explode(separator: '.', string: $host, limit: 2)[1]);
}
if ($domain = $this->findByName(name: $host)) {
return $domain;
} else {
return false;
}
}
/**
* @param \App\Entity\Domain $domain
*
* @return string|false
*/
public function insert(Domain $domain): bool|string
{
$domainName = $domain->getName();
$this->logger->info(message: "insert($domainName)");
$sql = " $sql = "
INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel) INSERT INTO " . DatabaseConnection::TABLE_USERS . " (name, panel)
VALUES (:name, :panel)"; VALUES (:name, :panel)";
try { try {
@ -158,22 +113,17 @@ class DomainRepository
} catch (PDOException $e) { } catch (PDOException $e) {
exit($e->getMessage()); exit($e->getMessage());
} }
*/
return false;
} }
/** public function update(User $user): bool|int
* @param \App\Entity\Domain $domain
*
* @return false|int
*/
public function update(Domain $domain): bool|int
{ {
$domainName = $domain->getName(); $id = $user->getId();
$this->logger->debug(message: "update($domainName)");
$id = $domain->getId();
$current = $this->findByID(id: $id); $current = $this->findByID(id: $id);
/*
if (empty($domain->getName())) { if (empty($domain->getName())) {
$name = $current->getName(); $name = $current->getName();
} else { } else {
@ -186,7 +136,7 @@ class DomainRepository
} }
$sql = " $sql = "
UPDATE " . DatabaseConnection::TABLE_DOMAINS . " SET UPDATE " . DatabaseConnection::TABLE_USER . " SET
name = :name, name = :name,
panel = :panel panel = :panel
WHERE id = :id"; WHERE id = :id";
@ -203,26 +153,20 @@ class DomainRepository
echo $e->getMessage(); echo $e->getMessage();
return false; return false;
} }
*/
return false;
} }
/** public function delete(User $user): int
* @param \App\Entity\Domain $domain
*
* @return int
*/
public function delete(Domain $domain): int
{ {
$domainName = $domain->getName();
$this->logger->debug(message: "delete($domainName)");
$sql = " $sql = "
DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . " DELETE FROM " . DatabaseConnection::TABLE_USERS . "
WHERE id = :id"; WHERE id = :id";
try { try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql); $statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$id = $domain->getId(); $id = $user->getId();
$statement->bindParam(param: 'id', var: $id); $statement->bindParam(param: 'id', var: $id);
$statement->execute(); $statement->execute();
@ -232,24 +176,4 @@ class DomainRepository
} }
} }
/**
* @param String $field
*
* @return int
*/
public function getLongestEntry(string $field): int
{
$sql = "
SELECT MAX(LENGTH(" . $field . ")) as length FROM " . DatabaseConnection::TABLE_DOMAINS;
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->execute();
$result = $statement->fetch();
return $result['length'];
} catch (PDOException $e) {
exit($e->getMessage());
}
}
} }

View File

@ -1,4 +1,11 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Service; namespace App\Service;
@ -11,23 +18,21 @@ class Config
{ {
private array $config; private array $config;
/**
* @throws Exception
*/
public function __construct() public function __construct()
{ {
// Check for either config.json.local or config.json.
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local"; $configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local";
if (!file_exists(filename: $configFile)) { if (!file_exists(filename: $configFile)) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json"; $configFile = dirname(path: __DIR__, levels: 2) . "/config.json";
} }
if (!file_exists(filename: $configFile)) { if (!file_exists(filename: $configFile)) {
throw new Exception(message: 'Missing config file'); die('Missing config file');
} }
$configJSON = file_get_contents(filename: $configFile); $configJSON = file_get_contents(filename: $configFile);
if (json_decode(json: $configJSON) === null) { if (json_decode(json: $configJSON) === null) {
throw new Exception(message: 'Config file is not valid JSON.'); die('Config file is not valid JSON.');
} }
$this->config = json_decode(json: $configJSON, associative: true); $this->config = json_decode(json: $configJSON, associative: true);

View File

@ -1,27 +1,35 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Service; namespace App\Service;
use PDO; use PDO;
/** /**
* * Take care of the PDO object.
*/ */
class DatabaseConnection class DatabaseConnection
{ {
private PDO $dbConnection; private PDO $dbConnection;
// Currently no prefixes are used, but could be easily added to config.json.
const TABLE_PREFIX = ''; const TABLE_PREFIX = '';
const TABLE_USERS = self::TABLE_PREFIX . "users"; const TABLE_USERS = self::TABLE_PREFIX . "users";
const TABLE_ADDRESSES = self::TABLE_PREFIX . "addresses"; const TABLE_ADDRESSES = self::TABLE_PREFIX . "addresses";
public function __construct(private readonly Config $configController) public function __construct(private readonly Config $config)
{ {
$dbHost = $this->configController->getConfig(configKey: 'dbHost'); $dbHost = $this->config->getConfig(configKey: 'dbHost');
$dbPort = $this->configController->getConfig(configKey: 'dbPort'); $dbPort = $this->config->getConfig(configKey: 'dbPort');
$dbDatabase = $this->configController->getConfig(configKey: 'dbDatabase'); $dbDatabase = $this->config->getConfig(configKey: 'dbDatabase');
$dbUser = $this->configController->getConfig(configKey: 'dbUser'); $dbUser = $this->config->getConfig(configKey: 'dbUser');
$dbPassword = $this->configController->getConfig(configKey: 'dbPassword'); $dbPassword = $this->config->getConfig(configKey: 'dbPassword');
$this->dbConnection = new PDO( $this->dbConnection = new PDO(
dsn: "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4;dbname=$dbDatabase", dsn: "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4;dbname=$dbDatabase",

View File

@ -1,4 +1,11 @@
<?php <?php
/*
* Copyright (c) 2022. Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace App\Service; namespace App\Service;
@ -15,8 +22,14 @@ class Router
{ {
private array $routes; private array $routes;
public function __construct(private readonly Template $template)
{
// empty body
}
/* /*
* This method takes a route like /admin/users/{user} and creates a regex to match on call * This method takes a route like /admin/users/{user} and creates a regex to match on call
* More complex routes as /posts/{thread}/show/{page} are supported as well.
*/ */
function addRoute(string $name, string $route, Closure $callback): void function addRoute(string $name, string $route, Closure $callback): void
{ {
@ -26,6 +39,7 @@ class Router
// create regex for route: // create regex for route:
$regex = preg_replace(pattern: '/(?<={).+?(?=})/', replacement: '(.*?)', subject: $route); $regex = preg_replace(pattern: '/(?<={).+?(?=})/', replacement: '(.*?)', subject: $route);
// code below is ugly, better match including the braces // code below is ugly, better match including the braces
$regex = str_replace(search: '{', replace: '', subject: $regex); $regex = str_replace(search: '{', replace: '', subject: $regex);
$regex = str_replace(search: '}', replace: '', subject: $regex); $regex = str_replace(search: '}', replace: '', subject: $regex);
@ -37,8 +51,7 @@ class Router
} }
/* /*
* Check is there is a known route and executed the callback. * Check if there is a known route and executes the callback.
* Currently no 404 handling.
*/ */
public function handleRouting(): void public function handleRouting(): void
{ {
@ -57,7 +70,7 @@ class Router
return; return;
} }
} }
// Throw a 404 result later … $this->template->render(templateName: 'status/404.html.php');
die("Invalid route: $requestUri");
} }
} }

View File

@ -1,18 +1,37 @@
<?php <?php
/*
* Copyright (c) 2022 Micha Espey <tracer@24unix.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service; namespace App\Service;
use Exception; /*
* As I'm not allowed to use 3rd party code like Twig or Smarty I ended up
* using PHP as a templating engine.
*/
class Template class Template
{ {
/*
* Just store the information about the template base dir.
*/
public function __construct(private readonly string $templateDir) public function __construct(private readonly string $templateDir)
{ {
// empty body // empty body
} }
public function render(string $templateName): void /*
* Add variables to template and throw it out
*/
public function render(string $templateName, array $vars = []): void
{ {
foreach ($vars as $name => $value) {
$$name = $value;
}
include $this->templateDir . $templateName; include $this->templateDir . $templateName;
exit(0);
} }
} }

View File

@ -0,0 +1,5 @@
<?php include dirname(path: __DIR__) . '/_header.html.php'; ?>
<h2>403 Permission denied</h2>
<?php include dirname(path: __DIR__) . '/_footer.html.php' ?>

View File

@ -0,0 +1,5 @@
<?php include dirname(path: __DIR__) . '/_header.html.php'; ?>
<h2>404 Page not found</h2>
<?php include dirname(path: __DIR__) . '/_footer.html.php' ?>