Merge pull request 'Dev' (#10) from dev into main
Reviewed-on: #10
@@ -16,7 +16,8 @@ dist-ssr
|
||||
/docs
|
||||
|
||||
cache
|
||||
uploads
|
||||
uploads/*
|
||||
!uploads/.htaccess
|
||||
extensions/dev_*
|
||||
.agents
|
||||
skills-lock.json
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L]
|
||||
|
||||
# Allow direct access to uploaded files with URL format: /uploads/{filepath;,}
|
||||
RewriteRule ^uploads/.*\.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC]
|
||||
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
|
||||
|
||||
# Rewrite all remaining requests to index.php
|
||||
|
||||
@@ -9,10 +9,10 @@ return [
|
||||
| General settings for configuring the PageBuilder.
|
||||
|
|
||||
*/
|
||||
'general' => [
|
||||
'language' => 'en',
|
||||
'assets_url' => '/plugi-core/dist',
|
||||
'uploads_url' => '/uploads'
|
||||
"general" => [
|
||||
"language" => "en",
|
||||
"assets_url" => "/plugi-core/dist",
|
||||
"uploads_url" => "/uploads",
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -23,9 +23,9 @@ return [
|
||||
| File storage settings.
|
||||
|
|
||||
*/
|
||||
'storage' => [
|
||||
'use_database' => true,
|
||||
'uploads_folder' => __DIR__ . '/uploads'
|
||||
"storage" => [
|
||||
"use_database" => true,
|
||||
"uploads_folder" => __DIR__ . "/uploads",
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -37,10 +37,10 @@ return [
|
||||
| credentials configured in this setting block.
|
||||
|
|
||||
*/
|
||||
'auth' => [
|
||||
'use_login' => true,
|
||||
'class' => Plugi\Modules\Auth\Auth::class,
|
||||
'url' => '/admin/auth',
|
||||
"auth" => [
|
||||
"use_login" => true,
|
||||
"class" => Plugi\Modules\Auth\Auth::class,
|
||||
"url" => "/admin/auth",
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -51,10 +51,10 @@ return [
|
||||
| By default a basic WebsiteManager is provided for creating/editing pages.
|
||||
|
|
||||
*/
|
||||
'website_manager' => [
|
||||
'use_website_manager' => true,
|
||||
'class' => Plugi\Modules\WebsiteManager\WebsiteManager::class,
|
||||
'url' => '/admin'
|
||||
"website_manager" => [
|
||||
"use_website_manager" => true,
|
||||
"class" => Plugi\Modules\WebsiteManager\WebsiteManager::class,
|
||||
"url" => "/admin",
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -65,8 +65,8 @@ return [
|
||||
| By default a setting class is provided for accessing website settings.
|
||||
|
|
||||
*/
|
||||
'setting' => [
|
||||
'class' => Plugi\Setting::class
|
||||
"setting" => [
|
||||
"class" => Plugi\Setting::class,
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -77,12 +77,12 @@ return [
|
||||
| By default a PageBuilder is provided based on GrapesJS.
|
||||
|
|
||||
*/
|
||||
'pagebuilder' => [
|
||||
'class' => Plugi\Modules\GrapesJS\PageBuilder::class,
|
||||
'url' => '/admin/pagebuilder',
|
||||
'actions' => [
|
||||
'back' => '/admin'
|
||||
]
|
||||
"pagebuilder" => [
|
||||
"class" => Plugi\Modules\GrapesJS\PageBuilder::class,
|
||||
"url" => "/admin/pagebuilder",
|
||||
"actions" => [
|
||||
"back" => "/admin?tab=pages",
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -93,14 +93,14 @@ return [
|
||||
| By default a Page class is provided with knowledge about its layout and URL.
|
||||
|
|
||||
*/
|
||||
'page' => [
|
||||
'class' => Plugi\Page::class,
|
||||
'table' => 'pages',
|
||||
'translation' => [
|
||||
'class' => Plugi\PageTranslation::class,
|
||||
'table' => 'page_translations',
|
||||
'foreign_key' => 'page_id',
|
||||
]
|
||||
"page" => [
|
||||
"class" => Plugi\Page::class,
|
||||
"table" => "pages",
|
||||
"translation" => [
|
||||
"class" => Plugi\PageTranslation::class,
|
||||
"table" => "page_translations",
|
||||
"foreign_key" => "page_id",
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -114,10 +114,10 @@ return [
|
||||
| The cached html is removed if the page is saved again in the page builder.
|
||||
|
|
||||
*/
|
||||
'cache' => [
|
||||
'enabled' => false,
|
||||
'folder' => __DIR__ . '/cache',
|
||||
'class' => Plugi\Cache::class
|
||||
"cache" => [
|
||||
"enabled" => false,
|
||||
"folder" => __DIR__ . "/cache",
|
||||
"class" => Plugi\Cache::class,
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -130,11 +130,11 @@ return [
|
||||
| containing a view, model (optional) and controller (optional).
|
||||
|
|
||||
*/
|
||||
'theme' => [
|
||||
'class' => Plugi\Theme::class,
|
||||
'folder' => __DIR__ . '/themes',
|
||||
'folder_url' => '/themes',
|
||||
'active_theme' => 'theme-one'
|
||||
"theme" => [
|
||||
"class" => Plugi\Theme::class,
|
||||
"folder" => __DIR__ . "/themes",
|
||||
"folder_url" => "/themes",
|
||||
"active_theme" => "theme-one",
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -145,8 +145,8 @@ return [
|
||||
| Settings for resolving pages based on the current URI.
|
||||
|
|
||||
*/
|
||||
'router' => [
|
||||
'class' => Plugi\Modules\Router\DatabasePageRouter::class
|
||||
"router" => [
|
||||
"class" => Plugi\Modules\Router\DatabasePageRouter::class,
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -158,17 +158,17 @@ return [
|
||||
| blank when the server does not require authentication.
|
||||
|
|
||||
*/
|
||||
'mail' => [
|
||||
'class' => Plugi\Core\Mailer::class,
|
||||
'transport' => 'smtp',
|
||||
'host' => $_ENV['MAIL_HOST'] ?? '',
|
||||
'port' => (int) ($_ENV['MAIL_PORT'] ?? 587),
|
||||
'encryption' => $_ENV['MAIL_ENCRYPTION'] ?? 'tls',
|
||||
'username' => $_ENV['MAIL_USERNAME'] ?? '',
|
||||
'password' => $_ENV['MAIL_PASSWORD'] ?? '',
|
||||
'from_address' => $_ENV['MAIL_FROM_ADDRESS'] ?? '',
|
||||
'from_name' => $_ENV['MAIL_FROM_NAME'] ?? '',
|
||||
'timeout' => (int) ($_ENV['MAIL_TIMEOUT'] ?? 10),
|
||||
"mail" => [
|
||||
"class" => Plugi\Core\Mailer::class,
|
||||
"transport" => "smtp",
|
||||
"host" => $_ENV["MAIL_HOST"] ?? "",
|
||||
"port" => (int) ($_ENV["MAIL_PORT"] ?? 587),
|
||||
"encryption" => $_ENV["MAIL_ENCRYPTION"] ?? "tls",
|
||||
"username" => $_ENV["MAIL_USERNAME"] ?? "",
|
||||
"password" => $_ENV["MAIL_PASSWORD"] ?? "",
|
||||
"from_address" => $_ENV["MAIL_FROM_ADDRESS"] ?? "",
|
||||
"from_name" => $_ENV["MAIL_FROM_NAME"] ?? "",
|
||||
"timeout" => (int) ($_ENV["MAIL_TIMEOUT"] ?? 10),
|
||||
],
|
||||
|
||||
/*
|
||||
@@ -182,6 +182,5 @@ return [
|
||||
| Important: when overriding a class always extend the original class.
|
||||
|
|
||||
*/
|
||||
'class_replacements' => [
|
||||
],
|
||||
"class_replacements" => [],
|
||||
];
|
||||
|
||||
@@ -7,22 +7,44 @@ use Plugi\Extensions\Form\Finishers\FinishersRepository;
|
||||
|
||||
class SubmissionHandler
|
||||
{
|
||||
public const MAX_REQUEST_BYTES = 65536;
|
||||
public const MAX_FIELD_BYTES = 16384;
|
||||
public const MAX_FIELDS = 100;
|
||||
|
||||
private $formsRepository;
|
||||
private $finishersRepository;
|
||||
private $rateLimiter;
|
||||
|
||||
public function __construct($formsRepository = null, $finishersRepository = null)
|
||||
public function __construct($formsRepository = null, $finishersRepository = null, $rateLimiter = null)
|
||||
{
|
||||
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
|
||||
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
|
||||
$this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter();
|
||||
}
|
||||
|
||||
public function handle($formId, string $rawData): array
|
||||
{
|
||||
if (strlen($rawData) > self::MAX_REQUEST_BYTES) {
|
||||
return $this->failure(413, ['The submission is too large.']);
|
||||
}
|
||||
|
||||
$formId = filter_var($formId, FILTER_VALIDATE_INT);
|
||||
if ($formId === false || $formId < 1) {
|
||||
return $this->failure(400, ['A valid form id is required.']);
|
||||
}
|
||||
|
||||
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
if (!is_string($clientIp) || filter_var($clientIp, FILTER_VALIDATE_IP) === false) {
|
||||
$clientIp = 'unknown';
|
||||
}
|
||||
try {
|
||||
if (!$this->rateLimiter->consume($formId, $clientIp)) {
|
||||
return $this->failure(429, ['Too many submissions. Please try again later.']);
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
return $this->failure(503, ['Submissions are temporarily unavailable.']);
|
||||
}
|
||||
|
||||
try {
|
||||
$form = $this->formsRepository->findWithId($formId);
|
||||
} catch (\Throwable $exception) {
|
||||
@@ -125,6 +147,10 @@ class SubmissionHandler
|
||||
$knownFields = [];
|
||||
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
|
||||
|
||||
if (count($submittedFields) > self::MAX_FIELDS) {
|
||||
return ['The submission contains too many fields.'];
|
||||
}
|
||||
|
||||
foreach ($formFields as $field) {
|
||||
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
|
||||
return ['The form contains an invalid field configuration.'];
|
||||
@@ -160,6 +186,20 @@ class SubmissionHandler
|
||||
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
|
||||
return ['The submission contains an unknown field.'];
|
||||
}
|
||||
$value = $submittedFields[$name];
|
||||
if (is_string($value) && strlen($value) > self::MAX_FIELD_BYTES) {
|
||||
return ['A submitted field is too large.'];
|
||||
}
|
||||
if (is_array($value)) {
|
||||
if (count($value) > self::MAX_FIELDS) {
|
||||
return ['A submitted field contains too many values.'];
|
||||
}
|
||||
foreach ($value as $item) {
|
||||
if (is_string($item) && strlen($item) > self::MAX_FIELD_BYTES) {
|
||||
return ['A submitted field is too large.'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($knownFields as $name => $field) {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Extensions\Form;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class SubmissionRateLimiter
|
||||
{
|
||||
private const MAX_SUBMISSIONS = 5;
|
||||
private const WINDOW_SECONDS = 600;
|
||||
|
||||
private $db;
|
||||
private string $table;
|
||||
|
||||
public function __construct($db = null)
|
||||
{
|
||||
global $phpb_db;
|
||||
|
||||
$this->db = $db ?? $phpb_db ?? null;
|
||||
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', $_ENV['DATABASE_PREFIX'] ?? '');
|
||||
$this->table = '`' . $prefix . 'ext__form_submission_limits`';
|
||||
}
|
||||
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
if (!is_object($this->db)) {
|
||||
throw new RuntimeException('The submission rate limit store is unavailable.');
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$ipHash = hash('sha256', $clientIp);
|
||||
if (!$this->db->query(
|
||||
"INSERT IGNORE INTO {$this->table} (formId, ipHash, startedAt, submissions) VALUES (?, ?, ?, 0)",
|
||||
[$formId, $ipHash, $now]
|
||||
)) {
|
||||
throw new RuntimeException('The submission rate limit could not be initialized.');
|
||||
}
|
||||
|
||||
$allowed = $this->db->transaction(function () use ($formId, $ipHash, $now): bool {
|
||||
$rows = $this->db->select(
|
||||
"SELECT startedAt, submissions FROM {$this->table} WHERE formId = ? AND ipHash = ? FOR UPDATE",
|
||||
[$formId, $ipHash]
|
||||
);
|
||||
if (empty($rows)) {
|
||||
throw new RuntimeException('The submission rate limit could not be loaded.');
|
||||
}
|
||||
|
||||
$startedAt = (int) $rows[0]['startedAt'];
|
||||
$submissions = (int) $rows[0]['submissions'];
|
||||
if ($now - $startedAt >= self::WINDOW_SECONDS) {
|
||||
$startedAt = $now;
|
||||
$submissions = 0;
|
||||
}
|
||||
if ($submissions >= self::MAX_SUBMISSIONS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->db->query(
|
||||
"UPDATE {$this->table} SET startedAt = ?, submissions = ? WHERE formId = ? AND ipHash = ?",
|
||||
[$startedAt, $submissions + 1, $formId, $ipHash]
|
||||
)) {
|
||||
throw new RuntimeException('The submission rate limit could not be updated.');
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if ($allowed && random_int(1, 100) === 1) {
|
||||
try {
|
||||
$this->db->query(
|
||||
"DELETE FROM {$this->table} WHERE startedAt < ?",
|
||||
[$now - (self::WINDOW_SECONDS * 2)]
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
}
|
||||
}
|
||||
|
||||
return $allowed;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,17 @@ return [
|
||||
],
|
||||
"uniqueKeys" => [],
|
||||
],
|
||||
"submission_limits" => [
|
||||
"columns" => [
|
||||
"formId" => "int NOT NULL",
|
||||
"ipHash" => "char(64) NOT NULL",
|
||||
"startedAt" => "int unsigned NOT NULL",
|
||||
"submissions" => "int unsigned NOT NULL",
|
||||
],
|
||||
"uniqueKeys" => [
|
||||
"form_ip" => ["formId", "ipHash"],
|
||||
],
|
||||
],
|
||||
"definitions" => [
|
||||
"columns" => [
|
||||
"name" => "varchar(255) NOT NULL",
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
<?php
|
||||
|
||||
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
|
||||
$result = $handler->handle($_GET['id'] ?? null, file_get_contents('php://input') ?: '');
|
||||
$rawData = file_get_contents(
|
||||
'php://input',
|
||||
false,
|
||||
null,
|
||||
0,
|
||||
\Plugi\Extensions\Form\SubmissionHandler::MAX_REQUEST_BYTES + 1
|
||||
);
|
||||
$result = $handler->handle($_GET['id'] ?? null, is_string($rawData) ? $rawData : '');
|
||||
|
||||
http_response_code($result['status']);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace FormExtensionTests {
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php';
|
||||
|
||||
class TestMailer
|
||||
{
|
||||
@@ -160,6 +161,40 @@ namespace FormExtensionTests {
|
||||
return ['class' => $this->finishers[$key]];
|
||||
}
|
||||
}
|
||||
|
||||
class RateLimitDatabase
|
||||
{
|
||||
public array $rows = [];
|
||||
|
||||
public function query(string $query, array $parameters = []): bool
|
||||
{
|
||||
if (str_starts_with($query, 'INSERT IGNORE')) {
|
||||
$key = $parameters[0] . ':' . $parameters[1];
|
||||
$this->rows[$key] ??= ['startedAt' => $parameters[2], 'submissions' => 0];
|
||||
return true;
|
||||
}
|
||||
if (str_starts_with($query, 'UPDATE')) {
|
||||
$key = $parameters[2] . ':' . $parameters[3];
|
||||
$this->rows[$key] = ['startedAt' => $parameters[0], 'submissions' => $parameters[1]];
|
||||
return true;
|
||||
}
|
||||
if (str_starts_with($query, 'DELETE')) {
|
||||
return true;
|
||||
}
|
||||
throw new \RuntimeException('Unexpected rate limiter query.');
|
||||
}
|
||||
|
||||
public function select(string $query, array $parameters): array
|
||||
{
|
||||
$key = $parameters[0] . ':' . $parameters[1];
|
||||
return isset($this->rows[$key]) ? [$this->rows[$key]] : [];
|
||||
}
|
||||
|
||||
public function transaction(callable $callback): mixed
|
||||
{
|
||||
return $callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Plugi {
|
||||
@@ -177,6 +212,7 @@ namespace {
|
||||
|
||||
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
|
||||
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
|
||||
use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
|
||||
use Plugi\Extensions\Form\SubmissionHandler;
|
||||
|
||||
if (!function_exists('phpb_instance')) {
|
||||
@@ -193,11 +229,41 @@ namespace {
|
||||
}
|
||||
}
|
||||
|
||||
function makeHandler($form): SubmissionHandler
|
||||
function makeHandler($form, $rateLimiter = null): SubmissionHandler
|
||||
{
|
||||
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository());
|
||||
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository(), $rateLimiter ?? new AllowSubmissionRateLimiter());
|
||||
}
|
||||
|
||||
class AllowSubmissionRateLimiter
|
||||
{
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class RejectSubmissionRateLimiter
|
||||
{
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$rateLimitDatabase = new TestRateLimitDatabase();
|
||||
$rateLimiter = new \Plugi\Extensions\Form\SubmissionRateLimiter($rateLimitDatabase);
|
||||
for ($submission = 0; $submission < 5; $submission++) {
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions within the limit must be allowed.');
|
||||
}
|
||||
assertSameValue(false, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions over the limit must be rejected.');
|
||||
assertSameValue(true, $rateLimiter->consume(8, '203.0.113.1'), 'Rate limits must be scoped to each form.');
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.2'), 'Rate limits must be scoped to each client IP.');
|
||||
$rateLimitKey = '7:' . hash('sha256', '203.0.113.1');
|
||||
$rateLimitDatabase->rows[$rateLimitKey]['startedAt'] = time() - 601;
|
||||
$rateLimitDatabase->rows[$rateLimitKey]['submissions'] = 5;
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Expired rate limit windows must reset.');
|
||||
assertSameValue(1, $rateLimitDatabase->rows[$rateLimitKey]['submissions'], 'The reset window must begin at one submission.');
|
||||
|
||||
function validForm(array $finishers = []): array
|
||||
{
|
||||
return [
|
||||
@@ -223,6 +289,31 @@ namespace {
|
||||
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
|
||||
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$result = makeHandler($form, new RejectSubmissionRateLimiter())->handle(7, $validPayload);
|
||||
assertSameValue(429, $result['status'], 'Rate-limited submissions must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Rate-limited submissions must not run actions');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$result = makeHandler($form)->handle(7, str_repeat('x', 65537));
|
||||
assertSameValue(413, $result['status'], 'Oversized request bodies must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized requests must not run actions');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$oversizedField = json_encode(['fields' => ['name' => str_repeat('A', 16385)]]);
|
||||
$result = makeHandler($form)->handle(7, $oversizedField);
|
||||
assertSameValue(422, $result['status'], 'Oversized field values must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized fields must not run actions');
|
||||
|
||||
$tooManyFields = array_fill_keys(array_map('strval', range(1, 101)), 'value');
|
||||
$result = makeHandler($form)->handle(7, json_encode(['fields' => $tooManyFields]));
|
||||
assertSameValue(422, $result['status'], 'Submissions with too many fields must be rejected');
|
||||
|
||||
$submitRoute = file_get_contents(dirname(__DIR__) . '/routes/submit.php');
|
||||
if (strpos($submitRoute, 'MAX_REQUEST_BYTES + 1') === false) {
|
||||
throw new \RuntimeException('The submission route must read no more than the configured body limit plus one byte.');
|
||||
}
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
|
||||
$result = makeHandler($form)->handle(7, $validPayload);
|
||||
|
||||
@@ -16,6 +16,7 @@ return [
|
||||
'name' => 'varchar(255)',
|
||||
'layout' => 'varchar(255)',
|
||||
'data' => 'longtext',
|
||||
'draft_data' => 'longtext NULL',
|
||||
'type' => 'varchar(63)',
|
||||
'status' => 'varchar(63)',
|
||||
'parent_id' => 'int',
|
||||
@@ -57,6 +58,8 @@ return [
|
||||
'original_file' => 'varchar(512)',
|
||||
'mime_type' => 'varchar(50)',
|
||||
'server_file' => 'varchar(512)',
|
||||
'alt_text' => "varchar(1000) NOT NULL DEFAULT ''",
|
||||
'folder' => "varchar(255) NOT NULL DEFAULT ''",
|
||||
],
|
||||
'uniqueKeys' => [
|
||||
'public_id' => ['public_id'],
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAMA,eACE,uBACA,SACA,gBAGF,EACE,mCACA,gCACA,2BAGF,kCACE,cAGF,gBACE,eAGF,YACE,gBAGF,OACE,qBACA,YACA,WACA,gBAEA,qBACE,mBAIJ,cACE,kBACA,YACA,WACA,sBACA,cACA,sCAEA,qBACE,kBACA,UAGF,sBACE,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACE,eACA,eACA,gBACA,kBACA,cAGJ,sBACE,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEF,kBACE,+BAIJ,sBACE,gBAGF,eACE,YACA,MACA,yBAEF,aACE,uBAGF,cACE,UAEA,8BACE,uBAGJ,mDAGE,aAEF,eACE,UAEF,YACE,yBACA,mBACA,cAEF,eACE,cAEF,gBACE,cAEF,wBACE,cAEF,iBACE,WACA,wBACA,qBACA,gBAEF,oBACE,UACA,WAEF,0BACE,8BAEF,0BACE,oCACA,kBAEA,gCACE,oCAMJ,cACE,SAEA,0BACE,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACE,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIN,gBACE,QAEF,sCAEE,OACA,wBACA,qBACA,gBACA,MA1Lc,MA2Ld,iBACA,gBACA,cACA,eACA,eACA,gBAEF,wBACE,iBACA,mBACA,yBACA,gBAEA,0CACE,gBAGF,4BACE,YACA,gBAGF,gCACE,mBACA,YAGJ,iCAEE,KAxNc,MA2Nd,4BACE,2BAEF,6BACE,4BAEF,8BACE,4BAOJ,cACE,yBAGA,6DAEE,WAGJ,WACE,yBACA,gBACA,YAEA,uDAGE,YAGF,0BACE,6BAOJ,gBACE,kBACA,gBACA,MAxQc,MAyQd,eACA,mBACA,YACA,YACA,aACA,mBAEA,sEACE,iBAEA,oFACE,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gGACE,qBAKR,gBACE,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAMF,cACE,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACE,kBACA,SACA,SACA,eACA,cAGF,oBACE,mBACA,4BACA,gBACA,YAEA,iCACE,cAKN,WACE,YACA,gBACA,mBACA,WACA,uBAEA,cACE,YAGF,iBACE,yBAGF,wBACE,YACA,gBACA,kBACA,WAEA,4BACE,WAIN,cACE,mBACA,YAEF,sBACE,mBACA,oBAEF,iBACE,gBACA,YACA,aAEA,mBACE,iBACA,gBAGJ,oBACE,mBAEF,6BACE,8BACA,mBAEF,eACE,8BAMF,4BACE,8BAEF,yCACE,oCAEF,wCACE,wDAEF,6HAKE,8BACA,2CACA,iBACA,eACA,mBAEF,sHAGE,8BAEF,gBACE,gBACA,oBAEF,iBACE,aAEF,eACE,iBAMF,2BACE,uCAMF,eACE,cAEF,gBACE,mBAEF,oDAEE,WAEF,oBACE,uBACA,sBAEF,kBACE,mBACA,eACA,mBAEF,yDAEE,kBAEF,+BACE,WAEF,8BACE,iBACA,oBAEF,kCACE,gBAEF,iCACE,mBAEF,eACE,oBAEF,gCACE,gBACA,UAEA,0DACE,kBAEA,gFACE,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGF,8DACE,eACA,iBAQN,wBACE,kBACA,OACA,SACA,OAjgB8B,KAkgB9B,MAngBc,MAogBd,SACA,UACA,mBACA,gBACA,aAEA,yDAEE,OACA,oBACA,mBACA,uBACA,YACA,8BACA,gBACA,cACA,eACA,cACA,qBACA,YACA,8BAEA,qEACE,mBACA,WAEF,iFACE,iBAIJ,uCACE,mBACA,sBAEA,iDACE,aAIJ,uCACE,mBAEF,yCACE,mBChjBJ,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHigBJ,qBACE,cACA,eAEA,gCACE,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACE,qBAIJ,sCACE,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGF,0BACE,iBACA,kBACA,eACA,eACA,YACA,6CIxlBF,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
|
||||
{"version":3,"sourceRoot":"","sources":["file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/fields.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss","file:///Users/paulspenke/Repositories/Plugi/plugi/plugi-core/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss"],"names":[],"mappings":"AAKA,eAGI,uBACA,SACA,gBAGJ,EACI,mCACA,gCACA,2BAGJ,kCAEI,cAGJ,gBACI,eAGJ,YACI,gBAGJ,OACI,qBACA,YACA,WACA,gBAEA,qBACI,mBAIR,cACI,kBACA,YACA,WACA,sBACA,cACA,WACI,2BAGJ,qBACI,kBACA,UAGJ,sBACI,kBACA,QACA,SACA,gCACA,YACA,aAEA,4BACI,eACA,eACA,gBACA,kBACA,cAGR,sBACI,uBACA,wBACA,yBACA,6BACA,kBACA,oCAEJ,kBACI,KACI,0BAKZ,sBAEI,gBAGJ,eACI,YACA,MACA,yBAEJ,aACI,uBAGJ,cACI,UAEA,8BACI,uBAGR,mDAGI,aAEJ,eACI,UAEJ,YACI,yBACA,mBACA,cAEJ,eACI,cAEJ,gBACI,cAEJ,wBACI,cAEJ,iBACI,WACA,wBACA,qBACA,gBAEJ,oBACI,UACA,WAEJ,0BACI,8BAEJ,0BACI,oCACA,kBAEA,gCACI,oCAMR,cACI,SAEA,0BACI,aACA,eACA,4BACA,wBACA,qBACA,gBACA,mBACA,cACA,gCACA,eAEA,wCACI,aACA,yBACA,gCACA,iCACA,wBACA,qBACA,gBACA,WACA,gCAIZ,gBACI,QAEJ,sCAEI,OACA,wBACA,qBACA,gBACA,MAjMY,MAkMZ,iBACA,gBACA,cACA,eACA,eACA,gBAEJ,wBACI,iBACA,mBACA,0BACA,gBAEA,0CACI,gBAGJ,4BACI,YACA,gBAGJ,gCACI,mBACA,YAGR,iCAEI,KA/NY,MAkOZ,4BACI,2BAEJ,6BACI,4BAEJ,8BACI,4BAMR,cACI,yBAGA,6DAEI,WAGR,WACI,yBACA,gBACA,YAEA,uDAGI,YAGJ,0BACI,6BAMR,gBACI,kBACA,gBACA,MA7QY,MA8QZ,YACA,mBACA,YAEA,sEAEI,iBAEA,oFACI,mBACA,cACA,yBACA,kBACA,gBACA,eACA,aACA,eAEA,gGACI,qBAKhB,gBACI,kBACA,OACA,MACA,YACA,cACA,mBACA,gBACA,YACA,eACA,YACA,WACA,aACA,mBACA,uBAKJ,cACI,eACA,mBACA,qBACA,gBACA,YACA,iBAEA,0BACI,kBACA,SACA,SACA,eACA,cAGJ,oBACI,mBACA,4BACA,gBACA,YAEA,iCACI,cAKZ,WACI,YACA,gBACA,mBACA,WACA,uBAEA,cACI,YAGJ,iBACI,yBAGJ,wBACI,YACA,gBACA,kBACA,WAEA,4BACI,WAIZ,cACI,mBACA,YAEJ,sBACI,mBACA,oBAEJ,iBACI,gBACA,YACA,aAEA,mBACI,iBACA,gBAGR,oBACI,mBAEJ,6BACI,8BACA,mBAEJ,eACI,8BAKJ,4BACI,8BAEJ,yCACI,oCAEJ,wCACI,wDAEJ,6HAKI,8BACA,2CACA,iBACA,eACA,mBAEJ,sHAGI,8BAEJ,gBACI,gBACA,oBAEJ,iBACI,aAEJ,eACI,iBAKJ,2BACI,uCAKJ,eACI,cAEJ,gBACI,mBAEJ,oDAEI,WAEJ,oBACI,uBACA,sBAEJ,kBACI,mBACA,eACA,mBAEJ,yDAEI,kBAEJ,+BACI,WAEJ,8BACI,iBACA,oBAEJ,kCACI,gBAEJ,iCACI,mBAEJ,eACI,oBAEJ,gCACI,gBACA,UAEA,0DACI,kBAEA,gFACI,kBACA,QACA,MACA,gBACA,yBACA,qBACA,cACA,gBAGJ,8DACI,eACA,iBAOZ,wBACI,kBACA,OACA,SACA,MAhgBY,MAigBZ,SACA,YACA,mBACA,gBACA,sBAEA,uCACI,mBACA,sBAEA,iDACI,aAIR,uCACI,mBAEJ,yCACI,mBCphBR,WACE,yBAGA,yBACE,sBACA,WAGJ,gBACE,cAEF,kBACE,cAEF,oCACE,cAEA,2CACE,yBACA,WAGJ,mBACE,6BAEF,mBACE,gCAGF,iBACE,qBAEF,sCACE,iBACA,gBACA,oBACA,WAEF,oDACE,yBCxCF,+BACE,mBACA,cAGF,cACE,WACA,cACA,iBAEA,gEAEE,aAEF,2BACE,cAEF,+BACE,yBACA,YACA,gDACA,WAEA,qCACE,yBAMJ,gEAEE,cAGF,+CACE,uCACA,uCAGF,+BACE,yBAEA,2CACE,gBACA,WACA,iBAGF,0CACE,UACA,yBAEA,iDACE,WACA,mBAKN,0CACE,WAEA,gDACE,WChEN,sBACE,aAEF,oBACE,gBACA,cAEF,eACE,aAEF,cACE,2BACA,yBACA,sBACA,qBACA,iBAGF,cACE,qBACA,gBACA,uBACA,gBACA,kBACA,sBACA,yBACA,sBACA,qBACA,iBACA,eACA,gBACA,qBACA,8HACA,WACA,yBACA,yBAIA,yBACE,WACA,WAEF,oCACE,WAKF,2BACE,uCACA,0BAEF,oCACE,cACA,iBHqeJ,qBACI,cACA,eAEA,gCACI,yBACA,yBACA,WACA,iBACA,kBACA,aACA,eAEA,sCACI,qBAIR,sCACI,gBACA,wRACA,4BACA,sCACA,qBACA,mBAGJ,0BACI,iBACA,kBACA,eACA,eACA,YACA,6CI5jBN,kCACE,uBAGF,kCACE,aAEF,uEACE,OAGF,mCACE,kBACA,eACA,qDACA,kDACA,2CACA"}
|
||||
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 2.8 MiB |
|
Before Width: | Height: | Size: 1.4 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 3.1 MiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 2.9 MiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 3.1 MiB |
@@ -83,6 +83,7 @@ return [
|
||||
'pagebuilder' => [
|
||||
'filter-placeholder' => 'Filter',
|
||||
'loading-text' => 'Seiteneditor wird geladen...',
|
||||
'page-selector' => 'Seite auswählen',
|
||||
'style-no-element-selected' => 'Wähle ein Element aus um das Aussehen anzupassen.',
|
||||
'trait-no-element-selected' => 'Wähle ein Element aus um die Attribute anzupassen',
|
||||
'trait-settings' => 'Einstellungen',
|
||||
@@ -91,6 +92,13 @@ return [
|
||||
'view-settings' => 'Einstellungen',
|
||||
'view-style-manager' => 'Aussehen anpassen',
|
||||
'save-page' => 'Speichern',
|
||||
'save-draft' => 'Entwurf speichern',
|
||||
'preview-draft' => 'Entwurf ansehen',
|
||||
'publish-draft' => 'Veröffentlichen',
|
||||
'draft-available' => 'Entwurf verfügbar',
|
||||
'draft-status' => 'Entwurf gespeichert — unveröffentlicht',
|
||||
'published-status' => 'Veröffentlicht',
|
||||
'confirm-publish' => 'Diesen Entwurf veröffentlichen? Dadurch werden die Live-Seiteninhalte ersetzt.',
|
||||
'view-page' => 'Ansehen',
|
||||
'go-back' => 'Zurück',
|
||||
'viewport-selector' => 'Vorschauansicht',
|
||||
@@ -100,7 +108,10 @@ return [
|
||||
'page' => 'Seite',
|
||||
'page-content' => 'Seiteninhalte',
|
||||
'toastr-changes-saved' => 'Änderungen gespeichert',
|
||||
'toastr-draft-saved' => 'Entwurf gespeichert. Öffentliche Besucher sehen weiterhin die veröffentlichte Seite.',
|
||||
'toastr-published' => 'Entwurf veröffentlicht.',
|
||||
'toastr-saving-failed' => 'Fehler beim Speichern',
|
||||
'toastr-publishing-failed' => 'Der Entwurf konnte nicht veröffentlicht werden. Der gespeicherte Entwurf bleibt erhalten.',
|
||||
'toastr-component-update-failed' => 'Fehler beim Laden',
|
||||
'toastr-switching-language-failed' => 'Fehler beim Ändern der Sprache',
|
||||
'yes' => 'Ja',
|
||||
|
||||
@@ -83,6 +83,7 @@ return [
|
||||
'pagebuilder' => [
|
||||
'filter-placeholder' => 'Filter',
|
||||
'loading-text' => 'Loading pagebuilder..',
|
||||
'page-selector' => 'Select page',
|
||||
'style-no-element-selected' => 'Select an element to modify the style.',
|
||||
'trait-no-element-selected' => 'Select an element to modify any attributes.',
|
||||
'trait-settings' => 'Settings',
|
||||
@@ -91,6 +92,13 @@ return [
|
||||
'view-settings' => 'Settings',
|
||||
'view-style-manager' => 'Style Manager',
|
||||
'save-page' => 'Save',
|
||||
'save-draft' => 'Save draft',
|
||||
'preview-draft' => 'Preview draft',
|
||||
'publish-draft' => 'Publish',
|
||||
'draft-available' => 'Draft available',
|
||||
'draft-status' => 'Draft saved — unpublished',
|
||||
'published-status' => 'Published',
|
||||
'confirm-publish' => 'Publish this draft? It will replace the live page content.',
|
||||
'view-page' => 'View',
|
||||
'go-back' => 'Back',
|
||||
'viewport-selector' => 'Preview viewport',
|
||||
@@ -100,7 +108,10 @@ return [
|
||||
'page' => 'Page',
|
||||
'page-content' => 'Page contents',
|
||||
'toastr-changes-saved' => 'Changes saved',
|
||||
'toastr-draft-saved' => 'Draft saved. Public visitors still see the published page.',
|
||||
'toastr-published' => 'Draft published.',
|
||||
'toastr-saving-failed' => 'Error while saving changes',
|
||||
'toastr-publishing-failed' => 'Could not publish the draft. The saved draft remains available.',
|
||||
'toastr-component-update-failed' => 'Error while reloading component',
|
||||
'toastr-switching-language-failed' => 'Error while switching language',
|
||||
'yes' => 'Yes',
|
||||
|
||||
@@ -82,6 +82,7 @@ return [
|
||||
'pagebuilder' => [
|
||||
'filter-placeholder' => 'Filtrera',
|
||||
'loading-text' => 'Laddar sidbyggaren...',
|
||||
'page-selector' => 'Välj sida',
|
||||
'style-no-element-selected' => 'Välj ett element för att ändra stilen.',
|
||||
'trait-no-element-selected' => 'Välj ett element för att ändra dess attribut.',
|
||||
'trait-settings' => 'Inställningar',
|
||||
@@ -90,6 +91,13 @@ return [
|
||||
'view-settings' => 'Inställningar',
|
||||
'view-style-manager' => 'Stilhanterare',
|
||||
'save-page' => 'Spara',
|
||||
'save-draft' => 'Spara utkast',
|
||||
'preview-draft' => 'Förhandsgranska utkast',
|
||||
'publish-draft' => 'Publicera',
|
||||
'draft-available' => 'Utkast finns',
|
||||
'draft-status' => 'Utkast sparat — opublicerat',
|
||||
'published-status' => 'Publicerad',
|
||||
'confirm-publish' => 'Publicera utkastet? Det ersätter sidans publicerade innehåll.',
|
||||
'view-page' => 'Visa',
|
||||
'go-back' => 'Tillbaka',
|
||||
'viewport-selector' => 'Förhandsgranskningens vy',
|
||||
@@ -99,7 +107,10 @@ return [
|
||||
'page' => 'Sida',
|
||||
'page-content' => 'Sidinnehåll',
|
||||
'toastr-changes-saved' => 'Ändringarna har sparats',
|
||||
'toastr-draft-saved' => 'Utkast sparat. Besökare ser fortfarande den publicerade sidan.',
|
||||
'toastr-published' => 'Utkast publicerat.',
|
||||
'toastr-saving-failed' => 'Det gick inte att spara ändringarna',
|
||||
'toastr-publishing-failed' => 'Utkastet kunde inte publiceras. Det sparade utkastet finns kvar.',
|
||||
'toastr-component-update-failed' => 'Det gick inte att läsa in komponenten igen',
|
||||
'toastr-switching-language-failed' => 'Det gick inte att byta språk',
|
||||
'yes' => 'Ja',
|
||||
|
||||
@@ -133,6 +133,19 @@ class DB
|
||||
return $stmt->execute($parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a custom query and return the number of affected rows.
|
||||
*/
|
||||
public function queryAffectedRows(string $query, array $parameters = []): int|false
|
||||
{
|
||||
$stmt = $this->pdo->prepare($query);
|
||||
if (! $stmt->execute($parameters)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $stmt->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the callback inside a database transaction, rolling back false results and exceptions.
|
||||
*/
|
||||
@@ -303,7 +316,7 @@ class DB
|
||||
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
|
||||
if (empty($sanitizedColumn)) continue;
|
||||
// Validate column definition against a safe pattern
|
||||
if (!is_string($columnDefinition) || !preg_match('/^[A-Z\s(),0-9_`]+$/i', $columnDefinition)) continue;
|
||||
if (!is_string($columnDefinition) || !preg_match("/^[A-Z\\s(),0-9_`']+$/i", $columnDefinition)) continue;
|
||||
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
|
||||
}
|
||||
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
|
||||
|
||||
@@ -9,6 +9,7 @@ use Plugi\Modules\GrapesJS\Block\BlockAdapter;
|
||||
use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator;
|
||||
use Plugi\Modules\GrapesJS\Upload\Uploader;
|
||||
use Plugi\PageTranslationService;
|
||||
use Plugi\Repositories\PageDraftPublishedCacheInvalidationException;
|
||||
use Plugi\Repositories\PageRepository;
|
||||
use Plugi\Repositories\UploadRepository;
|
||||
use Exception;
|
||||
@@ -35,9 +36,9 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->theme = phpb_instance('theme', [
|
||||
phpb_config('theme'),
|
||||
phpb_config('theme.active_theme')
|
||||
$this->theme = phpb_instance("theme", [
|
||||
phpb_config("theme"),
|
||||
phpb_config("theme.active_theme"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -64,60 +65,112 @@ class PageBuilder implements PageBuilderContract
|
||||
{
|
||||
phpb_set_in_editmode();
|
||||
|
||||
if ($route === 'thumb_generator') {
|
||||
if ($route === "thumb_generator") {
|
||||
$thumbGenerator = new ThumbGenerator($this->theme);
|
||||
return $thumbGenerator->handleThumbRequest($action);
|
||||
}
|
||||
|
||||
if (is_null($page)) {
|
||||
$pageId = $_GET['page'] ?? null;
|
||||
$pageRepository = new PageRepository;
|
||||
$pageId = $_GET["page"] ?? null;
|
||||
$pageRepository = new PageRepository();
|
||||
$page = $pageRepository->findWithId($pageId);
|
||||
}
|
||||
if (! ($page instanceof PageContract)) {
|
||||
if (!($page instanceof PageContract)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch ($action) {
|
||||
case null:
|
||||
case 'edit':
|
||||
case "edit":
|
||||
$this->renderPageBuilder($page);
|
||||
exit();
|
||||
break;
|
||||
case 'store':
|
||||
if (isset($_POST) && isset($_POST['data'])) {
|
||||
$data = json_decode($_POST['data'], true);
|
||||
case "store":
|
||||
if (isset($_POST) && isset($_POST["data"])) {
|
||||
$data = json_decode($_POST["data"], true);
|
||||
$this->updatePage($page, $data);
|
||||
exit();
|
||||
}
|
||||
break;
|
||||
case 'upload':
|
||||
case "storeDraft":
|
||||
if (
|
||||
($_SERVER["REQUEST_METHOD"] ?? "") === "POST" &&
|
||||
isset($_POST["data"])
|
||||
) {
|
||||
$data = json_decode($_POST["data"], true);
|
||||
if (!is_array($data)) {
|
||||
http_response_code(400);
|
||||
header("Content-Type: application/json");
|
||||
echo json_encode(["success" => false]);
|
||||
exit();
|
||||
}
|
||||
|
||||
$saved = new PageRepository()->updatePageDraftData(
|
||||
$page,
|
||||
$data,
|
||||
);
|
||||
http_response_code($saved ? 200 : 500);
|
||||
header("Content-Type: application/json");
|
||||
echo json_encode(["success" => $saved]);
|
||||
exit();
|
||||
}
|
||||
break;
|
||||
case "publish":
|
||||
if (($_SERVER["REQUEST_METHOD"] ?? "") === "POST") {
|
||||
$cacheWarning = false;
|
||||
try {
|
||||
$published = new PageRepository()->publishPageDraft(
|
||||
$page,
|
||||
);
|
||||
} catch (PageDraftPublishedCacheInvalidationException) {
|
||||
$published = true;
|
||||
$cacheWarning = true;
|
||||
}
|
||||
http_response_code($published ? 200 : 409);
|
||||
header("Content-Type: application/json");
|
||||
echo json_encode([
|
||||
"success" => $published,
|
||||
"cacheWarning" => $cacheWarning,
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
http_response_code(405);
|
||||
exit();
|
||||
case "upload":
|
||||
if (isset($_FILES)) {
|
||||
$this->handleFileUpload();
|
||||
}
|
||||
break;
|
||||
case 'upload_delete':
|
||||
if (isset($_POST['id'])) {
|
||||
case "upload_delete":
|
||||
if (isset($_POST["id"])) {
|
||||
$this->handleFileDelete();
|
||||
}
|
||||
break;
|
||||
case 'renderBlock':
|
||||
case "renderBlock":
|
||||
$language = $this->getValidPostedLanguage();
|
||||
if ($language === null) {
|
||||
$this->respondToInvalidLanguageRequest();
|
||||
}
|
||||
if (isset($_POST['data'])) {
|
||||
$this->renderPageBuilderBlock($page, $language, json_decode($_POST['data'], true));
|
||||
if (isset($_POST["data"])) {
|
||||
$this->renderPageBuilderBlock(
|
||||
$page,
|
||||
$language,
|
||||
json_decode($_POST["data"], true),
|
||||
);
|
||||
exit();
|
||||
}
|
||||
break;
|
||||
case 'renderLanguageVariant':
|
||||
case "renderLanguageVariant":
|
||||
$language = $this->getValidPostedLanguage();
|
||||
if ($language === null) {
|
||||
$this->respondToInvalidLanguageRequest();
|
||||
}
|
||||
if (isset($_POST['data'])) {
|
||||
$this->renderLanguageVariant($page, $language, json_decode($_POST['data'], true));
|
||||
if (isset($_POST["data"])) {
|
||||
$this->renderLanguageVariant(
|
||||
$page,
|
||||
$language,
|
||||
json_decode($_POST["data"], true),
|
||||
);
|
||||
exit();
|
||||
}
|
||||
break;
|
||||
@@ -134,33 +187,65 @@ class PageBuilder implements PageBuilderContract
|
||||
public function handleFileUpload()
|
||||
{
|
||||
$publicId = sha1(uniqid(rand(), true));
|
||||
$uploader = phpb_instance(Uploader::class, ['files']);
|
||||
$uploader = phpb_instance(Uploader::class, ["files"]);
|
||||
$allowedImages = [
|
||||
"image/jpeg" => "jpg",
|
||||
"image/png" => "png",
|
||||
"image/gif" => "gif",
|
||||
"image/webp" => "webp",
|
||||
"image/bmp" => "bmp",
|
||||
];
|
||||
if (
|
||||
!is_string($uploader->file_src_name) ||
|
||||
!isset($allowedImages[$uploader->file_src_mime])
|
||||
) {
|
||||
http_response_code(415);
|
||||
die("Upload error: Unsupported image type");
|
||||
}
|
||||
|
||||
$sourceName = basename(
|
||||
str_replace("\\", "/", $uploader->file_src_name),
|
||||
);
|
||||
$originalFile = preg_replace("/[^A-Za-z0-9._-]/", "-", $sourceName);
|
||||
$originalFile = substr($originalFile, 0, 150);
|
||||
$baseName = preg_replace(
|
||||
"/[^A-Za-z0-9_-]+/",
|
||||
"-",
|
||||
pathinfo($sourceName, PATHINFO_FILENAME),
|
||||
);
|
||||
$baseName = trim(substr($baseName, 0, 100), "-_");
|
||||
$fileName =
|
||||
($baseName !== "" ? $baseName : "image") .
|
||||
"." .
|
||||
$allowedImages[$uploader->file_src_mime];
|
||||
|
||||
$uploader->MIME_allowed = array_keys($allowedImages);
|
||||
$uploader
|
||||
->file_name($publicId . '/' . str_replace(' ', '-', $uploader->file_src_name))
|
||||
->upload_to(phpb_config('storage.uploads_folder') . '/')
|
||||
->file_name($publicId . "/" . $fileName)
|
||||
->upload_to(phpb_config("storage.uploads_folder") . "/")
|
||||
->mime_check()
|
||||
->run();
|
||||
|
||||
if (! $uploader->was_uploaded) {
|
||||
if (!$uploader->was_uploaded) {
|
||||
die("Upload error: {$uploader->error}");
|
||||
} else {
|
||||
$originalFile = str_replace(' ', '-', $uploader->file_src_name);
|
||||
$originalMime = $uploader->file_src_mime;
|
||||
$serverFile = $uploader->final_file_name;
|
||||
|
||||
$uploadRepository = new UploadRepository;
|
||||
$uploadRepository = new UploadRepository();
|
||||
$uploadedFile = $uploadRepository->create([
|
||||
'public_id' => $publicId,
|
||||
'original_file' => $originalFile,
|
||||
'mime_type' => $originalMime,
|
||||
'server_file' => $serverFile
|
||||
"public_id" => $publicId,
|
||||
"original_file" => $originalFile,
|
||||
"mime_type" => $originalMime,
|
||||
"server_file" => $serverFile,
|
||||
]);
|
||||
|
||||
echo json_encode([
|
||||
'data' => [
|
||||
'public_id' => $publicId,
|
||||
'src' => $uploadedFile->getUrl(),
|
||||
'type' => 'image'
|
||||
]
|
||||
"data" => [
|
||||
"public_id" => $publicId,
|
||||
"src" => $uploadedFile->getUrl(),
|
||||
"type" => "image",
|
||||
],
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
@@ -171,12 +256,15 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function handleFileDelete()
|
||||
{
|
||||
$uploadRepository = new UploadRepository;
|
||||
$uploadedFileResult = $uploadRepository->findWhere('public_id', $_POST['id']);
|
||||
$uploadRepository = new UploadRepository();
|
||||
$uploadedFileResult = $uploadRepository->findWhere(
|
||||
"public_id",
|
||||
$_POST["id"],
|
||||
);
|
||||
if (empty($uploadedFileResult)) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'File not found'
|
||||
"success" => false,
|
||||
"message" => "File not found",
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
@@ -184,18 +272,26 @@ class PageBuilder implements PageBuilderContract
|
||||
$uploadedFile = $uploadedFileResult[0];
|
||||
$uploadRepository->destroy($uploadedFile->id);
|
||||
|
||||
$serverFilePath = realpath(phpb_config('storage.uploads_folder') . '/' . $uploadedFile->server_file);
|
||||
$serverFilePath = realpath(
|
||||
phpb_config("storage.uploads_folder") .
|
||||
"/" .
|
||||
$uploadedFile->server_file,
|
||||
);
|
||||
if ($serverFilePath) {
|
||||
unlink($serverFilePath);
|
||||
}
|
||||
|
||||
$parentDirectory = realpath(phpb_config('storage.uploads_folder') . '/' . dirname($uploadedFile->server_file));
|
||||
if ($parentDirectory && dirname($uploadedFile->server_file) !== '.') {
|
||||
$parentDirectory = realpath(
|
||||
phpb_config("storage.uploads_folder") .
|
||||
"/" .
|
||||
dirname($uploadedFile->server_file),
|
||||
);
|
||||
if ($parentDirectory && dirname($uploadedFile->server_file) !== ".") {
|
||||
rmdir($parentDirectory);
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true
|
||||
"success" => true,
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
@@ -210,16 +306,37 @@ class PageBuilder implements PageBuilderContract
|
||||
{
|
||||
phpb_set_in_editmode();
|
||||
|
||||
$pageRepository = new PageRepository();
|
||||
$editablePages = array_values(array_filter(
|
||||
$pageRepository->getAll(),
|
||||
static function ($availablePage) {
|
||||
return $availablePage->get("type") !== "redirect";
|
||||
},
|
||||
));
|
||||
|
||||
$draftData = $pageRepository->getPageDraftData($page);
|
||||
$hasDraft = $draftData !== null;
|
||||
if ($hasDraft) {
|
||||
$page->setData(["data" => $draftData], false);
|
||||
}
|
||||
|
||||
// init variables that should be accessible in the view
|
||||
$pageBuilder = $this;
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [
|
||||
$this->theme,
|
||||
$page,
|
||||
true,
|
||||
]);
|
||||
$activeLanguages = array_keys(phpb_active_languages());
|
||||
$currentLanguage = (new PageTranslationService())->resolveLocale($_SESSION['plugi_language'] ?? null, $activeLanguages);
|
||||
$currentLanguage = new PageTranslationService()->resolveLocale(
|
||||
$_SESSION["plugi_language"] ?? null,
|
||||
$activeLanguages,
|
||||
);
|
||||
if ($currentLanguage !== null) {
|
||||
$_SESSION['plugi_language'] = $currentLanguage;
|
||||
$_SESSION["plugi_language"] = $currentLanguage;
|
||||
$pageRenderer->setLanguage($currentLanguage);
|
||||
} else {
|
||||
unset($_SESSION['plugi_language']);
|
||||
unset($_SESSION["plugi_language"]);
|
||||
}
|
||||
|
||||
// create an array of theme blocks and theme block settings for in the page builder sidebar
|
||||
@@ -227,8 +344,11 @@ class PageBuilder implements PageBuilderContract
|
||||
$blockSettings = [];
|
||||
foreach ($this->theme->getThemeBlocks() as $themeBlock) {
|
||||
$slug = phpb_e($themeBlock->getSlug());
|
||||
$adapter = phpb_instance(BlockAdapter::class, [$pageRenderer, $themeBlock]);
|
||||
if ($themeBlock->get('hidden') !== true) {
|
||||
$adapter = phpb_instance(BlockAdapter::class, [
|
||||
$pageRenderer,
|
||||
$themeBlock,
|
||||
]);
|
||||
if ($themeBlock->get("hidden") !== true) {
|
||||
$blocks[$slug] = $adapter->getBlockManagerArray();
|
||||
}
|
||||
$blockSettings[$slug] = $adapter->getBlockSettingsArray();
|
||||
@@ -236,14 +356,14 @@ class PageBuilder implements PageBuilderContract
|
||||
|
||||
// create an array of all uploaded assets
|
||||
$assets = [];
|
||||
foreach ((new UploadRepository)->getAll() as $file) {
|
||||
foreach (new UploadRepository()->getAll() as $file) {
|
||||
$assets[] = [
|
||||
'src' => $file->getUrl(),
|
||||
'public_id' => $file->public_id
|
||||
"src" => $file->getUrl(),
|
||||
"public_id" => $file->public_id,
|
||||
];
|
||||
}
|
||||
|
||||
require __DIR__ . '/resources/views/layout.php';
|
||||
require __DIR__ . "/resources/views/layout.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -255,8 +375,11 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function renderPage(PageContract $page, $language = null): string
|
||||
{
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page]);
|
||||
if (! is_null($language)) {
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [
|
||||
$this->theme,
|
||||
$page,
|
||||
]);
|
||||
if (!is_null($language)) {
|
||||
$pageRenderer->setLanguage($language);
|
||||
}
|
||||
return $pageRenderer->render();
|
||||
@@ -270,16 +393,26 @@ class PageBuilder implements PageBuilderContract
|
||||
* @param array $blockData
|
||||
* @throws Exception
|
||||
*/
|
||||
public function renderPageBuilderBlock(PageContract $page, string $language, $blockData = [])
|
||||
{
|
||||
public function renderPageBuilderBlock(
|
||||
PageContract $page,
|
||||
string $language,
|
||||
$blockData = [],
|
||||
) {
|
||||
phpb_set_in_editmode();
|
||||
|
||||
$blockData = is_array($blockData) ? $blockData : [];
|
||||
$page->setData(['data' => $blockData], false);
|
||||
$page->setData(["data" => $blockData], false);
|
||||
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [
|
||||
$this->theme,
|
||||
$page,
|
||||
true,
|
||||
]);
|
||||
$pageRenderer->setLanguage($language);
|
||||
echo $pageRenderer->parseShortcodes($blockData['html'], $blockData['blocks']);
|
||||
echo $pageRenderer->parseShortcodes(
|
||||
$blockData["html"],
|
||||
$blockData["blocks"],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -290,21 +423,33 @@ class PageBuilder implements PageBuilderContract
|
||||
* @param array $blockData
|
||||
* @throws Exception
|
||||
*/
|
||||
public function renderLanguageVariant(PageContract $page, string $language, $blockData = [])
|
||||
{
|
||||
public function renderLanguageVariant(
|
||||
PageContract $page,
|
||||
string $language,
|
||||
$blockData = [],
|
||||
) {
|
||||
phpb_set_in_editmode();
|
||||
if (! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
|
||||
if (
|
||||
!new PageTranslationService()->isAvailableLocale(
|
||||
$language,
|
||||
array_keys(phpb_active_languages()),
|
||||
)
|
||||
) {
|
||||
$this->respondToInvalidLanguageRequest();
|
||||
}
|
||||
$_SESSION['plugi_language'] = $language;
|
||||
$_SESSION["plugi_language"] = $language;
|
||||
|
||||
$blockData = is_array($blockData) ? $blockData : [];
|
||||
$page->setData(['data' => $blockData], false);
|
||||
$page->setData(["data" => $blockData], false);
|
||||
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
|
||||
$pageRenderer = phpb_instance(PageRenderer::class, [
|
||||
$this->theme,
|
||||
$page,
|
||||
true,
|
||||
]);
|
||||
$pageRenderer->setLanguage($language);
|
||||
echo json_encode([
|
||||
'dynamicBlocks' => $pageRenderer->getPageBlocksData()[$language]
|
||||
"dynamicBlocks" => $pageRenderer->getPageBlocksData()[$language],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -315,8 +460,14 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
protected function getValidPostedLanguage(): ?string
|
||||
{
|
||||
$language = $_POST['language'] ?? null;
|
||||
if (! is_string($language) || ! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
|
||||
$language = $_POST["language"] ?? null;
|
||||
if (
|
||||
!is_string($language) ||
|
||||
!new PageTranslationService()->isAvailableLocale(
|
||||
$language,
|
||||
array_keys(phpb_active_languages()),
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -329,8 +480,8 @@ class PageBuilder implements PageBuilderContract
|
||||
protected function respondToInvalidLanguageRequest(): void
|
||||
{
|
||||
http_response_code(400);
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['message' => 'Unsupported language.']);
|
||||
header("Content-Type: application/json");
|
||||
echo json_encode(["message" => "Unsupported language."]);
|
||||
exit();
|
||||
}
|
||||
|
||||
@@ -343,7 +494,7 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function updatePage(PageContract $page, $data)
|
||||
{
|
||||
$pageRepository = new PageRepository;
|
||||
$pageRepository = new PageRepository();
|
||||
return $pageRepository->updatePageData($page, $data);
|
||||
}
|
||||
|
||||
@@ -356,12 +507,9 @@ class PageBuilder implements PageBuilderContract
|
||||
{
|
||||
$pages = [];
|
||||
|
||||
$pageRepository = new PageRepository;
|
||||
$pageRepository = new PageRepository();
|
||||
foreach ($pageRepository->getAll() as $page) {
|
||||
$pages[] = [
|
||||
phpb_e($page->getName()),
|
||||
phpb_e($page->getId())
|
||||
];
|
||||
$pages[] = [phpb_e($page->getName()), phpb_e($page->getId())];
|
||||
}
|
||||
|
||||
return $pages;
|
||||
@@ -376,9 +524,13 @@ class PageBuilder implements PageBuilderContract
|
||||
public function getPageComponents(PageContract $page)
|
||||
{
|
||||
$data = $page->getBuilderData();
|
||||
$components = $data['components'] ?? [0 => []];
|
||||
$components = $data["components"] ?? [0 => []];
|
||||
// backwards compatibility, components are now stored for each main container (@todo: remove this at the first mayor version)
|
||||
if (isset($components[0]) && ! empty($components[0]) && ! isset($components[0][0])) {
|
||||
if (
|
||||
isset($components[0]) &&
|
||||
!empty($components[0]) &&
|
||||
!isset($components[0][0])
|
||||
) {
|
||||
$components = [0 => $components];
|
||||
}
|
||||
return $components;
|
||||
@@ -393,8 +545,8 @@ class PageBuilder implements PageBuilderContract
|
||||
public function getPageStyleComponents(PageContract $page)
|
||||
{
|
||||
$data = $page->getBuilderData();
|
||||
if (isset($data['style'])) {
|
||||
return $data['style'];
|
||||
if (isset($data["style"])) {
|
||||
return $data["style"];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -408,10 +560,10 @@ class PageBuilder implements PageBuilderContract
|
||||
public function getPageStyleCss(PageContract $page)
|
||||
{
|
||||
$data = $page->getBuilderData();
|
||||
if (isset($data['css'])) {
|
||||
return $data['css'];
|
||||
if (isset($data["css"])) {
|
||||
return $data["css"];
|
||||
}
|
||||
return '';
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -422,7 +574,7 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function customStyle(?string $css = null)
|
||||
{
|
||||
if (! is_null($css)) {
|
||||
if (!is_null($css)) {
|
||||
$this->css = $css;
|
||||
}
|
||||
return $this->css;
|
||||
@@ -437,9 +589,9 @@ class PageBuilder implements PageBuilderContract
|
||||
*/
|
||||
public function customScripts(string $location, ?string $scripts = null)
|
||||
{
|
||||
if (! is_null($scripts)) {
|
||||
if (!is_null($scripts)) {
|
||||
$this->scripts[$location] = $scripts;
|
||||
}
|
||||
return $this->scripts[$location] ?? '';
|
||||
return $this->scripts[$location] ?? "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,6 +201,113 @@ class PageRenderer
|
||||
return $pageHtml;
|
||||
}
|
||||
|
||||
public static function appendPreviewTokenToLinks(string $pageHtml, string $token): string
|
||||
{
|
||||
$baseUrl = parse_url(phpb_full_url('/'));
|
||||
if ($token === '' || ! is_array($baseUrl) || empty($baseUrl['host'])) {
|
||||
return $pageHtml;
|
||||
}
|
||||
|
||||
$document = new \DOMDocument('1.0', 'UTF-8');
|
||||
$previousLibxmlErrorSetting = libxml_use_internal_errors(true);
|
||||
$loaded = @$document->loadHTML('<?xml encoding="UTF-8">' . $pageHtml, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED | LIBXML_NONET);
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previousLibxmlErrorSetting);
|
||||
if (! $loaded) {
|
||||
return $pageHtml;
|
||||
}
|
||||
|
||||
foreach ($document->childNodes as $child) {
|
||||
if ($child->nodeType === XML_PI_NODE) {
|
||||
$document->removeChild($child);
|
||||
}
|
||||
}
|
||||
$rewriteRelativeLinks = true;
|
||||
$baseElement = $document->getElementsByTagName('base')->item(0);
|
||||
if ($baseElement && $baseElement->hasAttribute('href')) {
|
||||
$documentBase = parse_url($baseElement->getAttribute('href'));
|
||||
$rewriteRelativeLinks = is_array($documentBase) && static::isSameSiteUrl($documentBase, $baseUrl);
|
||||
}
|
||||
$preservedUrls = [];
|
||||
foreach ($document->getElementsByTagName('a') as $link) {
|
||||
if ($link->hasAttribute('href')) {
|
||||
$url = $link->getAttribute('href');
|
||||
if (str_contains($url, '\\')) {
|
||||
$placeholder = '__phpb_preview_link_' . count($preservedUrls) . '__';
|
||||
while (str_contains($pageHtml, $placeholder)) {
|
||||
$placeholder .= '_';
|
||||
}
|
||||
$preservedUrls[$placeholder] = $url;
|
||||
$link->setAttribute('href', $placeholder);
|
||||
} else {
|
||||
$link->setAttribute('href', static::appendPreviewTokenToUrl($url, $token, $baseUrl, $rewriteRelativeLinks));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$renderedHtml = $document->saveHTML() ?: $pageHtml;
|
||||
foreach ($preservedUrls as $placeholder => $url) {
|
||||
$renderedHtml = str_replace($placeholder, htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), $renderedHtml);
|
||||
}
|
||||
|
||||
return $renderedHtml;
|
||||
}
|
||||
|
||||
public static function appendPreviewTokenToUrl(string $url, string $token, array $baseUrl, bool $rewriteRelativeLinks): string
|
||||
{
|
||||
if ($url === '' || str_starts_with($url, '#') || preg_match('/^[\x00-\x20]/', $url) || str_contains($url, '\\')) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
$urlParts = parse_url($url);
|
||||
if ($urlParts === false || isset($urlParts['user']) || isset($urlParts['pass'])) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
if (isset($urlParts['host']) || isset($urlParts['scheme'])) {
|
||||
if (! static::isSameSiteUrl($urlParts, $baseUrl)) {
|
||||
return $url;
|
||||
}
|
||||
} elseif (! $rewriteRelativeLinks || str_starts_with($url, '//')) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
$fragmentPosition = strpos($url, '#');
|
||||
$fragment = $fragmentPosition === false ? '' : substr($url, $fragmentPosition);
|
||||
$urlWithoutFragment = $fragmentPosition === false ? $url : substr($url, 0, $fragmentPosition);
|
||||
$queryPosition = strpos($urlWithoutFragment, '?');
|
||||
$urlPath = $queryPosition === false ? $urlWithoutFragment : substr($urlWithoutFragment, 0, $queryPosition);
|
||||
$query = $queryPosition === false ? '' : substr($urlWithoutFragment, $queryPosition + 1);
|
||||
$queryParts = $query === '' ? [] : explode('&', $query);
|
||||
$queryParts = array_values(array_filter($queryParts, static function (string $part): bool {
|
||||
return urldecode(explode('=', $part, 2)[0]) !== 'previewToken';
|
||||
}));
|
||||
$queryParts[] = 'previewToken=' . rawurlencode($token);
|
||||
|
||||
return $urlPath . '?' . implode('&', $queryParts) . $fragment;
|
||||
}
|
||||
|
||||
private static function isSameSiteUrl(array $urlParts, array $baseUrl): bool
|
||||
{
|
||||
$scheme = strtolower($urlParts['scheme'] ?? '');
|
||||
$baseScheme = strtolower($baseUrl['scheme'] ?? '');
|
||||
if (isset($urlParts['user']) || isset($urlParts['pass'])
|
||||
|| ($scheme !== '' && ($scheme !== $baseScheme || ! isset($urlParts['host'])))) {
|
||||
return false;
|
||||
}
|
||||
if (! isset($urlParts['host'])) {
|
||||
return $scheme === '';
|
||||
}
|
||||
|
||||
return strtolower($urlParts['host']) === strtolower($baseUrl['host'])
|
||||
&& static::getUrlPort($urlParts, $scheme ?: $baseScheme) === static::getUrlPort($baseUrl, $baseScheme);
|
||||
}
|
||||
|
||||
private static function getUrlPort(array $urlParts, string $scheme): int
|
||||
{
|
||||
return $urlParts['port'] ?? ($scheme === 'https' ? 443 : 80);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the page body for display on the website.
|
||||
* The body contains all blocks which are put into the selected layout.
|
||||
|
||||
@@ -27,7 +27,6 @@ class Uploader {
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
if ($finfo) {
|
||||
$mime = finfo_file($finfo, $filePath);
|
||||
finfo_close($finfo);
|
||||
if (!empty($mime)) {
|
||||
return $mime;
|
||||
}
|
||||
@@ -256,6 +255,11 @@ class Uploader {
|
||||
* @throws Exception
|
||||
*/
|
||||
public function run() {
|
||||
$uploadRoot = rtrim($this->upload_to, '/\\');
|
||||
if ($uploadRoot === '') {
|
||||
$uploadRoot = DIRECTORY_SEPARATOR;
|
||||
}
|
||||
|
||||
// check whether the final name is in random mode
|
||||
if ($this->file_name !== true) {
|
||||
// preserve file extension if provided
|
||||
@@ -264,13 +268,24 @@ class Uploader {
|
||||
} else {
|
||||
$file = $this->file_name;
|
||||
}
|
||||
$path = $this->upload_to . $file;
|
||||
$this->upload_to = dirname($path);
|
||||
} else {
|
||||
$hash = bin2hex(random_bytes(16));
|
||||
$file = $hash . '.' . $this->file_src_name_ext;
|
||||
$path = $this->upload_to . $file;
|
||||
}
|
||||
if (!$this->isSafeRelativePath($file)) {
|
||||
$this->was_uploaded = false;
|
||||
$this->error = 'Invalid destination file name.';
|
||||
return false;
|
||||
}
|
||||
$relativeFile = str_replace('\\', '/', $file);
|
||||
$destinationDirectory = $this->getSafeDestinationDirectory($uploadRoot, $relativeFile);
|
||||
if ($destinationDirectory === null) {
|
||||
$this->was_uploaded = false;
|
||||
$this->error = 'Destination directory must remain inside the upload folder.';
|
||||
return false;
|
||||
}
|
||||
$path = $destinationDirectory . DIRECTORY_SEPARATOR . basename($relativeFile);
|
||||
$this->upload_to = $destinationDirectory;
|
||||
|
||||
$get_mime = isset($this->mime_check) ? true : false;
|
||||
|
||||
@@ -282,6 +297,9 @@ class Uploader {
|
||||
$this->was_uploaded = false;
|
||||
$this->error = "Incorrect type of file";
|
||||
}
|
||||
if (!$this->was_uploaded) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check file maximum size
|
||||
if ($this->file_src_size > $this->get_file_max_size) {
|
||||
@@ -290,18 +308,6 @@ class Uploader {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check whether destination directory exists or attempt to create it
|
||||
if ($this->get_auto_create_path) {
|
||||
if (! $this->r_mkdir($this->upload_to)) {
|
||||
$this->was_uploaded = false;
|
||||
$this->error = "Destination directory can't be created. Can't carry on a process";
|
||||
return false;
|
||||
}
|
||||
} elseif (! is_dir($this->upload_to)) {
|
||||
$this->error = "Destination directory doesn't exist. Can't carry on a process";
|
||||
return false;
|
||||
}
|
||||
|
||||
// check whether file already exists or if are replacing it
|
||||
if (file_exists($path)) {
|
||||
if (! $this->get_auto_replace) {
|
||||
@@ -364,6 +370,60 @@ class Uploader {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function isSafeRelativePath(string $file): bool
|
||||
{
|
||||
$file = str_replace('\\', '/', $file);
|
||||
if ($file === '' || str_starts_with($file, '/') || preg_match('/^[A-Za-z]:/', $file) || str_contains($file, "\0")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (explode('/', $file) as $segment) {
|
||||
if ($segment === '' || $segment === '.' || $segment === '..') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function getSafeDestinationDirectory(string $uploadRoot, string $relativeFile): ?string
|
||||
{
|
||||
if (!is_dir($uploadRoot) && (!$this->get_auto_create_path || !$this->r_mkdir($uploadRoot))) {
|
||||
$this->error = "Destination directory can't be created. Can't carry on a process";
|
||||
return null;
|
||||
}
|
||||
|
||||
$realRoot = realpath($uploadRoot);
|
||||
if (!$realRoot) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$relativeDirectory = dirname($relativeFile);
|
||||
if ($relativeDirectory === '.') {
|
||||
return $realRoot;
|
||||
}
|
||||
|
||||
$directory = $realRoot;
|
||||
foreach (explode('/', $relativeDirectory) as $segment) {
|
||||
$nextDirectory = $directory . DIRECTORY_SEPARATOR . $segment;
|
||||
if (is_link($nextDirectory)) {
|
||||
return null;
|
||||
}
|
||||
if (!is_dir($nextDirectory) && (!$this->get_auto_create_path || !$this->_mkdir($nextDirectory))) {
|
||||
$this->error = "Destination directory can't be created. Can't carry on a process";
|
||||
return null;
|
||||
}
|
||||
|
||||
$realDirectory = realpath($nextDirectory);
|
||||
if (!$realDirectory || !str_starts_with($realDirectory, $realRoot . DIRECTORY_SEPARATOR)) {
|
||||
return null;
|
||||
}
|
||||
$directory = $realDirectory;
|
||||
}
|
||||
|
||||
return $directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create directories recursively.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
export function bindDraftActions(saveButton, publishButton, saveDraft, confirmPublish) {
|
||||
if (saveButton) {
|
||||
saveButton.addEventListener('click', () => saveDraft(false));
|
||||
}
|
||||
if (publishButton) {
|
||||
publishButton.addEventListener('click', () => {
|
||||
if (confirmPublish()) saveDraft(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export function bindLanguageSelector(document, window) {
|
||||
document.addEventListener("change", function(e) {
|
||||
const radio = e.target.closest("#language-selector input[type='radio']");
|
||||
if (!radio) return;
|
||||
let selectedLanguage = radio.value;
|
||||
|
||||
window.switchLanguage(selectedLanguage, function(success) {
|
||||
if (success) {
|
||||
window.activateLanguage(selectedLanguage);
|
||||
} else {
|
||||
const languageSelector = radio.closest("#language-selector");
|
||||
languageSelector.querySelectorAll('input[type="radio"]').forEach(languageRadio => {
|
||||
languageRadio.checked = languageRadio.value === window.currentLanguage;
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { bindLanguageSelector } from './language-selection.js';
|
||||
|
||||
|
||||
/**
|
||||
@@ -73,19 +74,7 @@
|
||||
/**
|
||||
* Switch pagebuilder to another language variant on changing the language selector.
|
||||
*/
|
||||
document.addEventListener("change", function(e) {
|
||||
const select = e.target.closest("#language-selector select");
|
||||
if (!select) return;
|
||||
let selectedLanguage = select.value;
|
||||
|
||||
window.switchLanguage(selectedLanguage, function(success) {
|
||||
if (success) {
|
||||
activateLanguage(selectedLanguage);
|
||||
} else {
|
||||
select.value = window.currentLanguage;
|
||||
}
|
||||
});
|
||||
});
|
||||
bindLanguageSelector(document, window);
|
||||
|
||||
/**
|
||||
* Activate the given language variant in the pagebuilder.
|
||||
|
||||
@@ -6,7 +6,7 @@ const sidebarHeader = document.getElementById('sidebar-header');
|
||||
const sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
|
||||
const panelsEl = document.querySelector('.gjs-pn-panels');
|
||||
const gjsEl = document.getElementById('gjs');
|
||||
const viewportSelector = document.getElementById('viewport-select');
|
||||
const viewportSelector = document.getElementById('viewport-selector');
|
||||
|
||||
if (window.editor) {
|
||||
bindViewportSelector(window.editor, viewportSelector);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
|
||||
import { bindDraftActions } from './draft-actions.js';
|
||||
|
||||
window.pageData = {};
|
||||
|
||||
@@ -14,12 +15,13 @@
|
||||
/**
|
||||
* Save page on clicking save button.
|
||||
*/
|
||||
const savePageBtn = document.getElementById("save-page");
|
||||
if (savePageBtn) {
|
||||
savePageBtn.addEventListener('click', function() {
|
||||
saveAllTranslationsToServer();
|
||||
});
|
||||
}
|
||||
bindDraftActions(
|
||||
document.getElementById('save-page'),
|
||||
document.getElementById('publish-page'),
|
||||
publishAfterSave => saveAllTranslationsToServer(publishAfterSave),
|
||||
() => window.confirm(window.translations['confirm-publish'])
|
||||
);
|
||||
updateDraftStatus(window.draftAvailable);
|
||||
|
||||
/**
|
||||
* Save page on Ctrl + S.
|
||||
@@ -242,30 +244,31 @@
|
||||
/**
|
||||
* Save the data of all translation variants on the server.
|
||||
*/
|
||||
function saveAllTranslationsToServer() {
|
||||
function saveAllTranslationsToServer(publishAfterSave = false) {
|
||||
if (window.pageActionInProgress) return;
|
||||
window.pageActionInProgress = true;
|
||||
updateDraftStatus(window.draftAvailable);
|
||||
toggleSaving();
|
||||
|
||||
saveCurrentTranslationLocally(async function() {
|
||||
|
||||
// update all language variants with the latest data of the current language we just saved locally
|
||||
Object.keys(window.languages || {}).forEach(languageCode => {
|
||||
if (languageCode !== window.currentLanguage) {
|
||||
applyChangesFromCurrentLanguageToNewLanguage(languageCode);
|
||||
}
|
||||
});
|
||||
|
||||
let data = window.pageData;
|
||||
data.style = removeOldStyleSelectors(data.style);
|
||||
data.blocks = window.pageBlocks;
|
||||
|
||||
const saveBtn = document.getElementById("save-page");
|
||||
const saveUrl = saveBtn ? (saveBtn.dataset.url || saveBtn.getAttribute('data-url')) : '';
|
||||
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('data', JSON.stringify(data));
|
||||
formData.append('_csrf_token', window.csrfToken);
|
||||
|
||||
try {
|
||||
// update all language variants with the latest data of the current language we just saved locally
|
||||
Object.keys(window.languages || {}).forEach(languageCode => {
|
||||
if (languageCode !== window.currentLanguage) {
|
||||
applyChangesFromCurrentLanguageToNewLanguage(languageCode);
|
||||
}
|
||||
});
|
||||
|
||||
let data = window.pageData;
|
||||
data.style = removeOldStyleSelectors(data.style);
|
||||
data.blocks = window.pageBlocks;
|
||||
|
||||
const saveBtn = document.getElementById('save-page');
|
||||
const saveUrl = saveBtn ? (saveBtn.dataset.url || saveBtn.getAttribute('data-url')) : '';
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('data', JSON.stringify(data));
|
||||
formData.append('_csrf_token', window.csrfToken);
|
||||
|
||||
const response = await fetch(saveUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -276,32 +279,75 @@
|
||||
body: formData
|
||||
});
|
||||
|
||||
toggleSaving();
|
||||
|
||||
if (!response.ok) {
|
||||
let errData = {};
|
||||
try { errData = await response.json(); } catch(e) {}
|
||||
let errorMessage = response.statusText + ' ' + response.status;
|
||||
errorMessage = errData.message ? (errorMessage + ': "' + errData.message + '"') : errorMessage;
|
||||
window.toastr.error(errorMessage);
|
||||
window.toastr.error(window.translations['toastr-saving-failed']);
|
||||
return;
|
||||
throw new Error(response.statusText + ' ' + response.status);
|
||||
}
|
||||
|
||||
window.toastr.success(window.translations['toastr-changes-saved']);
|
||||
window.draftAvailable = true;
|
||||
updateDraftStatus(true);
|
||||
if (publishAfterSave) {
|
||||
const publishData = new URLSearchParams();
|
||||
publishData.append('_csrf_token', window.csrfToken);
|
||||
const publishResponse = await fetch(window.publishPageUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-CSRF-Token': window.csrfToken
|
||||
},
|
||||
body: publishData
|
||||
});
|
||||
if (!publishResponse.ok) {
|
||||
throw new Error(publishResponse.statusText + ' ' + publishResponse.status);
|
||||
}
|
||||
window.draftAvailable = false;
|
||||
updateDraftStatus(false);
|
||||
window.toastr.success(window.translations['toastr-published']);
|
||||
} else {
|
||||
window.toastr.success(window.translations['toastr-draft-saved']);
|
||||
}
|
||||
|
||||
setTimeout(function() {
|
||||
window.changesOffset = window.editor.getModel().get('changesCount');
|
||||
}, 250);
|
||||
} catch(error) {
|
||||
toggleSaving();
|
||||
console.error(error);
|
||||
window.toastr.error(error.message || 'Error');
|
||||
window.toastr.error(window.translations['toastr-saving-failed']);
|
||||
window.toastr.error(window.translations[publishAfterSave ? 'toastr-publishing-failed' : 'toastr-saving-failed']);
|
||||
} finally {
|
||||
window.pageActionInProgress = false;
|
||||
toggleSaving();
|
||||
updateDraftStatus(window.draftAvailable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateDraftStatus(hasDraft) {
|
||||
const status = document.getElementById('draft-status');
|
||||
if (status) {
|
||||
status.textContent = window.translations[hasDraft ? 'draft-status' : 'published-status'];
|
||||
status.classList.toggle('badge-warning', hasDraft);
|
||||
status.classList.toggle('badge-success', ! hasDraft);
|
||||
}
|
||||
|
||||
const publishButton = document.getElementById('publish-page');
|
||||
if (publishButton) {
|
||||
publishButton.disabled = ! hasDraft || window.pageActionInProgress;
|
||||
}
|
||||
|
||||
const previewLink = document.getElementById('view-page');
|
||||
if (previewLink) {
|
||||
previewLink.classList.toggle('btn-disabled', ! hasDraft);
|
||||
if (hasDraft) {
|
||||
previewLink.removeAttribute('tabindex');
|
||||
previewLink.removeAttribute('aria-disabled');
|
||||
} else {
|
||||
previewLink.setAttribute('tabindex', '-1');
|
||||
previewLink.setAttribute('aria-disabled', 'true');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the given component in storage format (in context of its container with all siblings removed).
|
||||
*
|
||||
|
||||
@@ -4,8 +4,9 @@ export function bindViewportSelector(editor, selector) {
|
||||
}
|
||||
|
||||
selector.addEventListener('change', function() {
|
||||
if (selector.value) {
|
||||
editor.setDevice(selector.value);
|
||||
const checkedRadio = selector.querySelector('input[type="radio"]:checked');
|
||||
if (checkedRadio && checkedRadio.value) {
|
||||
editor.setDevice(checkedRadio.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,604 +1,576 @@
|
||||
$sidebar-width: 325px;
|
||||
$sidebar-bottom-buttons-height: 40px;
|
||||
|
||||
$sidebar-bottom-buttons-height: 104px;
|
||||
|
||||
/* GENERAL */
|
||||
|
||||
html, body, #gjs {
|
||||
height: 100% !important;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
html,
|
||||
body,
|
||||
#gjs {
|
||||
height: 100% !important;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
* {
|
||||
-webkit-box-shadow: none !important;
|
||||
-moz-box-shadow: none !important;
|
||||
box-shadow: none !important;
|
||||
-webkit-box-shadow: none !important;
|
||||
-moz-box-shadow: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.form-control, .form-control:focus {
|
||||
color: #e1e1e1;
|
||||
.form-control,
|
||||
.form-control:focus {
|
||||
color: #e1e1e1;
|
||||
}
|
||||
|
||||
.cursor-pointer {
|
||||
cursor: pointer;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.gjs-editor {
|
||||
font-size: 0.9rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.toast {
|
||||
opacity: 1 !important;
|
||||
border: none;
|
||||
right: 15px;
|
||||
box-shadow: none;
|
||||
opacity: 1 !important;
|
||||
border: none;
|
||||
right: 15px;
|
||||
box-shadow: none;
|
||||
|
||||
&.toast-success {
|
||||
background: #2dc837;
|
||||
}
|
||||
&.toast-success {
|
||||
background: #2dc837;
|
||||
}
|
||||
}
|
||||
|
||||
#phpb-loading {
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background-color: #fff;
|
||||
z-index: 10000;
|
||||
transition: opacity 0.3s, visibility 0.3s;
|
||||
|
||||
&.loaded {
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.circle {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%,-50%);
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background-color: #fff;
|
||||
z-index: 10000;
|
||||
transition:
|
||||
opacity 0.3s,
|
||||
visibility 0.3s;
|
||||
|
||||
.text {
|
||||
font-size: 20px;
|
||||
margin: 0 -30px;
|
||||
margin-top: 20px;
|
||||
text-align: center;
|
||||
color: #0091d1;
|
||||
&.loaded {
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.circle {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
|
||||
.text {
|
||||
font-size: 20px;
|
||||
margin: 0 -30px;
|
||||
margin-top: 20px;
|
||||
text-align: center;
|
||||
color: #0091d1;
|
||||
}
|
||||
}
|
||||
.loader {
|
||||
width: calc(100% - 0px);
|
||||
height: calc(100% - 0px);
|
||||
border: 8px solid #0091d1;
|
||||
border-top: 8px solid #004a6c;
|
||||
border-radius: 50%;
|
||||
animation: rotate 5s linear infinite;
|
||||
}
|
||||
@keyframes rotate {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
.loader {
|
||||
width: calc(100% - 0px);
|
||||
height: calc(100% - 0px);
|
||||
border: 8px solid #0091d1;
|
||||
border-top: 8px solid #004a6c;
|
||||
border-radius: 50%;
|
||||
animation: rotate 5s linear infinite;
|
||||
}
|
||||
@keyframes rotate {
|
||||
100% {transform: rotate(360deg);}
|
||||
}
|
||||
}
|
||||
|
||||
.btn.focus, .btn:focus {
|
||||
box-shadow: none;
|
||||
.btn.focus,
|
||||
.btn:focus {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.gjs-cv-canvas {
|
||||
height: 100%;
|
||||
top: 0;
|
||||
width: calc(100% - #{$sidebar-width});
|
||||
height: 100%;
|
||||
top: 0;
|
||||
width: calc(100% - #{$sidebar-width});
|
||||
}
|
||||
.gjs-toolbar {
|
||||
z-index: 100 !important;
|
||||
z-index: 100 !important;
|
||||
}
|
||||
|
||||
.gjs-pn-panel {
|
||||
padding: 0;
|
||||
padding: 0;
|
||||
|
||||
.gjs-pn-buttons {
|
||||
justify-content: center;
|
||||
}
|
||||
.gjs-pn-buttons {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
.gjs-pn-commands,
|
||||
.gjs-pn-options,
|
||||
.gjs-pn-devices-c {
|
||||
display: none;
|
||||
display: none;
|
||||
}
|
||||
.gjs-devices-c {
|
||||
padding: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.gjs-one-bg {
|
||||
background-color: #313844;
|
||||
border-bottom: none;
|
||||
color: #c4c7ce;
|
||||
background-color: #313844;
|
||||
border-bottom: none;
|
||||
color: #c4c7ce;
|
||||
}
|
||||
.gjs-two-color {
|
||||
color: #e1e1e1;
|
||||
color: #e1e1e1;
|
||||
}
|
||||
.gjs-four-color {
|
||||
color: #e1e1e1;
|
||||
color: #e1e1e1;
|
||||
}
|
||||
.gjs-four-color-h:hover {
|
||||
color: #e1e1e1;
|
||||
color: #e1e1e1;
|
||||
}
|
||||
.gjs-pn-commands {
|
||||
width: 100%;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
width: 100%;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
::-webkit-scrollbar {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: #313844 !important;
|
||||
background: #313844 !important;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #a5acb9 !important;
|
||||
border-radius: 3px;
|
||||
background-color: #a5acb9 !important;
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover {
|
||||
background-color: #0091d1 !important;
|
||||
}
|
||||
&:hover {
|
||||
background-color: #0091d1 !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* SIDEBAR */
|
||||
|
||||
.gjs-pn-views {
|
||||
top: 40px;
|
||||
top: 80px;
|
||||
|
||||
.gjs-pn-btn {
|
||||
width: 33.33%;
|
||||
margin-right: 0;
|
||||
padding: 16px 15px 16px 15px;
|
||||
-webkit-border-radius: 0;
|
||||
-moz-border-radius: 0;
|
||||
border-radius: 0;
|
||||
background: #3a3f4a;
|
||||
color: #e3e3e3;
|
||||
border-bottom: 1px solid #3a3f4a;
|
||||
font-size: 16px;
|
||||
.gjs-pn-btn {
|
||||
width: 33.33%;
|
||||
margin-right: 0;
|
||||
padding: 16px 15px 16px 15px;
|
||||
-webkit-border-radius: 0;
|
||||
-moz-border-radius: 0;
|
||||
border-radius: 0;
|
||||
background: #3a3f4a;
|
||||
color: #e3e3e3;
|
||||
border-bottom: 1px solid #3a3f4a;
|
||||
font-size: 16px;
|
||||
|
||||
&.gjs-pn-active {
|
||||
padding: 15px;
|
||||
background-color: #515664;
|
||||
border-bottom-left-radius: unset;
|
||||
border-bottom-right-radius: unset;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
color: #fff;
|
||||
border-bottom: 3px solid #0091d1;
|
||||
&.gjs-pn-active {
|
||||
padding: 15px;
|
||||
background-color: #515664;
|
||||
border-bottom-left-radius: unset;
|
||||
border-bottom-right-radius: unset;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
color: #fff;
|
||||
border-bottom: 3px solid #0091d1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.gjs-pn-options {
|
||||
right: 0;
|
||||
right: 0;
|
||||
}
|
||||
.gjs-pn-views,
|
||||
.gjs-pn-views-container {
|
||||
left: 0;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
width: $sidebar-width;
|
||||
padding-bottom: 0;
|
||||
margin-bottom: 0;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
left: 0;
|
||||
-webkit-box-shadow: none;
|
||||
-moz-box-shadow: none;
|
||||
box-shadow: none;
|
||||
width: $sidebar-width;
|
||||
padding-bottom: 0;
|
||||
margin-bottom: 0;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
}
|
||||
.gjs-pn-views-container {
|
||||
padding-top: 89px;
|
||||
background: #22272e;
|
||||
height: calc(100% - #{$sidebar-bottom-buttons-height});
|
||||
overflow: hidden;
|
||||
|
||||
> div:first-of-type {
|
||||
margin-top: 44px;
|
||||
}
|
||||
|
||||
> div {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
> div > div {
|
||||
padding-top: 89px;
|
||||
background: #22272e;
|
||||
border: none;
|
||||
}
|
||||
height: calc(100% - #{$sidebar-bottom-buttons-height});
|
||||
overflow: hidden;
|
||||
|
||||
> div:first-of-type {
|
||||
margin-top: 44px;
|
||||
}
|
||||
|
||||
> div {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
> div > div {
|
||||
background: #22272e;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
.gjs-cv-canvas,
|
||||
.gjs-pn-devices-c {
|
||||
left: $sidebar-width;
|
||||
left: $sidebar-width;
|
||||
}
|
||||
.gjs-pn-panel {
|
||||
#gjs-sm-caret {
|
||||
padding-right: 0 !important;
|
||||
}
|
||||
.fa-caret-down {
|
||||
margin-right: 5px !important;
|
||||
}
|
||||
.fa-caret-right {
|
||||
margin-right: 8px !important;
|
||||
}
|
||||
#gjs-sm-caret {
|
||||
padding-right: 0 !important;
|
||||
}
|
||||
.fa-caret-down {
|
||||
margin-right: 5px !important;
|
||||
}
|
||||
.fa-caret-right {
|
||||
margin-right: 8px !important;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* SIDEBAR FIELDS */
|
||||
|
||||
.gjs-three-bg {
|
||||
background-color: #0091d1;
|
||||
background-color: #0091d1;
|
||||
}
|
||||
.gjs-clm-tags {
|
||||
#gjs-clm-close,
|
||||
#gjs-clm-checkbox {
|
||||
color: #fff;
|
||||
}
|
||||
#gjs-clm-close,
|
||||
#gjs-clm-checkbox {
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
.gjs-field {
|
||||
background-color: #22272e;
|
||||
border-radius: 0;
|
||||
padding: 2px;
|
||||
background-color: #22272e;
|
||||
border-radius: 0;
|
||||
padding: 2px;
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
padding: 5px;
|
||||
}
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.gjs-d-s-arrow {
|
||||
border-top: 4px solid rgb(100, 100, 100);
|
||||
}
|
||||
.gjs-d-s-arrow {
|
||||
border-top: 4px solid rgb(100, 100, 100);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* SIDEBAR HEADER */
|
||||
|
||||
#sidebar-header {
|
||||
position: absolute;
|
||||
box-shadow: none;
|
||||
width: $sidebar-width;
|
||||
padding: 0 10px;
|
||||
background: #22272e;
|
||||
height: 40px;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
position: absolute;
|
||||
box-shadow: none;
|
||||
width: $sidebar-width;
|
||||
height: 80px;
|
||||
background: #22272e;
|
||||
z-index: 100;
|
||||
|
||||
#language-selector, #viewport-selector {
|
||||
margin-left: auto;
|
||||
#language-selector,
|
||||
#viewport-selector {
|
||||
margin-left: auto;
|
||||
|
||||
select {
|
||||
background: #2e323b;
|
||||
color: #e3e3e3;
|
||||
border: 1px solid #474c57;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
select {
|
||||
background: #2e323b;
|
||||
color: #e3e3e3;
|
||||
border: 1px solid #474c57;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#toggle-sidebar {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
color: #c4c7ce;
|
||||
background: #22272e;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
height: 40px;
|
||||
width: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
color: #c4c7ce;
|
||||
background: #22272e;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
height: 36px;
|
||||
width: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
|
||||
/* BLOCKS PANEL VIEW */
|
||||
|
||||
#block-search {
|
||||
position: fixed;
|
||||
background: #22272e;
|
||||
border-color: #3a3f4a;
|
||||
border-radius: 0;
|
||||
width: 325px;
|
||||
margin-top: -44px;
|
||||
|
||||
i.fa-search {
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
left: 9px;
|
||||
font-size: 15px;
|
||||
color: #515664;
|
||||
}
|
||||
|
||||
input {
|
||||
background: #181b1e;
|
||||
padding: 22px 20px 22px 30px;
|
||||
position: fixed;
|
||||
background: #22272e;
|
||||
border-color: #3a3f4a;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
width: 325px;
|
||||
margin-top: -44px;
|
||||
|
||||
&::placeholder {
|
||||
color: #515664;
|
||||
i.fa-search {
|
||||
position: absolute;
|
||||
top: 14px;
|
||||
left: 9px;
|
||||
font-size: 15px;
|
||||
color: #515664;
|
||||
}
|
||||
|
||||
input {
|
||||
background: #181b1e;
|
||||
padding: 22px 20px 22px 30px;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
|
||||
&::placeholder {
|
||||
color: #515664;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.gjs-block {
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
padding-bottom: 8px;
|
||||
margin: 5px;
|
||||
width: calc(50% - 10px);
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
padding-bottom: 8px;
|
||||
margin: 5px;
|
||||
width: calc(50% - 10px);
|
||||
|
||||
&.fa {
|
||||
padding: 8px;
|
||||
}
|
||||
&.fa {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: #0091d1 !important;
|
||||
}
|
||||
&:hover {
|
||||
color: #0091d1 !important;
|
||||
}
|
||||
|
||||
.block-thumb {
|
||||
height: 70px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 5px;
|
||||
opacity: 0.8;
|
||||
.block-thumb {
|
||||
height: 70px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 5px;
|
||||
opacity: 0.8;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
img {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.gjs-blocks-c {
|
||||
background: #22272e;
|
||||
padding: 4px;
|
||||
background: #22272e;
|
||||
padding: 4px;
|
||||
}
|
||||
.gjs-block-categories {
|
||||
background: #22272e;
|
||||
padding-bottom: 45px;
|
||||
background: #22272e;
|
||||
padding-bottom: 45px;
|
||||
}
|
||||
.gjs-block-label {
|
||||
font-size: 0.8rem;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
font-size: 0.8rem;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
|
||||
b {
|
||||
display: contents;
|
||||
font-weight: 800;
|
||||
}
|
||||
b {
|
||||
display: contents;
|
||||
font-weight: 800;
|
||||
}
|
||||
}
|
||||
.gjs-block-category {
|
||||
background: #5a6371;
|
||||
background: #5a6371;
|
||||
}
|
||||
.gjs-block-category.gjs-open {
|
||||
border-bottom: none !important;
|
||||
margin-bottom: 10px;
|
||||
border-bottom: none !important;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.gjs-blocks-cs {
|
||||
border-bottom: none !important;
|
||||
border-bottom: none !important;
|
||||
}
|
||||
|
||||
|
||||
/* LAYERS PANEL VIEW */
|
||||
|
||||
.gjs-layer .gjs-layer-title {
|
||||
background: #5a6371 !important;
|
||||
background: #5a6371 !important;
|
||||
}
|
||||
.gjs-layer.gjs-selected .gjs-layer-title {
|
||||
background-color: #0091d1 !important;
|
||||
background-color: #0091d1 !important;
|
||||
}
|
||||
.gjs-layer.gjs-hovered .gjs-layer-title {
|
||||
background-color: #0091d170 !important
|
||||
background-color: #0091d170 !important;
|
||||
}
|
||||
.gjs-category-title,
|
||||
.gjs-sm-sector .gjs-sm-title,
|
||||
.gjs-clm-tags .gjs-sm-title,
|
||||
.gjs-block-category .gjs-title,
|
||||
.gjs-layer-title {
|
||||
background: #424853 !important;
|
||||
border-bottom: 2px solid #363d48 !important;
|
||||
letter-spacing: 0;
|
||||
font-size: 16px;
|
||||
font-weight: normal;
|
||||
background: #424853 !important;
|
||||
border-bottom: 2px solid #363d48 !important;
|
||||
letter-spacing: 0;
|
||||
font-size: 16px;
|
||||
font-weight: normal;
|
||||
}
|
||||
.gjs-sm-sector.gjs-sm-open .gjs-sm-title,
|
||||
.gjs-clm-tags.gjs-open .gjs-sm-title,
|
||||
.gjs-block-category.gjs-open .gjs-title {
|
||||
background: #545d6c !important;
|
||||
background: #545d6c !important;
|
||||
}
|
||||
.gjs-layer-name {
|
||||
padding-top: 2px;
|
||||
padding-bottom: 13px;
|
||||
padding-top: 2px;
|
||||
padding-bottom: 13px;
|
||||
}
|
||||
.gjs-layer-count {
|
||||
display: none;
|
||||
display: none;
|
||||
}
|
||||
.gjs-layer-vis {
|
||||
padding-top: 11px
|
||||
padding-top: 11px;
|
||||
}
|
||||
|
||||
|
||||
/* LAYERS PANEL VIEW */
|
||||
|
||||
.gjs-sm-sector.gjs-sm-open {
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
|
||||
/* TRAITS PANEL VIEW */
|
||||
|
||||
.gjs-trt-trait {
|
||||
display: block;
|
||||
display: block;
|
||||
}
|
||||
.gjs-trt-header {
|
||||
font-weight: normal;
|
||||
font-weight: normal;
|
||||
}
|
||||
.gjs-trt-trait .gjs-label,
|
||||
.gjs-trt-trait .gjs-field {
|
||||
width: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
.gjs-field-checkbox {
|
||||
height: 17px !important;
|
||||
width: 17px !important;
|
||||
height: 17px !important;
|
||||
width: 17px !important;
|
||||
}
|
||||
.gjs-traits-label {
|
||||
font-weight: normal;
|
||||
font-size: 16px;
|
||||
border-bottom: none;
|
||||
font-weight: normal;
|
||||
font-size: 16px;
|
||||
border-bottom: none;
|
||||
}
|
||||
.gjs-sm-sector #gjs-sm-caret,
|
||||
.gjs-clm-tags #gjs-sm-caret {
|
||||
font-size: initial;
|
||||
font-size: initial;
|
||||
}
|
||||
.gjs-trt-traits .gjs-label-wrp {
|
||||
width: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
.gjs-trt-traits p.no-settings {
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
.gjs-trt-trait__wrp:first-of-type {
|
||||
padding-top: 8px;
|
||||
padding-top: 8px;
|
||||
}
|
||||
.gjs-trt-trait__wrp:last-of-type {
|
||||
padding-bottom: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.gjs-trt-trait {
|
||||
padding-bottom: 10px;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
.gjs-trt-trait .gjs-field-image {
|
||||
background: none;
|
||||
padding: 0;
|
||||
background: none;
|
||||
padding: 0;
|
||||
|
||||
.image__preview-container {
|
||||
text-align: center;
|
||||
.image__preview-container {
|
||||
text-align: center;
|
||||
|
||||
.image__remove-button {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
border-radius: 0;
|
||||
background-color: #e9eef2;
|
||||
border-color: #e9eef2;
|
||||
color: #515664;
|
||||
padding: 2px 6px;
|
||||
.image__remove-button {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
border-radius: 0;
|
||||
background-color: #e9eef2;
|
||||
border-color: #e9eef2;
|
||||
color: #515664;
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 150px;
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: 150px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* SIDEBAR BOTTOM BUTTONS */
|
||||
|
||||
#sidebar-bottom-buttons {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
height: $sidebar-bottom-buttons-height;
|
||||
width: $sidebar-width;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: #474c57;
|
||||
border-top: none;
|
||||
display: flex;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
width: $sidebar-width;
|
||||
margin: 0;
|
||||
padding: 4px;
|
||||
background: #474c57;
|
||||
border-top: none;
|
||||
box-sizing: border-box;
|
||||
|
||||
button,
|
||||
a {
|
||||
flex: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
border-left: 1px solid #343944;
|
||||
border-radius: 0;
|
||||
color: #e3e3e3;
|
||||
font-size: 13px;
|
||||
padding: 0 4px;
|
||||
text-decoration: none;
|
||||
border: none;
|
||||
border-left: 1px solid #343944;
|
||||
button.waiting {
|
||||
background: #0091d1;
|
||||
color: #fff !important;
|
||||
|
||||
&:hover {
|
||||
background: #017eb5;
|
||||
color: #fff;
|
||||
i.fa-save {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
&:first-child {
|
||||
border-left: none;
|
||||
|
||||
#go-back:hover {
|
||||
background: #b03541;
|
||||
}
|
||||
}
|
||||
|
||||
button.waiting {
|
||||
background: #0091d1;
|
||||
color: #fff !important;
|
||||
|
||||
i.fa-save {
|
||||
display: none;
|
||||
#save-page:hover {
|
||||
background: #419147;
|
||||
}
|
||||
}
|
||||
|
||||
#go-back:hover {
|
||||
background: #b03541;
|
||||
}
|
||||
#save-page:hover {
|
||||
background: #419147;
|
||||
}
|
||||
}
|
||||
|
||||
@import 'fields';
|
||||
@import 'style-manager';
|
||||
@import 'asset-manager';
|
||||
@import "fields";
|
||||
@import "style-manager";
|
||||
@import "asset-manager";
|
||||
|
||||
.gjs-link-modal-form {
|
||||
color: #d1d5db;
|
||||
font-size: 14px;
|
||||
|
||||
.gjs-field {
|
||||
background-color: #2e323b;
|
||||
border: 1px solid #474c57;
|
||||
color: #fff;
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
outline: none;
|
||||
color: #d1d5db;
|
||||
font-size: 14px;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
.gjs-field {
|
||||
background-color: #2e323b;
|
||||
border: 1px solid #474c57;
|
||||
color: #fff;
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
outline: none;
|
||||
font-size: 14px;
|
||||
|
||||
&:focus {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
select.gjs-field {
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a0aec0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
background-size: 16px;
|
||||
padding-right: 32px;
|
||||
}
|
||||
select.gjs-field {
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a0aec0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
background-size: 16px;
|
||||
padding-right: 32px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 6px 14px;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: background-color 0.15s ease-in-out;
|
||||
}
|
||||
.btn {
|
||||
padding: 6px 14px;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: background-color 0.15s ease-in-out;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,34 +8,52 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="text">
|
||||
<?= phpb_trans('pagebuilder.loading-text') ?>
|
||||
<?= phpb_trans("pagebuilder.loading-text") ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="gjs"></div>
|
||||
|
||||
<script type="text/javascript" src="<?= phpb_asset('pagebuilder/grapesjs-touch-v0.1.1.min.js') ?>"></script>
|
||||
<?php $previewUrl = phpb_full_url($page->getPreviewRoute()); ?>
|
||||
|
||||
<script type="text/javascript" src="<?= phpb_asset(
|
||||
"pagebuilder/grapesjs-touch-v0.1.1.min.js",
|
||||
) ?>"></script>
|
||||
<script type="text/javascript">
|
||||
|
||||
window.languages = <?= json_encode(phpb_active_languages()) ?>;
|
||||
window.currentLanguage = <?= json_encode($currentLanguage) ?>;
|
||||
window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>;
|
||||
window.contentContainerComponents = <?= json_encode($pageBuilder->getPageComponents($page)) ?>;
|
||||
window.translations = <?= json_encode(phpb_trans("pagebuilder")) ?>;
|
||||
window.contentContainerComponents = <?= json_encode(
|
||||
$pageBuilder->getPageComponents($page),
|
||||
) ?>;
|
||||
window.themeBlocks = <?= json_encode($blocks) ?>;
|
||||
window.blockSettings = <?= json_encode($blockSettings) ?>;
|
||||
window.pageBlocks = <?= json_encode($pageRenderer->getPageBlocksData()) ?>;
|
||||
window.pages = <?= json_encode($pageBuilder->getPages()) ?>;
|
||||
window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>';
|
||||
window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>';
|
||||
window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>';
|
||||
window.renderBlockUrl = '<?= phpb_url("pagebuilder", [
|
||||
"action" => "renderBlock",
|
||||
"page" => $page->getId(),
|
||||
]) ?>';
|
||||
window.injectionScriptUrl = '<?= phpb_asset(
|
||||
"pagebuilder/page-injection.js",
|
||||
) ?>';
|
||||
window.renderLanguageVariantUrl = '<?= phpb_url("pagebuilder", [
|
||||
"action" => "renderLanguageVariant",
|
||||
"page" => $page->getId(),
|
||||
]) ?>';
|
||||
window.publishPageUrl = <?= json_encode(
|
||||
phpb_url("pagebuilder", ["action" => "publish", "page" => $page->getId()]),
|
||||
) ?>;
|
||||
window.draftAvailable = <?= json_encode($hasDraft) ?>;
|
||||
window.csrfToken = '<?= phpb_e(\Plugi\Core\Csrf::getToken()) ?>';
|
||||
|
||||
<?php
|
||||
$config = require __DIR__ . '/grapesjs/config.php';
|
||||
$config = require __DIR__ . "/grapesjs/config.php";
|
||||
// Add CSRF token header to GrapesJS file uploads
|
||||
$config['assetManager']['headers'] = [
|
||||
'X-CSRF-Token' => \Plugi\Core\Csrf::getToken()
|
||||
$config["assetManager"]["headers"] = [
|
||||
"X-CSRF-Token" => \Plugi\Core\Csrf::getToken(),
|
||||
];
|
||||
?>
|
||||
let config = <?= json_encode($config) ?>;
|
||||
@@ -54,30 +72,38 @@ if (window.customConfig !== undefined) {
|
||||
}
|
||||
|
||||
window.initialComponents = <?= json_encode($pageRenderer->render()) ?>;
|
||||
window.initialStyle = <?= json_encode($pageBuilder->getPageStyleComponents($page)) ?>;
|
||||
window.initialStyle = <?= json_encode(
|
||||
$pageBuilder->getPageStyleComponents($page),
|
||||
) ?>;
|
||||
window.initialCss = <?= json_encode($pageBuilder->getPageStyleCss($page)) ?>;
|
||||
window.grapesJSTranslations = {
|
||||
<?= $currentLanguage ?>: {
|
||||
styleManager: {
|
||||
empty: '<?= phpb_trans('pagebuilder.style-no-element-selected') ?>'
|
||||
empty: '<?= phpb_trans("pagebuilder.style-no-element-selected") ?>'
|
||||
},
|
||||
traitManager: {
|
||||
empty: '<?= phpb_trans('pagebuilder.trait-no-element-selected') ?>',
|
||||
label: '<?= phpb_trans('pagebuilder.trait-settings') ?>',
|
||||
empty: '<?= phpb_trans("pagebuilder.trait-no-element-selected") ?>',
|
||||
label: '<?= phpb_trans("pagebuilder.trait-settings") ?>',
|
||||
traits: {
|
||||
options: {
|
||||
target: {
|
||||
false: '<?= phpb_trans('pagebuilder.no') ?>',
|
||||
_blank: '<?= phpb_trans('pagebuilder.yes') ?>'
|
||||
false: '<?= phpb_trans("pagebuilder.no") ?>',
|
||||
_blank: '<?= phpb_trans("pagebuilder.yes") ?>'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
assetManager: {
|
||||
addButton: '<?= phpb_trans('pagebuilder.asset-manager.add-image') ?>',
|
||||
addButton: '<?= phpb_trans(
|
||||
"pagebuilder.asset-manager.add-image",
|
||||
) ?>',
|
||||
inputPlh: 'http://path/to/the/image.jpg',
|
||||
modalTitle: '<?= phpb_trans('pagebuilder.asset-manager.modal-title') ?>',
|
||||
uploadTitle: '<?= phpb_trans('pagebuilder.asset-manager.drop-files') ?>'
|
||||
modalTitle: '<?= phpb_trans(
|
||||
"pagebuilder.asset-manager.modal-title",
|
||||
) ?>',
|
||||
uploadTitle: '<?= phpb_trans(
|
||||
"pagebuilder.asset-manager.drop-files",
|
||||
) ?>'
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -94,64 +120,133 @@ window.editor.setStyle(window.initialStyle);
|
||||
</script>
|
||||
|
||||
<?php
|
||||
require __DIR__ . '/grapesjs/asset-manager.php';
|
||||
require __DIR__ . '/grapesjs/component-type-manager.php';
|
||||
require __DIR__ . '/grapesjs/style-manager.php';
|
||||
require __DIR__ . '/grapesjs/trait-manager.php';
|
||||
require __DIR__ . "/grapesjs/asset-manager.php";
|
||||
require __DIR__ . "/grapesjs/component-type-manager.php";
|
||||
require __DIR__ . "/grapesjs/style-manager.php";
|
||||
require __DIR__ . "/grapesjs/trait-manager.php";
|
||||
?>
|
||||
|
||||
<button id="toggle-sidebar" class="btn btn-sm btn-ghost">
|
||||
<i class="fa fa-bars"></i>
|
||||
</button>
|
||||
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 px-2">
|
||||
<?php
|
||||
if (sizeof(phpb_active_languages()) > 1):
|
||||
?>
|
||||
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 p-2">
|
||||
<?php if (sizeof(phpb_active_languages()) > 1): ?>
|
||||
<div class="flex-grow"></div>
|
||||
<div id="language-selector">
|
||||
<select class="select select-xs w-24 text-xs">
|
||||
<?php
|
||||
foreach (phpb_active_languages() as $languageCode => $languageTranslation):
|
||||
?>
|
||||
<option value="<?= phpb_e($languageCode) ?>" <?= $languageCode === $currentLanguage ? 'selected' : '' ?>>
|
||||
<?= phpb_e(strtoupper($languageCode)) ?> - <?= phpb_e($languageTranslation) ?>
|
||||
</option>
|
||||
<?php
|
||||
endforeach;
|
||||
?>
|
||||
</select>
|
||||
<fieldset>
|
||||
<legend class="sr-only"><?= phpb_e(
|
||||
phpb_trans("website-manager.website-languages"),
|
||||
) ?></legend>
|
||||
<div class="join">
|
||||
<?php foreach (
|
||||
array_keys(phpb_active_languages())
|
||||
as $languageCode
|
||||
): ?>
|
||||
<label class="btn btn-xs font-mono join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
||||
<input type="radio" name="pagebuilder-language" value="<?= phpb_e(
|
||||
$languageCode,
|
||||
) ?>" class="sr-only" <?= $languageCode === $currentLanguage
|
||||
? "checked"
|
||||
: "" ?>>
|
||||
<span><?= phpb_e(strtoupper($languageCode)) ?></span>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<?php
|
||||
endif;
|
||||
?>
|
||||
<div id="viewport-selector" class="ml-auto">
|
||||
<label class="sr-only" for="viewport-select"><?= phpb_trans('pagebuilder.viewport-selector') ?></label>
|
||||
<select id="viewport-select" class="select select-xs w-28 text-xs" aria-label="<?= phpb_e(phpb_trans('pagebuilder.viewport-selector')) ?>">
|
||||
<option value="Desktop"><?= phpb_trans('pagebuilder.viewport-desktop') ?></option>
|
||||
<option value="Tablet"><?= phpb_trans('pagebuilder.viewport-tablet') ?></option>
|
||||
<option value="Mobile"><?= phpb_trans('pagebuilder.viewport-mobile') ?></option>
|
||||
<?php endif; ?>
|
||||
<fieldset id="viewport-selector" class="ml-auto">
|
||||
<legend class="sr-only"><?= phpb_e(
|
||||
phpb_trans("pagebuilder.viewport-selector"),
|
||||
) ?></legend>
|
||||
<div class="join">
|
||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
||||
<input type="radio" name="pagebuilder-viewport" value="Desktop" class="sr-only" aria-label="<?= phpb_e(
|
||||
phpb_trans("pagebuilder.viewport-desktop"),
|
||||
) ?>" checked>
|
||||
<i class="ph ph-desktop" aria-hidden="true"></i>
|
||||
</label>
|
||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
||||
<input type="radio" name="pagebuilder-viewport" value="Tablet" class="sr-only" aria-label="<?= phpb_e(
|
||||
phpb_trans("pagebuilder.viewport-tablet"),
|
||||
) ?>">
|
||||
<i class="ph ph-device-tablet" aria-hidden="true"></i>
|
||||
</label>
|
||||
<label class="btn btn-xs join-item cursor-pointer has-[:checked]:bg-primary has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary">
|
||||
<input type="radio" name="pagebuilder-viewport" value="Mobile" class="sr-only" aria-label="<?= phpb_e(
|
||||
phpb_trans("pagebuilder.viewport-mobile"),
|
||||
) ?>">
|
||||
<i class="ph ph-device-mobile" aria-hidden="true"></i>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="w-full">
|
||||
<label for="page-selector" class="sr-only"><?= phpb_e(
|
||||
phpb_trans("pagebuilder.page-selector"),
|
||||
) ?></label>
|
||||
<select id="page-selector" class="select select-sm w-full" onchange="const pageUrl = this.value; this.value = this.querySelector('option[selected]').value; window.location.href = pageUrl">
|
||||
<?php foreach ($editablePages as $editablePage): ?>
|
||||
<option value="<?= phpb_e(
|
||||
phpb_url("pagebuilder", ["page" => $editablePage->getId()]),
|
||||
) ?>" <?= $editablePage->getId() === $page->getId()
|
||||
? "selected"
|
||||
: "" ?>><?= phpb_e($editablePage->getName()) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="sidebar-bottom-buttons" class="flex items-center justify-between">
|
||||
<button id="save-page" class="btn btn-sm btn-success flex-1 rounded-none text-white gap-2" data-url="<?= phpb_url('pagebuilder', ['action' => 'store', 'page' => $page->getId()]) ?>">
|
||||
<div id="sidebar-bottom-buttons" class="grid grid-cols-2 gap-1 p-1">
|
||||
<div class="col-span-2 px-2 py-1 text-center">
|
||||
<span id="draft-status" class="badge badge-sm <?= $hasDraft
|
||||
? "badge-warning"
|
||||
: "badge-success" ?>" role="status" aria-live="polite">
|
||||
<?= phpb_trans(
|
||||
$hasDraft
|
||||
? "pagebuilder.draft-status"
|
||||
: "pagebuilder.published-status",
|
||||
) ?>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button id="save-page" type="button" class="btn btn-sm btn-success gap-2" data-url="<?= phpb_url(
|
||||
"pagebuilder",
|
||||
["action" => "storeDraft", "page" => $page->getId()],
|
||||
) ?>">
|
||||
<span class="loading loading-spinner loading-xs" style="display: none;" role="status" aria-hidden="true"></span>
|
||||
<i class="fa fa-save"></i>
|
||||
<span><?= phpb_trans('pagebuilder.save-page') ?></span>
|
||||
<span><?= phpb_trans("pagebuilder.save-draft") ?></span>
|
||||
</button>
|
||||
|
||||
<a id="view-page" href="<?= phpb_e(phpb_full_url($page->getRoute())) ?>" target="_blank" class="btn btn-sm btn-info flex-1 rounded-none text-white gap-2">
|
||||
<a id="view-page" href="<?= phpb_e(
|
||||
$previewUrl,
|
||||
) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-info gap-2 <?= $hasDraft
|
||||
? ""
|
||||
: "btn-disabled" ?>" <?= $hasDraft
|
||||
? ""
|
||||
: 'tabindex="-1" aria-disabled="true"' ?>>
|
||||
<i class="fa fa-external-link"></i>
|
||||
<span><?= phpb_trans('pagebuilder.view-page') ?></span>
|
||||
<span><?= phpb_trans("pagebuilder.preview-draft") ?></span>
|
||||
</a>
|
||||
|
||||
<a id="go-back" href="<?= phpb_e(phpb_full_url(phpb_config('pagebuilder.actions.back'))) ?>" class="btn btn-sm btn-neutral flex-1 rounded-none text-white gap-2">
|
||||
<button id="publish-page" type="button" class="btn btn-sm btn-warning gap-2" <?= $hasDraft
|
||||
? ""
|
||||
: "disabled" ?>>
|
||||
<i class="fa fa-globe"></i>
|
||||
<span><?= phpb_trans("pagebuilder.publish-draft") ?></span>
|
||||
</button>
|
||||
|
||||
<a id="go-back" href="<?= phpb_e(
|
||||
phpb_full_url(phpb_config("pagebuilder.actions.back")),
|
||||
) ?>" class="btn btn-sm btn-neutral gap-2">
|
||||
<i class="fa fa-arrow-circle-left"></i>
|
||||
<span><?= phpb_trans('pagebuilder.go-back') ?></span>
|
||||
<span><?= phpb_trans("pagebuilder.go-back") ?></span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div id="block-search">
|
||||
<i class="fa fa-search"></i>
|
||||
<input type="text" class="input input-sm w-full" placeholder="<?= phpb_trans('pagebuilder.filter-placeholder') ?>">
|
||||
<input type="text" class="input input-sm w-full" placeholder="<?= phpb_trans(
|
||||
"pagebuilder.filter-placeholder",
|
||||
) ?>">
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ use Plugi\Contracts\WebsiteManagerContract;
|
||||
use Plugi\Extensions;
|
||||
use Plugi\PageTranslationService;
|
||||
use Plugi\Repositories\MenuRepository;
|
||||
use Plugi\Repositories\PageDraftPublishedCacheInvalidationException;
|
||||
use Plugi\Repositories\PageRepository;
|
||||
use Plugi\Repositories\SettingRepository;
|
||||
use Plugi\Repositories\UploadRepository;
|
||||
@@ -26,83 +27,243 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
exit();
|
||||
}
|
||||
|
||||
if ($route === 'quality' && $action === 'scan' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
|
||||
if (! function_exists('phpb_validate_csrf') || ! phpb_validate_csrf()) {
|
||||
http_response_code(403);
|
||||
die('Invalid CSRF token. Please refresh the page and try again.');
|
||||
if ($route === "media" && $action === "update_metadata") {
|
||||
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
|
||||
http_response_code(405);
|
||||
exit();
|
||||
}
|
||||
$_GET['tab'] = 'quality';
|
||||
$this->renderQualityChecks((new SiteQualityCheckService())->run());
|
||||
$this->handleUpdateMediaMetadata();
|
||||
exit();
|
||||
}
|
||||
|
||||
if ($route === 'settings') {
|
||||
if ($action === 'renderBlockThumbs') {
|
||||
if ($route === "drafts" && $action === "publish_all") {
|
||||
$result = $this->handlePublishAllDrafts();
|
||||
if ($result === null) {
|
||||
exit();
|
||||
}
|
||||
|
||||
if ($result["total"] === 0) {
|
||||
$flashData = [
|
||||
"message-type" => "info",
|
||||
"message" => "No unpublished page changes were found.",
|
||||
];
|
||||
} elseif (
|
||||
empty($result["failed"]) &&
|
||||
empty($result["cache_warnings"])
|
||||
) {
|
||||
$pageCount = count($result["published"]);
|
||||
$flashData = [
|
||||
"message-type" => "success",
|
||||
"message" => sprintf(
|
||||
"Published changes for %d page%s.",
|
||||
$pageCount,
|
||||
$pageCount === 1 ? "" : "s",
|
||||
),
|
||||
];
|
||||
} else {
|
||||
$message = sprintf(
|
||||
"Published changes for %d of %d pages.",
|
||||
count($result["published"]),
|
||||
$result["total"],
|
||||
);
|
||||
if (!empty($result["failed"])) {
|
||||
$message .= sprintf(
|
||||
" Failed pages: %s. Their drafts remain available to retry.",
|
||||
implode(", ", $result["failed"]),
|
||||
);
|
||||
}
|
||||
if (!empty($result["cache_warnings"])) {
|
||||
$message .= sprintf(
|
||||
" Route cache invalidation failed for: %s.",
|
||||
implode(", ", $result["cache_warnings"]),
|
||||
);
|
||||
}
|
||||
$flashData = [
|
||||
"message-type" => empty($result["published"])
|
||||
? "error"
|
||||
: "warning",
|
||||
"message" => $message,
|
||||
];
|
||||
}
|
||||
|
||||
phpb_redirect(phpb_url("website_manager"), $flashData);
|
||||
}
|
||||
|
||||
if (
|
||||
$route === "quality" &&
|
||||
$action === "scan" &&
|
||||
($_SERVER["REQUEST_METHOD"] ?? "") === "POST"
|
||||
) {
|
||||
if (
|
||||
!function_exists("phpb_validate_csrf") ||
|
||||
!phpb_validate_csrf()
|
||||
) {
|
||||
http_response_code(403);
|
||||
die(
|
||||
"Invalid CSRF token. Please refresh the page and try again."
|
||||
);
|
||||
}
|
||||
$_GET["tab"] = "quality";
|
||||
$this->renderQualityChecks(new SiteQualityCheckService()->run());
|
||||
exit();
|
||||
}
|
||||
|
||||
if ($route === "settings") {
|
||||
if ($action === "renderBlockThumbs") {
|
||||
$this->renderBlockThumbs();
|
||||
exit();
|
||||
}
|
||||
if ($action === 'update') {
|
||||
if ($action === "update") {
|
||||
$this->handleUpdateSettings();
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
if ($route === 'menus') {
|
||||
if ($action === 'update') {
|
||||
if ($route === "menus") {
|
||||
if ($action === "update") {
|
||||
$this->handleUpdateMenus();
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
if ($route === 'database') {
|
||||
if ($action === 'update') {
|
||||
if ($route === "database") {
|
||||
if ($action === "update") {
|
||||
$this->handleUpdateDB();
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
if ($route === 'page_settings') {
|
||||
if ($action === 'create') {
|
||||
if ($route === "page_settings") {
|
||||
if ($action === "create") {
|
||||
$this->handleCreate();
|
||||
exit();
|
||||
}
|
||||
|
||||
$pageId = $_GET['page'] ?? null;
|
||||
$pageRepository = new PageRepository;
|
||||
$pageId = $_GET["page"] ?? null;
|
||||
$pageRepository = new PageRepository();
|
||||
$page = $pageRepository->findWithId($pageId);
|
||||
if (! ($page instanceof PageContract)) {
|
||||
phpb_redirect(phpb_url('website_manager'));
|
||||
if (!($page instanceof PageContract)) {
|
||||
phpb_redirect(phpb_url("website_manager"));
|
||||
}
|
||||
|
||||
if ($action === 'edit') {
|
||||
if ($action === "edit") {
|
||||
$this->handleEdit($page);
|
||||
exit();
|
||||
} else if ($action === 'destroy') {
|
||||
} elseif ($action === "destroy") {
|
||||
$this->handleDestroy($page);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish every page with a valid saved draft and return per-page outcomes.
|
||||
*/
|
||||
public function handlePublishAllDrafts(): ?array
|
||||
{
|
||||
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
|
||||
http_response_code(405);
|
||||
return null;
|
||||
}
|
||||
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
|
||||
http_response_code(403);
|
||||
return null;
|
||||
}
|
||||
|
||||
$pageRepository = new PageRepository();
|
||||
$result = [
|
||||
"total" => 0,
|
||||
"published" => [],
|
||||
"failed" => [],
|
||||
"cache_warnings" => [],
|
||||
];
|
||||
foreach ($pageRepository->getAll() as $page) {
|
||||
if ($pageRepository->getPageDraftData($page) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result["total"]++;
|
||||
try {
|
||||
$published = $pageRepository->publishPageDraft($page);
|
||||
} catch (PageDraftPublishedCacheInvalidationException) {
|
||||
$result["published"][] = (string) $page->getName();
|
||||
$result["cache_warnings"][] = (string) $page->getName();
|
||||
continue;
|
||||
} catch (\Throwable) {
|
||||
$published = false;
|
||||
}
|
||||
|
||||
$result[
|
||||
$published ? "published" : "failed"
|
||||
][] = (string) $page->getName();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a CSRF-protected update to upload metadata.
|
||||
*/
|
||||
public function handleUpdateMediaMetadata(): bool
|
||||
{
|
||||
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
|
||||
http_response_code(405);
|
||||
return false;
|
||||
}
|
||||
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
|
||||
http_response_code(403);
|
||||
return false;
|
||||
}
|
||||
|
||||
$allowedFields = ["_csrf_token", "public_id", "folder", "alt_text"];
|
||||
if (array_diff(array_keys($_POST), $allowedFields)) {
|
||||
return $this->redirectMediaMetadataResult(false);
|
||||
}
|
||||
|
||||
$publicId = $_POST["public_id"] ?? null;
|
||||
$metadata = array_intersect_key(
|
||||
$_POST,
|
||||
array_flip(["folder", "alt_text"]),
|
||||
);
|
||||
if (!is_string($publicId) || $publicId === "" || empty($metadata)) {
|
||||
return $this->redirectMediaMetadataResult(false);
|
||||
}
|
||||
|
||||
$success = new UploadRepository()->updateMetadata($publicId, $metadata);
|
||||
return $this->redirectMediaMetadataResult($success);
|
||||
}
|
||||
|
||||
private function redirectMediaMetadataResult(bool $success): bool
|
||||
{
|
||||
phpb_redirect(phpb_url("website_manager", ["tab" => "files"]), [
|
||||
"message-type" => $success ? "success" : "error",
|
||||
"message" => $success
|
||||
? "Media metadata updated."
|
||||
: "Media metadata could not be updated.",
|
||||
]);
|
||||
|
||||
return $success;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle requests for creating a new page.
|
||||
*/
|
||||
public function handleCreate()
|
||||
{
|
||||
$errorMessage = null;
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
try {
|
||||
$pageRepository = new PageRepository;
|
||||
$pageRepository = new PageRepository();
|
||||
$page = $pageRepository->create($_POST);
|
||||
} catch (\Throwable) {
|
||||
$page = false;
|
||||
}
|
||||
if ($page) {
|
||||
phpb_redirect(phpb_url('website_manager'), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.page-created')
|
||||
phpb_redirect(phpb_url("website_manager"), [
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans("website-manager.page-created"),
|
||||
]);
|
||||
}
|
||||
$errorMessage = phpb_trans('website-manager.page-create-failed');
|
||||
$errorMessage = phpb_trans("website-manager.page-create-failed");
|
||||
}
|
||||
|
||||
$this->renderPageSettings(null, $errorMessage);
|
||||
@@ -115,13 +276,13 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function handleEdit(PageContract $page)
|
||||
{
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$pageRepository = new PageRepository;
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$pageRepository = new PageRepository();
|
||||
$success = $pageRepository->update($page, $_POST);
|
||||
if ($success) {
|
||||
phpb_redirect(phpb_url('website_manager'), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.page-updated')
|
||||
phpb_redirect(phpb_url("website_manager"), [
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans("website-manager.page-updated"),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -136,16 +297,16 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function handleDestroy(PageContract $page)
|
||||
{
|
||||
$pageRepository = new PageRepository;
|
||||
if (! $pageRepository->destroy($page->getId())) {
|
||||
phpb_redirect(phpb_url('website_manager'), [
|
||||
'message-type' => 'error',
|
||||
'message' => phpb_trans('website-manager.page-delete-failed')
|
||||
$pageRepository = new PageRepository();
|
||||
if (!$pageRepository->destroy($page->getId())) {
|
||||
phpb_redirect(phpb_url("website_manager"), [
|
||||
"message-type" => "error",
|
||||
"message" => phpb_trans("website-manager.page-delete-failed"),
|
||||
]);
|
||||
}
|
||||
phpb_redirect(phpb_url('website_manager'), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.page-deleted')
|
||||
phpb_redirect(phpb_url("website_manager"), [
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans("website-manager.page-deleted"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -154,14 +315,19 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function handleUpdateSettings()
|
||||
{
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$settingRepository = new SettingRepository;
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$settingRepository = new SettingRepository();
|
||||
$success = $settingRepository->updateSettings($_POST);
|
||||
if ($success) {
|
||||
phpb_redirect(phpb_url('website_manager', ['tab' => 'settings']), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.settings-updated')
|
||||
]);
|
||||
phpb_redirect(
|
||||
phpb_url("website_manager", ["tab" => "settings"]),
|
||||
[
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans(
|
||||
"website-manager.settings-updated",
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,13 +337,13 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function handleUpdateMenus()
|
||||
{
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$settingRepository = new MenuRepository;
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$settingRepository = new MenuRepository();
|
||||
$success = $settingRepository->updateMenus($_POST);
|
||||
if ($success) {
|
||||
phpb_redirect(phpb_url('website_manager', ['tab' => 'menus']), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.menus-updated')
|
||||
phpb_redirect(phpb_url("website_manager", ["tab" => "menus"]), [
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans("website-manager.menus-updated"),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -189,11 +355,11 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
public function handleUpdateDB()
|
||||
{
|
||||
global $phpb_db;
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
if ($_SERVER["REQUEST_METHOD"] === "POST") {
|
||||
$phpb_db->resolveDiffDB();
|
||||
phpb_redirect(phpb_url('website_manager', ['tab' => 'info']), [
|
||||
'message-type' => 'success',
|
||||
'message' => phpb_trans('website-manager.db-updated')
|
||||
phpb_redirect(phpb_url("website_manager", ["tab" => "info"]), [
|
||||
"message-type" => "success",
|
||||
"message" => phpb_trans("website-manager.db-updated"),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -203,34 +369,72 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function renderOverview()
|
||||
{
|
||||
$pageRepository = new PageRepository;
|
||||
$pageRepository = new PageRepository();
|
||||
$pages = $pageRepository->getAll();
|
||||
uasort($pages, function ($a, $b){
|
||||
return ($a->getRoute() < $b->getRoute()) ? -1 : 1;
|
||||
uasort($pages, function ($a, $b) {
|
||||
return $a->getRoute() < $b->getRoute() ? -1 : 1;
|
||||
});
|
||||
|
||||
$activeLanguages = phpb_active_languages();
|
||||
$pageTranslationCoverage = (new PageTranslationService())->getPageCoverage($pages, $activeLanguages);
|
||||
$draftPages = [];
|
||||
foreach ($pages as $page) {
|
||||
if ($pageRepository->getPageDraftData($page) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filesRepository = new UploadRepository;
|
||||
$route = $page->getRoute();
|
||||
|
||||
$draftPages[] = [
|
||||
"name" => $page->getName(),
|
||||
"route" => $route,
|
||||
"previewUrl" => phpb_full_url($page->getPreviewRoute()),
|
||||
];
|
||||
}
|
||||
|
||||
$activeLanguages = phpb_active_languages();
|
||||
$pageTranslationCoverage = new PageTranslationService()->getPageCoverage(
|
||||
$pages,
|
||||
$activeLanguages,
|
||||
);
|
||||
|
||||
$filesRepository = new UploadRepository();
|
||||
$files = $filesRepository->getAll();
|
||||
|
||||
$menuRepository = new MenuRepository;
|
||||
$menuRepository = new MenuRepository();
|
||||
$menus = $menuRepository->getHydratedMenus();
|
||||
$menusJson = json_encode($menus);
|
||||
|
||||
$completedTranslations = 0;
|
||||
foreach ($pageTranslationCoverage as $coverage) {
|
||||
$completedTranslations += $coverage["completeCount"];
|
||||
}
|
||||
$expectedTranslations = count($pages) * count($activeLanguages);
|
||||
$dashboardSummary = [
|
||||
"pageCount" => count($pages),
|
||||
"uploadCount" => count($files),
|
||||
"menuCount" => count($menus),
|
||||
"completedTranslations" => $completedTranslations,
|
||||
"expectedTranslations" => $expectedTranslations,
|
||||
"translationCoveragePercent" =>
|
||||
$expectedTranslations > 0
|
||||
? (int) round(
|
||||
($completedTranslations / $expectedTranslations) * 100,
|
||||
)
|
||||
: null,
|
||||
"activeLanguageCount" => count($activeLanguages),
|
||||
];
|
||||
|
||||
$menuPages = [];
|
||||
foreach ($pages as $page) {
|
||||
$menuPages[] = [
|
||||
'id' => $page->getId(),
|
||||
'title' => $page->getName(),
|
||||
'route' => $page->getRoute()
|
||||
"id" => $page->getId(),
|
||||
"title" => $page->getName(),
|
||||
"route" => $page->getRoute(),
|
||||
];
|
||||
}
|
||||
$menuPagesJson = json_encode($menuPages);
|
||||
|
||||
$viewFile = 'overview';
|
||||
require __DIR__ . '/resources/layouts/master.php';
|
||||
$viewFile = "overview";
|
||||
require __DIR__ . "/resources/layouts/master.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -238,8 +442,8 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function renderQualityChecks(?array $qualityReport = null)
|
||||
{
|
||||
$viewFile = 'overview';
|
||||
require __DIR__ . '/resources/layouts/master.php';
|
||||
$viewFile = "overview";
|
||||
require __DIR__ . "/resources/layouts/master.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,16 +451,18 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*
|
||||
* @param PageContract $page
|
||||
*/
|
||||
public function renderPageSettings(?PageContract $page = null, ?string $errorMessage = null)
|
||||
{
|
||||
$action = isset($page) ? 'edit' : 'create';
|
||||
$theme = phpb_instance('theme', [
|
||||
phpb_config('theme'),
|
||||
phpb_config('theme.active_theme')
|
||||
public function renderPageSettings(
|
||||
?PageContract $page = null,
|
||||
?string $errorMessage = null,
|
||||
) {
|
||||
$action = isset($page) ? "edit" : "create";
|
||||
$theme = phpb_instance("theme", [
|
||||
phpb_config("theme"),
|
||||
phpb_config("theme.active_theme"),
|
||||
]);
|
||||
|
||||
$viewFile = 'page-settings';
|
||||
require __DIR__ . '/resources/layouts/master.php';
|
||||
$viewFile = "page-settings";
|
||||
require __DIR__ . "/resources/layouts/master.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -264,8 +470,8 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function renderMenuSettings()
|
||||
{
|
||||
$viewFile = 'menu-settings';
|
||||
require __DIR__ . '/resources/layouts/master.php';
|
||||
$viewFile = "menu-settings";
|
||||
require __DIR__ . "/resources/layouts/master.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,8 +479,8 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function renderBlockThumbs()
|
||||
{
|
||||
$viewFile = 'block-thumbs';
|
||||
require __DIR__ . '/resources/layouts/master.php';
|
||||
$viewFile = "block-thumbs";
|
||||
require __DIR__ . "/resources/layouts/master.php";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -282,7 +488,7 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
*/
|
||||
public function renderWelcomePage()
|
||||
{
|
||||
$viewFile = 'welcome';
|
||||
require __DIR__ . '/resources/layouts/empty.php';
|
||||
$viewFile = "welcome";
|
||||
require __DIR__ . "/resources/layouts/empty.php";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'dashboard' => [
|
||||
'title' => 'Dashboard',
|
||||
'include' => __DIR__ . '/dashboard.php',
|
||||
'icon' => '<i class="ph ph-squares-four"></i>',
|
||||
],
|
||||
'pages' => [
|
||||
'title' => phpb_trans('website-manager.pages'),
|
||||
'include' => __DIR__ . '/pages.php',
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
$pageCount = $dashboardSummary['pageCount'];
|
||||
$menuCount = $dashboardSummary['menuCount'];
|
||||
$uploadCount = $dashboardSummary['uploadCount'];
|
||||
$completedTranslations = $dashboardSummary['completedTranslations'];
|
||||
$expectedTranslations = $dashboardSummary['expectedTranslations'];
|
||||
$activeLanguageCount = $dashboardSummary['activeLanguageCount'];
|
||||
$translationCoveragePercent = $dashboardSummary['translationCoveragePercent'];
|
||||
$hasNoPages = $pageCount === 0;
|
||||
$hasNoMenus = $menuCount === 0;
|
||||
$hasNoActiveLanguages = $activeLanguageCount === 0 && $pageCount > 0;
|
||||
$hasIncompleteTranslations = $expectedTranslations > 0 && $completedTranslations < $expectedTranslations;
|
||||
$hasAttention = $hasNoPages || $hasNoMenus || $hasNoActiveLanguages || $hasIncompleteTranslations;
|
||||
$translationCoverageLabel = $translationCoveragePercent === null
|
||||
? '—'
|
||||
: (phpb_e($translationCoveragePercent) . '%');
|
||||
|
||||
if ($expectedTranslations > 0) {
|
||||
$translationDescription = sprintf('%d of %d page translations complete', $completedTranslations, $expectedTranslations);
|
||||
} elseif ($activeLanguageCount === 0) {
|
||||
$translationDescription = 'No active languages configured';
|
||||
} else {
|
||||
$translationDescription = 'Add a page to begin tracking translation coverage';
|
||||
}
|
||||
?>
|
||||
<div class="space-y-8">
|
||||
<header class="space-y-1">
|
||||
<h2 class="text-xl font-bold tracking-tight text-base-content">Site overview</h2>
|
||||
<p class="text-sm text-base-content/60">A quick view of your content and site setup.</p>
|
||||
</header>
|
||||
|
||||
<section class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4" aria-label="Site summary">
|
||||
<article class="card border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="card-body p-5">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="stat p-0">
|
||||
<div class="stat-title">Pages</div>
|
||||
<div class="stat-value text-3xl"><?= phpb_e($pageCount) ?></div>
|
||||
<div class="stat-desc">Pages on your site</div>
|
||||
</div>
|
||||
<i class="text-xl text-base-content/50 ph-duotone ph-files" aria-hidden="true"></i>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="card-body p-5">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="stat p-0">
|
||||
<div class="stat-title">Menus</div>
|
||||
<div class="stat-value text-3xl"><?= phpb_e($menuCount) ?></div>
|
||||
<div class="stat-desc">Navigation menus configured</div>
|
||||
</div>
|
||||
<i class="text-xl text-base-content/50 ph-duotone ph-list-dashes" aria-hidden="true"></i>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="card-body p-5">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="stat p-0">
|
||||
<div class="stat-title">Media files</div>
|
||||
<div class="stat-value text-3xl"><?= phpb_e($uploadCount) ?></div>
|
||||
<div class="stat-desc">Uploaded files</div>
|
||||
</div>
|
||||
<i class="text-xl text-base-content/50 ph-duotone ph-folder-notch-open" aria-hidden="true"></i>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="card-body p-5">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="stat p-0">
|
||||
<div class="stat-title">Translation coverage</div>
|
||||
<div class="stat-value text-3xl"><?= $translationCoverageLabel ?></div>
|
||||
<div class="stat-desc"><?= phpb_e($translationDescription) ?></div>
|
||||
</div>
|
||||
<i class="text-xl text-base-content/50 ph-duotone ph-translate" aria-hidden="true"></i>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="space-y-3" aria-labelledby="dashboard-drafts-heading">
|
||||
<header class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h2 id="dashboard-drafts-heading" class="text-lg font-bold tracking-tight text-base-content">Unpublished changes</h2>
|
||||
<p class="text-sm text-base-content/60">
|
||||
<?= count($draftPages) === 1 ? '1 page has' : phpb_e(count($draftPages)) . ' pages have' ?> saved changes that are not published.
|
||||
</p>
|
||||
</div>
|
||||
<?php if (! empty($draftPages)): ?>
|
||||
<form method="post" action="<?= phpb_e(phpb_url('website_manager', ['route' => 'drafts', 'action' => 'publish_all'])) ?>" onsubmit="return confirm('Publish all <?= count($draftPages) ?> pages with unpublished changes?')">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<button class="btn btn-primary" type="submit">
|
||||
<i class="ph-duotone ph-upload-simple" aria-hidden="true"></i>
|
||||
Publish all changes
|
||||
</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</header>
|
||||
<?php if (empty($draftPages)): ?>
|
||||
<div class="alert alert-info" role="status">
|
||||
<i class="text-xl ph-duotone ph-check-circle" aria-hidden="true"></i>
|
||||
<span>There are no unpublished page changes.</span>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<ul class="list rounded-box border border-base-300 bg-base-100">
|
||||
<?php foreach ($draftPages as $draftPage): ?>
|
||||
<li class="list-row">
|
||||
<div class="min-w-0 list-col-grow">
|
||||
<p class="font-medium text-base-content"><?= phpb_e($draftPage['name']) ?></p>
|
||||
<p class="break-all font-mono text-sm text-base-content/60"><?= is_string($draftPage['route']) && $draftPage['route'] !== '' ? phpb_e($draftPage['route']) : 'Route not set' ?></p>
|
||||
</div>
|
||||
<?php if (is_string($draftPage['previewUrl'])): ?>
|
||||
<a class="btn btn-sm" href="<?= phpb_e($draftPage['previewUrl']) ?>" target="_blank" rel="noopener noreferrer">
|
||||
<i class="ph-duotone ph-eye" aria-hidden="true"></i>
|
||||
Preview draft
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<section class="space-y-3" aria-labelledby="dashboard-attention-heading">
|
||||
<div>
|
||||
<h2 id="dashboard-attention-heading" class="text-lg font-bold tracking-tight text-base-content">Needs attention</h2>
|
||||
<p class="text-sm text-base-content/60">Setup items you may want to complete.</p>
|
||||
</div>
|
||||
<?php if (! $hasAttention): ?>
|
||||
<div class="alert alert-success" role="status">
|
||||
<i class="text-xl ph-duotone ph-check-circle" aria-hidden="true"></i>
|
||||
<span>Your pages, menus, and translations are set up. You can run quality checks whenever you’re ready.</span>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="space-y-3">
|
||||
<?php if ($hasNoPages): ?>
|
||||
<div class="alert alert-warning flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between" role="status">
|
||||
<span><i class="mr-2 text-xl ph-duotone ph-files" aria-hidden="true"></i>No pages yet. Create a page to start building your site.</span>
|
||||
<a class="btn btn-sm" href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'create']) ?>">Create a page</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if ($hasNoMenus): ?>
|
||||
<div class="alert alert-warning flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between" role="status">
|
||||
<span><i class="mr-2 text-xl ph-duotone ph-list-dashes" aria-hidden="true"></i>No navigation menus are set up yet.</span>
|
||||
<a class="btn btn-sm" href="<?= phpb_url('website_manager', ['tab' => 'menus']) ?>">Manage menus</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if ($hasNoActiveLanguages): ?>
|
||||
<div class="alert alert-info flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between" role="status">
|
||||
<span><i class="mr-2 text-xl ph-duotone ph-translate" aria-hidden="true"></i>No active languages are configured, so translation coverage cannot be measured.</span>
|
||||
<a class="btn btn-sm" href="<?= phpb_url('website_manager', ['tab' => 'settings']) ?>">Review settings</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if ($hasIncompleteTranslations): ?>
|
||||
<div class="alert alert-warning flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between" role="status">
|
||||
<span><i class="mr-2 text-xl ph-duotone ph-translate" aria-hidden="true"></i><?= phpb_e($completedTranslations) ?> of <?= phpb_e($expectedTranslations) ?> page translations are complete.</span>
|
||||
<a class="btn btn-sm" href="<?= phpb_url('website_manager', ['tab' => 'pages']) ?>">Review pages</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<section class="space-y-3" aria-labelledby="dashboard-actions-heading">
|
||||
<div>
|
||||
<h2 id="dashboard-actions-heading" class="text-lg font-bold tracking-tight text-base-content">Quick actions</h2>
|
||||
<p class="text-sm text-base-content/60">Jump straight to a common task.</p>
|
||||
</div>
|
||||
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<a class="card border border-base-300 bg-base-100 transition hover:border-base-content/30 hover:shadow-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-base-content" href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'create']) ?>">
|
||||
<div class="card-body gap-3 p-5">
|
||||
<i class="text-2xl text-base-content/60 ph-duotone ph-plus-circle" aria-hidden="true"></i>
|
||||
<h3 class="card-title text-base">Create a page</h3>
|
||||
<p class="text-sm text-base-content/60">Add a page and start shaping your site.</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="card border border-base-300 bg-base-100 transition hover:border-base-content/30 hover:shadow-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-base-content" href="<?= phpb_url('website_manager', ['tab' => 'menus']) ?>">
|
||||
<div class="card-body gap-3 p-5">
|
||||
<i class="text-2xl text-base-content/60 ph-duotone ph-list-dashes" aria-hidden="true"></i>
|
||||
<h3 class="card-title text-base">Manage menus</h3>
|
||||
<p class="text-sm text-base-content/60">Choose which pages appear in navigation.</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="card border border-base-300 bg-base-100 transition hover:border-base-content/30 hover:shadow-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-base-content" href="<?= phpb_url('website_manager', ['tab' => 'files']) ?>">
|
||||
<div class="card-body gap-3 p-5">
|
||||
<i class="text-2xl text-base-content/60 ph-duotone ph-upload-simple" aria-hidden="true"></i>
|
||||
<h3 class="card-title text-base">Upload files</h3>
|
||||
<p class="text-sm text-base-content/60">Add images and other media to your library.</p>
|
||||
</div>
|
||||
</a>
|
||||
<a class="card border border-base-300 bg-base-100 transition hover:border-base-content/30 hover:shadow-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-base-content" href="<?= phpb_url('website_manager', ['tab' => 'quality']) ?>">
|
||||
<div class="card-body gap-3 p-5">
|
||||
<i class="text-2xl text-base-content/60 ph-duotone ph-check-circle" aria-hidden="true"></i>
|
||||
<h3 class="card-title text-base">Run quality checks</h3>
|
||||
<p class="text-sm text-base-content/60">Start an on-demand review of your site.</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -1,3 +1,33 @@
|
||||
<?php
|
||||
$mediaFiles = [];
|
||||
$mediaFileTypes = [];
|
||||
$mediaFolders = [];
|
||||
foreach ($files as $file) {
|
||||
$mimeType = strtolower(trim((string) ($file->mime_type ?? '')));
|
||||
$mimeFamily = str_contains($mimeType, '/') ? strstr($mimeType, '/', true) : 'other';
|
||||
$folder = trim((string) ($file->folder ?? ''));
|
||||
$mediaFiles[] = [
|
||||
'file' => $file,
|
||||
'mimeType' => $mimeType,
|
||||
'mimeFamily' => $mimeFamily,
|
||||
'folder' => $folder,
|
||||
'isImage' => str_starts_with($mimeType, 'image/'),
|
||||
];
|
||||
$mediaFileTypes[$mimeFamily] = match ($mimeFamily) {
|
||||
'image' => 'Images',
|
||||
'video' => 'Videos',
|
||||
'audio' => 'Audio',
|
||||
'text' => 'Text files',
|
||||
'application' => 'Documents and other files',
|
||||
default => ucfirst($mimeFamily) . ' files',
|
||||
};
|
||||
if ($folder !== '') {
|
||||
$mediaFolders[$folder] = $folder;
|
||||
}
|
||||
}
|
||||
ksort($mediaFileTypes, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
ksort($mediaFolders, SORT_NATURAL | SORT_FLAG_CASE);
|
||||
?>
|
||||
<section class="card border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="card-body gap-6 p-4 sm:p-6 lg:p-8">
|
||||
<div class="flex flex-col gap-5 border-b border-base-300 pb-5 sm:flex-row sm:items-end sm:justify-between">
|
||||
@@ -23,26 +53,157 @@
|
||||
<p class="mt-1 text-sm text-base-content/60">Your uploaded files will appear here as a visual library.</p>
|
||||
</div>
|
||||
<?php else : ?>
|
||||
<ul class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<?php foreach ($files as $file) : ?>
|
||||
<li class="card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md">
|
||||
<section class="space-y-4" aria-label="Filter media library">
|
||||
<div class="grid gap-3 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] md:items-end">
|
||||
<label class="flex flex-col gap-1 text-sm font-medium" for="media-search">
|
||||
<span>Search uploads</span>
|
||||
<input id="media-search" type="search" class="input w-full" placeholder="Filename or public ID" autocomplete="off">
|
||||
</label>
|
||||
<label class="flex flex-col gap-1 text-sm font-medium" for="media-type-filter">
|
||||
<span>File type</span>
|
||||
<select id="media-type-filter" class="select w-full">
|
||||
<option value="">All types</option>
|
||||
<?php foreach ($mediaFileTypes as $mimeFamily => $label) : ?>
|
||||
<option value="<?= phpb_e($mimeFamily) ?>"><?= phpb_e($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1 text-sm font-medium" for="media-folder-filter">
|
||||
<span>Folder</span>
|
||||
<select id="media-folder-filter" class="select w-full">
|
||||
<option value="">All folders</option>
|
||||
<option value="__unsorted__">Unsorted</option>
|
||||
<?php foreach ($mediaFolders as $folder) : ?>
|
||||
<option value="folder:<?= phpb_e($folder) ?>"><?= phpb_e($folder) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<button id="media-filter-reset" type="button" class="btn btn-ghost">Clear filters</button>
|
||||
</div>
|
||||
<p id="media-results-count" class="text-sm text-base-content/60" role="status" aria-live="polite"></p>
|
||||
</section>
|
||||
|
||||
<datalist id="media-folder-suggestions">
|
||||
<?php foreach ($mediaFolders as $folder) : ?>
|
||||
<option value="<?= phpb_e($folder) ?>"></option>
|
||||
<?php endforeach; ?>
|
||||
</datalist>
|
||||
|
||||
<ul id="media-library-items" class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<?php foreach ($mediaFiles as $mediaFile) :
|
||||
$file = $mediaFile['file'];
|
||||
$mimeType = $mediaFile['mimeType'];
|
||||
$publicId = (string) ($file->public_id ?? '');
|
||||
$originalFile = (string) ($file->original_file ?? '');
|
||||
$folder = $mediaFile['folder'];
|
||||
$altText = (string) ($file->alt_text ?? '');
|
||||
?>
|
||||
<li class="media-library-item card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md"
|
||||
data-media-library-item
|
||||
data-file-name="<?= phpb_e($originalFile) ?>"
|
||||
data-public-id="<?= phpb_e($publicId) ?>"
|
||||
data-mime-family="<?= phpb_e($mediaFile['mimeFamily']) ?>"
|
||||
data-folder="<?= phpb_e($folder) ?>">
|
||||
<figure class="relative aspect-video bg-base-200">
|
||||
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($file->public_id) ?>" class="h-full w-full object-cover">
|
||||
<button type="button" onclick="deleteFile('<?= phpb_e($file->public_id) ?>')" class="btn btn-error btn-square btn-sm absolute right-3 top-3 shadow-sm" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?> <?= phpb_e($file->public_id) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
|
||||
<?php if ($mediaFile['isImage']) : ?>
|
||||
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($altText) ?>" class="h-full w-full object-cover">
|
||||
<?php else : ?>
|
||||
<div class="flex h-full w-full flex-col items-center justify-center gap-2 p-4 text-center text-base-content/70">
|
||||
<i class="text-4xl ph-duotone ph-file" aria-hidden="true"></i>
|
||||
<span class="text-xs font-medium"><?= phpb_e($mimeType !== '' ? $mimeType : 'Unknown file type') ?></span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<button type="button" onclick="deleteFile('<?= phpb_e($publicId) ?>')" class="btn btn-error btn-square btn-sm absolute right-3 top-3 shadow-sm" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?> <?= phpb_e($publicId) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
|
||||
<i class="ph-duotone ph-trash" aria-hidden="true"></i>
|
||||
</button>
|
||||
</figure>
|
||||
<div class="card-body gap-1 p-3">
|
||||
<p class="truncate text-sm font-medium" title="<?= phpb_e($file->public_id) ?>"><?= phpb_e($file->public_id) ?></p>
|
||||
<div class="card-body gap-3 p-3">
|
||||
<div class="min-w-0 space-y-1">
|
||||
<p class="truncate text-sm font-medium" title="<?= phpb_e($originalFile) ?>"><?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?></p>
|
||||
<p class="truncate text-xs text-base-content/60" title="<?= phpb_e($publicId) ?>"><?= phpb_e($publicId) ?></p>
|
||||
</div>
|
||||
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'media', 'action' => 'update_metadata']) ?>" class="flex flex-col gap-2 sm:flex-row sm:items-end" aria-label="Assign folder for <?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?>">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<input type="hidden" name="public_id" value="<?= phpb_e($publicId) ?>">
|
||||
<label class="flex min-w-0 flex-1 flex-col gap-1 text-xs font-medium">
|
||||
<span>Folder</span>
|
||||
<input type="text" name="folder" class="input input-sm w-full" list="media-folder-suggestions" maxlength="255" value="<?= phpb_e($folder) ?>" placeholder="Unsorted">
|
||||
</label>
|
||||
<button type="submit" class="btn btn-sm">Save folder</button>
|
||||
</form>
|
||||
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'media', 'action' => 'update_metadata']) ?>" class="flex flex-col gap-2" aria-label="Edit alt text for <?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?>">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<input type="hidden" name="public_id" value="<?= phpb_e($publicId) ?>">
|
||||
<label class="flex flex-col gap-1 text-xs font-medium">
|
||||
<span>Alt text</span>
|
||||
<input type="text" name="alt_text" class="input input-sm w-full" maxlength="1000" value="<?= phpb_e($altText) ?>" placeholder="Describe the image">
|
||||
</label>
|
||||
<button type="submit" class="btn btn-sm">Save alt text</button>
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<div id="media-no-results" class="hidden rounded-box border border-dashed border-base-300 bg-base-200/50 px-5 py-10 text-center" role="status">
|
||||
<h3 class="font-semibold text-base-content">No matching files</h3>
|
||||
<p class="mt-1 text-sm text-base-content/60">Try changing or clearing your filters.</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const items = Array.from(document.querySelectorAll('[data-media-library-item]'));
|
||||
const search = document.getElementById('media-search');
|
||||
const typeFilter = document.getElementById('media-type-filter');
|
||||
const folderFilter = document.getElementById('media-folder-filter');
|
||||
const resultCount = document.getElementById('media-results-count');
|
||||
const noResults = document.getElementById('media-no-results');
|
||||
const itemList = document.getElementById('media-library-items');
|
||||
if (!search || !typeFilter || !folderFilter || !resultCount || !noResults || !itemList) {
|
||||
return;
|
||||
}
|
||||
|
||||
function filterMediaLibrary() {
|
||||
const query = search.value.trim().toLocaleLowerCase();
|
||||
const selectedType = typeFilter.value;
|
||||
const selectedFolder = folderFilter.value;
|
||||
let visibleCount = 0;
|
||||
|
||||
items.forEach(function(item) {
|
||||
const matchesSearch = item.dataset.fileName.toLocaleLowerCase().includes(query)
|
||||
|| item.dataset.publicId.toLocaleLowerCase().includes(query);
|
||||
const matchesType = selectedType === '' || item.dataset.mimeFamily === selectedType;
|
||||
const matchesFolder = selectedFolder === ''
|
||||
|| (selectedFolder === '__unsorted__' && item.dataset.folder === '')
|
||||
|| (selectedFolder.startsWith('folder:') && item.dataset.folder === selectedFolder.slice(7));
|
||||
const matches = matchesSearch && matchesType && matchesFolder;
|
||||
|
||||
item.hidden = !matches;
|
||||
if (matches) {
|
||||
visibleCount++;
|
||||
}
|
||||
});
|
||||
|
||||
resultCount.textContent = `Showing ${visibleCount} of ${items.length} files`;
|
||||
noResults.classList.toggle('hidden', visibleCount !== 0);
|
||||
itemList.classList.toggle('hidden', visibleCount === 0);
|
||||
}
|
||||
|
||||
search.addEventListener('input', filterMediaLibrary);
|
||||
typeFilter.addEventListener('change', filterMediaLibrary);
|
||||
folderFilter.addEventListener('change', filterMediaLibrary);
|
||||
document.getElementById('media-filter-reset').addEventListener('click', function() {
|
||||
search.value = '';
|
||||
typeFilter.value = '';
|
||||
folderFilter.value = '';
|
||||
filterMediaLibrary();
|
||||
});
|
||||
|
||||
filterMediaLibrary();
|
||||
});
|
||||
|
||||
async function uploadFile() {
|
||||
let formData = new FormData();
|
||||
const fileupload = document.getElementById('fileupload');
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
<h2 class="text-xl font-bold tracking-tight text-base-content">Your pages</h2>
|
||||
<p class="text-sm text-base-content/60">Review routes and open the page editor or page settings.</p>
|
||||
</div>
|
||||
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'create']) ?>" class="btn btn-primary">
|
||||
<a href="<?= phpb_url("website_manager", [
|
||||
"route" => "page_settings",
|
||||
"action" => "create",
|
||||
]) ?>" class="btn btn-primary">
|
||||
<i class="ph-bold ph-plus" aria-hidden="true"></i>
|
||||
<?= phpb_trans('website-manager.add-new-page') ?>
|
||||
<?= phpb_trans("website-manager.add-new-page") ?>
|
||||
</a>
|
||||
</header>
|
||||
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
|
||||
@@ -14,10 +17,11 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="w-16">ID</th>
|
||||
<th><?= phpb_trans('website-manager.name') ?></th>
|
||||
<th><?= phpb_trans("website-manager.name") ?></th>
|
||||
<th>Localized titles and routes</th>
|
||||
<th>Coverage</th>
|
||||
<th class="w-44"><?= phpb_trans('website-manager.actions') ?></th>
|
||||
<th class="w-44"><?= phpb_trans(
|
||||
"website-manager.actions",
|
||||
) ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -35,67 +39,137 @@
|
||||
<?php foreach ($pages as $page): ?>
|
||||
<?php
|
||||
$pageRoute = $page->getRoute();
|
||||
$canViewPage = $page->get('type') !== 'redirect' && is_string($pageRoute) && $pageRoute !== '';
|
||||
$canViewPage =
|
||||
$page->get("type") !== "redirect" &&
|
||||
is_string($pageRoute) &&
|
||||
$pageRoute !== "";
|
||||
?>
|
||||
<tr>
|
||||
<td><?= phpb_e($page->getId()) ?></td>
|
||||
<td class="font-medium"><?= phpb_e($page->getName()) ?></td>
|
||||
<td>
|
||||
<div class="grid gap-2 sm:grid-cols-2">
|
||||
<?php foreach ($activeLanguages as $languageCode => $languageTranslation): ?>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium"><?= phpb_e(
|
||||
$page->getName(),
|
||||
) ?></span>
|
||||
<?php if ($page->get("draft_data") !== null): ?>
|
||||
<div class="tooltip" data-tip="<?= phpb_trans(
|
||||
"pagebuilder.draft-available",
|
||||
) ?>">
|
||||
<span class="badge badge-sm badge-warning"><i class="ph-bold ph-git-diff"></i></span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="flex gap-2 flex-col">
|
||||
<?php foreach (
|
||||
$activeLanguages
|
||||
as $languageCode => $languageTranslation
|
||||
): ?>
|
||||
<?php
|
||||
$localeCoverage = $pageTranslationCoverage[$page->getId()]['locales'][$languageCode] ?? null;
|
||||
$localeExists = $localeCoverage['exists'] ?? false;
|
||||
$localeComplete = $localeCoverage['complete'] ?? false;
|
||||
$localeStatus = $localeComplete ? 'Complete' : ($localeExists ? 'Needs attention' : 'Missing');
|
||||
$localeBadgeClass = $localeComplete ? 'badge-success' : ($localeExists ? 'badge-warning' : 'badge-error');
|
||||
$localeTitle = $localeCoverage['title'] ?? null;
|
||||
$localeRoute = $localeCoverage['route'] ?? null;
|
||||
$localeTitleLabel = is_string($localeTitle) && trim($localeTitle) !== ''
|
||||
? phpb_e($localeTitle)
|
||||
: ($page->get('type') === 'redirect' ? 'Redirect page' : 'Title not set');
|
||||
$localeCoverage =
|
||||
$pageTranslationCoverage[$page->getId()][
|
||||
"locales"
|
||||
][$languageCode] ?? null;
|
||||
$localeExists =
|
||||
$localeCoverage["exists"] ?? false;
|
||||
$localeComplete =
|
||||
$localeCoverage["complete"] ?? false;
|
||||
$localeStatus = $localeComplete
|
||||
? "Complete"
|
||||
: ($localeExists
|
||||
? "Needs attention"
|
||||
: "Missing");
|
||||
$localeBadgeClass = $localeComplete
|
||||
? "badge-success"
|
||||
: ($localeExists
|
||||
? "badge-warning"
|
||||
: "badge-error");
|
||||
$localeTitle = $localeCoverage["title"] ?? null;
|
||||
$localeRoute = $localeCoverage["route"] ?? null;
|
||||
$localeTitleLabel =
|
||||
is_string($localeTitle) &&
|
||||
trim($localeTitle) !== ""
|
||||
? phpb_e($localeTitle)
|
||||
: ($page->get("type") === "redirect"
|
||||
? "Redirect page"
|
||||
: "Title not set");
|
||||
?>
|
||||
<div class="min-w-0 rounded-box border border-base-300 p-3">
|
||||
<div class="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-xs font-semibold text-base-content/70">
|
||||
<?= phpb_trans('languages.' . $languageCode) ?>
|
||||
<span class="font-mono">(<?= phpb_e($languageCode) ?>)</span>
|
||||
<div class="min-w-0 rounded-box border border-base-300 p-3 flex gap-3">
|
||||
<div class="tooltip" data-tip="<?= $localeStatus ?>">
|
||||
<span class="badge badge-sm font-mono font-semibold uppercase <?= $localeBadgeClass ?>">
|
||||
<?= phpb_e($languageCode) ?>
|
||||
</span>
|
||||
<span class="badge badge-sm <?= $localeBadgeClass ?>"><?= $localeStatus ?></span>
|
||||
</div>
|
||||
<p class="truncate text-sm font-medium" title="<?= phpb_e($localeTitle) ?>">
|
||||
<p class="truncate text-sm font-medium" title="<?= phpb_e(
|
||||
$localeTitle,
|
||||
) ?>">
|
||||
<?= $localeTitleLabel ?>
|
||||
</p>
|
||||
<p class="break-all font-mono text-xs text-base-content/60" title="<?= phpb_e($localeRoute) ?>">
|
||||
<?= is_string($localeRoute) && trim($localeRoute) !== '' ? phpb_e($localeRoute) : 'Route not set' ?>
|
||||
<p class="break-all font-mono text-sm text-base-content/60" title="<?= phpb_e(
|
||||
$localeRoute,
|
||||
) ?>">
|
||||
<?= is_string($localeRoute) &&
|
||||
trim($localeRoute) !== ""
|
||||
? phpb_e($localeRoute)
|
||||
: "Route not set" ?>
|
||||
</p>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<?php
|
||||
$pageCoverage = $pageTranslationCoverage[$page->getId()] ?? ['completeCount' => 0, 'localeCount' => count($activeLanguages)];
|
||||
$coverageClass = $pageCoverage['localeCount'] > 0 && $pageCoverage['completeCount'] === $pageCoverage['localeCount']
|
||||
? 'badge-success'
|
||||
: ($pageCoverage['completeCount'] > 0 ? 'badge-warning' : 'badge-error');
|
||||
?>
|
||||
<span class="badge <?= $coverageClass ?>">
|
||||
<?= phpb_e($pageCoverage['completeCount']) ?> / <?= phpb_e($pageCoverage['localeCount']) ?> complete
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="flex items-center gap-1">
|
||||
<a href="<?= phpb_e($canViewPage ? phpb_full_url($pageRoute) : '#') ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $canViewPage ? '' : 'btn-disabled' ?>" <?= $canViewPage ? '' : 'tabindex="-1" aria-disabled="true"' ?>>
|
||||
<a href="<?= phpb_e(
|
||||
$canViewPage
|
||||
? phpb_full_url($page->getPreviewRoute())
|
||||
: "#",
|
||||
) ?>" title="<?= phpb_trans(
|
||||
"website-manager.view",
|
||||
) ?>" aria-label="<?= phpb_e(
|
||||
phpb_trans("website-manager.view"),
|
||||
) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $canViewPage
|
||||
? ""
|
||||
: "btn-disabled" ?>" <?= $canViewPage
|
||||
? ""
|
||||
: 'tabindex="-1" aria-disabled="true"' ?>>
|
||||
<i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i>
|
||||
</a>
|
||||
<a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>>
|
||||
<a href="<?= phpb_url("pagebuilder", [
|
||||
"page" => $page->getId(),
|
||||
]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get(
|
||||
"type",
|
||||
) === "redirect"
|
||||
? "btn-disabled"
|
||||
: "" ?>" title="<?= phpb_trans(
|
||||
"website-manager.edit",
|
||||
) ?>" aria-label="<?= phpb_e(
|
||||
phpb_trans("website-manager.edit"),
|
||||
) ?>" <?= $page->get("type") === "redirect"
|
||||
? 'tabindex="-1" aria-disabled="true"'
|
||||
: "" ?>>
|
||||
<i class="text-xl ph-duotone ph-pencil-line" aria-hidden="true"></i>
|
||||
</a>
|
||||
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'edit', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.settings') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.settings')) ?>" class="btn btn-ghost btn-square btn-sm">
|
||||
<a href="<?= phpb_url("website_manager", [
|
||||
"route" => "page_settings",
|
||||
"action" => "edit",
|
||||
"page" => $page->getId(),
|
||||
]) ?>" title="<?= phpb_trans(
|
||||
"website-manager.settings",
|
||||
) ?>" aria-label="<?= phpb_e(
|
||||
phpb_trans("website-manager.settings"),
|
||||
) ?>" class="btn btn-ghost btn-square btn-sm">
|
||||
<i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
|
||||
</a>
|
||||
<a href="<?= phpb_url('website_manager', ['route' => 'page_settings', 'action' => 'destroy', 'page' => $page->getId()]) ?>" title="<?= phpb_trans('website-manager.remove') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?>" class="btn btn-error btn-square btn-sm">
|
||||
<a href="<?= phpb_url("website_manager", [
|
||||
"route" => "page_settings",
|
||||
"action" => "destroy",
|
||||
"page" => $page->getId(),
|
||||
]) ?>" title="<?= phpb_trans(
|
||||
"website-manager.remove",
|
||||
) ?>" aria-label="<?= phpb_e(
|
||||
phpb_trans("website-manager.remove"),
|
||||
) ?>" class="btn btn-error btn-square btn-sm">
|
||||
<i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@@ -26,13 +26,15 @@ class Page implements PageContract
|
||||
public function setData($data, $fullOverwrite = true)
|
||||
{
|
||||
// if page builder data is set, try to decode json
|
||||
if (isset($data['data']) && is_string($data['data'])) {
|
||||
$data['data'] = json_decode($data['data'], true);
|
||||
if (isset($data["data"]) && is_string($data["data"])) {
|
||||
$data["data"] = json_decode($data["data"], true);
|
||||
}
|
||||
if ($fullOverwrite) {
|
||||
$this->attributes = $data;
|
||||
} elseif (is_array($data)) {
|
||||
$this->attributes = is_null($this->attributes) ? [] : $this->attributes;
|
||||
} elseif (is_array($data)) {
|
||||
$this->attributes = is_null($this->attributes)
|
||||
? []
|
||||
: $this->attributes;
|
||||
foreach ($data as $key => $value) {
|
||||
$this->attributes[$key] = $value;
|
||||
}
|
||||
@@ -66,7 +68,7 @@ class Page implements PageContract
|
||||
*/
|
||||
public function getBuilderData()
|
||||
{
|
||||
return $this->attributes['data'] ?? [];
|
||||
return $this->attributes["data"] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,7 +78,7 @@ class Page implements PageContract
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->get('id');
|
||||
return $this->get("id");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,7 +88,7 @@ class Page implements PageContract
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->get('name');
|
||||
return $this->get("name");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,7 +98,7 @@ class Page implements PageContract
|
||||
*/
|
||||
public function getLayout()
|
||||
{
|
||||
return $this->get('layout');
|
||||
return $this->get("layout");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,10 +109,18 @@ class Page implements PageContract
|
||||
public function getTranslations()
|
||||
{
|
||||
if (is_null($this->translations)) {
|
||||
$records = (new PageTranslationRepository)->findWhere(phpb_config('page.translation.foreign_key'), $this->getId());
|
||||
$records = new PageTranslationRepository()->findWhere(
|
||||
phpb_config("page.translation.foreign_key"),
|
||||
$this->getId(),
|
||||
);
|
||||
$translations = [];
|
||||
foreach ($records as $record) {
|
||||
if (in_array($record->locale, array_keys(phpb_active_languages()))) {
|
||||
if (
|
||||
in_array(
|
||||
$record->locale,
|
||||
array_keys(phpb_active_languages()),
|
||||
)
|
||||
) {
|
||||
$translations[$record->locale] = (array) $record;
|
||||
}
|
||||
}
|
||||
@@ -129,7 +139,11 @@ class Page implements PageContract
|
||||
public function getTranslation(string $setting, ?string $locale = null)
|
||||
{
|
||||
$translations = $this->getTranslations();
|
||||
return (new PageTranslationService())->resolveTranslation($translations, $setting, $locale);
|
||||
return new PageTranslationService()->resolveTranslation(
|
||||
$translations,
|
||||
$setting,
|
||||
$locale,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,13 +154,46 @@ class Page implements PageContract
|
||||
*/
|
||||
public function getRoute(?string $locale = null)
|
||||
{
|
||||
$routeTranslation = $this->getTranslation('route', $locale);
|
||||
$routeTranslation = $this->getTranslation("route", $locale);
|
||||
foreach (phpb_route_parameters() as $routeParameter => $value) {
|
||||
$routeTranslation = str_replace('{' . $routeParameter . '}', $value, $routeTranslation);
|
||||
$routeTranslation = str_replace(
|
||||
"{" . $routeParameter . "}",
|
||||
$value,
|
||||
$routeTranslation,
|
||||
);
|
||||
}
|
||||
return $routeTranslation;
|
||||
}
|
||||
|
||||
protected function getPreviewToken(): string
|
||||
{
|
||||
if (
|
||||
!isset($_SESSION["phpb_preview_token"]) ||
|
||||
!is_string($_SESSION["phpb_preview_token"]) ||
|
||||
$_SESSION["phpb_preview_token"] === ""
|
||||
) {
|
||||
$_SESSION["phpb_preview_token"] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
return $_SESSION["phpb_preview_token"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the route of this page.
|
||||
*
|
||||
* @param string|null $locale
|
||||
* @return mixed|string|null
|
||||
*/
|
||||
public function getPreviewRoute(?string $locale = null)
|
||||
{
|
||||
$previewUrl = $this->getRoute($locale);
|
||||
$previewUrl .=
|
||||
(str_contains($previewUrl, "?") ? "&" : "?") .
|
||||
"previewToken=" .
|
||||
rawurlencode($this->getPreviewToken());
|
||||
return $previewUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of the given property of this Page.
|
||||
*
|
||||
@@ -172,9 +219,9 @@ class Page implements PageContract
|
||||
public function invalidateCache()
|
||||
{
|
||||
$routes = array_map(function ($translation) {
|
||||
return $translation['route'] ?? null;
|
||||
return $translation["route"] ?? null;
|
||||
}, $this->getTranslations());
|
||||
|
||||
(new PageTranslationService())->invalidateRoutes($routes);
|
||||
new PageTranslationService()->invalidateRoutes($routes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use Plugi\Contracts\PageBuilderContract;
|
||||
use Plugi\Contracts\RouterContract;
|
||||
use Plugi\Contracts\ThemeContract;
|
||||
use Plugi\Modules\GrapesJS\PageRenderer;
|
||||
use Plugi\Repositories\PageRepository;
|
||||
use Plugi\Repositories\UploadRepository;
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Extensions;
|
||||
@@ -468,9 +469,14 @@ class Plugi
|
||||
}
|
||||
}
|
||||
|
||||
$hasPreviewToken = array_key_exists('previewToken', $_GET);
|
||||
$previewToken = $_GET['previewToken'] ?? null;
|
||||
$isAuthenticatedPreview = $this->isAuthenticatedPreviewRequest($previewToken);
|
||||
|
||||
// try to find page in cache
|
||||
$cache = phpb_instance('cache');
|
||||
if (phpb_config('cache.enabled') &&
|
||||
if (! $hasPreviewToken &&
|
||||
phpb_config('cache.enabled') &&
|
||||
! isset($_GET['ignore_cache']) &&
|
||||
! isset($_GET['refresh_cache']) &&
|
||||
! isset($_COOKIE['ignore_cache']) &&
|
||||
@@ -504,11 +510,24 @@ class Plugi
|
||||
// render page if resolved
|
||||
if ($page) {
|
||||
if ($page->get('type') === 'redirect') {
|
||||
phpb_redirect($pageTranslation->target);
|
||||
$target = $pageTranslation->target;
|
||||
if ($isAuthenticatedPreview) {
|
||||
$target = PageRenderer::appendPreviewTokenToUrl($target, $previewToken, parse_url(phpb_full_url('/')), true);
|
||||
}
|
||||
phpb_redirect($target);
|
||||
}
|
||||
if ($isAuthenticatedPreview) {
|
||||
$draftData = (new PageRepository())->getPageDraftData($page);
|
||||
if ($draftData !== null) {
|
||||
$page->setData(['data' => $draftData], false);
|
||||
}
|
||||
}
|
||||
// TODO add menu etc
|
||||
$renderedContent = $this->pageBuilder->renderPage($page, $pageTranslation->locale);
|
||||
if (!str_contains($pageTranslation->route, '/*')) {
|
||||
if ($isAuthenticatedPreview) {
|
||||
$renderedContent = PageRenderer::appendPreviewTokenToLinks($renderedContent, $previewToken);
|
||||
}
|
||||
if (! $hasPreviewToken && !str_contains($pageTranslation->route, '/*')) {
|
||||
$this->cacheRenderedPage($renderedContent);
|
||||
}
|
||||
echo $renderedContent;
|
||||
@@ -517,6 +536,16 @@ class Plugi
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function isAuthenticatedPreviewRequest($previewToken): bool
|
||||
{
|
||||
if (! is_string($previewToken) || $previewToken === '' || ! phpb_is_authenticated()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sessionToken = $_SESSION['phpb_preview_token'] ?? null;
|
||||
return is_string($sessionToken) && $sessionToken !== '' && hash_equals($sessionToken, $previewToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a PageTranslation from the given URL.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Repositories;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class PageDraftPublishedCacheInvalidationException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -28,9 +28,11 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->table = empty(phpb_config('page.table')) ? 'pages' : phpb_config('page.table');
|
||||
$this->table = empty(phpb_config("page.table"))
|
||||
? "pages"
|
||||
: phpb_config("page.table");
|
||||
parent::__construct();
|
||||
$this->class = phpb_instance('page');
|
||||
$this->class = phpb_instance("page");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,28 +44,36 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
*/
|
||||
public function create(array $data)
|
||||
{
|
||||
foreach (['name', 'layout'] as $field) {
|
||||
if (! isset($data[$field]) || ! is_string($data[$field]) || trim($data[$field]) === '') {
|
||||
foreach (["name", "layout"] as $field) {
|
||||
if (
|
||||
!isset($data[$field]) ||
|
||||
!is_string($data[$field]) ||
|
||||
trim($data[$field]) === ""
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (! isset($data['type']) || ! is_string($data['type']) || ! in_array($data['type'], ['static', 'redirect'], true)) {
|
||||
if (
|
||||
!isset($data["type"]) ||
|
||||
!is_string($data["type"]) ||
|
||||
!in_array($data["type"], ["static", "redirect"], true)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$activeLanguages = phpb_active_languages();
|
||||
if (! $this->hasValidTranslationData($data, $activeLanguages)) {
|
||||
if (!$this->hasValidTranslationData($data, $activeLanguages)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->db->transaction(function () use ($data) {
|
||||
$page = parent::create([
|
||||
'name' => $data['name'],
|
||||
'layout' => $data['layout'],
|
||||
'type' => $data['type'],
|
||||
"name" => $data["name"],
|
||||
"layout" => $data["layout"],
|
||||
"type" => $data["type"],
|
||||
]);
|
||||
if (! ($page instanceof PageContract)) {
|
||||
if (!($page instanceof PageContract)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -80,33 +90,40 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
*/
|
||||
public function update($page, array $data)
|
||||
{
|
||||
foreach (['name', 'layout'] as $field) {
|
||||
if (! isset($data[$field]) || ! is_string($data[$field])) {
|
||||
foreach (["name", "layout"] as $field) {
|
||||
if (!isset($data[$field]) || !is_string($data[$field])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$activeLanguages = phpb_active_languages();
|
||||
if (! $this->hasValidTranslationData($data, $activeLanguages)) {
|
||||
if (!$this->hasValidTranslationData($data, $activeLanguages)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$translationService = new PageTranslationService();
|
||||
$oldRoutes = [];
|
||||
$updateResult = $this->db->transaction(function () use ($page, $data, $translationService, &$oldRoutes) {
|
||||
$updateResult = $this->db->transaction(function () use (
|
||||
$page,
|
||||
$data,
|
||||
$translationService,
|
||||
&$oldRoutes,
|
||||
) {
|
||||
$oldRoutes = $translationService->getPageRoutes($page->getId());
|
||||
if (! $this->replaceTranslations($page, $data)) {
|
||||
if (!$this->replaceTranslations($page, $data)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::update($page, [
|
||||
'name' => $data['name'],
|
||||
'layout' => $data['layout'],
|
||||
'type' => $data['type'],
|
||||
"name" => $data["name"],
|
||||
"layout" => $data["layout"],
|
||||
"type" => $data["type"],
|
||||
]);
|
||||
});
|
||||
if ($updateResult) {
|
||||
$translationService->invalidateRoutes(array_merge($oldRoutes, array_values($data['route'])));
|
||||
$translationService->invalidateRoutes(
|
||||
array_merge($oldRoutes, array_values($data["route"])),
|
||||
);
|
||||
}
|
||||
return $updateResult;
|
||||
}
|
||||
@@ -121,26 +138,33 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
protected function replaceTranslations(PageContract $page, array $data)
|
||||
{
|
||||
$activeLanguages = phpb_active_languages();
|
||||
if (! $this->hasValidTranslationData($data, $activeLanguages)
|
||||
|| $this->hasRouteCollision($data, $activeLanguages, $page->getId())) {
|
||||
if (
|
||||
!$this->hasValidTranslationData($data, $activeLanguages) ||
|
||||
$this->hasRouteCollision($data, $activeLanguages, $page->getId())
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pageTranslationRepository = new PageTranslationRepository;
|
||||
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $page->getId())) {
|
||||
$pageTranslationRepository = new PageTranslationRepository();
|
||||
if (
|
||||
!$pageTranslationRepository->destroyWhere(
|
||||
phpb_config("page.translation.foreign_key"),
|
||||
$page->getId(),
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||
$translation = $pageTranslationRepository->create([
|
||||
phpb_config('page.translation.foreign_key') => $page->getId(),
|
||||
'locale' => $languageCode,
|
||||
'title' => $data['title'][$languageCode],
|
||||
'meta_title' => $data['meta_title'][$languageCode],
|
||||
'meta_description' => $data['meta_description'][$languageCode],
|
||||
'route' => $data['route'][$languageCode],
|
||||
'target' => $data['target'][$languageCode],
|
||||
phpb_config("page.translation.foreign_key") => $page->getId(),
|
||||
"locale" => $languageCode,
|
||||
"title" => $data["title"][$languageCode],
|
||||
"meta_title" => $data["meta_title"][$languageCode],
|
||||
"meta_description" => $data["meta_description"][$languageCode],
|
||||
"route" => $data["route"][$languageCode],
|
||||
"target" => $data["target"][$languageCode],
|
||||
]);
|
||||
if (! ($translation instanceof PageTranslationContract)) {
|
||||
if (!($translation instanceof PageTranslationContract)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -148,28 +172,54 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function hasValidTranslationData(array $data, array $activeLanguages): bool
|
||||
{
|
||||
if (empty($activeLanguages) || ! isset($data['type']) || ! is_string($data['type'])
|
||||
|| ! in_array($data['type'], ['static', 'redirect'], true)) {
|
||||
protected function hasValidTranslationData(
|
||||
array $data,
|
||||
array $activeLanguages,
|
||||
): bool {
|
||||
if (
|
||||
empty($activeLanguages) ||
|
||||
!isset($data["type"]) ||
|
||||
!is_string($data["type"]) ||
|
||||
!in_array($data["type"], ["static", "redirect"], true)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (['title', 'meta_title', 'meta_description', 'route', 'target'] as $field) {
|
||||
if (! isset($data[$field]) || ! is_array($data[$field])) {
|
||||
foreach (
|
||||
["title", "meta_title", "meta_description", "route", "target"]
|
||||
as $field
|
||||
) {
|
||||
if (!isset($data[$field]) || !is_array($data[$field])) {
|
||||
return false;
|
||||
}
|
||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||
if (! array_key_exists($languageCode, $data[$field]) || ! is_string($data[$field][$languageCode])) {
|
||||
foreach (
|
||||
$activeLanguages
|
||||
as $languageCode => $languageTranslation
|
||||
) {
|
||||
if (
|
||||
!array_key_exists($languageCode, $data[$field]) ||
|
||||
!is_string($data[$field][$languageCode])
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ($field === 'route' && trim($data[$field][$languageCode]) === '') {
|
||||
if (
|
||||
$field === "route" &&
|
||||
trim($data[$field][$languageCode]) === ""
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ($field === 'title' && $data['type'] === 'static' && trim($data[$field][$languageCode]) === '') {
|
||||
if (
|
||||
$field === "title" &&
|
||||
$data["type"] === "static" &&
|
||||
trim($data[$field][$languageCode]) === ""
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if ($field === 'target' && $data['type'] === 'redirect' && trim($data[$field][$languageCode]) === '') {
|
||||
if (
|
||||
$field === "target" &&
|
||||
$data["type"] === "redirect" &&
|
||||
trim($data[$field][$languageCode]) === ""
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -178,18 +228,21 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function hasRouteCollision(array $data, array $activeLanguages, $pageId = null): bool
|
||||
{
|
||||
protected function hasRouteCollision(
|
||||
array $data,
|
||||
array $activeLanguages,
|
||||
$pageId = null,
|
||||
): bool {
|
||||
$routes = [];
|
||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||
$route = $data['route'][$languageCode];
|
||||
$route = $data["route"][$languageCode];
|
||||
if (array_key_exists($route, $routes)) {
|
||||
return true;
|
||||
}
|
||||
$routes[$route] = true;
|
||||
}
|
||||
|
||||
$pageTranslationRepository = new PageTranslationRepository;
|
||||
$pageTranslationRepository = new PageTranslationRepository();
|
||||
foreach (array_keys($routes) as $route) {
|
||||
if ($pageTranslationRepository->routeExists($route, $pageId)) {
|
||||
return true;
|
||||
@@ -209,7 +262,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
public function updatePageData($page, array $data)
|
||||
{
|
||||
$updateResult = parent::update($page, [
|
||||
'data' => json_encode($data),
|
||||
"data" => json_encode($data),
|
||||
]);
|
||||
if ($updateResult) {
|
||||
$page->invalidateCache();
|
||||
@@ -217,6 +270,63 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
return $updateResult;
|
||||
}
|
||||
|
||||
public function getPageDraftData($page): ?array
|
||||
{
|
||||
$draftData = $page->getData()["draft_data"] ?? null;
|
||||
if (!is_string($draftData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decodedData = json_decode($draftData, true);
|
||||
return is_array($decodedData) ? $decodedData : null;
|
||||
}
|
||||
|
||||
public function updatePageDraftData($page, array $data): bool
|
||||
{
|
||||
$draftData = json_encode($data);
|
||||
if ($draftData === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$updateResult = parent::update($page, ["draft_data" => $draftData]);
|
||||
if ($updateResult) {
|
||||
$page->setData(["draft_data" => $draftData], false);
|
||||
}
|
||||
return $updateResult;
|
||||
}
|
||||
|
||||
public function publishPageDraft($page): bool
|
||||
{
|
||||
$draftData = $page->getData()["draft_data"] ?? null;
|
||||
if (
|
||||
!is_string($draftData) ||
|
||||
!is_array(json_decode($draftData, true))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$updateResult = $this->db->queryAffectedRows(
|
||||
"UPDATE {$this->table} SET data=?, draft_data=NULL WHERE draft_data=? AND id=?",
|
||||
[$draftData, $draftData, $page->getId()],
|
||||
);
|
||||
if ($updateResult !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$page->setData(["data" => $draftData, "draft_data" => null], false);
|
||||
try {
|
||||
$page->invalidateCache();
|
||||
} catch (\Throwable $exception) {
|
||||
throw new PageDraftPublishedCacheInvalidationException(
|
||||
"Page draft was published, but route cache invalidation failed.",
|
||||
0,
|
||||
$exception,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the given page from the database.
|
||||
*
|
||||
@@ -227,10 +337,19 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
||||
{
|
||||
$translationService = new PageTranslationService();
|
||||
$routes = [];
|
||||
$destroyResult = $this->db->transaction(function () use ($id, $translationService, &$routes) {
|
||||
$destroyResult = $this->db->transaction(function () use (
|
||||
$id,
|
||||
$translationService,
|
||||
&$routes,
|
||||
) {
|
||||
$routes = $translationService->getPageRoutes($id);
|
||||
$pageTranslationRepository = new PageTranslationRepository();
|
||||
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $id)) {
|
||||
if (
|
||||
!$pageTranslationRepository->destroyWhere(
|
||||
phpb_config("page.translation.foreign_key"),
|
||||
$id,
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,46 @@ class UploadRepository extends BaseRepository
|
||||
'original_file' => $data['original_file'],
|
||||
'mime_type' => $data['mime_type'],
|
||||
'server_file' => $data['server_file'],
|
||||
'alt_text' => '',
|
||||
'folder' => '',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update supported media-library metadata for the upload with the given public ID.
|
||||
*/
|
||||
public function updateMetadata(string $publicId, array $metadata): bool
|
||||
{
|
||||
$fieldLimits = [
|
||||
'alt_text' => 1000,
|
||||
'folder' => 255,
|
||||
];
|
||||
if ($publicId === '' || strlen($publicId) > 50 || empty($metadata)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$validatedMetadata = [];
|
||||
foreach ($metadata as $field => $value) {
|
||||
if (! isset($fieldLimits[$field]) || ! is_string($value) || ! $this->isValidMetadataValue($value, $fieldLimits[$field])) {
|
||||
return false;
|
||||
}
|
||||
$validatedMetadata[$field] = $field === 'folder' ? trim($value) : $value;
|
||||
}
|
||||
|
||||
$uploads = $this->findWhere('public_id', $publicId);
|
||||
if (empty($uploads)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->update($uploads[0], $validatedMetadata);
|
||||
}
|
||||
|
||||
private function isValidMetadataValue(string $value, int $maxLength): bool
|
||||
{
|
||||
if (strlen($value) > $maxLength * 4 || ! preg_match('//u', $value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match_all('/./us', $value) <= $maxLength;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Modules\WebsiteManager\WebsiteManager;
|
||||
use Plugi\Repositories\UploadRepository;
|
||||
|
||||
require_once __DIR__ . '/../src/Contracts/WebsiteManagerContract.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/UploadedFile.php';
|
||||
require_once __DIR__ . '/../src/Repositories/UploadRepository.php';
|
||||
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
|
||||
|
||||
class MediaLibrarySettingRepositoryStub
|
||||
{
|
||||
public function updateSettings(array $settings): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class_alias(MediaLibrarySettingRepositoryStub::class, 'Plugi\\Repositories\\SettingRepository');
|
||||
|
||||
class MediaLibraryRedirectException extends RuntimeException
|
||||
{
|
||||
public function __construct(public string $url, public array $flashData)
|
||||
{
|
||||
parent::__construct('Redirect requested.');
|
||||
}
|
||||
}
|
||||
|
||||
class MediaLibraryTestDatabase extends DB
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->pdo = new PDO('sqlite::memory:');
|
||||
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->databaseName = 'media_library_test';
|
||||
}
|
||||
|
||||
public function createSchema(): void
|
||||
{
|
||||
$this->pdo->exec("CREATE TABLE testuploads (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
public_id VARCHAR(50),
|
||||
original_file VARCHAR(512),
|
||||
mime_type VARCHAR(50),
|
||||
server_file VARCHAR(512),
|
||||
alt_text VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
folder VARCHAR(255) NOT NULL DEFAULT ''
|
||||
)");
|
||||
}
|
||||
}
|
||||
|
||||
class MediaLibrarySchemaUpdateTestDatabase extends MediaLibraryTestDatabase
|
||||
{
|
||||
public function createLegacySchema(): void
|
||||
{
|
||||
$this->pdo->exec('CREATE TABLE testuploads (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
public_id VARCHAR(50),
|
||||
original_file VARCHAR(512),
|
||||
mime_type VARCHAR(50),
|
||||
server_file VARCHAR(512)
|
||||
)');
|
||||
}
|
||||
|
||||
public function getDBDefinition(): array
|
||||
{
|
||||
$tables = require __DIR__ . '/../config/tables.php';
|
||||
return [
|
||||
'uploads' => [
|
||||
'columns' => $tables['uploads']['columns'],
|
||||
'uniqueKeys' => [],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function diffDB(): array
|
||||
{
|
||||
$definition = $this->getDBDefinition()['uploads'];
|
||||
$existingColumns = $this->select('PRAGMA table_info(testuploads)', []);
|
||||
$existingColumnNames = array_column($existingColumns, 'name');
|
||||
$missingColumns = array_diff_key($definition['columns'], array_fill_keys($existingColumnNames, true));
|
||||
|
||||
return [
|
||||
'uploads' => [
|
||||
'columns' => $missingColumns,
|
||||
'uniqueKeys' => [],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function phpb_remove_non_alpha_numeric(string $value): string
|
||||
{
|
||||
return preg_replace('/\W*/', '', $value);
|
||||
}
|
||||
|
||||
function phpb_url(string $module, array $parameters = []): string
|
||||
{
|
||||
return '/' . $module . '?' . http_build_query($parameters);
|
||||
}
|
||||
|
||||
function phpb_trans(string $key): string
|
||||
{
|
||||
return $key;
|
||||
}
|
||||
|
||||
function phpb_e($value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
function phpb_csrf_field(): void
|
||||
{
|
||||
echo '<input type="hidden" name="_csrf_token" value="test-token">';
|
||||
}
|
||||
|
||||
function phpb_validate_csrf(): bool
|
||||
{
|
||||
return $GLOBALS['mediaLibraryCsrfValid'] ?? false;
|
||||
}
|
||||
|
||||
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
||||
{
|
||||
throw new MediaLibraryRedirectException($url, $flashData);
|
||||
}
|
||||
|
||||
function assertMediaLibrary(bool $condition, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
function runMediaLibraryCase(string $name, callable $case): bool
|
||||
{
|
||||
try {
|
||||
$case();
|
||||
fwrite(STDOUT, "PASS: {$name}\n");
|
||||
return true;
|
||||
} catch (Throwable $exception) {
|
||||
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class MediaLibraryViewUpload
|
||||
{
|
||||
public function __construct(
|
||||
public string $public_id,
|
||||
public string $original_file,
|
||||
public string $mime_type,
|
||||
public string $folder = '',
|
||||
public string $alt_text = ''
|
||||
) {
|
||||
}
|
||||
|
||||
public function getUrl(): string
|
||||
{
|
||||
return '/uploads/' . $this->public_id . '/' . $this->original_file;
|
||||
}
|
||||
}
|
||||
|
||||
function renderMediaLibraryView(array $files): string
|
||||
{
|
||||
ob_start();
|
||||
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/files.php';
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
$_ENV['DATABASE_PREFIX'] = 'test';
|
||||
$phpb_db = new MediaLibraryTestDatabase;
|
||||
$phpb_db->createSchema();
|
||||
$repository = new UploadRepository;
|
||||
$websiteManager = new WebsiteManager;
|
||||
$cases = [
|
||||
'schema defines defaulted metadata columns' => function (): void {
|
||||
$tables = require __DIR__ . '/../config/tables.php';
|
||||
assertMediaLibrary(
|
||||
($tables['uploads']['columns']['alt_text'] ?? null) === "varchar(1000) NOT NULL DEFAULT ''",
|
||||
'Alt text should be a bounded, empty-default upload column.'
|
||||
);
|
||||
assertMediaLibrary(
|
||||
($tables['uploads']['columns']['folder'] ?? null) === "varchar(255) NOT NULL DEFAULT ''",
|
||||
'Folder should be an empty-default upload column.'
|
||||
);
|
||||
},
|
||||
'new uploads initialize metadata as empty strings' => function () use ($repository): void {
|
||||
$upload = $repository->create([
|
||||
'public_id' => 'new-upload',
|
||||
'original_file' => 'new.png',
|
||||
'mime_type' => 'image/png',
|
||||
'server_file' => 'new-upload/new.png',
|
||||
]);
|
||||
|
||||
assertMediaLibrary($upload !== null, 'A valid upload should be created.');
|
||||
assertMediaLibrary($upload->alt_text === '', 'New uploads should start with blank alt text.');
|
||||
assertMediaLibrary($upload->folder === '', 'New uploads should start without a folder.');
|
||||
},
|
||||
'legacy upload rows receive blank metadata defaults' => function () use ($phpb_db, $repository): void {
|
||||
$phpb_db->query(
|
||||
'INSERT INTO testuploads (public_id, original_file, mime_type, server_file) VALUES (?, ?, ?, ?)',
|
||||
['legacy-upload', 'legacy.jpg', 'image/jpeg', 'legacy-upload/legacy.jpg']
|
||||
);
|
||||
$upload = $repository->findWhere('public_id', 'legacy-upload')[0] ?? null;
|
||||
|
||||
assertMediaLibrary($upload !== null, 'A legacy upload should remain available.');
|
||||
assertMediaLibrary($upload->alt_text === '', 'Legacy uploads should have blank alt text.');
|
||||
assertMediaLibrary($upload->folder === '', 'Legacy uploads should be unsorted.');
|
||||
},
|
||||
'schema update adds metadata defaults without losing existing uploads' => function (): void {
|
||||
$database = new MediaLibrarySchemaUpdateTestDatabase;
|
||||
$database->createLegacySchema();
|
||||
$database->query(
|
||||
'INSERT INTO testuploads (public_id, original_file, mime_type, server_file) VALUES (?, ?, ?, ?)',
|
||||
['migrated-upload', 'existing.jpg', 'image/jpeg', 'migrated-upload/existing.jpg']
|
||||
);
|
||||
|
||||
$database->resolveDiffDB();
|
||||
$upload = $database->select('SELECT * FROM testuploads WHERE public_id = ?', ['migrated-upload'])[0] ?? null;
|
||||
|
||||
assertMediaLibrary($upload !== null, 'The schema update should retain existing upload rows.');
|
||||
assertMediaLibrary(array_key_exists('alt_text', $upload) && $upload['alt_text'] === '', 'The schema update should add blank alt text.');
|
||||
assertMediaLibrary(array_key_exists('folder', $upload) && $upload['folder'] === '', 'The schema update should add blank folders.');
|
||||
},
|
||||
'metadata updates by public ID and can clear fields' => function () use ($repository): void {
|
||||
$upload = $repository->create([
|
||||
'public_id' => 'editable-upload',
|
||||
'original_file' => 'photo.jpg',
|
||||
'mime_type' => 'image/jpeg',
|
||||
'server_file' => 'editable-upload/photo.jpg',
|
||||
]);
|
||||
|
||||
assertMediaLibrary(
|
||||
$repository->updateMetadata('editable-upload', ['folder' => ' Campaigns ', 'alt_text' => 'Campaign photo']),
|
||||
'Valid metadata should update.'
|
||||
);
|
||||
$updated = $repository->findWhere('public_id', 'editable-upload')[0];
|
||||
assertMediaLibrary($updated->folder === 'Campaigns', 'The folder should persist.');
|
||||
assertMediaLibrary($updated->alt_text === 'Campaign photo', 'Alt text should persist.');
|
||||
|
||||
assertMediaLibrary(
|
||||
$repository->updateMetadata('editable-upload', ['folder' => '']),
|
||||
'A folder should be clearable.'
|
||||
);
|
||||
assertMediaLibrary(
|
||||
$repository->findWhere('public_id', 'editable-upload')[0]->folder === '',
|
||||
'Clearing a folder should restore the unsorted state.'
|
||||
);
|
||||
},
|
||||
'metadata updates reject missing records and unsupported values' => function () use ($repository): void {
|
||||
assertMediaLibrary(! $repository->updateMetadata('missing-upload', ['folder' => 'News']), 'Unknown uploads must not update.');
|
||||
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', []), 'Empty metadata updates must be rejected.');
|
||||
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['path' => 'elsewhere']), 'Unsupported fields must be rejected.');
|
||||
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['folder' => ['News']]), 'Non-string values must be rejected.');
|
||||
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['folder' => str_repeat('x', 256)]), 'Overlong folder labels must be rejected.');
|
||||
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['alt_text' => str_repeat('x', 1001)]), 'Overlong alt text must be rejected.');
|
||||
},
|
||||
'metadata action validates CSRF and persists allowed request fields' => function () use ($repository, $websiteManager): void {
|
||||
$repository->create([
|
||||
'public_id' => 'request-upload',
|
||||
'original_file' => 'request.png',
|
||||
'mime_type' => 'image/png',
|
||||
'server_file' => 'request-upload/request.png',
|
||||
]);
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_GET = [];
|
||||
$_POST = [
|
||||
'_csrf_token' => 'valid-token',
|
||||
'public_id' => 'request-upload',
|
||||
'folder' => 'News',
|
||||
];
|
||||
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
||||
|
||||
try {
|
||||
$websiteManager->handleRequest('media', 'update_metadata');
|
||||
throw new RuntimeException('A successful metadata update should redirect.');
|
||||
} catch (MediaLibraryRedirectException $redirect) {
|
||||
assertMediaLibrary(str_contains($redirect->url, 'tab=files'), 'Successful updates should return to the media tab.');
|
||||
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'success', 'Successful updates should show a success message.');
|
||||
}
|
||||
|
||||
assertMediaLibrary(
|
||||
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
||||
'The manager action should persist the requested folder.'
|
||||
);
|
||||
},
|
||||
'alt text saves through manager action and appears on image previews' => function () use ($repository, $websiteManager): void {
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = [
|
||||
'_csrf_token' => 'valid-token',
|
||||
'public_id' => 'request-upload',
|
||||
'alt_text' => 'Camera "test" & results',
|
||||
];
|
||||
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
||||
|
||||
try {
|
||||
$websiteManager->handleRequest('media', 'update_metadata');
|
||||
throw new RuntimeException('An alt-text update should redirect.');
|
||||
} catch (MediaLibraryRedirectException $redirect) {
|
||||
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'success', 'Saved alt text should show a success message.');
|
||||
}
|
||||
|
||||
$upload = $repository->findWhere('public_id', 'request-upload')[0];
|
||||
assertMediaLibrary($upload->alt_text === 'Camera "test" & results', 'Alt text should persist exactly as entered.');
|
||||
$html = renderMediaLibraryView([
|
||||
new MediaLibraryViewUpload($upload->public_id, $upload->original_file, $upload->mime_type, $upload->folder, $upload->alt_text),
|
||||
]);
|
||||
assertMediaLibrary(str_contains($html, 'alt="Camera "test" & results"'), 'The saved alt text should render as an escaped image alt attribute.');
|
||||
assertMediaLibrary(str_contains($html, 'value="Camera "test" & results"'), 'The editor should show the saved alt text.');
|
||||
},
|
||||
'metadata action rejects requests without a valid CSRF token' => function () use ($repository, $websiteManager): void {
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['public_id' => 'request-upload', 'folder' => 'Private'];
|
||||
$GLOBALS['mediaLibraryCsrfValid'] = false;
|
||||
|
||||
assertMediaLibrary(! $websiteManager->handleUpdateMediaMetadata(), 'The metadata action should reject invalid CSRF.');
|
||||
assertMediaLibrary(http_response_code() === 403, 'Invalid CSRF should set a forbidden status.');
|
||||
assertMediaLibrary(
|
||||
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
||||
'A rejected request must not change metadata.'
|
||||
);
|
||||
},
|
||||
'metadata action rejects unrecognized request fields' => function () use ($repository, $websiteManager): void {
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = [
|
||||
'_csrf_token' => 'valid-token',
|
||||
'public_id' => 'request-upload',
|
||||
'folder' => 'Private',
|
||||
'server_file' => 'attacker-controlled/path',
|
||||
];
|
||||
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
||||
|
||||
try {
|
||||
$websiteManager->handleUpdateMediaMetadata();
|
||||
throw new RuntimeException('An unsupported request field should be rejected.');
|
||||
} catch (MediaLibraryRedirectException $redirect) {
|
||||
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'error', 'Invalid fields should produce an error message.');
|
||||
}
|
||||
|
||||
assertMediaLibrary(
|
||||
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
||||
'A request with unsupported fields must not change metadata.'
|
||||
);
|
||||
},
|
||||
'media view exposes combined search and filter controls for mixed uploads' => function (): void {
|
||||
$files = [
|
||||
new MediaLibraryViewUpload('image-id', 'Campaign Photo.png', 'image/png', '', 'A campaign "photo" & more'),
|
||||
new MediaLibraryViewUpload('empty-alt-id', 'Empty Alt.png', 'image/png'),
|
||||
new MediaLibraryViewUpload('document-id', 'Press Kit.pdf', 'application/pdf', 'Press'),
|
||||
new MediaLibraryViewUpload('audio-id', 'Interview.mp3', 'audio/mpeg'),
|
||||
];
|
||||
$html = renderMediaLibraryView($files);
|
||||
|
||||
assertMediaLibrary(str_contains($html, 'id="media-search"'), 'The view should render a search field.');
|
||||
assertMediaLibrary(str_contains($html, 'id="media-type-filter"'), 'The view should render a MIME-derived type filter.');
|
||||
assertMediaLibrary(str_contains($html, 'id="media-folder-filter"'), 'The view should render a folder filter.');
|
||||
assertMediaLibrary(str_contains($html, 'id="media-filter-reset"'), 'The view should provide a clear-filters action.');
|
||||
assertMediaLibrary(str_contains($html, 'value="__unsorted__">Unsorted</option>'), 'Unassigned files should have an Unsorted filter option.');
|
||||
assertMediaLibrary(str_contains($html, 'data-file-name="Campaign Photo.png"'), 'Search data should include original filenames.');
|
||||
assertMediaLibrary(str_contains($html, 'data-public-id="image-id"'), 'Search data should include public IDs.');
|
||||
assertMediaLibrary(str_contains($html, 'data-mime-family="application"'), 'Type filters should derive from MIME types.');
|
||||
assertMediaLibrary(str_contains($html, 'value="folder:Press">Press</option>'), 'Existing folder labels should be filter options.');
|
||||
assertMediaLibrary(str_contains($html, 'name="folder"'), 'Each upload should have a virtual folder assignment field.');
|
||||
assertMediaLibrary(str_contains($html, 'name="alt_text"'), 'Each upload should have an alt-text editor.');
|
||||
assertMediaLibrary(str_contains($html, 'Alt text'), 'Alt text inputs should have a visible label.');
|
||||
assertMediaLibrary(str_contains($html, 'alt="A campaign "photo" & more"'), 'Saved text should be used as the image preview alt.');
|
||||
assertMediaLibrary(str_contains($html, 'alt=""'), 'Blank alt text should remain blank rather than using the filename.');
|
||||
assertMediaLibrary(! str_contains($html, 'alt="Empty Alt.png"'), 'Image filenames must not be substituted for blank authored alt text.');
|
||||
assertMediaLibrary(str_contains($html, 'id="media-no-results"'), 'The view should render an explicit no-results state.');
|
||||
assertMediaLibrary(substr_count($html, '<img ') === 2, 'Only image MIME types should render image previews.');
|
||||
assertMediaLibrary(str_contains($html, 'application/pdf'), 'Non-image uploads should show a file-type treatment.');
|
||||
assertMediaLibrary(str_contains($html, 'action=upload_delete'), 'Existing delete behavior should remain routed through PageBuilder.');
|
||||
assertMediaLibrary(str_contains($html, 'action=upload&page=1'), 'Existing upload behavior should remain routed through PageBuilder.');
|
||||
},
|
||||
'empty media view does not render active filters or require client controls' => function (): void {
|
||||
$html = renderMediaLibraryView([]);
|
||||
|
||||
assertMediaLibrary(str_contains($html, 'No files yet'), 'An empty library should retain its empty state.');
|
||||
assertMediaLibrary(! str_contains($html, 'id="media-search"'), 'An empty library should not render unnecessary filters.');
|
||||
},
|
||||
];
|
||||
|
||||
$passed = 0;
|
||||
foreach ($cases as $name => $case) {
|
||||
if (runMediaLibraryCase($name, $case)) {
|
||||
$passed++;
|
||||
}
|
||||
}
|
||||
|
||||
fwrite(STDOUT, sprintf("%d/%d media library cases passed.\n", $passed, count($cases)));
|
||||
exit($passed === count($cases) ? 0 : 1);
|
||||
@@ -3,6 +3,7 @@
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Contracts\PageContract;
|
||||
use Plugi\Contracts\PageTranslationContract;
|
||||
use Plugi\Core\Csrf;
|
||||
use Plugi\Modules\GrapesJS\PageBuilder;
|
||||
use Plugi\Modules\Router\DatabasePageRouter;
|
||||
use Plugi\Page;
|
||||
@@ -21,10 +22,12 @@ require_once __DIR__ . '/../src/Contracts/PageBuilderContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../src/Core/Csrf.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageDraftPublishedCacheInvalidationException.php';
|
||||
require_once __DIR__ . '/../src/PageTranslationService.php';
|
||||
require_once __DIR__ . '/../src/Page.php';
|
||||
require_once __DIR__ . '/../src/PageTranslation.php';
|
||||
@@ -33,6 +36,8 @@ require_once __DIR__ . '/../src/Repositories/PageRepository.php';
|
||||
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
|
||||
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
|
||||
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
|
||||
require_once __DIR__ . '/../src/Modules/GrapesJS/PageRenderer.php';
|
||||
require_once __DIR__ . '/../src/Extensions.php';
|
||||
require_once __DIR__ . '/../src/Plugi.php';
|
||||
|
||||
class PageCreationRedirectException extends RuntimeException
|
||||
@@ -53,6 +58,7 @@ class PageCreationTestDatabase extends DB
|
||||
public ?string $failOnDeleteTable = null;
|
||||
public bool $throwOnDeleteFailure = false;
|
||||
public bool $failOnPageUpdate = false;
|
||||
public ?int $failOnPageUpdateId = null;
|
||||
public array $schemaDiffs = [];
|
||||
|
||||
public function __construct()
|
||||
@@ -73,6 +79,9 @@ class PageCreationTestDatabase extends DB
|
||||
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
|
||||
return false;
|
||||
}
|
||||
if ($this->failOnPageUpdateId !== null && str_starts_with($query, 'UPDATE pages SET') && (int) end($parameters) === $this->failOnPageUpdateId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (str_starts_with($query, 'INSERT INTO page_translations')) {
|
||||
$this->translationInsertCount++;
|
||||
@@ -87,6 +96,18 @@ class PageCreationTestDatabase extends DB
|
||||
return parent::query($query, $parameters);
|
||||
}
|
||||
|
||||
public function queryAffectedRows(string $query, array $parameters = []): int|false
|
||||
{
|
||||
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
|
||||
return false;
|
||||
}
|
||||
if ($this->failOnPageUpdateId !== null && str_starts_with($query, 'UPDATE pages SET') && (int) end($parameters) === $this->failOnPageUpdateId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::queryAffectedRows($query, $parameters);
|
||||
}
|
||||
|
||||
public function all(string $table, array|string $columns = '*'): array
|
||||
{
|
||||
if ($table === 'page_translations') {
|
||||
@@ -112,6 +133,7 @@ class PageCreationTestDatabase extends DB
|
||||
name TEXT,
|
||||
layout TEXT,
|
||||
data TEXT,
|
||||
draft_data TEXT,
|
||||
type TEXT,
|
||||
status TEXT,
|
||||
parent_id INTEGER,
|
||||
@@ -219,11 +241,90 @@ class PageCreationTestWebsiteManager extends WebsiteManager
|
||||
class PageCreationTestCache
|
||||
{
|
||||
public static array $invalidatedRoutes = [];
|
||||
public static array $cacheReads = [];
|
||||
public static array $cacheWrites = [];
|
||||
public static ?string $cachedContent = null;
|
||||
public static bool $throwOnInvalidate = false;
|
||||
|
||||
public function invalidate(string $route): void
|
||||
{
|
||||
if (self::$throwOnInvalidate) {
|
||||
throw new RuntimeException('Simulated route cache invalidation failure.');
|
||||
}
|
||||
self::$invalidatedRoutes[] = $route;
|
||||
}
|
||||
|
||||
public function getForUrl(string $url): ?string
|
||||
{
|
||||
self::$cacheReads[] = $url;
|
||||
return self::$cachedContent;
|
||||
}
|
||||
|
||||
public function storeForUrl(string $url, string $content, int $lifetime): void
|
||||
{
|
||||
self::$cacheWrites[] = [$url, $content, $lifetime];
|
||||
}
|
||||
}
|
||||
|
||||
class PageCreationTestPublicRouter
|
||||
{
|
||||
public function __construct(private PageTranslationContract $translation)
|
||||
{
|
||||
}
|
||||
|
||||
public function resolve(string $url): PageTranslationContract
|
||||
{
|
||||
return $this->translation;
|
||||
}
|
||||
}
|
||||
|
||||
class PageCreationTestPublicPageBuilder
|
||||
{
|
||||
public array $renderedData = [];
|
||||
|
||||
public function renderPage(PageContract $page, ?string $language = null): string
|
||||
{
|
||||
$this->renderedData = $page->getBuilderData();
|
||||
return '<!doctype html><html><head><title>Page</title></head><body><main>Theme layout</main>'
|
||||
. '<a href="/about?locale=de#intro">Internal</a>'
|
||||
. '<a href="https://example.test/contact?next=1">Absolute internal</a>'
|
||||
. '<a href="https://external.test/page?x=1#fragment">External</a>'
|
||||
. '<a href="#section">Fragment</a>'
|
||||
. '<a href="?search=one">Query only</a>'
|
||||
. '<a href="/already?previewToken=stale&x=1">Existing token</a>'
|
||||
. '<a href="\\\\evil.example/path">Backslash external</a>'
|
||||
. '<a href="' . "\t" . '//evil.example/path">Tab-prefixed external</a>'
|
||||
. '<a href=" ' . '//evil.example/path">Space-prefixed external</a>'
|
||||
. '</body></html>';
|
||||
}
|
||||
}
|
||||
|
||||
function runPageCreationPublicRequest(PageTranslationContract $translation, array $query, bool $authenticated, string $sessionToken): array
|
||||
{
|
||||
global $pageCreationCurrentUrl;
|
||||
|
||||
$_GET = $query;
|
||||
$_COOKIE = [];
|
||||
$_SESSION = [
|
||||
'phpb_logged_in' => $authenticated,
|
||||
'phpb_preview_token' => $sessionToken,
|
||||
];
|
||||
$pageCreationCurrentUrl = '/new-page' . ($query === [] ? '' : '?' . http_build_query($query));
|
||||
PageCreationTestCache::$cacheReads = [];
|
||||
PageCreationTestCache::$cacheWrites = [];
|
||||
PageCreationTestCache::$cachedContent = null;
|
||||
\Plugi\Modules\GrapesJS\PageRenderer::$canBeCached = true;
|
||||
|
||||
$pageBuilder = new PageCreationTestPublicPageBuilder();
|
||||
$plugi = new \Plugi\Plugi();
|
||||
$reflection = new ReflectionClass(\Plugi\Plugi::class);
|
||||
$reflection->getProperty('pageBuilder')->setValue($plugi, $pageBuilder);
|
||||
$reflection->getProperty('router')->setValue($plugi, new PageCreationTestPublicRouter($translation));
|
||||
|
||||
ob_start();
|
||||
$handled = $plugi->handlePublicRequest();
|
||||
$html = ob_get_clean();
|
||||
return [$handled, $html, $pageBuilder];
|
||||
}
|
||||
|
||||
function phpb_config(?string $key = null): mixed
|
||||
@@ -249,6 +350,11 @@ function phpb_active_languages(): array
|
||||
return $pageCreationLanguages;
|
||||
}
|
||||
|
||||
function phpb_is_authenticated(): bool
|
||||
{
|
||||
return ! empty($_SESSION['phpb_logged_in']);
|
||||
}
|
||||
|
||||
function phpb_route_parameters(): array
|
||||
{
|
||||
return [];
|
||||
@@ -289,13 +395,22 @@ function phpb_on_url(string $module, array $parameters = []): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
function phpb_current_relative_url(): string
|
||||
function phpb_current_relative_url(bool $removeParameters = false): string
|
||||
{
|
||||
return '/admin/page_settings';
|
||||
global $pageCreationCurrentUrl;
|
||||
$url = $pageCreationCurrentUrl ?? '/admin/page_settings';
|
||||
return $removeParameters ? explode('?', $url, 2)[0] : $url;
|
||||
}
|
||||
|
||||
function phpb_static(string $name): string
|
||||
{
|
||||
return $name;
|
||||
}
|
||||
|
||||
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
||||
{
|
||||
global $pageCreationRedirectFlash;
|
||||
$pageCreationRedirectFlash = $flashData;
|
||||
throw new PageCreationRedirectException($url);
|
||||
}
|
||||
|
||||
@@ -308,6 +423,11 @@ function phpb_csrf_field(): void
|
||||
{
|
||||
}
|
||||
|
||||
function phpb_validate_csrf(): bool
|
||||
{
|
||||
return Csrf::validateToken($_POST['_csrf_token'] ?? '');
|
||||
}
|
||||
|
||||
function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]): void
|
||||
{
|
||||
global $phpb_db, $pageCreationConfig, $pageCreationLanguages;
|
||||
@@ -316,7 +436,10 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
|
||||
$pageCreationConfig = [
|
||||
'general' => [
|
||||
'language' => 'en',
|
||||
'uploads_url' => '/uploads',
|
||||
'assets_url' => '/assets',
|
||||
],
|
||||
'cache' => ['enabled' => true],
|
||||
'page' => [
|
||||
'table' => 'pages',
|
||||
'translation' => [
|
||||
@@ -327,6 +450,9 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
|
||||
];
|
||||
$pageCreationLanguages = $languages;
|
||||
PageCreationTestCache::$invalidatedRoutes = [];
|
||||
PageCreationTestCache::$cacheReads = [];
|
||||
PageCreationTestCache::$cacheWrites = [];
|
||||
PageCreationTestCache::$throwOnInvalidate = false;
|
||||
$phpb_db = new PageCreationTestDatabase();
|
||||
$phpb_db->createSchema();
|
||||
}
|
||||
@@ -345,6 +471,25 @@ function pageCreationPayload(array $overrides = []): array
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
function pageCreationAddDraft(PageRepository $repository, string $name, string $route): PageContract
|
||||
{
|
||||
if (! $repository->create(pageCreationPayload([
|
||||
'name' => $name,
|
||||
'route' => ['en' => $route, 'de' => '/de' . $route],
|
||||
]))) {
|
||||
throw new RuntimeException('Could not create a page for the batch publishing test.');
|
||||
}
|
||||
|
||||
global $phpb_db;
|
||||
$rows = $phpb_db->rows('pages');
|
||||
$page = $repository->findWithId($rows[array_key_last($rows)]['id']);
|
||||
if (! ($page instanceof PageContract) || ! $repository->updatePageDraftData($page, ['html' => ['<p>Draft</p>']])) {
|
||||
throw new RuntimeException('Could not save a draft for the batch publishing test.');
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
function assertPageCreation(bool $condition, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
@@ -710,13 +855,15 @@ $cases = [
|
||||
'name' => 'Missing locale page',
|
||||
'route' => ['en' => '/missing-en', 'de' => '/missing-de'],
|
||||
]));
|
||||
global $phpb_db;
|
||||
$draftPage = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
||||
$repository->updatePageDraftData($draftPage, ['html' => ['<p>Saved draft</p>']]);
|
||||
$pages = $repository->getAll();
|
||||
$pageRows = [];
|
||||
foreach ($pages as $page) {
|
||||
$pageRows[$page->getId()] = $page;
|
||||
}
|
||||
|
||||
global $phpb_db;
|
||||
$pageIds = array_keys($pageRows);
|
||||
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']);
|
||||
$phpb_db->query('DELETE FROM page_translations WHERE page_id = ? AND locale = ?', [$pageIds[2], 'de']);
|
||||
@@ -744,6 +891,7 @@ $cases = [
|
||||
assertPageCreation(str_contains($html, '/complete-de'), 'The page overview did not render the saved German route.');
|
||||
assertPageCreation(str_contains($html, 'New page'), 'The page overview did not render a saved localized title.');
|
||||
assertPageCreation(str_contains($html, '2 / 2 complete'), 'The page overview did not render the translation coverage summary.');
|
||||
assertPageCreation(str_contains($html, 'pagebuilder.draft-available'), 'The page overview did not indicate that a saved draft exists.');
|
||||
},
|
||||
'successful route updates invalidate old and new localized routes' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
@@ -828,6 +976,255 @@ $cases = [
|
||||
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
|
||||
);
|
||||
},
|
||||
'page drafts stay unpublished until promoted and publishing requires a draft' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$repository->create(pageCreationPayload());
|
||||
global $phpb_db;
|
||||
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
||||
$publishedData = ['html' => ['<p>Published</p>']];
|
||||
$draftData = ['html' => ['<p>Draft</p>']];
|
||||
assertPageCreation($repository->updatePageData($page, $publishedData) === true, 'Initial published data could not be saved.');
|
||||
PageCreationTestCache::$invalidatedRoutes = [];
|
||||
|
||||
assertPageCreation($repository->updatePageDraftData($page, $draftData) === true, 'Draft data could not be saved.');
|
||||
assertPageCreation($repository->getPageDraftData($page) === $draftData, 'Saved draft data could not be read back.');
|
||||
assertPageCreation(json_decode($phpb_db->rows('pages')[0]['data'], true) === $publishedData, 'Saving a draft changed the published page data.');
|
||||
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Saving a draft invalidated published page caches.');
|
||||
|
||||
assertPageCreation($repository->publishPageDraft($page) === true, 'A saved draft could not be published.');
|
||||
$pageRow = $phpb_db->rows('pages')[0];
|
||||
assertPageCreation(json_decode($pageRow['data'], true) === $draftData, 'Publishing did not promote the draft into published data.');
|
||||
assertPageCreation($pageRow['draft_data'] === null, 'Publishing did not clear the draft.');
|
||||
assertPageCreation(
|
||||
PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'],
|
||||
'Publishing did not invalidate the localized page caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
|
||||
);
|
||||
|
||||
PageCreationTestCache::$invalidatedRoutes = [];
|
||||
assertPageCreation($repository->publishPageDraft($page) === false, 'Publishing a page without a draft was reported as successful.');
|
||||
assertPageCreation(json_decode($phpb_db->rows('pages')[0]['data'], true) === $draftData, 'Publishing without a draft changed the published data.');
|
||||
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Publishing without a draft invalidated page caches.');
|
||||
|
||||
$schema = require __DIR__ . '/../config/tables.php';
|
||||
assertPageCreation(
|
||||
isset($schema['pages']['columns']['draft_data']) && str_contains(strtoupper($schema['pages']['columns']['draft_data']), 'NULL'),
|
||||
'The pages schema does not declare a nullable draft_data column.'
|
||||
);
|
||||
},
|
||||
'publishing a stale page snapshot preserves the newer draft' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$page = pageCreationAddDraft($repository, 'Concurrent page', '/concurrent');
|
||||
global $phpb_db;
|
||||
$stalePage = $repository->findWithId($page->getId());
|
||||
$newerDraft = ['html' => ['<p>Newer draft</p>']];
|
||||
assertPageCreation($repository->updatePageDraftData($page, $newerDraft), 'The newer draft could not be saved.');
|
||||
|
||||
assertPageCreation($repository->publishPageDraft($stalePage) === false, 'Publishing a stale draft snapshot was not reported as a conflict.');
|
||||
$pageRow = $phpb_db->rows('pages')[0];
|
||||
assertPageCreation($pageRow['draft_data'] === json_encode($newerDraft), 'Publishing a stale draft snapshot erased the newer draft.');
|
||||
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A stale draft snapshot invalidated the page cache.');
|
||||
},
|
||||
'website manager batch publishing promotes every valid draft' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'First page', '/first');
|
||||
pageCreationAddDraft($repository, 'Second page', '/second');
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
|
||||
$result = (new WebsiteManager())->handlePublishAllDrafts();
|
||||
|
||||
assertPageCreation($result === ['total' => 2, 'published' => ['First page', 'Second page'], 'failed' => [], 'cache_warnings' => []], 'Batch publication did not report all successful pages.');
|
||||
global $phpb_db;
|
||||
foreach ($phpb_db->rows('pages') as $pageRow) {
|
||||
assertPageCreation(json_decode($pageRow['data'], true) === ['html' => ['<p>Draft</p>']], 'Batch publication did not promote a page draft.');
|
||||
assertPageCreation($pageRow['draft_data'] === null, 'Batch publication did not clear a successfully published draft.');
|
||||
}
|
||||
assertPageCreation(count(PageCreationTestCache::$invalidatedRoutes) === 4, 'Batch publication did not invalidate routes for both published pages.');
|
||||
},
|
||||
'website manager batch publishing reports partial failures and preserves failed drafts' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$firstPage = pageCreationAddDraft($repository, 'First page', '/first');
|
||||
$secondPage = pageCreationAddDraft($repository, 'Second page', '/second');
|
||||
global $phpb_db, $pageCreationRedirectFlash;
|
||||
$phpb_db->failOnPageUpdateId = (int) $secondPage->getId();
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
$pageCreationRedirectFlash = [];
|
||||
|
||||
try {
|
||||
(new WebsiteManager())->handleRequest('drafts', 'publish_all');
|
||||
throw new RuntimeException('Batch publishing did not redirect after completion.');
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation($exception->redirectUrl === '/website_manager', 'Batch publishing redirected to an unexpected page.');
|
||||
}
|
||||
|
||||
assertPageCreation($pageCreationRedirectFlash['message-type'] === 'warning', 'Partial batch failure did not produce a warning.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Second page'), 'Partial batch feedback did not identify the failed page.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'remain available to retry'), 'Partial batch feedback did not explain that failed drafts are retained.');
|
||||
$rowsById = [];
|
||||
foreach ($phpb_db->rows('pages') as $pageRow) {
|
||||
$rowsById[(int) $pageRow['id']] = $pageRow;
|
||||
}
|
||||
assertPageCreation($rowsById[(int) $firstPage->getId()]['draft_data'] === null, 'The successful page draft was not cleared.');
|
||||
assertPageCreation($rowsById[(int) $secondPage->getId()]['draft_data'] !== null, 'The failed page draft was not preserved for retry.');
|
||||
assertPageCreation(count(PageCreationTestCache::$invalidatedRoutes) === 2, 'Partial batch failure invalidated routes for a failed page.');
|
||||
},
|
||||
'website manager reports a published page when cache invalidation fails' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'Cached page', '/cached');
|
||||
global $phpb_db, $pageCreationRedirectFlash;
|
||||
PageCreationTestCache::$throwOnInvalidate = true;
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
$pageCreationRedirectFlash = [];
|
||||
|
||||
try {
|
||||
(new WebsiteManager())->handleRequest('drafts', 'publish_all');
|
||||
throw new RuntimeException('Batch publishing did not redirect after completion.');
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation($exception->redirectUrl === '/website_manager', 'Batch publishing redirected to an unexpected page.');
|
||||
}
|
||||
|
||||
assertPageCreation($pageCreationRedirectFlash['message-type'] === 'warning', 'A post-save cache failure was not reported as a warning.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Published changes for 1'), 'Cache invalidation failure was reported as an unpublished page.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Cached page'), 'Cache warning did not identify the published page.');
|
||||
$pageRow = $phpb_db->rows('pages')[0];
|
||||
assertPageCreation($pageRow['draft_data'] === null, 'The published draft remained after cache invalidation failed.');
|
||||
assertPageCreation(json_decode($pageRow['data'], true) === ['html' => ['<p>Draft</p>']], 'The saved draft was not published before cache invalidation failed.');
|
||||
},
|
||||
'website manager batch publishing handles the no-draft state' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
|
||||
$result = (new WebsiteManager())->handlePublishAllDrafts();
|
||||
|
||||
assertPageCreation($result === ['total' => 0, 'published' => [], 'failed' => [], 'cache_warnings' => []], 'An empty batch returned unexpected publication results.');
|
||||
},
|
||||
'website manager batch publishing rejects missing and invalid CSRF tokens' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'Protected page', '/protected');
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['valid-token' => time()]];
|
||||
http_response_code(200);
|
||||
|
||||
$_POST = [];
|
||||
assertPageCreation((new WebsiteManager())->handlePublishAllDrafts() === null, 'Batch publication accepted a missing CSRF token.');
|
||||
assertPageCreation(http_response_code() === 403, 'Missing CSRF token did not receive a forbidden response.');
|
||||
|
||||
$_POST = ['_csrf_token' => 'invalid-token'];
|
||||
assertPageCreation((new WebsiteManager())->handlePublishAllDrafts() === null, 'Batch publication accepted an invalid CSRF token.');
|
||||
global $phpb_db;
|
||||
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
||||
http_response_code(200);
|
||||
},
|
||||
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$repository->create(pageCreationPayload([
|
||||
'route' => ['en' => '/new-page', 'de' => '/de/new-page'],
|
||||
]));
|
||||
global $phpb_db;
|
||||
$pageId = $phpb_db->rows('pages')[0]['id'];
|
||||
$page = $repository->findWithId($pageId);
|
||||
$publishedData = ['html' => ['<p>Published</p>']];
|
||||
$draftData = ['html' => ['<p>Draft</p>']];
|
||||
$repository->updatePageData($page, $publishedData);
|
||||
$repository->updatePageDraftData($page, $draftData);
|
||||
$translation = new PageTranslation();
|
||||
$translation->page_id = $pageId;
|
||||
$translation->locale = 'en';
|
||||
$translation->route = '/new-page';
|
||||
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
|
||||
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
|
||||
|
||||
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
||||
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
|
||||
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
|
||||
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
|
||||
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
|
||||
$document = new DOMDocument();
|
||||
@$document->loadHTML($html);
|
||||
$links = [];
|
||||
foreach ($document->getElementsByTagName('a') as $link) {
|
||||
$links[] = $link->getAttribute('href');
|
||||
}
|
||||
assertPageCreation($links[0] === '/about?locale=de&previewToken=valid-token#intro', 'Relative internal link lost its query or fragment while carrying preview mode.');
|
||||
assertPageCreation($links[1] === 'https://example.test/contact?next=1&previewToken=valid-token', 'Absolute same-site link did not carry preview mode.');
|
||||
assertPageCreation($links[2] === 'https://external.test/page?x=1#fragment', 'External link was modified for preview mode.');
|
||||
assertPageCreation($links[3] === '#section', 'Fragment-only link was modified for preview mode.');
|
||||
assertPageCreation($links[4] === '?search=one&previewToken=valid-token', 'Query-only link did not preserve its query while carrying preview mode.');
|
||||
assertPageCreation($links[5] === '/already?x=1&previewToken=valid-token', 'Existing preview token was not replaced while preserving other parameters.');
|
||||
assertPageCreation($links[6] === '\\\\evil.example/path', 'A backslash-prefixed external URL changed during preview serialization.');
|
||||
assertPageCreation($links[7] === '//evil.example/path', 'A tab-prefixed external URL received the preview token or changed destination during serialization.');
|
||||
assertPageCreation($links[8] === '//evil.example/path', 'A space-prefixed external URL received the preview token or changed destination during serialization.');
|
||||
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Preview request accessed the public page cache.');
|
||||
|
||||
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'invalid-token'], true, 'valid-token');
|
||||
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'An invalid preview token exposed the saved draft.');
|
||||
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Invalid-token request accessed the public page cache.');
|
||||
|
||||
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], false, 'valid-token');
|
||||
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'An unauthenticated preview request exposed the saved draft.');
|
||||
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Unauthenticated preview request accessed the public page cache.');
|
||||
|
||||
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, [], false, 'valid-token');
|
||||
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'A public request did not render the published page.');
|
||||
assertPageCreation(count(PageCreationTestCache::$cacheReads) === 1, 'Ordinary published request no longer reads the public cache.');
|
||||
assertPageCreation(count(PageCreationTestCache::$cacheWrites) === 1, 'Ordinary published request no longer stores rendered output.');
|
||||
},
|
||||
'preview link rewriting does not leak tokens through an external base URL' => function (): void {
|
||||
$html = '<!doctype html><html><head><base href="https://external.test/"></head><body>'
|
||||
. '<a href="/relative-link">Relative</a>'
|
||||
. '<a href="https://example.test/absolute-link">Same-site absolute</a>'
|
||||
. '</body></html>';
|
||||
$rewritten = \Plugi\Modules\GrapesJS\PageRenderer::appendPreviewTokenToLinks($html, 'valid-token');
|
||||
$document = new DOMDocument();
|
||||
@$document->loadHTML($rewritten);
|
||||
$links = [];
|
||||
foreach ($document->getElementsByTagName('a') as $link) {
|
||||
$links[] = $link->getAttribute('href');
|
||||
}
|
||||
|
||||
assertPageCreation($links[0] === '/relative-link', 'A relative link under an external base URL received the preview token.');
|
||||
assertPageCreation($links[1] === 'https://example.test/absolute-link?previewToken=valid-token', 'An explicit same-site URL was not preserved as a preview link.');
|
||||
},
|
||||
'authenticated preview redirects preserve tokens only for same-site targets' => function (): void {
|
||||
$checkRedirect = static function (string $target, string $expected): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$repository->create(pageCreationPayload([
|
||||
'type' => 'redirect',
|
||||
'target' => ['en' => $target, 'de' => $target],
|
||||
]));
|
||||
global $phpb_db;
|
||||
$translation = new PageTranslation();
|
||||
$translation->page_id = $phpb_db->rows('pages')[0]['id'];
|
||||
$translation->locale = 'en';
|
||||
$translation->route = '/redirect';
|
||||
$translation->target = $target;
|
||||
|
||||
try {
|
||||
runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
||||
throw new RuntimeException('Redirect page did not redirect.');
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation($exception->redirectUrl === $expected, 'Redirect target did not preserve authenticated preview mode correctly.');
|
||||
}
|
||||
};
|
||||
|
||||
$checkRedirect('/about?locale=de#intro', '/about?locale=de&previewToken=valid-token#intro');
|
||||
$checkRedirect('https://external.test/about?locale=de#intro', 'https://external.test/about?locale=de#intro');
|
||||
},
|
||||
'translation write failures roll back the base page and translations' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
global $phpb_db;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { bindDraftActions } from '../src/Modules/GrapesJS/resources/assets/js/draft-actions.js';
|
||||
|
||||
function button() {
|
||||
let clickHandler;
|
||||
return {
|
||||
addEventListener(eventName, handler) {
|
||||
assert.equal(eventName, 'click');
|
||||
clickHandler = handler;
|
||||
},
|
||||
click() {
|
||||
clickHandler();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('draft action saves edits and publishes only after confirmation', () => {
|
||||
const saveButton = button();
|
||||
const publishButton = button();
|
||||
const actions = [];
|
||||
let confirmation = false;
|
||||
|
||||
bindDraftActions(saveButton, publishButton, publishAfterSave => actions.push(publishAfterSave), () => confirmation);
|
||||
saveButton.click();
|
||||
publishButton.click();
|
||||
confirmation = true;
|
||||
publishButton.click();
|
||||
|
||||
assert.deepEqual(actions, [false, true]);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { bindLanguageSelector } from '../src/Modules/GrapesJS/resources/assets/js/language-selection.js';
|
||||
|
||||
function createHarness(switchSuccess) {
|
||||
let changeHandler;
|
||||
const radios = [
|
||||
{ value: 'en', checked: false },
|
||||
{ value: 'de', checked: true },
|
||||
];
|
||||
const selector = {
|
||||
querySelectorAll(query) {
|
||||
assert.equal(query, 'input[type="radio"]');
|
||||
return radios;
|
||||
},
|
||||
};
|
||||
radios[1].closest = function(query) {
|
||||
if (query === "#language-selector input[type='radio']") return this;
|
||||
if (query === '#language-selector') return selector;
|
||||
throw new Error(`Unexpected selector: ${query}`);
|
||||
};
|
||||
const document = {
|
||||
addEventListener(eventName, handler) {
|
||||
assert.equal(eventName, 'change');
|
||||
changeHandler = handler;
|
||||
},
|
||||
};
|
||||
const calls = { switched: [], activated: [] };
|
||||
const window = {
|
||||
currentLanguage: 'en',
|
||||
switchLanguage(language, callback) {
|
||||
calls.switched.push(language);
|
||||
callback(switchSuccess);
|
||||
},
|
||||
activateLanguage(language) {
|
||||
calls.activated.push(language);
|
||||
this.currentLanguage = language;
|
||||
},
|
||||
};
|
||||
|
||||
bindLanguageSelector(document, window);
|
||||
changeHandler({ target: radios[1] });
|
||||
|
||||
return { calls, radios, window };
|
||||
}
|
||||
|
||||
test('language changes activate the selected language when switching succeeds', () => {
|
||||
const { calls, radios, window } = createHarness(true);
|
||||
|
||||
assert.deepEqual(calls.switched, ['de']);
|
||||
assert.deepEqual(calls.activated, ['de']);
|
||||
assert.equal(window.currentLanguage, 'de');
|
||||
assert.equal(radios[1].checked, true);
|
||||
});
|
||||
|
||||
test('language changes restore the current radio when switching fails', () => {
|
||||
const { calls, radios, window } = createHarness(false);
|
||||
|
||||
assert.deepEqual(calls.switched, ['de']);
|
||||
assert.deepEqual(calls.activated, []);
|
||||
assert.equal(window.currentLanguage, 'en');
|
||||
assert.equal(radios[0].checked, true);
|
||||
assert.equal(radios[1].checked, false);
|
||||
});
|
||||
@@ -19,8 +19,12 @@ test('viewport changes select a device without changing project data or invoking
|
||||
saveCalls++;
|
||||
},
|
||||
};
|
||||
let checkedRadio;
|
||||
const selector = {
|
||||
value: 'Desktop',
|
||||
querySelector(selector) {
|
||||
assert.equal(selector, 'input[type="radio"]:checked');
|
||||
return checkedRadio;
|
||||
},
|
||||
addEventListener(eventName, handler) {
|
||||
assert.equal(eventName, 'change');
|
||||
changeHandler = handler;
|
||||
@@ -29,7 +33,7 @@ test('viewport changes select a device without changing project data or invoking
|
||||
|
||||
bindViewportSelector(editor, selector);
|
||||
for (const device of ['Desktop', 'Tablet', 'Mobile']) {
|
||||
selector.value = device;
|
||||
checkedRadio = { value: device };
|
||||
changeHandler();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
use Plugi\Modules\GrapesJS\Upload\Uploader;
|
||||
|
||||
require_once __DIR__ . '/../src/Modules/GrapesJS/Upload/Uploader.php';
|
||||
|
||||
function assertUploadSecurity(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
$uploadRoot = sys_get_temp_dir() . '/plugi-upload-security-' . bin2hex(random_bytes(8));
|
||||
assertUploadSecurity(mkdir($uploadRoot), 'The upload security test folder could not be created.');
|
||||
|
||||
$outsideFile = dirname($uploadRoot) . '/plugi-upload-escape-' . bin2hex(random_bytes(8)) . '.php';
|
||||
$imagePath = __DIR__ . '/../dist/pagebuilder/images/image-placeholder.png';
|
||||
$traversalUpload = new Uploader([
|
||||
'name' => 'image.png',
|
||||
'tmp_name' => $imagePath,
|
||||
'size' => filesize($imagePath),
|
||||
'error' => UPLOAD_ERR_OK,
|
||||
], false);
|
||||
$traversalUpload
|
||||
->file_name('../' . basename($outsideFile))
|
||||
->upload_to($uploadRoot . '/')
|
||||
->run();
|
||||
assertUploadSecurity(!$traversalUpload->was_uploaded, 'Path traversal destinations must be rejected.');
|
||||
assertUploadSecurity(!file_exists($outsideFile), 'Path traversal must not create files outside the upload folder.');
|
||||
|
||||
$linkedDirectory = $uploadRoot . '/linked';
|
||||
assertUploadSecurity(symlink(dirname($uploadRoot), $linkedDirectory), 'The upload symlink test could not be created.');
|
||||
$symlinkFile = dirname($uploadRoot) . '/plugi-upload-symlink-' . bin2hex(random_bytes(8)) . '.png';
|
||||
$symlinkUpload = new Uploader([
|
||||
'name' => 'image.png',
|
||||
'tmp_name' => $imagePath,
|
||||
'size' => filesize($imagePath),
|
||||
'error' => UPLOAD_ERR_OK,
|
||||
], false);
|
||||
$symlinkUpload
|
||||
->file_name('linked/' . basename($symlinkFile))
|
||||
->upload_to($uploadRoot . '/')
|
||||
->run();
|
||||
assertUploadSecurity(!$symlinkUpload->was_uploaded, 'Symlinked destination folders must be rejected.');
|
||||
assertUploadSecurity(!file_exists($symlinkFile), 'Symlinked destinations must not create files outside the upload folder.');
|
||||
assertUploadSecurity(unlink($linkedDirectory), 'The upload symlink test could not be removed.');
|
||||
|
||||
$scriptUpload = new Uploader([
|
||||
'name' => 'payload.php',
|
||||
'tmp_name' => __FILE__,
|
||||
'size' => filesize(__FILE__),
|
||||
'error' => UPLOAD_ERR_OK,
|
||||
], false);
|
||||
$scriptUpload->MIME_allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'];
|
||||
$scriptUpload
|
||||
->file_name('payload.jpg')
|
||||
->upload_to($uploadRoot . '/')
|
||||
->mime_check()
|
||||
->run();
|
||||
assertUploadSecurity(!$scriptUpload->was_uploaded, 'Non-image uploads must be rejected when image MIME validation is enabled.');
|
||||
|
||||
$uploadRules = file_get_contents(dirname(__DIR__, 2) . '/uploads/.htaccess');
|
||||
assertUploadSecurity(strpos($uploadRules, 'Require all denied') !== false, 'Uploaded PHP scripts must be denied by the Apache upload rules.');
|
||||
assertUploadSecurity(rmdir($uploadRoot), 'The upload security test folder could not be removed.');
|
||||
|
||||
echo "Upload security checks passed.\n";
|
||||
@@ -0,0 +1,17 @@
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine On
|
||||
RewriteRule \.(?:php[0-9]*|phtml|phar)(?:/|$) - [F,NC]
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_authz_core.c>
|
||||
<FilesMatch "(?i)\.(php[0-9]*|phtml|phar)$">
|
||||
Require all denied
|
||||
</FilesMatch>
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_access_compat.c>
|
||||
<FilesMatch "(?i)\.(php[0-9]*|phtml|phar)$">
|
||||
Order allow,deny
|
||||
Deny from all
|
||||
</FilesMatch>
|
||||
</IfModule>
|
||||