Namespace and ClassPath rewrites
This commit is contained in:
27
Core/Objects/DatabaseEntity/ApiKey.class.php
Normal file
27
Core/Objects/DatabaseEntity/ApiKey.class.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
|
||||
class ApiKey extends DatabaseEntity {
|
||||
|
||||
private bool $active;
|
||||
#[MaxLength(64)] public String $apiKey;
|
||||
public \DateTime $validUntil;
|
||||
public User $user;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"active" => $this->active,
|
||||
"apiKey" => $this->apiKey,
|
||||
"validUntil" => $this->validUntil->getTimestamp()
|
||||
];
|
||||
}
|
||||
}
|
||||
21
Core/Objects/DatabaseEntity/Attribute/DefaultValue.class.php
Normal file
21
Core/Objects/DatabaseEntity/Attribute/DefaultValue.class.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class DefaultValue {
|
||||
|
||||
private mixed $value;
|
||||
|
||||
public function __construct(mixed $value) {
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
public function getValue() {
|
||||
if (is_string($this->value) && isClass($this->value)) {
|
||||
return new $this->value();
|
||||
}
|
||||
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
}
|
||||
17
Core/Objects/DatabaseEntity/Attribute/Enum.class.php
Normal file
17
Core/Objects/DatabaseEntity/Attribute/Enum.class.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Enum {
|
||||
|
||||
private array $values;
|
||||
|
||||
public function __construct(string ...$values) {
|
||||
$this->values = $values;
|
||||
}
|
||||
|
||||
public function getValues(): array {
|
||||
return $this->values;
|
||||
}
|
||||
|
||||
}
|
||||
7
Core/Objects/DatabaseEntity/Attribute/Json.class.php
Normal file
7
Core/Objects/DatabaseEntity/Attribute/Json.class.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Json {
|
||||
|
||||
}
|
||||
16
Core/Objects/DatabaseEntity/Attribute/Many.class.php
Normal file
16
Core/Objects/DatabaseEntity/Attribute/Many.class.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Many {
|
||||
|
||||
private string $type;
|
||||
|
||||
public function __construct(string $type) {
|
||||
$this->type = $type;
|
||||
}
|
||||
|
||||
public function getValue(): string {
|
||||
return $this->type;
|
||||
}
|
||||
}
|
||||
15
Core/Objects/DatabaseEntity/Attribute/MaxLength.class.php
Normal file
15
Core/Objects/DatabaseEntity/Attribute/MaxLength.class.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class MaxLength {
|
||||
private int $maxLength;
|
||||
|
||||
function __construct(int $maxLength) {
|
||||
$this->maxLength = $maxLength;
|
||||
}
|
||||
|
||||
public function getValue(): int {
|
||||
return $this->maxLength;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Transient {
|
||||
|
||||
}
|
||||
7
Core/Objects/DatabaseEntity/Attribute/Unique.class.php
Normal file
7
Core/Objects/DatabaseEntity/Attribute/Unique.class.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity\Attribute;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_PROPERTY)] class Unique {
|
||||
|
||||
}
|
||||
130
Core/Objects/DatabaseEntity/DatabaseEntity.class.php
Normal file
130
Core/Objects/DatabaseEntity/DatabaseEntity.class.php
Normal file
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\SQL\Condition\Compare;
|
||||
use Core\Driver\SQL\Condition\Condition;
|
||||
use Core\Driver\SQL\SQL;
|
||||
|
||||
abstract class DatabaseEntity {
|
||||
|
||||
private static array $handlers = [];
|
||||
protected ?int $id;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
public abstract function jsonSerialize(): array;
|
||||
|
||||
public function preInsert(array &$row) { }
|
||||
public function postFetch(SQL $sql, array $row) { }
|
||||
|
||||
public static function fromRow(SQL $sql, array $row): static {
|
||||
$handler = self::getHandler($sql);
|
||||
return $handler->entityFromRow($row);
|
||||
}
|
||||
|
||||
public static function newInstance(\ReflectionClass $reflectionClass, array $row) {
|
||||
return $reflectionClass->newInstanceWithoutConstructor();
|
||||
}
|
||||
|
||||
public static function find(SQL $sql, int $id, bool $fetchEntities = false, bool $fetchRecursive = false): static|bool|null {
|
||||
$handler = self::getHandler($sql);
|
||||
if ($fetchEntities) {
|
||||
return DatabaseEntityQuery::fetchOne(self::getHandler($sql))
|
||||
->where(new Compare($handler->getTableName() . ".id", $id))
|
||||
->fetchEntities($fetchRecursive)
|
||||
->execute();
|
||||
} else {
|
||||
return $handler->fetchOne($id);
|
||||
}
|
||||
}
|
||||
|
||||
public static function exists(SQL $sql, int $id): bool {
|
||||
$handler = self::getHandler($sql);
|
||||
$res = $sql->select($sql->count())
|
||||
->from($handler->getTableName())
|
||||
->where(new Compare($handler->getTableName() . ".id", $id))
|
||||
->execute();
|
||||
|
||||
return $res !== false && $res[0]["count"] !== 0;
|
||||
}
|
||||
|
||||
public static function findBuilder(SQL $sql): DatabaseEntityQuery {
|
||||
return DatabaseEntityQuery::fetchOne(self::getHandler($sql));
|
||||
}
|
||||
|
||||
public static function findAll(SQL $sql, ?Condition $condition = null): ?array {
|
||||
$handler = self::getHandler($sql);
|
||||
return $handler->fetchMultiple($condition);
|
||||
}
|
||||
|
||||
public static function findAllBuilder(SQL $sql): DatabaseEntityQuery {
|
||||
return DatabaseEntityQuery::fetchAll(self::getHandler($sql));
|
||||
}
|
||||
|
||||
public function save(SQL $sql, ?array $columns = null): bool {
|
||||
$handler = self::getHandler($sql);
|
||||
$res = $handler->insertOrUpdate($this, $columns);
|
||||
if ($res === false) {
|
||||
return false;
|
||||
} else if ($this->id === null) {
|
||||
$this->id = $res;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function insert(SQL $sql): bool {
|
||||
$handler = self::getHandler($sql);
|
||||
$res = $handler->insert($this);
|
||||
if ($res === false) {
|
||||
return false;
|
||||
} else if ($this->id === null) {
|
||||
$this->id = $res;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function delete(SQL $sql): bool {
|
||||
$handler = self::getHandler($sql);
|
||||
if ($this->id === null) {
|
||||
$handler->getLogger()->error("Cannot delete entity without id");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($handler->delete($this->id)) {
|
||||
$this->id = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getHandler(SQL $sql, $obj_or_class = null): DatabaseEntityHandler {
|
||||
|
||||
if (!$obj_or_class) {
|
||||
$obj_or_class = get_called_class();
|
||||
}
|
||||
|
||||
if (!($obj_or_class instanceof \ReflectionClass)) {
|
||||
$class = new \ReflectionClass($obj_or_class);
|
||||
} else {
|
||||
$class = $obj_or_class;
|
||||
}
|
||||
|
||||
$handler = self::$handlers[$class->getShortName()] ?? null;
|
||||
if (!$handler) {
|
||||
$handler = new DatabaseEntityHandler($sql, $class);
|
||||
self::$handlers[$class->getShortName()] = $handler;
|
||||
}
|
||||
|
||||
return $handler;
|
||||
}
|
||||
|
||||
public function getId(): ?int {
|
||||
return $this->id;
|
||||
}
|
||||
}
|
||||
414
Core/Objects/DatabaseEntity/DatabaseEntityHandler.php
Normal file
414
Core/Objects/DatabaseEntity/DatabaseEntityHandler.php
Normal file
@@ -0,0 +1,414 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\Logger\Logger;
|
||||
use Core\Driver\SQL\Column\BoolColumn;
|
||||
use Core\Driver\SQL\Column\DateTimeColumn;
|
||||
use Core\Driver\SQL\Column\EnumColumn;
|
||||
use Core\Driver\SQL\Column\IntColumn;
|
||||
use Core\Driver\SQL\Column\JsonColumn;
|
||||
use Core\Driver\SQL\Column\StringColumn;
|
||||
use Core\Driver\SQL\Condition\Compare;
|
||||
use Core\Driver\SQL\Condition\Condition;
|
||||
use Core\Driver\SQL\Column\DoubleColumn;
|
||||
use Core\Driver\SQL\Column\FloatColumn;
|
||||
use Core\Driver\SQL\Constraint\ForeignKey;
|
||||
use Core\Driver\SQL\Query\CreateTable;
|
||||
use Core\Driver\SQL\Query\Select;
|
||||
use Core\Driver\SQL\SQL;
|
||||
use Core\Driver\SQL\Strategy\CascadeStrategy;
|
||||
use Core\Driver\SQL\Strategy\SetNullStrategy;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Enum;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Json;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Transient;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Unique;
|
||||
use PHPUnit\Util\Exception;
|
||||
|
||||
class DatabaseEntityHandler {
|
||||
|
||||
private \ReflectionClass $entityClass;
|
||||
private string $tableName;
|
||||
private array $columns;
|
||||
private array $properties;
|
||||
private array $relations;
|
||||
private array $constraints;
|
||||
private SQL $sql;
|
||||
private Logger $logger;
|
||||
|
||||
public function __construct(SQL $sql, \ReflectionClass $entityClass) {
|
||||
$this->sql = $sql;
|
||||
$className = $entityClass->getName();
|
||||
$this->logger = new Logger($entityClass->getShortName(), $sql);
|
||||
$this->entityClass = $entityClass;
|
||||
if (!$this->entityClass->isSubclassOf(DatabaseEntity::class)) {
|
||||
$this->raiseError("Cannot persist class '$className': Not an instance of DatabaseEntity or not instantiable.");
|
||||
}
|
||||
|
||||
$this->tableName = $this->entityClass->getShortName();
|
||||
$this->columns = []; // property name => database column name
|
||||
$this->properties = []; // property name => \ReflectionProperty
|
||||
$this->relations = []; // property name => referenced table name
|
||||
$this->constraints = []; // \Driver\SQL\Constraint\Constraint
|
||||
|
||||
foreach ($this->entityClass->getProperties() as $property) {
|
||||
$propertyName = $property->getName();
|
||||
if ($propertyName === "id") {
|
||||
$this->properties[$propertyName] = $property;
|
||||
continue;
|
||||
}
|
||||
|
||||
$propertyType = $property->getType();
|
||||
$columnName = self::getColumnName($propertyName);
|
||||
if (!($propertyType instanceof \ReflectionNamedType)) {
|
||||
$this->raiseError("Cannot persist class '$className': Property '$propertyName' has no valid type");
|
||||
}
|
||||
|
||||
$nullable = $propertyType->allowsNull();
|
||||
$propertyTypeName = $propertyType->getName();
|
||||
if (!empty($property->getAttributes(Transient::class))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$defaultValue = (self::getAttribute($property, DefaultValue::class))?->getValue();
|
||||
$isUnique = !empty($property->getAttributes(Unique::class));
|
||||
|
||||
if ($propertyTypeName === 'string') {
|
||||
$enum = self::getAttribute($property, Enum::class);
|
||||
if ($enum) {
|
||||
$this->columns[$propertyName] = new EnumColumn($columnName, $enum->getValues(), $nullable, $defaultValue);
|
||||
} else {
|
||||
$maxLength = self::getAttribute($property, MaxLength::class);
|
||||
$this->columns[$propertyName] = new StringColumn($columnName, $maxLength?->getValue(), $nullable, $defaultValue);
|
||||
}
|
||||
} else if ($propertyTypeName === 'int') {
|
||||
$this->columns[$propertyName] = new IntColumn($columnName, $nullable, $defaultValue);
|
||||
} else if ($propertyTypeName === 'float') {
|
||||
$this->columns[$propertyName] = new FloatColumn($columnName, $nullable, $defaultValue);
|
||||
} else if ($propertyTypeName === 'double') {
|
||||
$this->columns[$propertyName] = new DoubleColumn($columnName, $nullable, $defaultValue);
|
||||
} else if ($propertyTypeName === 'bool') {
|
||||
$this->columns[$propertyName] = new BoolColumn($columnName, $defaultValue ?? false);
|
||||
} else if ($propertyTypeName === 'DateTime') {
|
||||
$this->columns[$propertyName] = new DateTimeColumn($columnName, $nullable, $defaultValue);
|
||||
/*} else if ($propertyName === 'array') {
|
||||
$many = self::getAttribute($property, Many::class);
|
||||
if ($many) {
|
||||
$requestedType = $many->getValue();
|
||||
if (isClass($requestedType)) {
|
||||
$requestedClass = new \ReflectionClass($requestedType);
|
||||
} else {
|
||||
$this->raiseError("Cannot persist class '$className': Property '$propertyName' has non persist-able type: $requestedType");
|
||||
}
|
||||
} else {
|
||||
$this->raiseError("Cannot persist class '$className': Property '$propertyName' has non persist-able type: $propertyTypeName");
|
||||
}*/
|
||||
} else if ($propertyTypeName !== "mixed") {
|
||||
try {
|
||||
$requestedClass = new \ReflectionClass($propertyTypeName);
|
||||
if ($requestedClass->isSubclassOf(DatabaseEntity::class)) {
|
||||
$columnName .= "_id";
|
||||
$requestedHandler = ($requestedClass->getName() === $this->entityClass->getName()) ?
|
||||
$this : DatabaseEntity::getHandler($this->sql, $requestedClass);
|
||||
$strategy = $nullable ? new SetNullStrategy() : new CascadeStrategy();
|
||||
$this->columns[$propertyName] = new IntColumn($columnName, $nullable, $defaultValue);
|
||||
$this->constraints[] = new ForeignKey($columnName, $requestedHandler->tableName, "id", $strategy);
|
||||
$this->relations[$propertyName] = $requestedHandler;
|
||||
} else {
|
||||
$this->raiseError("Cannot persist class '$className': Property '$propertyName' has non persist-able type: $propertyTypeName");
|
||||
}
|
||||
} catch (\Exception $ex) {
|
||||
$this->raiseError("Cannot persist class '$className' property '$propertyTypeName': " . $ex->getMessage());
|
||||
}
|
||||
} else {
|
||||
if (!empty($property->getAttributes(Json::class))) {
|
||||
$this->columns[$propertyName] = new JsonColumn($columnName, $nullable, $defaultValue);
|
||||
} else {
|
||||
$this->raiseError("Cannot persist class '$className': Property '$propertyName' has non persist-able type: $propertyTypeName");
|
||||
}
|
||||
}
|
||||
|
||||
$this->properties[$propertyName] = $property;
|
||||
|
||||
if ($isUnique) {
|
||||
$this->constraints[] = new \Core\Driver\SQL\Constraint\Unique($columnName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function getAttribute(\ReflectionProperty $property, string $attributeClass): ?object {
|
||||
$attributes = $property->getAttributes($attributeClass);
|
||||
$attribute = array_shift($attributes);
|
||||
return $attribute?->newInstance();
|
||||
}
|
||||
|
||||
public static function getColumnName(string $propertyName): string {
|
||||
// abcTestLOL => abc_test_lol
|
||||
return strtolower(preg_replace_callback("/([a-z])([A-Z]+)/", function ($m) {
|
||||
return $m[1] . "_" . strtolower($m[2]);
|
||||
}, $propertyName));
|
||||
}
|
||||
|
||||
public function getReflection(): \ReflectionClass {
|
||||
return $this->entityClass;
|
||||
}
|
||||
|
||||
public function getLogger(): Logger {
|
||||
return $this->logger;
|
||||
}
|
||||
|
||||
public function getTableName(): string {
|
||||
return $this->tableName;
|
||||
}
|
||||
|
||||
public function getRelations(): array {
|
||||
return $this->relations;
|
||||
}
|
||||
|
||||
public function getColumnNames(): array {
|
||||
$columns = ["$this->tableName.id"];
|
||||
foreach ($this->columns as $column) {
|
||||
$columns[] = $this->tableName . "." . $column->getName();
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
public function getColumns(): array {
|
||||
return $this->columns;
|
||||
}
|
||||
|
||||
public function dependsOn(): array {
|
||||
$foreignTables = array_map(function (DatabaseEntityHandler $relationHandler) {
|
||||
return $relationHandler->getTableName();
|
||||
}, $this->relations);
|
||||
return array_unique($foreignTables);
|
||||
}
|
||||
|
||||
public static function getPrefixedRow(array $row, string $prefix): array {
|
||||
$rel_row = [];
|
||||
foreach ($row as $relKey => $relValue) {
|
||||
if (startsWith($relKey, $prefix)) {
|
||||
$rel_row[substr($relKey, strlen($prefix))] = $relValue;
|
||||
}
|
||||
}
|
||||
return $rel_row;
|
||||
}
|
||||
|
||||
public function entityFromRow(array $row): ?DatabaseEntity {
|
||||
try {
|
||||
|
||||
$entity = call_user_func($this->entityClass->getName() . "::newInstance", $this->entityClass, $row);
|
||||
if (!($entity instanceof DatabaseEntity)) {
|
||||
$this->logger->error("Created Object is not of type DatabaseEntity");
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($this->columns as $propertyName => $column) {
|
||||
$columnName = $column->getName();
|
||||
if (array_key_exists($columnName, $row)) {
|
||||
$value = $row[$columnName];
|
||||
$property = $this->properties[$propertyName];
|
||||
|
||||
if ($column instanceof DateTimeColumn) {
|
||||
$value = new \DateTime($value);
|
||||
} else if ($column instanceof JsonColumn) {
|
||||
$value = json_decode($value);
|
||||
} else if (isset($this->relations[$propertyName])) {
|
||||
$relColumnPrefix = self::getColumnName($propertyName) . "_";
|
||||
if (array_key_exists($relColumnPrefix . "id", $row)) {
|
||||
$relId = $row[$relColumnPrefix . "id"];
|
||||
if ($relId !== null) {
|
||||
$relationHandler = $this->relations[$propertyName];
|
||||
$value = $relationHandler->entityFromRow(self::getPrefixedRow($row, $relColumnPrefix));
|
||||
} else if (!$column->notNull()) {
|
||||
$value = null;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$property->setAccessible(true);
|
||||
$property->setValue($entity, $value);
|
||||
}
|
||||
}
|
||||
|
||||
$this->properties["id"]->setAccessible(true);
|
||||
$this->properties["id"]->setValue($entity, $row["id"]);
|
||||
$entity->postFetch($this->sql, $row);
|
||||
return $entity;
|
||||
} catch (\Exception $exception) {
|
||||
$this->logger->error("Error creating entity from database row: " . $exception->getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function getSelectQuery(): Select {
|
||||
return $this->sql->select(...$this->getColumnNames())
|
||||
->from($this->tableName);
|
||||
}
|
||||
|
||||
public function fetchOne(int $id): DatabaseEntity|bool|null {
|
||||
$res = $this->getSelectQuery()
|
||||
->where(new Compare($this->tableName . ".id", $id))
|
||||
->first()
|
||||
->execute();
|
||||
|
||||
if ($res === false || $res === null) {
|
||||
return $res;
|
||||
} else {
|
||||
return $this->entityFromRow($res);
|
||||
}
|
||||
}
|
||||
|
||||
public function fetchMultiple(?Condition $condition = null): ?array {
|
||||
$query = $this->getSelectQuery();
|
||||
|
||||
if ($condition) {
|
||||
$query->where($condition);
|
||||
}
|
||||
|
||||
$res = $query->execute();
|
||||
if ($res === false) {
|
||||
return null;
|
||||
} else {
|
||||
$entities = [];
|
||||
foreach ($res as $row) {
|
||||
$entity = $this->entityFromRow($row);
|
||||
if ($entity) {
|
||||
$entities[$entity->getId()] = $entity;
|
||||
}
|
||||
}
|
||||
return $entities;
|
||||
}
|
||||
}
|
||||
|
||||
public function getTableQuery(): CreateTable {
|
||||
$query = $this->sql->createTable($this->tableName)
|
||||
->onlyIfNotExists()
|
||||
->addSerial("id")
|
||||
->primaryKey("id");
|
||||
|
||||
foreach ($this->columns as $column) {
|
||||
$query->addColumn($column);
|
||||
}
|
||||
|
||||
foreach ($this->constraints as $constraint) {
|
||||
$query->addConstraint($constraint);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public function createTable(): bool {
|
||||
$query = $this->getTableQuery();
|
||||
return $query->execute();
|
||||
}
|
||||
|
||||
private function prepareRow(DatabaseEntity $entity, string $action, ?array $columns = null) {
|
||||
$row = [];
|
||||
foreach ($this->columns as $propertyName => $column) {
|
||||
if ($columns && !in_array($column->getName(), $columns)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$property = $this->properties[$propertyName];
|
||||
$property->setAccessible(true);
|
||||
if ($property->isInitialized($entity)) {
|
||||
$value = $property->getValue($entity);
|
||||
if (isset($this->relations[$propertyName])) {
|
||||
$value = $value->getId();
|
||||
}
|
||||
} else if (!$this->columns[$propertyName]->notNull()) {
|
||||
$value = null;
|
||||
} else {
|
||||
$defaultValue = self::getAttribute($property, DefaultValue::class);
|
||||
if ($defaultValue) {
|
||||
$value = $defaultValue->getValue();
|
||||
} else if ($action !== "update") {
|
||||
$this->logger->error("Cannot $action entity: property '$propertyName' was not initialized yet.");
|
||||
return false;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$row[$column->getName()] = $value;
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
public function update(DatabaseEntity $entity, ?array $columns = null) {
|
||||
$row = $this->prepareRow($entity, "update", $columns);
|
||||
if ($row === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$entity->preInsert($row);
|
||||
$query = $this->sql->update($this->tableName)
|
||||
->where(new Compare($this->tableName . ".id", $entity->getId()));
|
||||
|
||||
foreach ($row as $columnName => $value) {
|
||||
$query->set($columnName, $value);
|
||||
}
|
||||
|
||||
return $query->execute();
|
||||
}
|
||||
|
||||
public function insert(DatabaseEntity $entity) {
|
||||
$row = $this->prepareRow($entity, "insert");
|
||||
if ($row === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$entity->preInsert($row);
|
||||
|
||||
// insert with id?
|
||||
$entityId = $entity->getId();
|
||||
if ($entityId !== null) {
|
||||
$row["id"] = $entityId;
|
||||
}
|
||||
|
||||
$query = $this->sql->insert($this->tableName, array_keys($row))
|
||||
->addRow(...array_values($row));
|
||||
|
||||
// return id if its auto-generated
|
||||
if ($entityId === null) {
|
||||
$query->returning("id");
|
||||
}
|
||||
|
||||
$res = $query->execute();
|
||||
if ($res !== false) {
|
||||
return $this->sql->getLastInsertId();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function insertOrUpdate(DatabaseEntity $entity, ?array $columns = null) {
|
||||
$id = $entity->getId();
|
||||
if ($id === null) {
|
||||
return $this->insert($entity);
|
||||
} else {
|
||||
return $this->update($entity, $columns);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(int $id) {
|
||||
return $this->sql
|
||||
->delete($this->tableName)
|
||||
->where(new Compare($this->tableName . ".id", $id))
|
||||
->execute();
|
||||
}
|
||||
|
||||
private function raiseError(string $message) {
|
||||
$this->logger->error($message);
|
||||
throw new Exception($message);
|
||||
}
|
||||
}
|
||||
135
Core/Objects/DatabaseEntity/DatabaseEntityQuery.class.php
Normal file
135
Core/Objects/DatabaseEntity/DatabaseEntityQuery.class.php
Normal file
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\SQL\Condition\Condition;
|
||||
use Core\Driver\SQL\Join;
|
||||
use Core\Driver\SQL\Query\Select;
|
||||
use Core\Driver\SQL\SQL;
|
||||
|
||||
/**
|
||||
* this class is similar to \Driver\SQL\Query\Select but with reduced functionality
|
||||
* and more adapted to entities.
|
||||
*/
|
||||
class DatabaseEntityQuery {
|
||||
|
||||
private DatabaseEntityHandler $handler;
|
||||
private Select $selectQuery;
|
||||
private int $resultType;
|
||||
|
||||
private function __construct(DatabaseEntityHandler $handler, int $resultType) {
|
||||
$this->handler = $handler;
|
||||
$this->selectQuery = $handler->getSelectQuery();
|
||||
$this->resultType = $resultType;
|
||||
|
||||
if ($this->resultType === SQL::FETCH_ONE) {
|
||||
$this->selectQuery->first();
|
||||
}
|
||||
}
|
||||
|
||||
public static function fetchAll(DatabaseEntityHandler $handler): DatabaseEntityQuery {
|
||||
return new DatabaseEntityQuery($handler, SQL::FETCH_ALL);
|
||||
}
|
||||
|
||||
public static function fetchOne(DatabaseEntityHandler $handler): DatabaseEntityQuery {
|
||||
return new DatabaseEntityQuery($handler, SQL::FETCH_ONE);
|
||||
}
|
||||
|
||||
public function limit(int $limit): DatabaseEntityQuery {
|
||||
$this->selectQuery->limit($limit);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function where(Condition ...$condition): DatabaseEntityQuery {
|
||||
$this->selectQuery->where(...$condition);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function orderBy(string ...$column): DatabaseEntityQuery {
|
||||
$this->selectQuery->orderBy(...$column);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function ascending(): DatabaseEntityQuery {
|
||||
$this->selectQuery->ascending();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function descending(): DatabaseEntityQuery {
|
||||
$this->selectQuery->descending();
|
||||
return $this;
|
||||
}
|
||||
|
||||
// TODO: clean this up
|
||||
public function fetchEntities(bool $recursive = false): DatabaseEntityQuery {
|
||||
|
||||
// $this->selectQuery->dump();
|
||||
|
||||
$relIndex = 1;
|
||||
foreach ($this->handler->getRelations() as $propertyName => $relationHandler) {
|
||||
$this->fetchRelation($propertyName, $this->handler->getTableName(), $this->handler, $relationHandler, $relIndex, $recursive);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function fetchRelation(string $propertyName, string $tableName, DatabaseEntityHandler $src, DatabaseEntityHandler $relationHandler,
|
||||
int &$relIndex = 1, bool $recursive = false, string $relationColumnPrefix = "") {
|
||||
|
||||
$columns = $src->getColumns();
|
||||
|
||||
$foreignColumn = $columns[$propertyName];
|
||||
$foreignColumnName = $foreignColumn->getName();
|
||||
$referencedTable = $relationHandler->getTableName();
|
||||
$isNullable = !$foreignColumn->notNull();
|
||||
$alias = "t$relIndex"; // t1, t2, t3, ...
|
||||
$relIndex++;
|
||||
|
||||
|
||||
if ($isNullable) {
|
||||
$this->selectQuery->leftJoin($referencedTable, "$tableName.$foreignColumnName", "$alias.id", $alias);
|
||||
} else {
|
||||
$this->selectQuery->innerJoin($referencedTable, "$tableName.$foreignColumnName", "$alias.id", $alias);
|
||||
}
|
||||
|
||||
$relationColumnPrefix .= DatabaseEntityHandler::getColumnName($propertyName) . "_";
|
||||
$recursiveRelations = $relationHandler->getRelations();
|
||||
foreach ($relationHandler->getColumns() as $relPropertyName => $relColumn) {
|
||||
$relColumnName = $relColumn->getName();
|
||||
if (!isset($recursiveRelations[$relPropertyName]) || $recursive) {
|
||||
$this->selectQuery->addValue("$alias.$relColumnName as $relationColumnPrefix$relColumnName");
|
||||
if (isset($recursiveRelations[$relPropertyName]) && $recursive) {
|
||||
$this->fetchRelation($relPropertyName, $alias, $relationHandler, $recursiveRelations[$relPropertyName], $relIndex, $recursive, $relationColumnPrefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(): DatabaseEntity|array|null {
|
||||
$res = $this->selectQuery->execute();
|
||||
if ($res === null || $res === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->resultType === SQL::FETCH_ALL) {
|
||||
$entities = [];
|
||||
foreach ($res as $row) {
|
||||
$entity = $this->handler->entityFromRow($row);
|
||||
if ($entity) {
|
||||
$entities[$entity->getId()] = $entity;
|
||||
}
|
||||
}
|
||||
return $entities;
|
||||
} else if ($this->resultType === SQL::FETCH_ONE) {
|
||||
return $this->handler->entityFromRow($res);
|
||||
} else {
|
||||
$this->handler->getLogger()->error("Invalid result type for query builder, must be FETCH_ALL or FETCH_ONE");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function addJoin(Join $join): DatabaseEntityQuery {
|
||||
$this->selectQuery->addJoin($join);
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
133
Core/Objects/DatabaseEntity/GpgKey.class.php
Normal file
133
Core/Objects/DatabaseEntity/GpgKey.class.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\SQL\Expression\CurrentTimeStamp;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
|
||||
class GpgKey extends DatabaseEntity {
|
||||
|
||||
const GPG2 = "/usr/bin/gpg2";
|
||||
|
||||
private bool $confirmed;
|
||||
#[MaxLength(64)] private string $fingerprint;
|
||||
#[MaxLength(64)] private string $algorithm;
|
||||
private \DateTime $expires;
|
||||
#[DefaultValue(CurrentTimeStamp::class)] private \DateTime $added;
|
||||
|
||||
public function __construct(int $id, bool $confirmed, string $fingerprint, string $algorithm, string $expires) {
|
||||
parent::__construct($id);
|
||||
$this->confirmed = $confirmed;
|
||||
$this->fingerprint = $fingerprint;
|
||||
$this->algorithm = $algorithm;
|
||||
$this->expires = new \DateTime($expires);
|
||||
}
|
||||
|
||||
public static function encrypt(string $body, string $gpgFingerprint): array {
|
||||
$gpgFingerprint = escapeshellarg($gpgFingerprint);
|
||||
$cmd = self::GPG2 . " --encrypt --output - --recipient $gpgFingerprint --trust-model always --batch --armor";
|
||||
list($out, $err) = self::proc_exec($cmd, $body, true);
|
||||
if ($out === null) {
|
||||
return createError("Error while communicating with GPG agent");
|
||||
} else if ($err) {
|
||||
return createError($err);
|
||||
} else {
|
||||
return ["success" => true, "data" => $out];
|
||||
}
|
||||
}
|
||||
|
||||
private static function proc_exec(string $cmd, ?string $stdin = null, bool $raw = false): ?array {
|
||||
$descriptorSpec = array(0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]);
|
||||
$process = proc_open($cmd, $descriptorSpec, $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($stdin) {
|
||||
fwrite($pipes[0], $stdin);
|
||||
fclose($pipes[0]);
|
||||
}
|
||||
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$err = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
proc_close($process);
|
||||
return [($raw ? $out : trim($out)), $err];
|
||||
}
|
||||
|
||||
public static function getKeyInfo(string $key): array {
|
||||
list($out, $err) = self::proc_exec(self::GPG2 . " --show-key", $key);
|
||||
if ($out === null) {
|
||||
return createError("Error while communicating with GPG agent");
|
||||
}
|
||||
|
||||
if ($err) {
|
||||
return createError($err);
|
||||
}
|
||||
|
||||
$lines = explode("\n", $out);
|
||||
if (count($lines) > 4) {
|
||||
return createError("It seems like you have uploaded more than one GPG-Key");
|
||||
} else if (count($lines) !== 4 || !preg_match("/(\S+)\s+(\w+)\s+.*\[expires: ([0-9-]+)]/", $lines[0], $matches)) {
|
||||
return createError("Error parsing GPG output");
|
||||
}
|
||||
|
||||
$keyType = $matches[1];
|
||||
$keyAlg = $matches[2];
|
||||
$expires = \DateTime::createFromFormat("Y-m-d", $matches[3]);
|
||||
$fingerprint = trim($lines[1]);
|
||||
$keyData = ["type" => $keyType, "algorithm" => $keyAlg, "expires" => $expires, "fingerprint" => $fingerprint];
|
||||
return ["success" => true, "data" => $keyData];
|
||||
}
|
||||
|
||||
public static function importKey(string $key): array {
|
||||
list($out, $err) = self::proc_exec(self::GPG2 . " --import", $key);
|
||||
if ($out === null) {
|
||||
return createError("Error while communicating with GPG agent");
|
||||
}
|
||||
|
||||
if (preg_match("/gpg:\s+Total number processed:\s+(\d+)/", $err, $matches) && intval($matches[1]) > 0) {
|
||||
if ((preg_match("/.*\s+unchanged:\s+(\d+)/", $err, $matches) && intval($matches[1]) > 0) ||
|
||||
(preg_match("/.*\s+imported:\s+(\d+)/", $err, $matches) && intval($matches[1]) > 0)) {
|
||||
return ["success" => true];
|
||||
}
|
||||
}
|
||||
|
||||
return createError($err);
|
||||
}
|
||||
|
||||
public static function export($gpgFingerprint, bool $armored): array {
|
||||
$cmd = self::GPG2 . " --export ";
|
||||
if ($armored) {
|
||||
$cmd .= "--armor ";
|
||||
}
|
||||
$cmd .= escapeshellarg($gpgFingerprint);
|
||||
list($out, $err) = self::proc_exec($cmd);
|
||||
if ($err) {
|
||||
return createError($err);
|
||||
}
|
||||
|
||||
return ["success" => true, "data" => $out];
|
||||
}
|
||||
|
||||
public function isConfirmed(): bool {
|
||||
return $this->confirmed;
|
||||
}
|
||||
|
||||
public function getFingerprint(): string {
|
||||
return $this->fingerprint;
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"fingerprint" => $this->fingerprint,
|
||||
"algorithm" => $this->algorithm,
|
||||
"expires" => $this->expires->getTimestamp(),
|
||||
"added" => $this->added->getTimestamp(),
|
||||
"confirmed" => $this->confirmed
|
||||
];
|
||||
}
|
||||
}
|
||||
23
Core/Objects/DatabaseEntity/Group.class.php
Normal file
23
Core/Objects/DatabaseEntity/Group.class.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
|
||||
class Group extends DatabaseEntity {
|
||||
|
||||
#[MaxLength(32)] public string $name;
|
||||
#[MaxLength(10)] public string $color;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"name" => $this->name,
|
||||
"color" => $this->color
|
||||
];
|
||||
}
|
||||
}
|
||||
108
Core/Objects/DatabaseEntity/Language.class.php
Normal file
108
Core/Objects/DatabaseEntity/Language.class.php
Normal file
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity {
|
||||
|
||||
use Core\Driver\SQL\SQL;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Transient;
|
||||
use Core\Objects\lang\LanguageModule;
|
||||
|
||||
// TODO: language from cookie?
|
||||
class Language extends DatabaseEntity {
|
||||
|
||||
const LANG_CODE_PATTERN = "/^[a-zA-Z]{2}_[a-zA-Z]{2}$/";
|
||||
|
||||
#[MaxLength(5)] private string $code;
|
||||
#[MaxLength(32)] private string $name;
|
||||
|
||||
#[Transient] private array $modules = [];
|
||||
#[Transient] protected array $entries = [];
|
||||
|
||||
public function __construct(int $id, string $code, string $name) {
|
||||
parent::__construct($id);
|
||||
$this->code = $code;
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function getCode(): string {
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
public function getShortCode(): string {
|
||||
return substr($this->code, 0, 2);
|
||||
}
|
||||
|
||||
public function getName(): string {
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function loadModule(LanguageModule|string $module) {
|
||||
if (!is_object($module)) {
|
||||
$module = new $module();
|
||||
}
|
||||
|
||||
if (!in_array($module, $this->modules)) {
|
||||
$moduleEntries = $module->getEntries($this->code);
|
||||
$this->entries = array_merge($this->entries, $moduleEntries);
|
||||
$this->modules[] = $module;
|
||||
}
|
||||
}
|
||||
|
||||
public function translate(string $key): string {
|
||||
return $this->entries[$key] ?? $key;
|
||||
}
|
||||
|
||||
public function sendCookie(string $domain) {
|
||||
setcookie('lang', $this->code, 0, "/", $domain, false, false);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return array(
|
||||
'id' => $this->getId(),
|
||||
'code' => $this->code,
|
||||
'shortCode' => explode("_", $this->code)[0],
|
||||
'name' => $this->name,
|
||||
);
|
||||
}
|
||||
|
||||
public function activate() {
|
||||
global $LANGUAGE;
|
||||
$LANGUAGE = $this;
|
||||
}
|
||||
|
||||
public static function DEFAULT_LANGUAGE(bool $fromCookie = true): Language {
|
||||
if ($fromCookie && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
|
||||
$acceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
|
||||
$acceptedLanguages = explode(',', $acceptLanguage);
|
||||
foreach ($acceptedLanguages as $code) {
|
||||
if (strlen($code) == 2) {
|
||||
$code = $code . '_' . strtoupper($code);
|
||||
}
|
||||
|
||||
$code = str_replace("-", "_", $code);
|
||||
if (!preg_match(self::LANG_CODE_PATTERN, $code)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return new Language(0, $code, "");
|
||||
}
|
||||
}
|
||||
|
||||
return new Language(1, "en_US", "American English");
|
||||
}
|
||||
|
||||
public function getEntries(): array {
|
||||
return $this->entries;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
function L($key) {
|
||||
if (!array_key_exists('LANGUAGE', $GLOBALS))
|
||||
return $key;
|
||||
|
||||
global $LANGUAGE;
|
||||
return $LANGUAGE->translate($key);
|
||||
}
|
||||
}
|
||||
30
Core/Objects/DatabaseEntity/News.class.php
Normal file
30
Core/Objects/DatabaseEntity/News.class.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\API\Parameter\Parameter;
|
||||
use Core\Driver\SQL\Expression\CurrentTimeStamp;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
|
||||
class News extends DatabaseEntity {
|
||||
|
||||
public User $publishedBy;
|
||||
#[DefaultValue(CurrentTimeStamp::class)] private \DateTime $publishedAt;
|
||||
#[MaxLength(128)] public string $title;
|
||||
#[MaxLength(1024)] public string $text;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"publishedBy" => $this->publishedBy->jsonSerialize(),
|
||||
"publishedAt" => $this->publishedAt->format(Parameter::DATE_TIME_FORMAT),
|
||||
"title" => $this->title,
|
||||
"text" => $this->text
|
||||
];
|
||||
}
|
||||
}
|
||||
30
Core/Objects/DatabaseEntity/Notification.class.php
Normal file
30
Core/Objects/DatabaseEntity/Notification.class.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\API\Parameter\Parameter;
|
||||
use Core\Driver\SQL\Expression\CurrentTimeStamp;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Enum;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
|
||||
class Notification extends DatabaseEntity {
|
||||
|
||||
#[Enum('default', 'message', 'warning')] private string $type;
|
||||
#[DefaultValue(CurrentTimeStamp::class)] private \DateTime $createdAt;
|
||||
#[MaxLength(32)] public string $title;
|
||||
#[MaxLength(256)] public string $message;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"createdAt" => $this->createdAt->format(Parameter::DATE_TIME_FORMAT),
|
||||
"title" => $this->title,
|
||||
"message" => $this->message
|
||||
];
|
||||
}
|
||||
}
|
||||
128
Core/Objects/DatabaseEntity/Session.class.php
Normal file
128
Core/Objects/DatabaseEntity/Session.class.php
Normal file
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use DateTime;
|
||||
use Exception;
|
||||
use Firebase\JWT\JWT;
|
||||
use Core\Objects\Context;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Json;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Transient;
|
||||
|
||||
class Session extends DatabaseEntity {
|
||||
|
||||
# in minutes
|
||||
const DURATION = 60 * 60 * 24 * 14;
|
||||
#[Transient] private Context $context;
|
||||
|
||||
private User $user;
|
||||
private DateTime $expires;
|
||||
#[MaxLength(45)] private string $ipAddress;
|
||||
#[DefaultValue(true)] private bool $active;
|
||||
#[MaxLength(64)] private ?string $os;
|
||||
#[MaxLength(64)] private ?string $browser;
|
||||
#[DefaultValue(true)] public bool $stayLoggedIn;
|
||||
#[MaxLength(16)] private string $csrfToken;
|
||||
#[Json] private mixed $data;
|
||||
|
||||
public function __construct(Context $context, User $user, ?string $csrfToken = null) {
|
||||
parent::__construct();
|
||||
$this->context = $context;
|
||||
$this->user = $user;
|
||||
$this->stayLoggedIn = false;
|
||||
$this->csrfToken = $csrfToken ?? generateRandomString(16);
|
||||
$this->expires = (new DateTime())->modify(sprintf("+%d second", Session::DURATION));
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
public static function init(Context $context, int $userId, int $sessionId): ?Session {
|
||||
$session = Session::find($context->getSQL(), $sessionId, true, true);
|
||||
if (!$session || !$session->active || $session->user->getId() !== $userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$session->context = $context;
|
||||
return $session;
|
||||
}
|
||||
|
||||
public function getUser(): User {
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
private function updateMetaData() {
|
||||
$this->expires = (new \DateTime())->modify(sprintf("+%d minutes", Session::DURATION));
|
||||
$this->ipAddress = $this->context->isCLI() ? "127.0.0.1" : $_SERVER['REMOTE_ADDR'];
|
||||
try {
|
||||
$userAgent = @get_browser($_SERVER['HTTP_USER_AGENT'], true);
|
||||
$this->os = $userAgent['platform'] ?? "Unknown";
|
||||
$this->browser = $userAgent['parent'] ?? "Unknown";
|
||||
} catch (Exception $ex) {
|
||||
$this->os = "Unknown";
|
||||
$this->browser = "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
public function setData(array $data) {
|
||||
foreach ($data as $key => $value) {
|
||||
$_SESSION[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
public function getCookie(): string {
|
||||
$this->updateMetaData();
|
||||
$settings = $this->context->getSettings();
|
||||
$token = ['userId' => $this->user->getId(), 'sessionId' => $this->getId()];
|
||||
$jwtPublicKey = $settings->getJwtPublicKey();
|
||||
return JWT::encode($token, $jwtPublicKey->getKeyMaterial(), $jwtPublicKey->getAlgorithm());
|
||||
}
|
||||
|
||||
public function sendCookie(string $domain) {
|
||||
$sessionCookie = $this->getCookie();
|
||||
$secure = strcmp(getProtocol(), "https") === 0;
|
||||
setcookie('session', $sessionCookie, $this->getExpiresTime(), "/", $domain, $secure, true);
|
||||
}
|
||||
|
||||
public function getExpiresTime(): int {
|
||||
return ($this->stayLoggedIn ? $this->expires->getTimestamp() : 0);
|
||||
}
|
||||
|
||||
public function getExpiresSeconds(): int {
|
||||
return ($this->stayLoggedIn ? $this->expires->getTimestamp() - time() : -1);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return array(
|
||||
'id' => $this->getId(),
|
||||
'active' => $this->active,
|
||||
'expires' => $this->expires,
|
||||
'ipAddress' => $this->ipAddress,
|
||||
'os' => $this->os,
|
||||
'browser' => $this->browser,
|
||||
'csrf_token' => $this->csrfToken,
|
||||
'data' => $this->data,
|
||||
);
|
||||
}
|
||||
|
||||
public function destroy(): bool {
|
||||
session_destroy();
|
||||
$this->active = false;
|
||||
return $this->save($this->context->getSQL());
|
||||
}
|
||||
|
||||
public function update(): bool {
|
||||
$this->updateMetaData();
|
||||
|
||||
$this->expires = (new DateTime())->modify(sprintf("+%d second", Session::DURATION));
|
||||
$this->data = json_encode($_SESSION ?? []);
|
||||
|
||||
$sql = $this->context->getSQL();
|
||||
return $this->user->update($sql) &&
|
||||
$this->save($sql);
|
||||
}
|
||||
|
||||
public function getCsrfToken(): string {
|
||||
return $this->csrfToken;
|
||||
}
|
||||
}
|
||||
31
Core/Objects/DatabaseEntity/SystemLog.class.php
Normal file
31
Core/Objects/DatabaseEntity/SystemLog.class.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\API\Parameter\Parameter;
|
||||
use Core\Driver\SQL\Expression\CurrentTimeStamp;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Enum;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
|
||||
class SystemLog extends DatabaseEntity {
|
||||
|
||||
#[DefaultValue(CurrentTimeStamp::class)] private \DateTime $timestamp;
|
||||
private string $message;
|
||||
#[MaxLength(64)] #[DefaultValue('global')] private string $module;
|
||||
#[Enum('debug','info','warning','error','severe')] private string $severity;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"timestamp" => $this->timestamp->format(Parameter::DATE_TIME_FORMAT),
|
||||
"message" => $this->message,
|
||||
"module" => $this->module,
|
||||
"severity" => $this->severity
|
||||
];
|
||||
}
|
||||
}
|
||||
78
Core/Objects/DatabaseEntity/TwoFactorToken.class.php
Normal file
78
Core/Objects/DatabaseEntity/TwoFactorToken.class.php
Normal file
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\SQL\SQL;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Enum;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\TwoFactor\KeyBasedTwoFactorToken;
|
||||
use Core\Objects\TwoFactor\TimeBasedTwoFactorToken;
|
||||
|
||||
abstract class TwoFactorToken extends DatabaseEntity {
|
||||
|
||||
#[Enum('totp','fido')] private string $type;
|
||||
private bool $confirmed;
|
||||
private bool $authenticated;
|
||||
#[MaxLength(512)] private string $data;
|
||||
|
||||
public function __construct(string $type, ?int $id = null, bool $confirmed = false) {
|
||||
parent::__construct($id);
|
||||
$this->id = $id;
|
||||
$this->type = $type;
|
||||
$this->confirmed = $confirmed;
|
||||
$this->authenticated = $_SESSION["2faAuthenticated"] ?? false;
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
"id" => $this->getId(),
|
||||
"type" => $this->type,
|
||||
"confirmed" => $this->confirmed,
|
||||
"authenticated" => $this->authenticated,
|
||||
];
|
||||
}
|
||||
|
||||
public abstract function getData(): string;
|
||||
protected abstract function readData(string $data);
|
||||
|
||||
public function preInsert(array &$row) {
|
||||
$row["data"] = $this->getData();
|
||||
}
|
||||
|
||||
public function postFetch(SQL $sql, array $row) {
|
||||
parent::postFetch($sql, $row);
|
||||
$this->readData($row["data"]);
|
||||
}
|
||||
|
||||
public function authenticate() {
|
||||
$this->authenticated = true;
|
||||
$_SESSION["2faAuthenticated"] = true;
|
||||
}
|
||||
|
||||
public function getType(): string {
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
public function isConfirmed(): bool {
|
||||
return $this->confirmed;
|
||||
}
|
||||
|
||||
public function getId(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public static function newInstance(\ReflectionClass $reflectionClass, array $row) {
|
||||
if ($row["type"] === TimeBasedTwoFactorToken::TYPE) {
|
||||
return (new \ReflectionClass(TimeBasedTwoFactorToken::class))->newInstanceWithoutConstructor();
|
||||
} else if ($row["type"] === KeyBasedTwoFactorToken::TYPE) {
|
||||
return (new \ReflectionClass(KeyBasedTwoFactorToken::class))->newInstanceWithoutConstructor();
|
||||
} else {
|
||||
// TODO: error message
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function isAuthenticated(): bool {
|
||||
return $this->authenticated;
|
||||
}
|
||||
}
|
||||
109
Core/Objects/DatabaseEntity/User.class.php
Normal file
109
Core/Objects/DatabaseEntity/User.class.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace Core\Objects\DatabaseEntity;
|
||||
|
||||
use Core\Driver\SQL\Condition\Compare;
|
||||
use Core\Driver\SQL\Expression\CurrentTimeStamp;
|
||||
use Core\Driver\SQL\Join;
|
||||
use Core\Driver\SQL\SQL;
|
||||
use Core\Objects\DatabaseEntity\Attribute\DefaultValue;
|
||||
use Core\Objects\DatabaseEntity\Attribute\MaxLength;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Transient;
|
||||
use Core\Objects\DatabaseEntity\Attribute\Unique;
|
||||
|
||||
class User extends DatabaseEntity {
|
||||
|
||||
#[MaxLength(32)] #[Unique] public string $name;
|
||||
#[MaxLength(128)] public string $password;
|
||||
#[MaxLength(64)] public string $fullName;
|
||||
#[MaxLength(64)] #[Unique] public ?string $email;
|
||||
#[MaxLength(64)] private ?string $profilePicture;
|
||||
private ?\DateTime $lastOnline;
|
||||
#[DefaultValue(CurrentTimeStamp::class)] public \DateTime $registeredAt;
|
||||
public bool $confirmed;
|
||||
#[DefaultValue(1)] public Language $language;
|
||||
private ?GpgKey $gpgKey;
|
||||
private ?TwoFactorToken $twoFactorToken;
|
||||
|
||||
#[Transient] private array $groups;
|
||||
|
||||
public function __construct(?int $id = null) {
|
||||
parent::__construct($id);
|
||||
$this->groups = [];
|
||||
}
|
||||
|
||||
public function postFetch(SQL $sql, array $row) {
|
||||
parent::postFetch($sql, $row);
|
||||
$this->groups = [];
|
||||
|
||||
$groups = Group::findAllBuilder($sql)
|
||||
->fetchEntities()
|
||||
->addJoin(new Join("INNER", "UserGroup", "UserGroup.group_id", "Group.id"))
|
||||
->where(new Compare("UserGroup.user_id", $this->id))
|
||||
->execute();
|
||||
|
||||
if ($groups) {
|
||||
$this->groups = $groups;
|
||||
}
|
||||
}
|
||||
|
||||
public function getUsername(): string {
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function getFullName(): string {
|
||||
return $this->fullName;
|
||||
}
|
||||
|
||||
public function getEmail(): ?string {
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function getGroups(): array {
|
||||
return $this->groups;
|
||||
}
|
||||
|
||||
public function hasGroup(int $group): bool {
|
||||
return isset($this->groups[$group]);
|
||||
}
|
||||
|
||||
public function getGPG(): ?GpgKey {
|
||||
return $this->gpgKey;
|
||||
}
|
||||
|
||||
public function getTwoFactorToken(): ?TwoFactorToken {
|
||||
return $this->twoFactorToken;
|
||||
}
|
||||
|
||||
public function getProfilePicture(): ?string {
|
||||
return $this->profilePicture;
|
||||
}
|
||||
|
||||
public function __debugInfo(): array {
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'username' => $this->name,
|
||||
'language' => $this->language->getName(),
|
||||
];
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array {
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'name' => $this->name,
|
||||
'fullName' => $this->fullName,
|
||||
'profilePicture' => $this->profilePicture,
|
||||
'email' => $this->email,
|
||||
'groups' => $this->groups ?? null,
|
||||
'language' => (isset($this->language) ? $this->language->jsonSerialize() : null),
|
||||
'session' => (isset($this->session) ? $this->session->jsonSerialize() : null),
|
||||
"gpg" => (isset($this->gpgKey) ? $this->gpgKey->jsonSerialize() : null),
|
||||
"2fa" => (isset($this->twoFactorToken) ? $this->twoFactorToken->jsonSerialize() : null),
|
||||
];
|
||||
}
|
||||
|
||||
public function update(SQL $sql): bool {
|
||||
$this->lastOnline = new \DateTime();
|
||||
return $this->save($sql, ["last_online", "language_id"]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user