code cleanup

This commit is contained in:
Roman 2021-04-02 21:58:06 +02:00
parent 4a52ab2fd7
commit eea0aeacc6
67 changed files with 472 additions and 425 deletions

@ -44,7 +44,7 @@ namespace Api\ApiKey {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
@ -81,7 +81,7 @@ namespace Api\ApiKey {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -127,7 +127,7 @@ namespace Api\ApiKey {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -162,7 +162,7 @@ namespace Api\ApiKey {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -34,7 +34,7 @@ namespace Api\Contact {
parent::__construct($user, $externalCall, $parameters); parent::__construct($user, $externalCall, $parameters);
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -238,7 +238,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -292,7 +292,7 @@ namespace Api\File {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -316,7 +316,7 @@ namespace Api\File {
$this->csrfTokenRequired = true; $this->csrfTokenRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -360,7 +360,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -407,7 +407,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -450,7 +450,7 @@ namespace Api\File {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -482,7 +482,7 @@ namespace Api\File {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -551,7 +551,7 @@ namespace Api\File {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -653,7 +653,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -826,7 +826,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -891,7 +891,7 @@ namespace Api\File {
$this->csrfTokenRequired = true; $this->csrfTokenRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -946,7 +946,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -1017,7 +1017,7 @@ namespace Api\File {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -54,7 +54,7 @@ namespace Api\Groups {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -116,7 +116,7 @@ namespace Api\Groups {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -162,7 +162,7 @@ namespace Api\Groups {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -23,7 +23,7 @@ namespace Api\Language {
parent::__construct($user, $externalCall, array()); parent::__construct($user, $externalCall, array());
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -108,7 +108,7 @@ namespace Api\Language {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -24,7 +24,7 @@ namespace Api\Mail {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -77,7 +77,7 @@ namespace Api\Mail {
return null; return null;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -107,7 +107,7 @@ namespace Api\Notifications {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -213,7 +213,7 @@ namespace Api\Notifications {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -235,7 +235,7 @@ namespace Api\Notifications {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -8,14 +8,22 @@ class ArrayType extends Parameter {
public int $elementType; public int $elementType;
public int $canBeOne; public int $canBeOne;
public function __construct($name, $elementType = Parameter::TYPE_MIXED, $canBeOne=false, $optional = FALSE, $defaultValue = NULL) { /**
* ArrayType constructor.
* @param string $name the name of the parameter
* @param int $elementType element type inside the array, for example, allow only integer values (Parameter::TYPE_INT)
* @param bool $canBeOne true, if a single element can be passed inside the request (e.g. array=1 instead of array[]=1). Will be automatically casted to an array
* @param bool $optional true if the parameter is optional
* @param array|null $defaultValue the default value to use, if the parameter is not given
*/
public function __construct(string $name, int $elementType = Parameter::TYPE_MIXED, bool $canBeOne = false, bool $optional = FALSE, ?array $defaultValue = NULL) {
$this->elementType = $elementType; $this->elementType = $elementType;
$this->elementParameter = new Parameter('', $elementType); $this->elementParameter = new Parameter('', $elementType);
$this->canBeOne = $canBeOne; $this->canBeOne = $canBeOne;
parent::__construct($name, Parameter::TYPE_ARRAY, $optional, $defaultValue); parent::__construct($name, Parameter::TYPE_ARRAY, $optional, $defaultValue);
} }
public function parseParam($value) { public function parseParam($value): bool {
if(!is_array($value)) { if(!is_array($value)) {
if (!$this->canBeOne) { if (!$this->canBeOne) {
return false; return false;
@ -38,12 +46,12 @@ class ArrayType extends Parameter {
return true; return true;
} }
public function getTypeName() { public function getTypeName(): string {
$elementType = $this->elementParameter->getTypeName(); $elementType = $this->elementParameter->getTypeName();
return parent::getTypeName() . "($elementType)"; return parent::getTypeName() . "($elementType)";
} }
public function toString() { public function toString(): string {
$typeName = $this->getTypeName(); $typeName = $this->getTypeName();
$str = "$typeName $this->name"; $str = "$typeName $this->name";
$defaultValue = (is_null($this->value) ? 'NULL' : (is_array($this->value) ? '[' . implode(",", $this->value) . ']' : $this->value)); $defaultValue = (is_null($this->value) ? 'NULL' : (is_array($this->value) ? '[' . implode(",", $this->value) . ']' : $this->value));

@ -26,11 +26,11 @@ class Parameter {
public string $name; public string $name;
public $value; public $value;
public $optional; public bool $optional;
public int $type; public int $type;
public string $typeName; public string $typeName;
public function __construct($name, $type, $optional = FALSE, $defaultValue = NULL) { public function __construct(string $name, int $type, bool $optional = FALSE, $defaultValue = NULL) {
$this->name = $name; $this->name = $name;
$this->optional = $optional; $this->optional = $optional;
$this->value = $defaultValue; $this->value = $defaultValue;
@ -38,11 +38,11 @@ class Parameter {
$this->typeName = $this->getTypeName(); $this->typeName = $this->getTypeName();
} }
public function getTypeName() { public function getTypeName(): string {
return ($this->type >= 0 && $this->type < count(Parameter::names)) ? Parameter::names[$this->type] : "INVALID"; return ($this->type >= 0 && $this->type < count(Parameter::names)) ? Parameter::names[$this->type] : "INVALID";
} }
public function toString() { public function toString(): string {
$typeName = Parameter::names[$this->type]; $typeName = Parameter::names[$this->type];
$str = "$typeName $this->name"; $str = "$typeName $this->name";
@ -54,7 +54,7 @@ class Parameter {
return $str; return $str;
} }
public static function parseType($value) { public static function parseType($value): int {
if(is_array($value)) if(is_array($value))
return Parameter::TYPE_ARRAY; return Parameter::TYPE_ARRAY;
else if(is_numeric($value) && intval($value) == $value) else if(is_numeric($value) && intval($value) == $value)
@ -77,7 +77,7 @@ class Parameter {
return Parameter::TYPE_STRING; return Parameter::TYPE_STRING;
} }
public function parseParam($value) { public function parseParam($value): bool {
switch($this->type) { switch($this->type) {
case Parameter::TYPE_INT: case Parameter::TYPE_INT:
if(is_numeric($value) && intval($value) == $value) { if(is_numeric($value) && intval($value) == $value) {

@ -5,12 +5,12 @@ namespace Api\Parameter;
class StringType extends Parameter { class StringType extends Parameter {
public int $maxLength; public int $maxLength;
public function __construct($name, $maxLength = -1, $optional = FALSE, $defaultValue = NULL) { public function __construct(string $name, int $maxLength = -1, bool $optional = FALSE, ?string $defaultValue = NULL) {
$this->maxLength = $maxLength; $this->maxLength = $maxLength;
parent::__construct($name, Parameter::TYPE_STRING, $optional, $defaultValue); parent::__construct($name, Parameter::TYPE_STRING, $optional, $defaultValue);
} }
public function parseParam($value) { public function parseParam($value): bool {
if(!is_string($value)) { if(!is_string($value)) {
return false; return false;
} }
@ -23,12 +23,12 @@ class StringType extends Parameter {
return true; return true;
} }
public function getTypeName() { public function getTypeName(): string {
$maxLength = ($this->maxLength > 0 ? "($this->maxLength)" : ""); $maxLength = ($this->maxLength > 0 ? "($this->maxLength)" : "");
return parent::getTypeName() . $maxLength; return parent::getTypeName() . $maxLength;
} }
public function toString() { public function toString(): string {
$typeName = $this->getTypeName(); $typeName = $this->getTypeName();
$str = "$typeName $this->name"; $str = "$typeName $this->name";
$defaultValue = (is_null($this->value) ? 'NULL' : $this->value); $defaultValue = (is_null($this->value) ? 'NULL' : $this->value);

@ -16,7 +16,7 @@ class PatchSQL extends Request {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -35,7 +35,7 @@ namespace Api\Permission {
$this->isPublic = false; $this->isPublic = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -102,7 +102,7 @@ namespace Api\Permission {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -147,7 +147,7 @@ namespace Api\Permission {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -45,29 +45,30 @@ class Request {
} }
} }
public function parseParams($values) { public function parseParams($values): bool {
foreach($this->params as $name => $param) { foreach ($this->params as $name => $param) {
$value = $values[$name] ?? NULL; $value = $values[$name] ?? NULL;
$isEmpty = (is_string($value) && strlen($value) === 0) || (is_array($value) && empty($value)); $isEmpty = (is_string($value) && strlen($value) === 0) || (is_array($value) && empty($value));
if(!$param->optional && (is_null($value) || $isEmpty)) { if (!$param->optional && (is_null($value) || $isEmpty)) {
return $this->createError("Missing parameter: $name"); return $this->createError("Missing parameter: $name");
} }
if(!is_null($value) && !$isEmpty) { if (!is_null($value) && !$isEmpty) {
if(!$param->parseParam($value)) { if (!$param->parseParam($value)) {
$value = print_r($value, true); $value = print_r($value, true);
return $this->createError("Invalid Type for parameter: $name '$value' (Required: " . $param->getTypeName() . ")"); return $this->createError("Invalid Type for parameter: $name '$value' (Required: " . $param->getTypeName() . ")");
} }
} }
} }
return true; return true;
} }
public function parseVariableParams($values) { public function parseVariableParams($values) {
foreach($values as $name => $value) { foreach ($values as $name => $value) {
if(isset($this->params[$name])) continue; if (isset($this->params[$name])) continue;
$type = Parameter\Parameter::parseType($value); $type = Parameter\Parameter::parseType($value);
$param = new Parameter\Parameter($name, $type, true); $param = new Parameter\Parameter($name, $type, true);
$param->parseParam($value); $param->parseParam($value);
@ -75,19 +76,19 @@ class Request {
} }
} }
public function execute($values = array()) { public function execute($values = array()): bool {
$this->params = $this->aDefaultParams; $this->params = $this->aDefaultParams;
$this->success = false; $this->success = false;
$this->result = array(); $this->result = array();
$this->lastError = ''; $this->lastError = '';
if($this->user->isLoggedIn()) { if ($this->user->isLoggedIn()) {
$this->result['logoutIn'] = $this->user->getSession()->getExpiresSeconds(); $this->result['logoutIn'] = $this->user->getSession()->getExpiresSeconds();
} }
if($this->externalCall) { if ($this->externalCall) {
$values = $_REQUEST; $values = $_REQUEST;
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER["CONTENT_TYPE"]) && in_array("application/json", explode(";", $_SERVER["CONTENT_TYPE"]))) { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER["CONTENT_TYPE"]) && in_array("application/json", explode(";", $_SERVER["CONTENT_TYPE"]))) {
$jsonData = json_decode(file_get_contents('php://input'), true); $jsonData = json_decode(file_get_contents('php://input'), true);
if ($jsonData) { if ($jsonData) {
$values = array_merge($values, $jsonData); $values = array_merge($values, $jsonData);
@ -99,34 +100,34 @@ class Request {
} }
} }
if($this->isDisabled) { if ($this->isDisabled) {
$this->lastError = "This function is currently disabled."; $this->lastError = "This function is currently disabled.";
return false; return false;
} }
if($this->externalCall && !$this->isPublic) { if ($this->externalCall && !$this->isPublic) {
$this->lastError = 'This function is private.'; $this->lastError = 'This function is private.';
header('HTTP 1.1 403 Forbidden'); header('HTTP 1.1 403 Forbidden');
return false; return false;
} }
if(!in_array($_SERVER['REQUEST_METHOD'], $this->allowedMethods)) { if (!in_array($_SERVER['REQUEST_METHOD'], $this->allowedMethods)) {
$this->lastError = 'This method is not allowed'; $this->lastError = 'This method is not allowed';
header('HTTP 1.1 405 Method Not Allowed'); header('HTTP 1.1 405 Method Not Allowed');
return false; return false;
} }
if($this->externalCall) { if ($this->externalCall) {
$apiKeyAuthorized = false; $apiKeyAuthorized = false;
// Logged in or api key authorized? // Logged in or api key authorized?
if ($this->loginRequired) { if ($this->loginRequired) {
if(isset($values['api_key']) && $this->apiKeyAllowed) { if (isset($values['api_key']) && $this->apiKeyAllowed) {
$apiKey = $values['api_key']; $apiKey = $values['api_key'];
$apiKeyAuthorized = $this->user->authorize($apiKey); $apiKeyAuthorized = $this->user->authorize($apiKey);
} }
if(!$this->user->isLoggedIn() && !$apiKeyAuthorized) { if (!$this->user->isLoggedIn() && !$apiKeyAuthorized) {
$this->lastError = 'You are not logged in.'; $this->lastError = 'You are not logged in.';
header('HTTP 1.1 401 Unauthorized'); header('HTTP 1.1 401 Unauthorized');
return false; return false;
@ -134,7 +135,7 @@ class Request {
} }
// CSRF Token // CSRF Token
if($this->csrfTokenRequired && $this->user->isLoggedIn()) { if ($this->csrfTokenRequired && $this->user->isLoggedIn()) {
// csrf token required + external call // csrf token required + external call
// if it's not a call with API_KEY, check for csrf_token // if it's not a call with API_KEY, check for csrf_token
if (!isset($values["csrf_token"]) || strcmp($values["csrf_token"], $this->user->getSession()->getCsrfToken()) !== 0) { if (!isset($values["csrf_token"]) || strcmp($values["csrf_token"], $this->user->getSession()->getCsrfToken()) !== 0) {
@ -155,13 +156,15 @@ class Request {
} }
} }
if(!$this->parseParams($values)) if (!$this->parseParams($values)) {
return false; return false;
}
if($this->variableParamCount) if ($this->variableParamCount) {
$this->parseVariableParams($values); $this->parseVariableParams($values);
}
if(!$this->user->getSQL()->isConnected()) { if (!$this->user->getSQL()->isConnected()) {
$this->lastError = $this->user->getSQL()->getLastError(); $this->lastError = $this->user->getSQL()->getLastError();
return false; return false;
} }
@ -171,23 +174,39 @@ class Request {
return true; return true;
} }
protected function createError($err) { protected function createError($err): bool {
$this->success = false; $this->success = false;
$this->lastError = $err; $this->lastError = $err;
return false; return false;
} }
protected function getParam($name) { protected function getParam($name) {
return isset($this->params[$name]) ? $this->params[$name]->value : NULL; return $this->params[$name] ?? NULL;
} }
public function isPublic() { return $this->isPublic; } public function isPublic(): bool {
public function getLastError() { return $this->lastError; } return $this->isPublic;
public function getResult() { return $this->result; } }
public function success() { return $this->success; }
public function loginRequired() { return $this->loginRequired; } public function getLastError(): string {
public function isExternalCall() { return $this->externalCall; } return $this->lastError;
public function clearError() { $this->success = true; $this->lastError = ""; } }
public function getResult(): array {
return $this->result;
}
public function success(): bool {
return $this->success;
}
public function loginRequired(): bool {
return $this->loginRequired;
}
public function isExternalCall(): bool {
return $this->externalCall;
}
private function getMethod() { private function getMethod() {
$class = str_replace("\\", "/", get_class($this)); $class = str_replace("\\", "/", get_class($this));
@ -195,7 +214,7 @@ class Request {
return $class; return $class;
} }
public function getJsonResult() { public function getJsonResult(): string {
$this->result['success'] = $this->success; $this->result['success'] = $this->success;
$this->result['msg'] = $this->lastError; $this->result['msg'] = $this->lastError;
return json_encode($this->result); return json_encode($this->result);

@ -34,7 +34,7 @@ namespace Api\Routes {
parent::__construct($user, $externalCall, array()); parent::__construct($user, $externalCall, array());
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -81,7 +81,7 @@ namespace Api\Routes {
$this->isPublic = false; $this->isPublic = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -133,7 +133,7 @@ namespace Api\Routes {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -29,7 +29,7 @@ namespace Api\Settings {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }
@ -72,7 +72,7 @@ namespace Api\Settings {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -66,7 +66,7 @@ class Stats extends Request {
return ($this->success ? $res[0]["count"] : $this->success); return ($this->success ? $res[0]["count"] : $this->success);
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -9,11 +9,11 @@ namespace Api {
protected function userExists(?string $username, ?string $email) { protected function userExists(?string $username, ?string $email) {
$conditions = array(); $conditions = array();
if (!is_null($username) && !empty($username)) { if ($username) {
$conditions[] = new Compare("User.name", $username); $conditions[] = new Compare("User.name", $username);
} }
if (!is_null($email) && !empty($email)) { if ($email) {
$conditions[] = new Compare("User.email", $email); $conditions[] = new Compare("User.email", $email);
} }
@ -152,7 +152,7 @@ namespace Api\User {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -229,7 +229,7 @@ namespace Api\User {
return false; return false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -306,7 +306,7 @@ namespace Api\User {
)); ));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -350,7 +350,7 @@ namespace Api\User {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -377,7 +377,7 @@ namespace Api\User {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -469,7 +469,7 @@ namespace Api\User {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -533,7 +533,7 @@ namespace Api\User {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -586,7 +586,7 @@ namespace Api\User {
return $this->createError(L('Wrong username or password')); return $this->createError(L('Wrong username or password'));
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -648,7 +648,7 @@ namespace Api\User {
$this->apiKeyAllowed = false; $this->apiKeyAllowed = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -693,7 +693,7 @@ namespace Api\User {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -804,7 +804,7 @@ namespace Api\User {
return array(); return array();
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -847,7 +847,7 @@ namespace Api\User {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -945,7 +945,7 @@ namespace Api\User {
$this->loginRequired = true; $this->loginRequired = true;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -986,7 +986,7 @@ namespace Api\User {
$this->csrfTokenRequired = false; $this->csrfTokenRequired = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -1105,7 +1105,7 @@ namespace Api\User {
return $this->success; return $this->success;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -16,7 +16,7 @@ class VerifyCaptcha extends Request {
$this->isPublic = false; $this->isPublic = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if(!parent::execute($values)) { if(!parent::execute($values)) {
return false; return false;
} }

@ -27,7 +27,7 @@ namespace Api\Visitors {
$this->isPublic = false; $this->isPublic = false;
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }
@ -75,7 +75,7 @@ namespace Api\Visitors {
} }
} }
public function execute($values = array()) { public function execute($values = array()): bool {
if (!parent::execute($values)) { if (!parent::execute($values)) {
return false; return false;
} }

@ -15,27 +15,27 @@ class Configuration {
$class = \Configuration\Database::class; $class = \Configuration\Database::class;
$path = getClassPath($class, true); $path = getClassPath($class, true);
if(file_exists($path) && is_readable($path)) { if (file_exists($path) && is_readable($path)) {
include_once $path; include_once $path;
if(class_exists($class)) { if (class_exists($class)) {
$this->database = new \Configuration\Database(); $this->database = new \Configuration\Database();
} }
} }
} }
public function getDatabase() : ?ConnectionData { public function getDatabase(): ?ConnectionData {
return $this->database; return $this->database;
} }
public function getSettings() : Settings { public function getSettings(): Settings {
return $this->settings; return $this->settings;
} }
public function create(string $className, $data) { public function create(string $className, $data) {
$path = getClassPath("\\Configuration\\$className"); $path = getClassPath("\\Configuration\\$className");
if($data) { if ($data) {
if(is_string($data)) { if (is_string($data)) {
$key = addslashes($data); $key = addslashes($data);
$code = intendCode( $code = intendCode(
"<?php "<?php
@ -50,7 +50,7 @@ class Configuration {
}", false }", false
); );
} else if($data instanceof ConnectionData) { } else if ($data instanceof ConnectionData) {
$superClass = get_class($data); $superClass = get_class($data);
$host = addslashes($data->getHost()); $host = addslashes($data->getHost());
$port = intval($data->getPort()); $port = intval($data->getPort());
@ -58,7 +58,7 @@ class Configuration {
$password = addslashes($data->getPassword()); $password = addslashes($data->getPassword());
$properties = ""; $properties = "";
foreach($data->getProperties() as $key => $val) { foreach ($data->getProperties() as $key => $val) {
$key = addslashes($key); $key = addslashes($key);
$val = is_string($val) ? "'" . addslashes($val) . "'" : $val; $val = is_string($val) ? "'" . addslashes($val) . "'" : $val;
$properties .= "\n\$this->setProperty('$key', $val);"; $properties .= "\n\$this->setProperty('$key', $val);";
@ -86,9 +86,9 @@ class Configuration {
return @file_put_contents($path, $code); return @file_put_contents($path, $code);
} }
public function delete(string $className) { public function delete(string $className): bool {
$path = getClassPath("\\Configuration\\$className"); $path = getClassPath("\\Configuration\\$className");
if(file_exists($path)) { if (file_exists($path)) {
return unlink($path); return unlink($path);
} }

@ -11,7 +11,7 @@ class CreateDatabase extends DatabaseScript {
// NOTE: // NOTE:
// explicit serial ids removed due to postgres' serial implementation // explicit serial ids removed due to postgres' serial implementation
public static function createQueries(SQL $sql) { public static function createQueries(SQL $sql): array {
$queries = array(); $queries = array();
// Language // Language
@ -24,8 +24,8 @@ class CreateDatabase extends DatabaseScript {
->unique("name"); ->unique("name");
$queries[] = $sql->insert("Language", array("code", "name")) $queries[] = $sql->insert("Language", array("code", "name"))
->addRow( "en_US", 'American English') ->addRow("en_US", 'American English')
->addRow( "de_DE", 'Deutsch Standard'); ->addRow("de_DE", 'Deutsch Standard');
$queries[] = $sql->createTable("User") $queries[] = $sql->createTable("User")
->addSerial("uid") ->addSerial("uid")
@ -50,7 +50,7 @@ class CreateDatabase extends DatabaseScript {
->addString("browser", 64) ->addString("browser", 64)
->addJson("data", false, '{}') ->addJson("data", false, '{}')
->addBool("stay_logged_in", true) ->addBool("stay_logged_in", true)
->addString("csrf_token", 16 ) ->addString("csrf_token", 16)
->primaryKey("uid", "user_id") ->primaryKey("uid", "user_id")
->foreignKey("user_id", "User", "uid", new CascadeStrategy()); ->foreignKey("user_id", "User", "uid", new CascadeStrategy());
@ -82,7 +82,7 @@ class CreateDatabase extends DatabaseScript {
$queries[] = $sql->createTable("Notification") $queries[] = $sql->createTable("Notification")
->addSerial("uid") ->addSerial("uid")
->addEnum("type", array("default","message","warning"), false, "default") ->addEnum("type", array("default", "message", "warning"), false, "default")
->addDateTime("created_at", false, $sql->currentTimestamp()) ->addDateTime("created_at", false, $sql->currentTimestamp())
->addString("title", 32) ->addString("title", 32)
->addString("message", 256) ->addString("message", 256)
@ -200,7 +200,7 @@ class CreateDatabase extends DatabaseScript {
return $queries; return $queries;
} }
private static function MessageConfirmEmail() : string { private static function MessageConfirmEmail(): string {
return "Hello {{username}},<br>" . return "Hello {{username}},<br>" .
"You recently created an account on {{site_name}}. Please click on the following link to " . "You recently created an account on {{site_name}}. Please click on the following link to " .
"confirm your email address and complete your registration. If you haven't registered an " . "confirm your email address and complete your registration. If you haven't registered an " .
@ -210,7 +210,7 @@ class CreateDatabase extends DatabaseScript {
"{{site_name}} Administration"; "{{site_name}} Administration";
} }
private static function MessageAcceptInvite() : string { private static function MessageAcceptInvite(): string {
return "Hello {{username}},<br>" . return "Hello {{username}},<br>" .
"You were invited to create an account on {{site_name}}. Please click on the following link to " . "You were invited to create an account on {{site_name}}. Please click on the following link to " .
"confirm your email address and complete your registration by choosing a new password. " . "confirm your email address and complete your registration by choosing a new password. " .
@ -220,7 +220,7 @@ class CreateDatabase extends DatabaseScript {
"{{site_name}} Administration"; "{{site_name}} Administration";
} }
private static function MessageResetPassword() : string { private static function MessageResetPassword(): string {
return "Hello {{username}},<br>" . return "Hello {{username}},<br>" .
"you requested a password reset on {{site_name}}. Please click on the following link to " . "you requested a password reset on {{site_name}}. Please click on the following link to " .
"choose a new password. If this request was not intended, you can simply ignore the email. The Link is valid for one hour:<br><br>" . "choose a new password. If this request was not intended, you can simply ignore the email. The Link is valid for one hour:<br><br>" .
@ -233,7 +233,7 @@ class CreateDatabase extends DatabaseScript {
$patchDirectory = './core/Configuration/Patch/'; $patchDirectory = './core/Configuration/Patch/';
if (file_exists($patchDirectory) && is_dir($patchDirectory)) { if (file_exists($patchDirectory) && is_dir($patchDirectory)) {
$scan_arr = scandir($patchDirectory); $scan_arr = scandir($patchDirectory);
$files_arr = array_diff($scan_arr, array('.','..')); $files_arr = array_diff($scan_arr, array('.', '..'));
foreach ($files_arr as $file) { foreach ($files_arr as $file) {
$suffix = ".class.php"; $suffix = ".class.php";
if (endsWith($file, $suffix)) { if (endsWith($file, $suffix)) {
@ -241,7 +241,7 @@ class CreateDatabase extends DatabaseScript {
$className = "\\Configuration\\Patch\\$className"; $className = "\\Configuration\\Patch\\$className";
$method = "$className::createQueries"; $method = "$className::createQueries";
$patchQueries = call_user_func($method, $sql); $patchQueries = call_user_func($method, $sql);
foreach($patchQueries as $query) $queries[] = $query; foreach ($patchQueries as $query) $queries[] = $query;
} }
} }
} }

@ -10,7 +10,7 @@ use Driver\SQL\Strategy\UpdateStrategy;
class file_api extends DatabaseScript { class file_api extends DatabaseScript {
public static function createQueries(SQL $sql) { public static function createQueries(SQL $sql): array {
$queries = array(); $queries = array();

@ -11,12 +11,16 @@ use Objects\User;
class Settings { class Settings {
//
private bool $installationComplete;
// settings
private string $siteName; private string $siteName;
private string $baseUrl; private string $baseUrl;
private string $jwtSecret; private string $jwtSecret;
private bool $installationComplete;
private bool $registrationAllowed; private bool $registrationAllowed;
private bool $recaptchaEnabled; private bool $recaptchaEnabled;
private bool $mailEnabled;
private string $recaptchaPublicKey; private string $recaptchaPublicKey;
private string $recaptchaPrivateKey; private string $recaptchaPrivateKey;
@ -24,11 +28,11 @@ class Settings {
return $this->jwtSecret; return $this->jwtSecret;
} }
public function isInstalled() { public function isInstalled(): bool {
return $this->installationComplete; return $this->installationComplete;
} }
public static function loadDefaults() : Settings { public static function loadDefaults(): Settings {
$hostname = $_SERVER["SERVER_NAME"]; $hostname = $_SERVER["SERVER_NAME"];
$protocol = getProtocol(); $protocol = getProtocol();
$jwt = generateRandomString(32); $jwt = generateRandomString(32);
@ -42,10 +46,11 @@ class Settings {
$settings->recaptchaPublicKey = ""; $settings->recaptchaPublicKey = "";
$settings->recaptchaPrivateKey = ""; $settings->recaptchaPrivateKey = "";
$settings->recaptchaEnabled = false; $settings->recaptchaEnabled = false;
$settings->mailEnabled = false;
return $settings; return $settings;
} }
public function loadFromDatabase(User $user) { public function loadFromDatabase(User $user): bool {
$req = new \Api\Settings\Get($user); $req = new \Api\Settings\Get($user);
$success = $req->execute(); $success = $req->execute();
@ -58,6 +63,7 @@ class Settings {
$this->recaptchaEnabled = $result["recaptcha_enabled"] ?? $this->recaptchaEnabled; $this->recaptchaEnabled = $result["recaptcha_enabled"] ?? $this->recaptchaEnabled;
$this->recaptchaPublicKey = $result["recaptcha_public_key"] ?? $this->recaptchaPublicKey; $this->recaptchaPublicKey = $result["recaptcha_public_key"] ?? $this->recaptchaPublicKey;
$this->recaptchaPrivateKey = $result["recaptcha_private_key"] ?? $this->recaptchaPrivateKey; $this->recaptchaPrivateKey = $result["recaptcha_private_key"] ?? $this->recaptchaPrivateKey;
$this->mailEnabled = $result["mail_enabled"] ?? $this->mailEnabled;
if (!isset($result["jwt_secret"])) { if (!isset($result["jwt_secret"])) {
$req = new \Api\Settings\Set($user); $req = new \Api\Settings\Set($user);
@ -81,27 +87,27 @@ class Settings {
->addRow("recaptcha_private_key", $this->recaptchaPrivateKey, true, false); ->addRow("recaptcha_private_key", $this->recaptchaPrivateKey, true, false);
} }
public function getSiteName() : string { public function getSiteName(): string {
return $this->siteName; return $this->siteName;
} }
public function getBaseUrl() : string { public function getBaseUrl(): string {
return $this->baseUrl; return $this->baseUrl;
} }
public function isRecaptchaEnabled() : bool { public function isRecaptchaEnabled(): bool {
return $this->recaptchaEnabled; return $this->recaptchaEnabled;
} }
public function getRecaptchaSiteKey() : string { public function getRecaptchaSiteKey(): string {
return $this->recaptchaPublicKey; return $this->recaptchaPublicKey;
} }
public function getRecaptchaSecretKey() : string { public function getRecaptchaSecretKey(): string {
return $this->recaptchaPrivateKey; return $this->recaptchaPrivateKey;
} }
public function isRegistrationAllowed() : bool { public function isRegistrationAllowed(): bool {
return $this->registrationAllowed; return $this->registrationAllowed;
} }
} }

@ -34,7 +34,7 @@ namespace Documents\Account {
$this->loadFontawesome(); $this->loadFontawesome();
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'), array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'),
array('name' => 'format-detection', 'content' => 'telephone=yes'), array('name' => 'format-detection', 'content' => 'telephone=yes'),
@ -44,11 +44,11 @@ namespace Documents\Account {
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return "Account"; return "Account";
} }
} }
@ -59,7 +59,7 @@ namespace Documents\Account {
parent::__construct($document); parent::__construct($document);
} }
protected function getContent() { protected function getContent(): string {
$view = $this->getDocument()->getView(); $view = $this->getDocument()->getView();
if ($view === null) { if ($view === null) {

@ -19,8 +19,6 @@ namespace Documents {
namespace Documents\Admin { namespace Documents\Admin {
use Elements\Head; use Elements\Head;
use Elements\Link;
use Elements\Script;
class AdminHead extends Head { class AdminHead extends Head {
@ -32,7 +30,7 @@ namespace Documents\Admin {
$this->loadFontawesome(); $this->loadFontawesome();
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'), array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'),
array('name' => 'format-detection', 'content' => 'telephone=yes'), array('name' => 'format-detection', 'content' => 'telephone=yes'),
@ -42,12 +40,12 @@ namespace Documents\Admin {
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return "WebBase - Administration"; return $this->getSiteName() . " - Administration";
} }
} }
} }

@ -15,7 +15,6 @@ namespace Documents {
namespace Documents\Document404 { namespace Documents\Document404 {
use Elements\Body;
use Elements\Head; use Elements\Head;
use Elements\SimpleBody; use Elements\SimpleBody;
use Views\View404; use Views\View404;
@ -29,7 +28,7 @@ namespace Documents\Document404 {
protected function initSources() { protected function initSources() {
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'), array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'),
array('name' => 'format-detection', 'content' => 'telephone=yes'), array('name' => 'format-detection', 'content' => 'telephone=yes'),
@ -39,11 +38,11 @@ namespace Documents\Document404 {
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return "WebBase - Not Found"; return "WebBase - Not Found";
} }
} }
@ -58,7 +57,7 @@ namespace Documents\Document404 {
http_response_code(404); http_response_code(404);
} }
protected function getContent() { protected function getContent(): string {
return $this->load(View404::class); return $this->load(View404::class);
} }
} }

@ -28,7 +28,7 @@ namespace Documents\Files {
$this->loadFontawesome(); $this->loadFontawesome();
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'), array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'),
array('name' => 'format-detection', 'content' => 'telephone=yes'), array('name' => 'format-detection', 'content' => 'telephone=yes'),
@ -39,11 +39,11 @@ namespace Documents\Files {
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return "File Control Panel"; return "File Control Panel";
} }
} }
@ -54,7 +54,7 @@ namespace Documents\Files {
parent::__construct($document); parent::__construct($document);
} }
protected function getContent() { protected function getContent(): string {
$html = "<noscript>" . $this->createErrorText("Javascript is required for this site to render.") . "</noscript>"; $html = "<noscript>" . $this->createErrorText("Javascript is required for this site to render.") . "</noscript>";
$html .= "<div id=\"root\"></div>"; $html .= "<div id=\"root\"></div>";
$html .= new Script(Script::MIME_TEXT_JAVASCRIPT, Script::FILES); $html .= new Script(Script::MIME_TEXT_JAVASCRIPT, Script::FILES);

@ -41,7 +41,7 @@ namespace Documents\Install {
$this->addJS(Script::INSTALL); $this->addJS(Script::INSTALL);
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'), array('name' => 'viewport', 'content' => 'width=device-width, initial-scale=1.0'),
array('name' => 'format-detection', 'content' => 'telephone=yes'), array('name' => 'format-detection', 'content' => 'telephone=yes'),
@ -51,11 +51,11 @@ namespace Documents\Install {
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return "WebBase - Installation"; return "WebBase - Installation";
} }
@ -88,17 +88,17 @@ namespace Documents\Install {
$this->steps = array(); $this->steps = array();
} }
private function getParameter($name) { private function getParameter($name): ?string {
if(isset($_REQUEST[$name]) && is_string($_REQUEST[$name])) { if (isset($_REQUEST[$name]) && is_string($_REQUEST[$name])) {
return trim($_REQUEST[$name]); return trim($_REQUEST[$name]);
} }
return NULL; return NULL;
} }
private function getCurrentStep() { private function getCurrentStep(): int {
if(!$this->checkRequirements()["success"]) { if (!$this->checkRequirements()["success"]) {
return self::CHECKING_REQUIREMENTS; return self::CHECKING_REQUIREMENTS;
} }
@ -106,12 +106,12 @@ namespace Documents\Install {
$config = $user->getConfiguration(); $config = $user->getConfiguration();
// Check if database configuration exists // Check if database configuration exists
if(!$config->getDatabase()) { if (!$config->getDatabase()) {
return self::DATABASE_CONFIGURATION; return self::DATABASE_CONFIGURATION;
} }
$sql = $user->getSQL(); $sql = $user->getSQL();
if(!$sql || !$sql->isConnected()) { if (!$sql || !$sql->isConnected()) {
return self::DATABASE_CONFIGURATION; return self::DATABASE_CONFIGURATION;
} }
@ -156,33 +156,33 @@ namespace Documents\Install {
return $step; return $step;
} }
private function checkRequirements() { private function checkRequirements(): array {
$msg = $this->errorString; $msg = $this->errorString;
$success = true; $success = true;
$failedRequirements = array(); $failedRequirements = array();
$configDir = "core/Configuration/"; $configDir = "core/Configuration/";
if(!is_writeable($configDir)) { if (!is_writeable($configDir)) {
$failedRequirements[] = "<b>$configDir</b> is not writeable. Try running <b>chmod 700 $configDir</b>"; $failedRequirements[] = "<b>$configDir</b> is not writeable. Try running <b>chmod 700 $configDir</b>";
$success = false; $success = false;
} }
if (function_exists("posix_getuid")) { if (function_exists("posix_getuid")) {
$userId = posix_getuid(); $userId = posix_getuid();
if(fileowner($configDir) !== $userId) { if (fileowner($configDir) !== $userId) {
$username = posix_getpwuid($userId)['name']; $username = posix_getpwuid($userId)['name'];
$failedRequirements[] = "<b>$configDir</b> is not owned by current user: $username ($userId). Try running <b>chown -R $username $configDir</b>"; $failedRequirements[] = "<b>$configDir</b> is not owned by current user: $username ($userId). Try running <b>chown -R $username $configDir</b>";
$success = false; $success = false;
} }
} }
if(version_compare(PHP_VERSION, '7.4', '<')) { if (version_compare(PHP_VERSION, '7.4', '<')) {
$failedRequirements[] = "PHP Version <b>>= 7.4</b> is required. Got: <b>" . PHP_VERSION . "</b>"; $failedRequirements[] = "PHP Version <b>>= 7.4</b> is required. Got: <b>" . PHP_VERSION . "</b>";
$success = false; $success = false;
} }
if(!$success) { if (!$success) {
$msg = "The following requirements failed the check:<br>" . $msg = "The following requirements failed the check:<br>" .
$this->createUnorderedList($failedRequirements); $this->createUnorderedList($failedRequirements);
$this->errorString = $msg; $this->errorString = $msg;
@ -191,7 +191,7 @@ namespace Documents\Install {
return array("success" => $success, "msg" => $msg); return array("success" => $success, "msg" => $msg);
} }
private function databaseConfiguration() { private function databaseConfiguration(): array {
$host = $this->getParameter("host"); $host = $this->getParameter("host");
$port = $this->getParameter("port"); $port = $this->getParameter("port");
@ -204,44 +204,44 @@ namespace Documents\Install {
$success = true; $success = true;
$missingInputs = array(); $missingInputs = array();
if(is_null($host) || empty($host)) { if (is_null($host) || empty($host)) {
$success = false; $success = false;
$missingInputs[] = "Host"; $missingInputs[] = "Host";
} }
if(is_null($port) || empty($port)) { if (is_null($port) || empty($port)) {
$success = false; $success = false;
$missingInputs[] = "Port"; $missingInputs[] = "Port";
} }
if(is_null($username) || empty($username)) { if (is_null($username) || empty($username)) {
$success = false; $success = false;
$missingInputs[] = "Username"; $missingInputs[] = "Username";
} }
if(is_null($password)) { if (is_null($password)) {
$success = false; $success = false;
$missingInputs[] = "Password"; $missingInputs[] = "Password";
} }
if(is_null($database) || empty($database)) { if (is_null($database) || empty($database)) {
$success = false; $success = false;
$missingInputs[] = "Database"; $missingInputs[] = "Database";
} }
if(is_null($type) || empty($type)) { if (is_null($type) || empty($type)) {
$success = false; $success = false;
$missingInputs[] = "Type"; $missingInputs[] = "Type";
} }
$supportedTypes = array("mysql", "postgres"); $supportedTypes = array("mysql", "postgres");
if(!$success) { if (!$success) {
$msg = "Please fill out the following inputs:<br>" . $msg = "Please fill out the following inputs:<br>" .
$this->createUnorderedList($missingInputs); $this->createUnorderedList($missingInputs);
} else if(!is_numeric($port) || ($port = intval($port)) < 1 || $port > 65535) { } else if (!is_numeric($port) || ($port = intval($port)) < 1 || $port > 65535) {
$msg = "Port must be in range of 1-65535."; $msg = "Port must be in range of 1-65535.";
$success = false; $success = false;
} else if(!in_array($type, $supportedTypes)) { } else if (!in_array($type, $supportedTypes)) {
$msg = "Unsupported database type. Must be one of: " . implode(", ", $supportedTypes); $msg = "Unsupported database type. Must be one of: " . implode(", ", $supportedTypes);
$success = false; $success = false;
} else { } else {
@ -251,9 +251,9 @@ namespace Documents\Install {
$connectionData->setProperty('type', $type); $connectionData->setProperty('type', $type);
$sql = SQL::createConnection($connectionData); $sql = SQL::createConnection($connectionData);
$success = false; $success = false;
if(is_string($sql)) { if (is_string($sql)) {
$msg = "Error connecting to database: $sql"; $msg = "Error connecting to database: $sql";
} else if(!$sql->isConnected()) { } else if (!$sql->isConnected()) {
if (!$sql->checkRequirements()) { if (!$sql->checkRequirements()) {
$driverName = $sql->getDriverName(); $driverName = $sql->getDriverName();
$installLink = "https://www.php.net/manual/en/$driverName.setup.php"; $installLink = "https://www.php.net/manual/en/$driverName.setup.php";
@ -267,7 +267,7 @@ namespace Documents\Install {
$msg = ""; $msg = "";
$success = true; $success = true;
$queries = CreateDatabase::createQueries($sql); $queries = CreateDatabase::createQueries($sql);
foreach($queries as $query) { foreach ($queries as $query) {
if (!($res = $query->execute())) { if (!($res = $query->execute())) {
$msg = "Error creating tables: " . $sql->getLastError(); $msg = "Error creating tables: " . $sql->getLastError();
$success = false; $success = false;
@ -276,13 +276,13 @@ namespace Documents\Install {
} }
$config = $this->getDocument()->getUser()->getConfiguration(); $config = $this->getDocument()->getUser()->getConfiguration();
if(!$config->create("Database", $connectionData)) { if (!$config->create("Database", $connectionData)) {
$success = false; $success = false;
$msg = "Unable to write file"; $msg = "Unable to write file";
} }
} }
if($sql) { if ($sql) {
$sql->close(); $sql->close();
} }
} }
@ -290,10 +290,10 @@ namespace Documents\Install {
return array("success" => $success, "msg" => $msg); return array("success" => $success, "msg" => $msg);
} }
private function createUser() { private function createUser(): array {
$user = $this->getDocument()->getUser(); $user = $this->getDocument()->getUser();
if($this->getParameter("prev") === "true") { if ($this->getParameter("prev") === "true") {
$success = $user->getConfiguration()->delete("Database"); $success = $user->getConfiguration()->delete("Database");
$msg = $success ? "" : error_get_last(); $msg = $success ? "" : error_get_last();
return array("success" => $success, "msg" => $msg); return array("success" => $success, "msg" => $msg);
@ -307,22 +307,22 @@ namespace Documents\Install {
$success = true; $success = true;
$missingInputs = array(); $missingInputs = array();
if(is_null($username) || empty($username)) { if (is_null($username) || empty($username)) {
$success = false; $success = false;
$missingInputs[] = "Username"; $missingInputs[] = "Username";
} }
if(is_null($password) || empty($password)) { if (is_null($password) || empty($password)) {
$success = false; $success = false;
$missingInputs[] = "Password"; $missingInputs[] = "Password";
} }
if(is_null($confirmPassword) || empty($confirmPassword)) { if (is_null($confirmPassword) || empty($confirmPassword)) {
$success = false; $success = false;
$missingInputs[] = "Confirm Password"; $missingInputs[] = "Confirm Password";
} }
if(!$success) { if (!$success) {
$msg = "Please fill out the following inputs:<br>" . $msg = "Please fill out the following inputs:<br>" .
$this->createUnorderedList($missingInputs); $this->createUnorderedList($missingInputs);
} else { } else {
@ -347,10 +347,10 @@ namespace Documents\Install {
return array("msg" => $msg, "success" => $success); return array("msg" => $msg, "success" => $success);
} }
private function addMailService() { private function addMailService(): array {
$user = $this->getDocument()->getUser(); $user = $this->getDocument()->getUser();
if($this->getParameter("prev") === "true") { if ($this->getParameter("prev") === "true") {
$sql = $user->getSQL(); $sql = $user->getSQL();
$success = $sql->delete("User")->execute(); $success = $sql->delete("User")->execute();
$msg = $sql->getLastError(); $msg = $sql->getLastError();
@ -359,9 +359,9 @@ namespace Documents\Install {
$success = true; $success = true;
$msg = $this->errorString; $msg = $this->errorString;
if($this->getParameter("skip") === "true") { if ($this->getParameter("skip") === "true") {
$req = new \Api\Settings\Set($user); $req = new \Api\Settings\Set($user);
$success = $req->execute(array("settings" => array( "mail_enabled" => "0" ))); $success = $req->execute(array("settings" => array("mail_enabled" => "0")));
$msg = $req->getLastError(); $msg = $req->getLastError();
} else { } else {
@ -372,30 +372,30 @@ namespace Documents\Install {
$success = true; $success = true;
$missingInputs = array(); $missingInputs = array();
if(is_null($address) || empty($address)) { if (is_null($address) || empty($address)) {
$success = false; $success = false;
$missingInputs[] = "SMTP Address"; $missingInputs[] = "SMTP Address";
} }
if(is_null($port) || empty($port)) { if (is_null($port) || empty($port)) {
$success = false; $success = false;
$missingInputs[] = "Port"; $missingInputs[] = "Port";
} }
if(is_null($username) || empty($username)) { if (is_null($username) || empty($username)) {
$success = false; $success = false;
$missingInputs[] = "Username"; $missingInputs[] = "Username";
} }
if(is_null($password)) { if (is_null($password)) {
$success = false; $success = false;
$missingInputs[] = "Password"; $missingInputs[] = "Password";
} }
if(!$success) { if (!$success) {
$msg = "Please fill out the following inputs:<br>" . $msg = "Please fill out the following inputs:<br>" .
$this->createUnorderedList($missingInputs); $this->createUnorderedList($missingInputs);
} else if(!is_numeric($port) || ($port = intval($port)) < 1 || $port > 65535) { } else if (!is_numeric($port) || ($port = intval($port)) < 1 || $port > 65535) {
$msg = "Port must be in range of 1-65535."; $msg = "Port must be in range of 1-65535.";
$success = false; $success = false;
} else { } else {
@ -413,7 +413,7 @@ namespace Documents\Install {
try { try {
$success = $mail->SmtpConnect(); $success = $mail->SmtpConnect();
if(!$success) { if (!$success) {
$error = empty($mail->ErrorInfo) ? "Unknown Error" : $mail->ErrorInfo; $error = empty($mail->ErrorInfo) ? "Unknown Error" : $mail->ErrorInfo;
$msg = "Could not connect to SMTP Server: $error"; $msg = "Could not connect to SMTP Server: $error";
} else { } else {
@ -421,11 +421,11 @@ namespace Documents\Install {
$msg = ""; $msg = "";
$mail->smtpClose(); $mail->smtpClose();
} }
} catch(Exception $error) { } catch (Exception $error) {
$msg = "Could not connect to SMTP Server: " . $error->errorMessage(); $msg = "Could not connect to SMTP Server: " . $error->errorMessage();
} }
if($success) { if ($success) {
$req = new \Api\Settings\Set($user); $req = new \Api\Settings\Set($user);
$success = $req->execute(array("settings" => array( $success = $req->execute(array("settings" => array(
"mail_enabled" => "1", "mail_enabled" => "1",
@ -442,9 +442,9 @@ namespace Documents\Install {
return array("success" => $success, "msg" => $msg); return array("success" => $success, "msg" => $msg);
} }
private function performStep() { private function performStep(): array {
switch($this->currentStep) { switch ($this->currentStep) {
case self::CHECKING_REQUIREMENTS: case self::CHECKING_REQUIREMENTS:
return $this->checkRequirements(); return $this->checkRequirements();
@ -466,15 +466,15 @@ namespace Documents\Install {
} }
} }
private function createProgressSidebar() { private function createProgressSidebar(): string {
$items = array(); $items = array();
foreach($this->steps as $num => $step) { foreach ($this->steps as $num => $step) {
$title = $step["title"]; $title = $step["title"];
$status = $step["status"]; $status = $step["status"];
$currentStep = ($num == $this->currentStep) ? " id=\"currentStep\"" : ""; $currentStep = ($num == $this->currentStep) ? " id=\"currentStep\"" : "";
switch($status) { switch ($status) {
case self::PENDING: case self::PENDING:
$statusIcon = $this->createIcon("spinner"); $statusIcon = $this->createIcon("spinner");
$statusText = "Loading…"; $statusText = "Loading…";
@ -514,7 +514,7 @@ namespace Documents\Install {
return implode("", $items); return implode("", $items);
} }
private function createFormItem($formItem, $inline=false) { private function createFormItem($formItem, $inline = false): string {
$title = $formItem["title"]; $title = $formItem["title"];
$name = $formItem["name"]; $name = $formItem["name"];
@ -526,37 +526,37 @@ namespace Documents\Install {
"class" => "form-control" "class" => "form-control"
); );
if(isset($formItem["required"]) && $formItem["required"]) { if (isset($formItem["required"]) && $formItem["required"]) {
$attributes["required"] = ""; $attributes["required"] = "";
} }
if ($type !== "select") { if ($type !== "select") {
$attributes["type"] = $type; $attributes["type"] = $type;
if(isset($formItem["value"]) && $formItem["value"]) { if (isset($formItem["value"]) && $formItem["value"]) {
$attributes["value"] = $formItem["value"]; $attributes["value"] = $formItem["value"];
} }
if($type === "number") { if ($type === "number") {
if(isset($formItem["min"]) && is_numeric($formItem["min"])) if (isset($formItem["min"]) && is_numeric($formItem["min"]))
$attributes["min"] = $formItem["min"]; $attributes["min"] = $formItem["min"];
if(isset($formItem["max"]) && is_numeric($formItem["max"])) if (isset($formItem["max"]) && is_numeric($formItem["max"]))
$attributes["max"] = $formItem["max"]; $attributes["max"] = $formItem["max"];
if(isset($formItem["step"]) && is_numeric($formItem["step"])) if (isset($formItem["step"]) && is_numeric($formItem["step"]))
$attributes["step"] = $formItem["step"]; $attributes["step"] = $formItem["step"];
} }
} }
$replacements = array("+" => " ", "&" => "\" ", "=" => "=\""); $replacements = array("+" => " ", "&" => "\" ", "=" => "=\"");
$attributes = http_build_query($attributes) . "\""; $attributes = http_build_query($attributes) . "\"";
foreach($replacements as $key => $val) { foreach ($replacements as $key => $val) {
$attributes = str_replace($key, $val, $attributes); $attributes = str_replace($key, $val, $attributes);
} }
if ($type === "select") { if ($type === "select") {
$items = $formItem["items"] ?? array(); $items = $formItem["items"] ?? array();
$element = "<select $attributes>"; $element = "<select $attributes>";
foreach($items as $key => $val) { foreach ($items as $key => $val) {
$element .= "<option value=\"$key\">$val</option>"; $element .= "<option value=\"$key\">$val</option>";
} }
$element .= "</select>"; $element .= "</select>";
@ -564,7 +564,7 @@ namespace Documents\Install {
$element = "<input $attributes>"; $element = "<input $attributes>";
} }
if(!$inline) { if (!$inline) {
return return
"<div class=\"d-block my-3\"> "<div class=\"d-block my-3\">
<label for=\"$name\">$title</label> <label for=\"$name\">$title</label>
@ -579,7 +579,7 @@ namespace Documents\Install {
} }
} }
private function createProgessMainview() { private function createProgessMainview(): string {
$views = array( $views = array(
self::CHECKING_REQUIREMENTS => array( self::CHECKING_REQUIREMENTS => array(
@ -646,7 +646,7 @@ namespace Documents\Install {
) )
); );
if(!isset($views[$this->currentStep])) { if (!isset($views[$this->currentStep])) {
return ""; return "";
} }
@ -657,24 +657,24 @@ namespace Documents\Install {
$html = "<h4 class=\"mb-3\">$title</h4><hr class=\"mb-4\">"; $html = "<h4 class=\"mb-3\">$title</h4><hr class=\"mb-4\">";
if(isset($currentView["text"])) { if (isset($currentView["text"])) {
$text = $currentView["text"]; $text = $currentView["text"];
$html .= "<div class=\"my-3\">$text</i></div>"; $html .= "<div class=\"my-3\">$text</i></div>";
} }
if(isset($currentView["progressText"])) { if (isset($currentView["progressText"])) {
$progressText = $currentView["progressText"]; $progressText = $currentView["progressText"];
$html .= "<div id=\"progressText\" style=\"display:none\" class=\"my-3\">$progressText$spinnerIcon</i></div>"; $html .= "<div id=\"progressText\" style=\"display:none\" class=\"my-3\">$progressText$spinnerIcon</i></div>";
} }
if(isset($currentView["form"])) { if (isset($currentView["form"])) {
$html .= "<form id=\"installForm\">"; $html .= "<form id=\"installForm\">";
foreach($currentView["form"] as $formItem) { foreach ($currentView["form"] as $formItem) {
if($formItem["type"] === "row") { if ($formItem["type"] === "row") {
$html .= "<div class=\"row\">"; $html .= "<div class=\"row\">";
foreach($formItem["items"] as $item) { foreach ($formItem["items"] as $item) {
$html .= $this->createFormItem($item, true); $html .= $this->createFormItem($item, true);
} }
$html .= "</div>"; $html .= "</div>";
@ -691,7 +691,7 @@ namespace Documents\Install {
array("title" => "Go Back", "type" => "info", "id" => "btnPrev", "float" => "left", "disabled" => $prevDisabled) array("title" => "Go Back", "type" => "info", "id" => "btnPrev", "float" => "left", "disabled" => $prevDisabled)
); );
if($this->currentStep != self::FINISH_INSTALLATION) { if ($this->currentStep != self::FINISH_INSTALLATION) {
if ($this->currentStep == self::CHECKING_REQUIREMENTS) { if ($this->currentStep == self::CHECKING_REQUIREMENTS) {
$buttons[] = array("title" => "Retry", "type" => "success", "id" => "btnRetry", "float" => "right"); $buttons[] = array("title" => "Retry", "type" => "success", "id" => "btnRetry", "float" => "right");
} else { } else {
@ -701,14 +701,14 @@ namespace Documents\Install {
$buttons[] = array("title" => "Finish", "type" => "success", "id" => "btnFinish", "float" => "right"); $buttons[] = array("title" => "Finish", "type" => "success", "id" => "btnFinish", "float" => "right");
} }
if(isset($currentView["skip"])) { if (isset($currentView["skip"])) {
$buttons[] = array("title" => "Skip", "type" => "secondary", "id" => "btnSkip", "float" => "right"); $buttons[] = array("title" => "Skip", "type" => "secondary", "id" => "btnSkip", "float" => "right");
} }
$buttonsLeft = ""; $buttonsLeft = "";
$buttonsRight = ""; $buttonsRight = "";
foreach($buttons as $button) { foreach ($buttons as $button) {
$title = $button["title"]; $title = $button["title"];
$type = $button["type"]; $type = $button["type"];
$id = $button["id"]; $id = $button["id"];
@ -716,7 +716,7 @@ namespace Documents\Install {
$disabled = (isset($button["disabled"]) && $button["disabled"]) ? " disabled" : ""; $disabled = (isset($button["disabled"]) && $button["disabled"]) ? " disabled" : "";
$button = "<button type=\"button\" id=\"$id\" class=\"btn btn-$type m-1\"$disabled>$title</button>"; $button = "<button type=\"button\" id=\"$id\" class=\"btn btn-$type m-1\"$disabled>$title</button>";
if($float === "left") { if ($float === "left") {
$buttonsLeft .= $button; $buttonsLeft .= $button;
} else { } else {
$buttonsRight .= $button; $buttonsRight .= $button;
@ -732,7 +732,7 @@ namespace Documents\Install {
return $html; return $html;
} }
function getCode() { function getCode(): string {
$html = parent::getCode(); $html = parent::getCode();
$this->steps = array( $this->steps = array(
@ -761,16 +761,16 @@ namespace Documents\Install {
$this->currentStep = $this->getCurrentStep(); $this->currentStep = $this->getCurrentStep();
// set status // set status
for($step = self::CHECKING_REQUIREMENTS; $step < $this->currentStep; $step++) { for ($step = self::CHECKING_REQUIREMENTS; $step < $this->currentStep; $step++) {
$this->steps[$step]["status"] = self::SUCCESSFUL; $this->steps[$step]["status"] = self::SUCCESSFUL;
} }
if($this->currentStep == self::FINISH_INSTALLATION) { if ($this->currentStep == self::FINISH_INSTALLATION) {
$this->steps[$this->currentStep]["status"] = self::SUCCESSFUL; $this->steps[$this->currentStep]["status"] = self::SUCCESSFUL;
} }
// POST // POST
if($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$response = $this->performStep(); $response = $this->performStep();
$response["step"] = $this->currentStep; $response["step"] = $this->currentStep;
die(json_encode($response)); die(json_encode($response));

@ -4,7 +4,7 @@ namespace Driver\SQL\Column;
class BoolColumn extends Column { class BoolColumn extends Column {
public function __construct($name, $defaultValue=false) { public function __construct(string $name, bool $defaultValue = false) {
parent::__construct($name, false, $defaultValue); parent::__construct($name, false, $defaultValue);
} }

@ -8,14 +8,14 @@ class Column {
private bool $nullable; private bool $nullable;
private $defaultValue; private $defaultValue;
public function __construct($name, $nullable = false, $defaultValue = NULL) { public function __construct(string $name, bool $nullable = false, $defaultValue = NULL) {
$this->name = $name; $this->name = $name;
$this->nullable = $nullable; $this->nullable = $nullable;
$this->defaultValue = $defaultValue; $this->defaultValue = $defaultValue;
} }
public function getName() { return $this->name; } public function getName(): string { return $this->name; }
public function notNull() { return !$this->nullable; } public function notNull(): bool { return !$this->nullable; }
public function getDefaultValue() { return $this->defaultValue; } public function getDefaultValue() { return $this->defaultValue; }
} }

@ -4,7 +4,7 @@ namespace Driver\SQL\Column;
class DateTimeColumn extends Column { class DateTimeColumn extends Column {
public function __construct($name, $nullable=false, $defaultValue=NULL) { public function __construct(string $name, bool $nullable = false, $defaultValue = NULL) {
parent::__construct($name, $nullable, $defaultValue); parent::__construct($name, $nullable, $defaultValue);
} }
} }

@ -6,10 +6,10 @@ class EnumColumn extends Column {
private array $values; private array $values;
public function __construct($name, $values, $nullable=false, $defaultValue=NULL) { public function __construct(string $name, array $values, bool $nullable = false, $defaultValue = NULL) {
parent::__construct($name, $nullable, $defaultValue); parent::__construct($name, $nullable, $defaultValue);
$this->values = $values; $this->values = $values;
} }
public function getValues() { return $this->values; } public function getValues(): array { return $this->values; }
} }

@ -4,7 +4,7 @@ namespace Driver\SQL\Column;
class IntColumn extends Column { class IntColumn extends Column {
public function __construct($name, $nullable=false, $defaultValue=NULL) { public function __construct(string $name, bool $nullable = false, $defaultValue = NULL) {
parent::__construct($name, $nullable, $defaultValue); parent::__construct($name, $nullable, $defaultValue);
} }

@ -4,7 +4,7 @@ namespace Driver\SQL\Column;
class JsonColumn extends Column { class JsonColumn extends Column {
public function __construct($name, $nullable=false, $defaultValue=null) { public function __construct(string $name, bool $nullable = false, $defaultValue = null) {
parent::__construct($name, $nullable, $defaultValue); parent::__construct($name, $nullable, $defaultValue);
} }

@ -4,7 +4,7 @@ namespace Driver\SQL\Column;
class SerialColumn extends Column { class SerialColumn extends Column {
public function __construct($name, $defaultValue=NULL) { public function __construct(string $name, $defaultValue = NULL) {
parent::__construct($name, false, $defaultValue); # not nullable parent::__construct($name, false, $defaultValue); # not nullable
} }

@ -6,10 +6,10 @@ class StringColumn extends Column {
private ?int $maxSize; private ?int $maxSize;
public function __construct($name, $maxSize=null, $nullable=false, $defaultValue=null) { public function __construct(string $name, ?int $maxSize = null, bool $nullable = false, $defaultValue = null) {
parent::__construct($name, $nullable, $defaultValue); parent::__construct($name, $nullable, $defaultValue);
$this->maxSize = $maxSize; $this->maxSize = $maxSize;
} }
public function getMaxSize() { return $this->maxSize; } public function getMaxSize(): ?int { return $this->maxSize; }
} }

@ -8,14 +8,14 @@ class Compare extends Condition {
private string $column; private string $column;
private $value; private $value;
public function __construct($col, $val, $operator='=') { public function __construct(string $col, $val, string $operator = '=') {
$this->operator = $operator; $this->operator = $operator;
$this->column = $col; $this->column = $col;
$this->value = $val; $this->value = $val;
} }
public function getColumn() { return $this->column; } public function getColumn(): string { return $this->column; }
public function getValue() { return $this->value; } public function getValue() { return $this->value; }
public function getOperator() { return $this->operator; } public function getOperator(): string { return $this->operator; }
} }

@ -10,5 +10,5 @@ class CondAnd extends Condition {
$this->conditions = $conditions; $this->conditions = $conditions;
} }
public function getConditions() { return $this->conditions; } public function getConditions(): array { return $this->conditions; }
} }

@ -12,6 +12,6 @@ class CondIn extends Condition {
$this->expression = $expression; $this->expression = $expression;
} }
public function getColumn() { return $this->column; } public function getColumn(): string { return $this->column; }
public function getExpression() { return $this->expression; } public function getExpression() { return $this->expression; }
} }

@ -8,7 +8,7 @@ abstract class CondKeyword extends Condition {
private $rightExpression; private $rightExpression;
private string $keyword; private string $keyword;
public function __construct($keyword, $leftExpression, $rightExpression) { public function __construct(string $keyword, $leftExpression, $rightExpression) {
$this->leftExpression = $leftExpression; $this->leftExpression = $leftExpression;
$this->rightExpression = $rightExpression; $this->rightExpression = $rightExpression;
$this->keyword = $keyword; $this->keyword = $keyword;
@ -16,5 +16,5 @@ abstract class CondKeyword extends Condition {
public function getLeftExp() { return $this->leftExpression; } public function getLeftExp() { return $this->leftExpression; }
public function getRightExp() { return $this->rightExpression; } public function getRightExp() { return $this->rightExpression; }
public function getKeyword() { return $this->keyword; } public function getKeyword(): string { return $this->keyword; }
} }

@ -10,5 +10,5 @@ class CondNull extends Condition {
$this->column = $col; $this->column = $col;
} }
public function getColumn() { return $this->column; } public function getColumn(): string { return $this->column; }
} }

@ -10,5 +10,5 @@ class CondOr extends Condition {
$this->conditions = (!empty($conditions) && is_array($conditions[0])) ? $conditions[0] : $conditions; $this->conditions = (!empty($conditions) && is_array($conditions[0])) ? $conditions[0] : $conditions;
} }
public function getConditions() { return $this->conditions; } public function getConditions(): array { return $this->conditions; }
} }

@ -10,5 +10,5 @@ abstract class Constraint {
$this->columnNames = (!is_array($columnNames) ? array($columnNames) : $columnNames); $this->columnNames = (!is_array($columnNames) ? array($columnNames) : $columnNames);
} }
public function getColumnNames() { return $this->columnNames; } public function getColumnNames(): array { return $this->columnNames; }
} }

@ -10,14 +10,14 @@ class ForeignKey extends Constraint {
private string $referencedColumn; private string $referencedColumn;
private ?Strategy $strategy; private ?Strategy $strategy;
public function __construct($name, $refTable, $refColumn, $strategy = NULL) { public function __construct(string $name, string $refTable, string $refColumn, ?Strategy $strategy = NULL) {
parent::__construct($name); parent::__construct($name);
$this->referencedTable = $refTable; $this->referencedTable = $refTable;
$this->referencedColumn = $refColumn; $this->referencedColumn = $refColumn;
$this->strategy = $strategy; $this->strategy = $strategy;
} }
public function getReferencedTable() { return $this->referencedTable; } public function getReferencedTable(): string { return $this->referencedTable; }
public function getReferencedColumn() { return $this->referencedColumn; } public function getReferencedColumn(): string { return $this->referencedColumn; }
public function onDelete() { return $this->strategy; } public function onDelete(): ?Strategy { return $this->strategy; }
} }

@ -4,9 +4,10 @@ namespace Driver\SQL\Expression;
use Driver\SQL\Condition\Compare; use Driver\SQL\Condition\Compare;
# TODO: change confusing class inheritance here
class Add extends Compare { class Add extends Compare {
public function __construct($col, $val) { public function __construct(string $col, $val) {
parent::__construct($col, $val, "+"); parent::__construct($col, $val, "+");
} }

@ -8,9 +8,9 @@ class Join {
private string $table; private string $table;
private string $columnA; private string $columnA;
private string $columnB; private string $columnB;
private $tableAlias; private ?string $tableAlias;
public function __construct($type, $table, $columnA, $columnB, $tableAlias=null) { public function __construct(string $type, string $table, string $columnA, string $columnB, ?string $tableAlias = null) {
$this->type = $type; $this->type = $type;
$this->table = $table; $this->table = $table;
$this->columnA = $columnA; $this->columnA = $columnA;
@ -18,10 +18,10 @@ class Join {
$this->tableAlias = $tableAlias; $this->tableAlias = $tableAlias;
} }
public function getType() { return $this->type; } public function getType(): string { return $this->type; }
public function getTable() { return $this->table; } public function getTable(): string { return $this->table; }
public function getColumnA() { return $this->columnA; } public function getColumnA(): string { return $this->columnA; }
public function getColumnB() { return $this->columnB; } public function getColumnB(): string { return $this->columnB; }
public function getTableAlias() { return $this->tableAlias; } public function getTableAlias(): ?string { return $this->tableAlias; }
} }

@ -6,10 +6,10 @@ class Keyword {
private string $value; private string $value;
public function __construct($value) { public function __construct(string $value) {
$this->value = $value; $this->value = $value;
} }
public function getValue() { return $this->value; } public function getValue(): string { return $this->value; }
} }

@ -13,6 +13,8 @@ use Driver\SQL\Column\JsonColumn;
use Driver\SQL\Constraint\PrimaryKey; use Driver\SQL\Constraint\PrimaryKey;
use Driver\SQL\Constraint\Unique; use Driver\SQL\Constraint\Unique;
use Driver\SQL\Constraint\ForeignKey; use Driver\SQL\Constraint\ForeignKey;
use Driver\SQL\SQL;
use Driver\SQL\Strategy\Strategy;
class CreateTable extends Query { class CreateTable extends Query {
@ -21,7 +23,7 @@ class CreateTable extends Query {
private array $constraints; private array $constraints;
private bool $ifNotExists; private bool $ifNotExists;
public function __construct($sql, $name) { public function __construct(SQL $sql, string $name) {
parent::__construct($sql); parent::__construct($sql);
$this->tableName = $name; $this->tableName = $name;
$this->columns = array(); $this->columns = array();
@ -29,67 +31,67 @@ class CreateTable extends Query {
$this->ifNotExists = false; $this->ifNotExists = false;
} }
public function addSerial($name) { public function addSerial(string $name): CreateTable {
$this->columns[$name] = new SerialColumn($name); $this->columns[$name] = new SerialColumn($name);
return $this; return $this;
} }
public function addString($name, $maxSize=NULL, $nullable=false, $defaultValue=NULL) { public function addString(string $name, ?int $maxSize = NULL, bool $nullable = false, $defaultValue = NULL): CreateTable {
$this->columns[$name] = new StringColumn($name, $maxSize, $nullable, $defaultValue); $this->columns[$name] = new StringColumn($name, $maxSize, $nullable, $defaultValue);
return $this; return $this;
} }
public function addDateTime($name, $nullable=false, $defaultValue=NULL) { public function addDateTime(string $name, bool $nullable = false, $defaultValue = NULL): CreateTable {
$this->columns[$name] = new DateTimeColumn($name, $nullable, $defaultValue); $this->columns[$name] = new DateTimeColumn($name, $nullable, $defaultValue);
return $this; return $this;
} }
public function addInt($name, $nullable=false, $defaultValue=NULL) { public function addInt(string $name, bool $nullable = false, $defaultValue = NULL): CreateTable {
$this->columns[$name] = new IntColumn($name, $nullable, $defaultValue); $this->columns[$name] = new IntColumn($name, $nullable, $defaultValue);
return $this; return $this;
} }
public function addBool($name, $defaultValue=false) { public function addBool(string $name, $defaultValue = false): CreateTable {
$this->columns[$name] = new BoolColumn($name, $defaultValue); $this->columns[$name] = new BoolColumn($name, $defaultValue);
return $this; return $this;
} }
public function addJson($name, $nullable=false, $defaultValue=NULL) { public function addJson(string $name, bool $nullable = false, $defaultValue = NULL): CreateTable {
$this->columns[$name] = new JsonColumn($name, $nullable, $defaultValue); $this->columns[$name] = new JsonColumn($name, $nullable, $defaultValue);
return $this; return $this;
} }
public function addEnum($name, $values, $nullable=false, $defaultValue=NULL) { public function addEnum(string $name, array $values, bool $nullable = false, $defaultValue = NULL): CreateTable {
$this->columns[$name] = new EnumColumn($name, $values, $nullable, $defaultValue); $this->columns[$name] = new EnumColumn($name, $values, $nullable, $defaultValue);
return $this; return $this;
} }
public function primaryKey(...$names) { public function primaryKey(...$names): CreateTable {
$this->constraints[] = new PrimaryKey($names); $this->constraints[] = new PrimaryKey($names);
return $this; return $this;
} }
public function unique(...$names) { public function unique(...$names): CreateTable {
$this->constraints[] = new Unique($names); $this->constraints[] = new Unique($names);
return $this; return $this;
} }
public function foreignKey($name, $refTable, $refColumn, $strategy = NULL) { public function foreignKey(string $name, string $refTable, string $refColumn, ?Strategy $strategy = NULL): CreateTable {
$this->constraints[] = new ForeignKey($name, $refTable, $refColumn, $strategy); $this->constraints[] = new ForeignKey($name, $refTable, $refColumn, $strategy);
return $this; return $this;
} }
public function onlyIfNotExists() { public function onlyIfNotExists(): CreateTable {
$this->ifNotExists = true; $this->ifNotExists = true;
return $this; return $this;
} }
public function execute() { public function execute(): bool {
return $this->sql->executeCreateTable($this); return $this->sql->executeCreateTable($this);
} }
public function ifNotExists() { return $this->ifNotExists; } public function ifNotExists(): bool { return $this->ifNotExists; }
public function getTableName() { return $this->tableName; } public function getTableName(): string { return $this->tableName; }
public function getColumns() { return $this->columns; } public function getColumns(): array { return $this->columns; }
public function getConstraints() { return $this->constraints; } public function getConstraints(): array { return $this->constraints; }
} }

@ -3,19 +3,20 @@
namespace Driver\SQL\Query; namespace Driver\SQL\Query;
use Driver\SQL\Condition\CondOr; use Driver\SQL\Condition\CondOr;
use Driver\SQL\SQL;
class Delete extends Query { class Delete extends Query {
private string $table; private string $table;
private array $conditions; private array $conditions;
public function __construct($sql, $table) { public function __construct(SQL $sql, string $table) {
parent::__construct($sql); parent::__construct($sql);
$this->table = $table; $this->table = $table;
$this->conditions = array(); $this->conditions = array();
} }
public function where(...$conditions) { public function where(...$conditions): Delete {
$this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions)); $this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions));
return $this; return $this;
} }
@ -24,6 +25,6 @@ class Delete extends Query {
return $this->sql->executeDelete($this); return $this->sql->executeDelete($this);
} }
public function getTable() { return $this->table; } public function getTable(): string { return $this->table; }
public function getConditions() { return $this->conditions; } public function getConditions(): array { return $this->conditions; }
} }

@ -14,16 +14,16 @@ class Drop extends Query {
* @param SQL $sql * @param SQL $sql
* @param string $table * @param string $table
*/ */
public function __construct(\Driver\SQL\SQL $sql, string $table) { public function __construct(SQL $sql, string $table) {
parent::__construct($sql); parent::__construct($sql);
$this->table = $table; $this->table = $table;
} }
public function execute() { public function execute(): bool {
$this->sql->executeDrop($this); return $this->sql->executeDrop($this);
} }
public function getTable() { public function getTable(): string {
return $this->table; return $this->table;
} }
} }

@ -2,6 +2,7 @@
namespace Driver\SQL\Query; namespace Driver\SQL\Query;
use Driver\SQL\SQL;
use Driver\SQL\Strategy\Strategy; use Driver\SQL\Strategy\Strategy;
class Insert extends Query { class Insert extends Query {
@ -12,7 +13,7 @@ class Insert extends Query {
private ?Strategy $onDuplicateKey; private ?Strategy $onDuplicateKey;
private ?string $returning; private ?string $returning;
public function __construct($sql, $name, $columns=array()) { public function __construct(SQL $sql, string $name, array $columns = array()) {
parent::__construct($sql); parent::__construct($sql);
$this->tableName = $name; $this->tableName = $name;
$this->columns = $columns; $this->columns = $columns;
@ -21,28 +22,28 @@ class Insert extends Query {
$this->returning = NULL; $this->returning = NULL;
} }
public function addRow(...$values) { public function addRow(...$values): Insert {
$this->rows[] = $values; $this->rows[] = $values;
return $this; return $this;
} }
public function onDuplicateKeyStrategy($strategy) { public function onDuplicateKeyStrategy(Strategy $strategy): Insert {
$this->onDuplicateKey = $strategy; $this->onDuplicateKey = $strategy;
return $this; return $this;
} }
public function returning($column) { public function returning(string $column): Insert {
$this->returning = $column; $this->returning = $column;
return $this; return $this;
} }
public function execute() { public function execute(): bool {
return $this->sql->executeInsert($this); return $this->sql->executeInsert($this);
} }
public function getTableName() { return $this->tableName; } public function getTableName(): string { return $this->tableName; }
public function getColumns() { return $this->columns; } public function getColumns(): array { return $this->columns; }
public function getRows() { return $this->rows; } public function getRows(): array { return $this->rows; }
public function onDuplicateKey() { return $this->onDuplicateKey; } public function onDuplicateKey(): ?Strategy { return $this->onDuplicateKey; }
public function getReturning() { return $this->returning; } public function getReturning(): ?string { return $this->returning; }
} }

@ -9,16 +9,16 @@ abstract class Query {
protected SQL $sql; protected SQL $sql;
public bool $dump; public bool $dump;
public function __construct($sql) { public function __construct(SQL $sql) {
$this->sql = $sql; $this->sql = $sql;
$this->dump = false; $this->dump = false;
} }
public function dump() { public function dump(): Query {
$this->dump = true; $this->dump = true;
return $this; return $this;
} }
public abstract function execute(); public abstract function execute(): bool;
} }

@ -30,68 +30,68 @@ class Select extends Query {
$this->sortAscending = true; $this->sortAscending = true;
} }
public function from(...$tables) { public function from(...$tables): Select {
$this->tables = array_merge($this->tables, $tables); $this->tables = array_merge($this->tables, $tables);
return $this; return $this;
} }
public function where(...$conditions) { public function where(...$conditions): Select {
$this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions)); $this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions));
return $this; return $this;
} }
public function innerJoin($table, $columnA, $columnB, $tableAlias=null) { public function innerJoin(string $table, string $columnA, string $columnB, ?string $tableAlias = null): Select {
$this->joins[] = new Join("INNER", $table, $columnA, $columnB, $tableAlias); $this->joins[] = new Join("INNER", $table, $columnA, $columnB, $tableAlias);
return $this; return $this;
} }
public function leftJoin($table, $columnA, $columnB, $tableAlias=null) { public function leftJoin(string $table, string $columnA, string $columnB, ?string $tableAlias = null): Select {
$this->joins[] = new Join("LEFT", $table, $columnA, $columnB, $tableAlias); $this->joins[] = new Join("LEFT", $table, $columnA, $columnB, $tableAlias);
return $this; return $this;
} }
public function groupBy(...$columns) { public function groupBy(...$columns): Select {
$this->groupColumns = $columns; $this->groupColumns = $columns;
return $this; return $this;
} }
public function orderBy(...$columns) { public function orderBy(...$columns): Select {
$this->orderColumns = $columns; $this->orderColumns = $columns;
return $this; return $this;
} }
public function ascending() { public function ascending(): Select {
$this->sortAscending = true; $this->sortAscending = true;
return $this; return $this;
} }
public function descending() { public function descending(): Select {
$this->sortAscending = false; $this->sortAscending = false;
return $this; return $this;
} }
public function limit($limit) { public function limit(int $limit): Select {
$this->limit = $limit; $this->limit = $limit;
return $this; return $this;
} }
public function offset($offset) { public function offset(int $offset): Select {
$this->offset = $offset; $this->offset = $offset;
return $this; return $this;
} }
public function execute() { public function execute(): bool {
return $this->sql->executeSelect($this); return $this->sql->executeSelect($this);
} }
public function getColumns() { return $this->columns; } public function getColumns(): array { return $this->columns; }
public function getTables() { return $this->tables; } public function getTables(): array { return $this->tables; }
public function getConditions() { return $this->conditions; } public function getConditions(): array { return $this->conditions; }
public function getJoins() { return $this->joins; } public function getJoins(): array { return $this->joins; }
public function isOrderedAscending() { return $this->sortAscending; } public function isOrderedAscending(): bool { return $this->sortAscending; }
public function getOrderBy() { return $this->orderColumns; } public function getOrderBy(): array { return $this->orderColumns; }
public function getLimit() { return $this->limit; } public function getLimit(): int { return $this->limit; }
public function getOffset() { return $this->offset; } public function getOffset(): int { return $this->offset; }
public function getGroupBy() { return $this->groupColumns; } public function getGroupBy(): array { return $this->groupColumns; }
} }

@ -2,18 +2,20 @@
namespace Driver\SQL\Query; namespace Driver\SQL\Query;
use Driver\SQL\SQL;
class Truncate extends Query { class Truncate extends Query {
private string $tableName; private string $tableName;
public function __construct($sql, $name) { public function __construct(SQL $sql, string $name) {
parent::__construct($sql); parent::__construct($sql);
$this->tableName = $name; $this->tableName = $name;
} }
public function execute() { public function execute(): bool {
return $this->sql->executeTruncate($this); return $this->sql->executeTruncate($this);
} }
public function getTable() { return $this->tableName; } public function getTable(): string { return $this->tableName; }
} }

@ -3,6 +3,7 @@
namespace Driver\SQL\Query; namespace Driver\SQL\Query;
use Driver\SQL\Condition\CondOr; use Driver\SQL\Condition\CondOr;
use Driver\SQL\SQL;
class Update extends Query { class Update extends Query {
@ -10,28 +11,28 @@ class Update extends Query {
private string $table; private string $table;
private array $conditions; private array $conditions;
public function __construct($sql, $table) { public function __construct(SQL $sql, string $table) {
parent::__construct($sql); parent::__construct($sql);
$this->values = array(); $this->values = array();
$this->table = $table; $this->table = $table;
$this->conditions = array(); $this->conditions = array();
} }
public function where(...$conditions) { public function where(...$conditions): Update {
$this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions)); $this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions));
return $this; return $this;
} }
public function set($key, $val) { public function set(string $key, $val): Update {
$this->values[$key] = $val; $this->values[$key] = $val;
return $this; return $this;
} }
public function execute() { public function execute(): bool {
return $this->sql->executeUpdate($this); return $this->sql->executeUpdate($this);
} }
public function getTable() { return $this->table; } public function getTable(): string { return $this->table; }
public function getConditions() { return $this->conditions; } public function getConditions(): array { return $this->conditions; }
public function getValues() { return $this->values; } public function getValues(): array { return $this->values; }
} }

@ -12,9 +12,11 @@ class UpdateStrategy extends Strategy {
$this->values = $values; $this->values = $values;
} }
public function getConflictingColumns() { public function getConflictingColumns(): array {
return $this->conflictingColumns; return $this->conflictingColumns;
} }
public function getValues() { return $this->values; } public function getValues(): array {
return $this->values;
}
} }

@ -11,16 +11,16 @@ class EmptyHead extends Head {
protected function initSources() { protected function initSources() {
} }
protected function initMetas() { protected function initMetas(): array {
return array( return array(
); );
} }
protected function initRawFields() { protected function initRawFields(): array {
return array(); return array();
} }
protected function initTitle() { protected function initTitle(): string {
return ""; return "";
} }
} }

@ -24,9 +24,9 @@ abstract class Head extends View {
} }
protected abstract function initSources(); protected abstract function initSources();
protected abstract function initMetas(); protected abstract function initMetas(): array;
protected abstract function initRawFields(); protected abstract function initRawFields(): array;
protected abstract function initTitle(); protected abstract function initTitle(): string;
protected function init() { protected function init() {
$this->keywords = array(); $this->keywords = array();

@ -3,14 +3,15 @@
namespace Elements; namespace Elements;
abstract class SimpleBody extends Body { abstract class SimpleBody extends Body {
public function __construct($document) { public function __construct($document) {
parent::__construct($document); parent::__construct($document);
} }
public function getCode() { public function getCode(): string {
$content = $this->getContent(); $content = $this->getContent();
return parent::getCode() . "<body>$content</body>"; return parent::getCode() . "<body>$content</body>";
} }
protected abstract function getContent(); protected abstract function getContent(): string;
} }

@ -7,23 +7,25 @@ abstract class View extends StaticView {
private Document $document; private Document $document;
private bool $loadView; private bool $loadView;
protected bool $searchable; protected bool $searchable;
protected string $reference;
protected string $title; protected string $title;
protected array $langModules; protected array $langModules;
public function __construct(Document $document, $loadView = true) { public function __construct(Document $document, bool $loadView = true) {
$this->document = $document; $this->document = $document;
$this->searchable = false; $this->searchable = false;
$this->reference = "";
$this->title = "Untitled View"; $this->title = "Untitled View";
$this->langModules = array(); $this->langModules = array();
$this->loadView = $loadView; $this->loadView = $loadView;
} }
public function getTitle() { return $this->title; } public function getTitle(): string { return $this->title; }
public function getDocument() { return $this->document; } public function getDocument(): Document { return $this->document; }
public function isSearchable() { return $this->searchable; } public function isSearchable(): bool { return $this->searchable; }
public function getReference() { return $this->reference; }
public function getSiteName(): string {
// what a chain lol
return $this->getDocument()->getUser()->getConfiguration()->getSettings()->getSiteName();
}
protected function load(string $viewClass) : string { protected function load(string $viewClass) : string {
try { try {
@ -50,7 +52,7 @@ abstract class View extends StaticView {
// Virtual Methods // Virtual Methods
public function loadView() { } public function loadView() { }
public function getCode() { public function getCode(): string {
// Load translations // Load translations
$this->loadLanguageModules(); $this->loadLanguageModules();
@ -64,33 +66,33 @@ abstract class View extends StaticView {
} }
// UI Functions // UI Functions
private function createList($items, $tag) { private function createList($items, $tag): string {
if(count($items) === 0) if(count($items) === 0)
return "<$tag></$tag>"; return "<$tag></$tag>";
else else
return "<$tag><li>" . implode("</li><li>", $items) . "</li></$tag>"; return "<$tag><li>" . implode("</li><li>", $items) . "</li></$tag>";
} }
public function createOrderedList($items=array()) { public function createOrderedList($items=array()): string {
return $this->createList($items, "ol"); return $this->createList($items, "ol");
} }
public function createUnorderedList($items=array()) { public function createUnorderedList($items=array()): string {
return $this->createList($items, "ul"); return $this->createList($items, "ul");
} }
protected function createLink($link, $title=null, $classes="") { protected function createLink($link, $title=null, $classes=""): string {
if(is_null($title)) $title=$link; if(is_null($title)) $title=$link;
if(!empty($classes)) $classes = " class=\"$classes\""; if(!empty($classes)) $classes = " class=\"$classes\"";
return "<a href=\"$link\"$classes>$title</a>"; return "<a href=\"$link\"$classes>$title</a>";
} }
protected function createExternalLink($link, $title=null) { protected function createExternalLink($link, $title=null): string {
if(is_null($title)) $title=$link; if(is_null($title)) $title=$link;
return "<a href=\"$link\" target=\"_blank\" class=\"external\">$title</a>"; return "<a href=\"$link\" target=\"_blank\" class=\"external\">$title</a>";
} }
protected function createIcon($icon, $type = "fas", $classes = "") { protected function createIcon($icon, $type = "fas", $classes = ""): string {
$iconClass = "$type fa-$icon"; $iconClass = "$type fa-$icon";
if($icon === "spinner" || $icon === "circle-notch") if($icon === "spinner" || $icon === "circle-notch")
@ -102,39 +104,39 @@ abstract class View extends StaticView {
return "<i class=\"$iconClass\" ></i>"; return "<i class=\"$iconClass\" ></i>";
} }
protected function createErrorText($text, $id="", $hidden=false) { protected function createErrorText($text, $id="", $hidden=false): string {
return $this->createStatusText("danger", $text, $id, $hidden); return $this->createStatusText("danger", $text, $id, $hidden);
} }
protected function createWarningText($text, $id="", $hidden=false) { protected function createWarningText($text, $id="", $hidden=false): string {
return $this->createStatusText("warning", $text, $id, $hidden); return $this->createStatusText("warning", $text, $id, $hidden);
} }
protected function createSuccessText($text, $id="", $hidden=false) { protected function createSuccessText($text, $id="", $hidden=false): string {
return $this->createStatusText("success", $text, $id, $hidden); return $this->createStatusText("success", $text, $id, $hidden);
} }
protected function createSecondaryText($text, $id="", $hidden=false) { protected function createSecondaryText($text, $id="", $hidden=false): string {
return $this->createStatusText("secondary", $text, $id, $hidden); return $this->createStatusText("secondary", $text, $id, $hidden);
} }
protected function createInfoText($text, $id="", $hidden=false) { protected function createInfoText($text, $id="", $hidden=false): string {
return $this->createStatusText("info", $text, $id, $hidden); return $this->createStatusText("info", $text, $id, $hidden);
} }
protected function createStatusText($type, $text, $id="", $hidden=false, $classes="") { protected function createStatusText($type, $text, $id="", $hidden=false, $classes=""): string {
if(strlen($id) > 0) $id = " id=\"$id\""; if(strlen($id) > 0) $id = " id=\"$id\"";
if($hidden) $classes .= " hidden"; if($hidden) $classes .= " hidden";
if(strlen($classes) > 0) $classes = " $classes"; if(strlen($classes) > 0) $classes = " $classes";
return "<div class=\"alert alert-$type$hidden$classes\" role=\"alert\"$id>$text</div>"; return "<div class=\"alert alert-$type$hidden$classes\" role=\"alert\"$id>$text</div>";
} }
protected function createBadge($type, $text) { protected function createBadge($type, $text): string {
$text = htmlspecialchars($text); $text = htmlspecialchars($text);
return "<span class=\"badge badge-$type\">$text</span>"; return "<span class=\"badge badge-$type\">$text</span>";
} }
protected function createJumbotron(string $content, bool $fluid=false, $class="") { protected function createJumbotron(string $content, bool $fluid=false, $class=""): string {
$jumbotronClass = "jumbotron" . ($fluid ? "-fluid" : ""); $jumbotronClass = "jumbotron" . ($fluid ? "-fluid" : "");
if (!empty($class)) $jumbotronClass .= " $class"; if (!empty($class)) $jumbotronClass .= " $class";
@ -148,12 +150,12 @@ abstract class View extends StaticView {
</div>"; </div>";
} }
public function createSimpleParagraph(string $content, string $class="") { public function createSimpleParagraph(string $content, string $class=""): string {
if($class) $class = " class=\"$class\""; if($class) $class = " class=\"$class\"";
return "<p$class>$content</p>"; return "<p$class>$content</p>";
} }
public function createParagraph($title, $id, $content) { public function createParagraph($title, $id, $content): string {
$id = replaceCssSelector($id); $id = replaceCssSelector($id);
$iconId = urlencode("$id-icon"); $iconId = urlencode("$id-icon");
return " return "
@ -166,7 +168,7 @@ abstract class View extends StaticView {
</div>"; </div>";
} }
protected function createBootstrapTable($data, string $classes="") { protected function createBootstrapTable($data, string $classes=""): string {
$classes = empty($classes) ? "" : " $classes"; $classes = empty($classes) ? "" : " $classes";
$code = "<div class=\"container$classes\">"; $code = "<div class=\"container$classes\">";
foreach($data as $row) { foreach($data as $row) {

@ -3,9 +3,6 @@
namespace Objects; namespace Objects;
use Configuration\Configuration; use Configuration\Configuration;
use DateTime;
use Driver\SQL\Expression\Add;
use Driver\SQL\Strategy\UpdateStrategy;
use Exception; use Exception;
use External\JWT; use External\JWT;
use Driver\SQL\SQL; use Driver\SQL\SQL;
@ -52,19 +49,19 @@ class User extends ApiObject {
} }
} }
public function getId() { return $this->uid; } public function getId(): int { return $this->uid; }
public function isLoggedIn() { return $this->loggedIn; } public function isLoggedIn(): bool { return $this->loggedIn; }
public function getUsername() { return $this->username; } public function getUsername(): string { return $this->username; }
public function getEmail() { return $this->email; } public function getEmail(): ?string { return $this->email; }
public function getSQL() { return $this->sql; } public function getSQL(): ?SQL { return $this->sql; }
public function getLanguage() { return $this->language; } public function getLanguage(): Language { return $this->language; }
public function setLanguage(Language $language) { $this->language = $language; $language->load(); } public function setLanguage(Language $language) { $this->language = $language; $language->load(); }
public function getSession() { return $this->session; } public function getSession(): ?Session { return $this->session; }
public function getConfiguration() { return $this->configuration; } public function getConfiguration(): Configuration { return $this->configuration; }
public function getGroups() { return $this->groups; } public function getGroups(): array { return $this->groups; }
public function hasGroup(int $group) { return isset($this->groups[$group]); } public function hasGroup(int $group): bool { return isset($this->groups[$group]); }
public function __debugInfo() { public function __debugInfo(): array {
$debugInfo = array( $debugInfo = array(
'loggedIn' => $this->loggedIn, 'loggedIn' => $this->loggedIn,
'language' => $this->language->getName(), 'language' => $this->language->getName(),
@ -78,7 +75,7 @@ class User extends ApiObject {
return $debugInfo; return $debugInfo;
} }
public function jsonSerialize() { public function jsonSerialize(): array {
if ($this->isLoggedIn()) { if ($this->isLoggedIn()) {
return array( return array(
'uid' => $this->uid, 'uid' => $this->uid,
@ -103,7 +100,7 @@ class User extends ApiObject {
$this->session = null; $this->session = null;
} }
public function logout() { public function logout(): bool {
$success = true; $success = true;
if($this->loggedIn) { if($this->loggedIn) {
$success = $this->session->destroy(); $success = $this->session->destroy();
@ -113,7 +110,7 @@ class User extends ApiObject {
return $success; return $success;
} }
public function updateLanguage($lang) { public function updateLanguage($lang): bool {
if($this->sql) { if($this->sql) {
$request = new \Api\Language\Set($this); $request = new \Api\Language\Set($this);
return $request->execute(array("langCode" => $lang)); return $request->execute(array("langCode" => $lang));
@ -131,7 +128,13 @@ class User extends ApiObject {
session_write_close(); session_write_close();
} }
public function readData($userId, $sessionId, $sessionUpdate = true) { /**
* @param $userId user's id
* @param $sessionId session's id
* @param bool $sessionUpdate update session information, including session's lifetime and browser information
* @return bool true, if the data could be loaded
*/
public function readData($userId, $sessionId, $sessionUpdate = true): bool {
$res = $this->sql->select("User.name", "User.email", $res = $this->sql->select("User.name", "User.email",
"Language.uid as langId", "Language.code as langCode", "Language.name as langName", "Language.uid as langId", "Language.code as langCode", "Language.name as langName",
@ -203,10 +206,10 @@ class User extends ApiObject {
} }
} }
public function createSession($userId, $stayLoggedIn) { public function createSession($userId, $stayLoggedIn): bool {
$this->uid = $userId; $this->uid = $userId;
$this->session = Session::create($this, $stayLoggedIn); $this->session = Session::create($this, $stayLoggedIn);
if($this->session) { if ($this->session) {
$this->loggedIn = true; $this->loggedIn = true;
return true; return true;
} }
@ -214,10 +217,11 @@ class User extends ApiObject {
return false; return false;
} }
public function authorize($apiKey) { public function authorize($apiKey): bool {
if($this->loggedIn) if ($this->loggedIn) {
return true; return true;
}
$res = $this->sql->select("ApiKey.user_id as uid", "User.name", "User.email", "User.confirmed", $res = $this->sql->select("ApiKey.user_id as uid", "User.name", "User.email", "User.confirmed",
"Language.uid as langId", "Language.code as langCode", "Language.name as langName") "Language.uid as langId", "Language.code as langCode", "Language.name as langName")
@ -264,7 +268,7 @@ class User extends ApiObject {
} }
} }
private function isBot() { private function isBot(): bool {
if (!isset($_SERVER["HTTP_USER_AGENT"]) || empty($_SERVER["HTTP_USER_AGENT"])) { if (!isset($_SERVER["HTTP_USER_AGENT"]) || empty($_SERVER["HTTP_USER_AGENT"])) {
return false; return false;
} }

@ -26,7 +26,7 @@ abstract class AccountView extends View {
} }
} }
public function getCode() { public function getCode(): string {
$html = parent::getCode(); $html = parent::getCode();
$content = $this->getAccountContent(); $content = $this->getAccountContent();

@ -11,7 +11,7 @@ class AdminDashboardBody extends Body {
parent::__construct($document); parent::__construct($document);
} }
public function getCode() { public function getCode(): string {
$html = parent::getCode(); $html = parent::getCode();
$script = new Script(Script::MIME_TEXT_JAVASCRIPT, "/js/admin.min.js"); $script = new Script(Script::MIME_TEXT_JAVASCRIPT, "/js/admin.min.js");
$html .= "<body><div class=\"wrapper\" id=\"root\">$script</div></body>"; $html .= "<body><div class=\"wrapper\" id=\"root\">$script</div></body>";

@ -24,7 +24,7 @@ class LoginBody extends Body {
$head->addCSS(Link::ACCOUNT); $head->addCSS(Link::ACCOUNT);
} }
public function getCode() { public function getCode(): string {
$html = parent::getCode(); $html = parent::getCode();
$username = L("Username"); $username = L("Username");

@ -56,7 +56,7 @@ class LanguageFlags extends View {
} }
} }
public function getCode() { public function getCode(): string {
return implode('', $this->languageFlags); return implode('', $this->languageFlags);
} }
} }

@ -6,7 +6,7 @@ use Elements\View;
class View404 extends View { class View404 extends View {
public function getCode() { public function getCode(): string {
return parent::getCode() . "<b>Not found</b>"; return parent::getCode() . "<b>Not found</b>";
} }

@ -1,6 +1,6 @@
<?php <?php
define("WEBBASE_VERSION", "1.2.1"); define("WEBBASE_VERSION", "1.2.2");
function getProtocol() { function getProtocol() {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https" : "http"; return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https" : "http";