Compare commits

..

No commits in common. "master" and "v0.14" have entirely different histories.

11 changed files with 609 additions and 496 deletions

View File

@ -1,4 +1,4 @@
FROM php:8.1-cli-bookworm
FROM php:7.4.7-cli-buster
RUN apt-get update && apt-get install -y unzip
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

View File

@ -5,12 +5,12 @@
"license": "GNU GPL 3.0",
"require": {
"vlucas/phpdotenv": "^5.5",
"symfony/console": "^6.3",
"symfony/console": "^5.4",
"phpmailer/phpmailer": "^6.8",
"cocur/slugify": "^4.5"
"cocur/slugify": "^4.3"
},
"require-dev": {
"phpunit/phpunit": "^10.3",
"phpunit/phpunit": "^9.6",
"phpstan/phpstan": "^1.10"
},
"autoload": {

942
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,8 +4,6 @@ use SokoWeb\Interfaces\Database\IConnection;
use SokoWeb\Interfaces\Database\IResultSet;
use SokoWeb\Interfaces\Database\IStatement;
use mysqli;
use DateTime;
use DateTimeZone;
class Connection implements IConnection
{
@ -111,16 +109,5 @@ class Connection implements IConnection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->connection = new mysqli($this->host, $this->user, $this->password, $this->db, $this->port, $this->socket);
$this->connection->set_charset('utf8mb4');
$this->connection->query('SET time_zone = \'' . $this->getTimeZone() . '\'');
}
private function getTimeZone(): string {
$tz = new DateTimeZone(date_default_timezone_get());
$offset = $tz->getOffset(new DateTime('now', new DateTimeZone('UTC')));
$hours = intdiv($offset, 3600);
$minutes = abs(($offset % 3600) / 60);
return sprintf("%+03d:%02d", $hours, $minutes);
}
}

View File

