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
/*
* 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;
@ -13,4 +20,44 @@ class AddressBookEntry
{
// 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
/*
* 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;
@ -17,81 +24,51 @@ class Route
// empty body
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* @return string
*/
public function getRoute(): string
{
return $this->route;
}
/**
* @param string $route
*/
public function setRoute(string $route): void
{
$this->route = $route;
}
/**
* @return string
*/
public function getRegEx(): string
{
return $this->regEx;
}
/**
* @param string $regEx
*/
public function setRegEx(string $regEx): void
{
$this->regEx = $regEx;
}
/**
* @return array
*/
public function getParameters(): array
{
return $this->parameters;
}
/**
* @param array $parameters
*/
public function setParameters(array $parameters): void
{
$this->parameters = $parameters;
}
/**
* @return Closure
*/
public function getCallback(): Closure
{
return $this->callback;
}
/**
* @param Closure $callback
*/
public function setCallback(Closure $callback): void
{
$this->callback = $callback;

View File

@ -1,18 +1,99 @@
<?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;
use App\Enums\UserAuth;
class User
{
public function __construct(
private string $nick,
private string $password,
private string $nick = '',
private string $password = '',
private string $first = '',
private string $last = '',
private int $id = 0,
private bool $isAdmin = false
private bool $isAdmin = false,
private UserAuth $userAuth = UserAuth::AUTH_ANONYMOUS
)
{
// 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
/*
* 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;
use App\Service\Config;
use App\Service\DatabaseConnection;
use App\Entity\User;
use PDO;
use PDOException;
/**
*
* Handles CRUD od User class.
*/
class DomainRepository
class UserRepository
{
public function __construct(
private readonly DatabaseConnection $databaseConnection,
private readonly Config $configController)
public function __construct(private readonly DatabaseConnection $databaseConnection)
{
// empty body
}
@ -24,40 +28,35 @@ class DomainRepository
/**
* @return array
*/
public function findAll(): array
public function findAll(string $orderBy = 'nick'): array
{
$users = [];
$sql = "
SELECT id, nick, first, last, is_admin
FROM " . DatabaseConnection::TABLE_USERS . "
ORDER BY name";
ORDER BY :order";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':order', var: $order);
$statement->execute();
while ($result = $statement->fetch(mode: PDO::FETCH_ASSOC)) {
$domain = new Domain(name: $result['name'], panel: $result['panel'], id: $result['id']);
$domains[] = $domain;
$user = new User(nick: $result['nick'], first: $result['first'], last: $result['last'], id: $result['id']);
$users[] = $user;
}
return $domains;
return $users;
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param int $id
*
* @return bool|\App\Entity\Domain
*/
public function findByID(int $id): bool|Domain
public function findByID(int $id): ?User
{
$this->logger->debug(message: "findById($id)");
$sql = "
SELECT id, name, panel
FROM . " . DatabaseConnection::TABLE_DOMAINS . "
SELECT id, nick, first, last, is_admin
FROM " . DatabaseConnection::TABLE_USERS . "
WHERE id = :id";
try {
@ -65,85 +64,41 @@ class DomainRepository
$statement->bindParam(param: ':id', var: $id);
$statement->execute();
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 {
return false;
return null;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param String $name
*
* @return \App\Entity\Domain|bool
*/
public function findByName(string $name): Domain|bool
public function findByNick(string $nick): ?User
{
$this->logger->debug(message: "findByName($name)");
$sql = "
SELECT id, name, panel
FROM " . DatabaseConnection::TABLE_DOMAINS . "
WHERE name = :name";
SELECT id, nick, first, last, is_admin
FROM " . DatabaseConnection::TABLE_USERS . "
WHERE nick = :nick";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$statement->bindParam(param: ':name', var: $name);
$statement->bindParam(param: ':nick', var: $nick);
$statement->execute();
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 {
return false;
return null;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
/**
* @param string $host
*
* @return \App\Entity\Domain|bool
*/
public function findByHost(string $host): Domain|bool
public function insert(User $user): bool|string
{
$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 = "
INSERT INTO " . DatabaseConnection::TABLE_DOMAINS . " (name, panel)
INSERT INTO " . DatabaseConnection::TABLE_USERS . " (name, panel)
VALUES (:name, :panel)";
try {
@ -158,22 +113,17 @@ class DomainRepository
} catch (PDOException $e) {
exit($e->getMessage());
}
*/
return false;
}
/**
* @param \App\Entity\Domain $domain
*
* @return false|int
*/
public function update(Domain $domain): bool|int
public function update(User $user): bool|int
{
$domainName = $domain->getName();
$this->logger->debug(message: "update($domainName)");
$id = $domain->getId();
$id = $user->getId();
$current = $this->findByID(id: $id);
/*
if (empty($domain->getName())) {
$name = $current->getName();
} else {
@ -186,7 +136,7 @@ class DomainRepository
}
$sql = "
UPDATE " . DatabaseConnection::TABLE_DOMAINS . " SET
UPDATE " . DatabaseConnection::TABLE_USER . " SET
name = :name,
panel = :panel
WHERE id = :id";
@ -203,26 +153,20 @@ class DomainRepository
echo $e->getMessage();
return false;
}
*/
return false;
}
/**
* @param \App\Entity\Domain $domain
*
* @return int
*/
public function delete(Domain $domain): int
public function delete(User $user): int
{
$domainName = $domain->getName();
$this->logger->debug(message: "delete($domainName)");
$sql = "
DELETE FROM " . DatabaseConnection::TABLE_DOMAINS . "
DELETE FROM " . DatabaseConnection::TABLE_USERS . "
WHERE id = :id";
try {
$statement = $this->databaseConnection->getConnection()->prepare(query: $sql);
$id = $domain->getId();
$id = $user->getId();
$statement->bindParam(param: 'id', var: $id);
$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
/*
* 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;
@ -11,23 +18,21 @@ class Config
{
private array $config;
/**
* @throws Exception
*/
public function __construct()
{
// Check for either config.json.local or config.json.
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json.local";
if (!file_exists(filename: $configFile)) {
$configFile = dirname(path: __DIR__, levels: 2) . "/config.json";
}
if (!file_exists(filename: $configFile)) {
throw new Exception(message: 'Missing config file');
die('Missing config file');
}
$configJSON = file_get_contents(filename: $configFile);
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);

View File

@ -1,27 +1,35 @@
<?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;
use PDO;
/**
*
* Take care of the PDO object.
*/
class DatabaseConnection
{
private PDO $dbConnection;
// Currently no prefixes are used, but could be easily added to config.json.
const TABLE_PREFIX = '';
const TABLE_USERS = self::TABLE_PREFIX . "users";
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');
$dbPort = $this->configController->getConfig(configKey: 'dbPort');
$dbDatabase = $this->configController->getConfig(configKey: 'dbDatabase');
$dbUser = $this->configController->getConfig(configKey: 'dbUser');
$dbPassword = $this->configController->getConfig(configKey: 'dbPassword');
$dbHost = $this->config->getConfig(configKey: 'dbHost');
$dbPort = $this->config->getConfig(configKey: 'dbPort');
$dbDatabase = $this->config->getConfig(configKey: 'dbDatabase');
$dbUser = $this->config->getConfig(configKey: 'dbUser');
$dbPassword = $this->config->getConfig(configKey: 'dbPassword');
$this->dbConnection = new PDO(
dsn: "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4;dbname=$dbDatabase",

View File

@ -1,4 +1,11 @@
<?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;
@ -15,8 +22,14 @@ class Router
{
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
* More complex routes as /posts/{thread}/show/{page} are supported as well.
*/
function addRoute(string $name, string $route, Closure $callback): void
{
@ -26,6 +39,7 @@ class Router
// create regex for route:
$regex = preg_replace(pattern: '/(?<={).+?(?=})/', replacement: '(.*?)', subject: $route);
// code below is ugly, better match including the braces
$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.
* Currently no 404 handling.
* Check if there is a known route and executes the callback.
*/
public function handleRouting(): void
{
@ -57,7 +70,7 @@ class Router
return;
}
}
// Throw a 404 result later …
die("Invalid route: $requestUri");
$this->template->render(templateName: 'status/404.html.php');
}
}

View File

@ -1,18 +1,37 @@
<?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;
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
{
/*
* Just store the information about the template base dir.
*/
public function __construct(private readonly string $templateDir)
{
// 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;
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' ?>