web-base/core/Elements/Document.class.php

83 lines
1.9 KiB
PHP
Raw Normal View History

2020-02-09 23:02:19 +01:00
<?php
namespace Elements;
2021-12-08 16:53:43 +01:00
use Driver\SQL\SQL;
2020-04-03 15:56:04 +02:00
use Objects\User;
2020-02-09 23:02:19 +01:00
abstract class Document {
2020-04-03 15:56:04 +02:00
protected User $user;
protected bool $databaseRequired;
2021-12-08 16:53:43 +01:00
private bool $cspEnabled;
private ?string $cspNonce;
2022-02-20 16:53:26 +01:00
private array $cspWhitelist;
private string $domain;
2020-02-09 23:02:19 +01:00
2021-12-08 16:53:43 +01:00
public function __construct(User $user) {
2021-04-02 22:48:14 +02:00
$this->user = $user;
2021-12-08 16:53:43 +01:00
$this->cspEnabled = false;
$this->cspNonce = null;
2020-04-02 21:39:02 +02:00
$this->databaseRequired = true;
2022-02-20 16:53:26 +01:00
$this->cspWhitelist = [];
$this->domain = $user->getConfiguration()->getSettings()->getBaseUrl();
2020-02-09 23:02:19 +01:00
}
2021-12-08 16:53:43 +01:00
public function getSQL(): ?SQL {
return $this->user->getSQL();
}
2021-04-03 13:05:20 +02:00
2021-12-08 16:53:43 +01:00
public function getUser(): User {
return $this->user;
}
2020-02-09 23:02:19 +01:00
2021-12-08 16:53:43 +01:00
public function getCSPNonce(): ?string {
return $this->cspNonce;
}
2021-12-08 16:53:43 +01:00
public function isCSPEnabled(): bool {
return $this->cspEnabled;
2020-02-09 23:02:19 +01:00
}
2021-12-08 16:53:43 +01:00
public function enableCSP() {
$this->cspEnabled = true;
$this->cspNonce = generateRandomString(16, "base62");
}
2020-02-09 23:02:19 +01:00
2022-02-20 16:53:26 +01:00
protected function addCSPWhitelist(string $path) {
$this->cspWhitelist[] = $this->domain . $path;
}
2021-12-08 16:53:43 +01:00
public function getCode(): string {
2020-04-02 21:39:02 +02:00
if ($this->databaseRequired) {
2020-02-09 23:02:19 +01:00
$sql = $this->user->getSQL();
if (is_null($sql)) {
die("Database is not configured yet.");
2021-12-08 16:53:43 +01:00
} else if (!$sql->isConnected()) {
2020-02-09 23:02:19 +01:00
die("Database is not connected: " . $sql->getLastError());
}
}
2021-12-08 16:53:43 +01:00
if ($this->cspEnabled) {
2022-02-20 16:53:26 +01:00
$cspWhiteList = implode(" ", $this->cspWhitelist);
$csp = [
"default-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"script-src $cspWhiteList 'nonce-$this->cspNonce'"
];
2021-12-08 16:53:43 +01:00
if ($this->user->getConfiguration()->getSettings()->isRecaptchaEnabled()) {
$csp[] = "frame-src https://www.google.com/ 'self'";
}
2020-02-09 23:02:19 +01:00
2022-02-20 16:53:26 +01:00
$compiledCSP = implode("; ", $csp);
2021-12-08 16:53:43 +01:00
header("Content-Security-Policy: $compiledCSP;");
}
2020-02-09 23:02:19 +01:00
2021-12-08 16:53:43 +01:00
return "";
}
2020-04-03 15:56:04 +02:00
}