@ -7,15 +7,13 @@ class Request implements IRequest
{
private string $url;
private ?string $method = null;
private int $method;
private string $query = '';
private ?string $body = null;
private array $headers = [];
public function __construct(string $url = '', ?string $method = null)
public function __construct(string $url = '', int $method = self::HTTP_GET)
{
$this->url = $url;
$this->method = $method;
@ -26,7 +24,7 @@ class Request implements IRequest
$this->url = $url;
}
public function setMethod(string $method): void
public function setMethod(int $method): void
{
$this->method = $method;
}
@ -40,11 +38,6 @@ class Request implements IRequest
}
}
public function setBody(string $body): void
{
$this->body = $body;
}
public function setHeaders(array $headers): void
{
$this->headers = array_merge($this->headers, $headers);
@ -54,20 +47,13 @@ class Request implements IRequest
{
$ch = curl_init();
$url = $this->url . '?' . $this->query;
if ($this->method === self::HTTP_POST) {
$url = $this->url;
if ($this->body !== null) {
if ($this->method === null) {
$this->method = self::HTTP_POST;
}
if ($this->method === self::HTTP_POST) {
curl_setopt($ch, CURLOPT_POST, 1);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->body);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
} else {
$url = $this->url . '?' . $this->query;
}
curl_setopt($ch, CURLOPT_URL, $url);

View File

@ -2,24 +2,16 @@
interface IRequest
{
const HTTP_GET = 'GET';
const HTTP_GET = 0;
const HTTP_POST = 'POST';
const HTTP_PUT = 'PUT';
const HTTP_PATCH = 'PATCH';
const HTTP_DELETE = 'DELETE';
const HTTP_POST = 1;
public function setUrl(string $url): void;
public function setMethod(string $method): void;
public function setMethod(int $method): void;
public function setQuery($query): void;
public function setBody(string $body): void;
public function setHeaders(array $headers): void;
public function send(): IResponse;

View File

@ -29,6 +29,13 @@ class Mail
{
$this->body = file_get_contents(ROOT . '/mail/' . $template . '.html');
$baseParameters = [
'APP_NAME' => $_ENV['APP_NAME'],
'BASE_URL' => $_ENV['APP_URL'],
];
$params = array_merge($baseParameters, $params);
foreach ($params as $key => $param) {
$this->body = str_replace('{{' . $key . '}}', $param, $this->body);
}
@ -44,10 +51,8 @@ class Mail
if (!empty($_ENV['MAIL_HOST'])) {
$mailer->Mailer = 'smtp';
$mailer->Host = $_ENV['MAIL_HOST'];
$mailer->Port = !empty($_ENV['MAIL_PORT']) ? $_ENV['MAIL_PORT'] : 587;
$secureMaping = ['none' => '', 'starttls' => PHPMailer::ENCRYPTION_STARTTLS, 'smtps' => PHPMailer::ENCRYPTION_SMTPS];
$mailer->SMTPSecure = !empty($_ENV['MAIL_SECURE']) ? $secureMaping[$_ENV['MAIL_SECURE']] : '';
$mailer->Port = !empty($_ENV['MAIL_PORT']) ? $_ENV['MAIL_PORT'] : 25;
$mailer->SMTPSecure = !empty($_ENV['MAIL_SECURE']) ? $_ENV['MAIL_SECURE'] : '';
if (!empty($_ENV['MAIL_USER'])) {
$mailer->SMTPAuth = true;

View File

@ -6,12 +6,12 @@ use SokoWeb\Interfaces\Response\IRedirect;
use SokoWeb\Interfaces\Response\IContent;
use SokoWeb\Interfaces\Authentication\IAuthenticationRequired;
use SokoWeb\Interfaces\Authorization\ISecured;
use SokoWeb\Interfaces\Routing\IRouteCollection;
use SokoWeb\Interfaces\Database\IConnection;
use SokoWeb\Interfaces\Request\IRequest;
use SokoWeb\Response\Redirect;
use SokoWeb\Response\HtmlContent;
use SokoWeb\Response\JsonContent;
use SokoWeb\Routing\RouteCollection;
class HttpResponse
{
@ -19,7 +19,7 @@ class HttpResponse
private IConnection $dbConnection;
private IRouteCollection $routeCollection;
private RouteCollection $routeCollection;
private array $appConfig;
@ -32,7 +32,7 @@ class HttpResponse
public function __construct(
IRequest $request,
IConnection $dbConnection,
IRouteCollection $routeCollection,
RouteCollection $routeCollection,
array $appConfig,
string $requestMethod,
string $requestUrl
@ -55,11 +55,6 @@ class HttpResponse
public function render(): void
{
$this->handleCors();
if ($this->method === 'options') {
return;
}
$match = $this->routeCollection->match($this->method, $this->parsedUrl['path']);
if ($match === null) {
$this->render404();
@ -99,7 +94,6 @@ class HttpResponse
$response = call_user_func([$controller, $handler[1]]);
} catch (Exception $exception) {
$this->dbConnection->rollback();
error_log($exception);
$this->render500($exception);
return;
}
@ -115,63 +109,10 @@ class HttpResponse
}
}
private function handleCors(): void
{
$origin = $this->request->header('Origin');
if (!$origin) {
return;
}
if (isset($this->appConfig['cors']['allow_origins'])) {
if (in_array($origin, $this->appConfig['cors']['allow_origins']) || in_array('*', $this->appConfig['cors']['allow_origins'])) {
header("Access-Control-Allow-Origin: {$origin}");
}
}
if (!empty($this->appConfig['cors']['allow_credentials'])) {
header('Access-Control-Allow-Credentials: true');
}
if ($this->method !== 'options') {
return;
}
if (isset($this->appConfig['cors']['allow_headers'])) {
$headers = explode(',', $this->request->header('Access-Control-Request-Headers'));
if (in_array('*', $this->appConfig['cors']['allow_headers'])) {
$allow_headers = $headers;
} else {
$allow_headers = array_intersect($this->appConfig['cors']['allow_headers'], $headers);
}
if (count($allow_headers) > 0) {
header('Access-Control-Allow-Headers: ' . join(', ', $allow_headers));
}
}
if (isset($this->appConfig['cors']['allow_methods'])) {
if (in_array('*', $this->appConfig['cors']['allow_methods'])) {
$allow_methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT'];
} else {
$allow_methods = $this->appConfig['cors']['allow_methods'];
}
if (count($allow_methods) > 0) {
header('Access-Control-Allow-Methods: ' . join(', ', $allow_methods));
}
}
$max_age = $this->appConfig['cors']['max_age'] ?? 600;
header("Access-Control-Max-Age: {$max_age}");
}
private function redirectToLogin(): void
{
$this->request->session()->set('redirect_after_login', $this->rawUrl);
$response = new Redirect(
$this->routeCollection->getRoute($this->appConfig['loginRouteId'])
->generateLink(['redirect_after_login' => $this->rawUrl]),
IRedirect::TEMPORARY);
$response = new Redirect($this->routeCollection->getRoute($this->appConfig['loginRouteId'])->generateLink(), IRedirect::TEMPORARY);
header('Location: ' . $this->getRedirectUrl($response), true, $response->getHttpCode());
}

View File

@ -34,7 +34,7 @@ class Route implements IRoute
foreach ($this->pattern as $fragment) {
if (preg_match('/^{(\\w+)(\\?)?}$/', $fragment, $matches) === 1) {
if (isset($parameters[$matches[1]])) {
$link[] = rawurlencode($parameters[$matches[1]]);
$link[] = $parameters[$matches[1]];
unset($parameters[$matches[1]]);
} elseif (!isset($matches[2])) {//TODO: why? parameter not found but not optional
$link[] = $fragment;
@ -53,7 +53,7 @@ class Route implements IRoute
$queryParams[$key] = $value;
}
$query = count($queryParams) > 0 ? '?' . http_build_query($queryParams, encoding_type: PHP_QUERY_RFC3986) : '';
$query = count($queryParams) > 0 ? '?' . http_build_query($queryParams) : '';
return '/' . implode('/', $link) . $query;
}
@ -64,7 +64,7 @@ class Route implements IRoute
foreach ($path as $i => $fragment) {
if (preg_match('/^{(\\w+)(?:\\?)?}$/', $this->pattern[$i], $matches) === 1) {
$parameters[$matches[1]] = rawurldecode($fragment);
$parameters[$matches[1]] = $fragment;
} elseif ($fragment != $this->pattern[$i]) {
return null;
}

View File

@ -86,12 +86,12 @@ class DatabaseSessionHandler implements ISessionHandler
return true;
}
public function gc($maxlifetime): int|false
public function gc($maxlifetime): bool
{
// empty on purpose
// old sessions are deleted by MaintainDatabaseCommand
return 1;
return true;
}
public function create_sid(): string

View File

@ -17,7 +17,7 @@ final class GoogleOAuthTest extends TestCase
$redirectUrl = 'http://example.com/oauth';
$requestMock = $this->getMockBuilder(IRequest::class)
->onlyMethods(['setUrl', 'setMethod', 'setQuery', 'setHeaders', 'send'])
->setMethods(['setUrl', 'setMethod', 'setQuery', 'setHeaders', 'send'])
->getMock();
$googleOAuth = new GoogleOAuth($requestMock);
@ -48,10 +48,10 @@ final class GoogleOAuthTest extends TestCase
$redirectUrl = 'http://example.com/oauth';
$requestMock = $this->getMockBuilder(IRequest::class)
->onlyMethods(['setUrl', 'setMethod', 'setQuery', 'setHeaders', 'send'])
->setMethods(['setUrl', 'setMethod', 'setQuery', 'setHeaders', 'send'])
->getMock();
$responseMock = $this->getMockBuilder(IResponse::class)
->onlyMethods(['getBody', 'getHeaders'])
->setMethods(['getBody', 'getHeaders'])
->getMock();
$googleOAuth = new GoogleOAuth($requestMock);