Compare commits

...
11 Commits
Author SHA1 Message Date
deepDiverPaul e927c60770 page switching in editor 2026-11-30 16:34:21 +01:00
deepDiverPaul 54525acb03 replace the PageBuilder language and viewport dropdowns with accessible
radio button groups
2026-11-30 13:50:13 +01:00
deepDiverPaul f35aadafe8 improve publishing 2026-11-30 11:33:59 +01:00
deepDiverPaul 50b79fced9 update phosphor icons 2026-11-29 15:25:26 +01:00
deepDiverPaul 45535204a2 add draft/publishing workflow 2026-11-29 09:31:09 +01:00
deepDiverPaul 345a99cf32 Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are
size-bounded and rate-limited
2026-11-28 18:25:41 +01:00
deepDiverPaul cf721b04b0 media-library search, MIME-type and virtual-folder filters, persisted
folder and alt-text editing, and safe defaults for legacy uploads
2026-11-27 19:01:18 +01:00
deepDiverPaul 0a0c2d9d9b add dashboard 2026-11-27 18:01:48 +01:00
deepDiverPaul b8d75c88c2 update docs 2026-11-27 17:23:53 +01:00
deepDiverPaul 1da5895309 Update installation procedure 2026-11-27 17:05:08 +01:00
deepDiverPaul 78a283da6b Update .gitignore 2026-11-26 11:33:43 +01:00
89 changed files with 282761 additions and 34132 deletions
+21 -9
View File
@@ -1,12 +1,24 @@
STAGE=production STAGE=production
BASE_URL=http://localhost:63000 BASE_URL=http://localhost:63000
database_driver = mysql
database_host = mysql DATABASE_DRIVER=mysql
database_database = plugi DATABASE_HOST=mysql
database_username = plugi DATABASE_DATABASE=plugi
database_password = plugi DATABASE_USERNAME=plugi
database_charset = utf8 DATABASE_PASSWORD=change-me
database_collation = utf8_unicode_ci DATABASE_CHARSET=utf8mb4
database_prefix = DATABASE_PREFIX=
MYSQL_ROOT_PASSWORD=change-me-root
USERNAME=admin USERNAME=admin
PASSWORD = admin PASSWORD=
PASSWORD_HASH=
MAIL_HOST=
MAIL_PORT=587
MAIL_ENCRYPTION=tls
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
MAIL_TIMEOUT=10
+6 -2
View File
@@ -12,11 +12,13 @@ dist-ssr
*.local *.local
.env .env
/config.php
/docs
cache cache
uploads uploads/*
!uploads/.htaccess
extensions/dev_* extensions/dev_*
docs
.agents .agents
skills-lock.json skills-lock.json
@@ -31,3 +33,5 @@ skills-lock.json
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
.DS_Store
+1
View File
@@ -27,6 +27,7 @@
RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L] RewriteRule ^themes/([^/]+)/public/(.*)$ themes/$1/public/$2 [L]
# Allow direct access to uploaded files with URL format: /uploads/{filepath;,} # 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] RewriteRule ^uploads/(.*)$ uploads/$1 [L]
# Rewrite all remaining requests to index.php # Rewrite all remaining requests to index.php
+2 -3
View File
@@ -2,9 +2,8 @@ FROM php:8.4-apache-bookworm
WORKDIR "/var/www/html" WORKDIR "/var/www/html"
RUN apt-get update; \ RUN apt-get update; \
docker-php-ext-install pdo pdo_mysql; \ docker-php-ext-install pdo_mysql; \
apt-get -y --no-install-recommends install \ apt-get -y --no-install-recommends install \
git \ git; \
php8.4-mysql; \
apt-get clean; \ apt-get clean; \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+13 -14
View File
@@ -2,24 +2,23 @@
> A fork of [PHPagebuilder](https://github.com/HansSchouten/PHPagebuilder) by [Hans Schouten](https://github.com/HansSchouten). > A fork of [PHPagebuilder](https://github.com/HansSchouten/PHPagebuilder) by [Hans Schouten](https://github.com/HansSchouten).
> Still a work-in-progress Plugi is a website boilerplate with a drag-and-drop page builder.
This boilerplate defines the project structure for quickly creating a website that can be managed with a drag and drop ## Quick installation
pagebuilder.
## Installation 1. Use PHP 8.4 with the PDO MySQL extension and a MySQL 8 database. The supplied Docker image is based on PHP 8.4.
2. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`; set the database connection, public `BASE_URL`, and a unique admin username and password hash in `.env`.
3. Create the database and a database user, deploy the project at the web root, and make `uploads/` writable by the web server.
4. Open the site, sign in at `/admin/auth`, and follow the Website Manager database update prompt to create/update the schema.
To setup your website download the latest version of Plugi and upload it to the webroot directory of your website. See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
### Edit the config file ## Local Docker development
The file `config.php` holds all the basic configuration for your project. Edit as needed. Be sure to update the
login-credentials.
### Login The supplied Compose stack uses PHP 8.4 and MySQL 8.0 and is for local development only. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`, replace the sample database and MySQL root passwords, then run:
Now you should be able to log in to the admin panel by going to the `/admin` URL of your website using `admin` and
`admin` (you can change these in the config file). If you are able to login you can start building your website.
Note: make sure to disable error reporting in `index.php` once your website goes into production! ```sh
docker compose up --build -d
```
## Docker The app is available at `http://localhost:63000`; Adminer is bound to localhost at `http://localhost:63001`.
Simply run `docker-compose up -d` using the supplied `docker-compose.yml`. The image uses PHP 8.2
+55 -56
View File
@@ -9,10 +9,10 @@ return [
| General settings for configuring the PageBuilder. | General settings for configuring the PageBuilder.
| |
*/ */
'general' => [ "general" => [
'language' => 'en', "language" => "en",
'assets_url' => '/plugi-core/dist', "assets_url" => "/plugi-core/dist",
'uploads_url' => '/uploads' "uploads_url" => "/uploads",
], ],
/* /*
@@ -20,12 +20,12 @@ return [
| Storage settings | Storage settings
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Database and file storage settings. | File storage settings.
| |
*/ */
'storage' => [ "storage" => [
'use_database' => true, "use_database" => true,
'uploads_folder' => __DIR__ . '/uploads' "uploads_folder" => __DIR__ . "/uploads",
], ],
/* /*
@@ -37,10 +37,10 @@ return [
| credentials configured in this setting block. | credentials configured in this setting block.
| |
*/ */
'auth' => [ "auth" => [
'use_login' => true, "use_login" => true,
'class' => Plugi\Modules\Auth\Auth::class, "class" => Plugi\Modules\Auth\Auth::class,
'url' => '/admin/auth', "url" => "/admin/auth",
], ],
/* /*
@@ -51,10 +51,10 @@ return [
| By default a basic WebsiteManager is provided for creating/editing pages. | By default a basic WebsiteManager is provided for creating/editing pages.
| |
*/ */
'website_manager' => [ "website_manager" => [
'use_website_manager' => true, "use_website_manager" => true,
'class' => Plugi\Modules\WebsiteManager\WebsiteManager::class, "class" => Plugi\Modules\WebsiteManager\WebsiteManager::class,
'url' => '/admin' "url" => "/admin",
], ],
/* /*
@@ -65,8 +65,8 @@ return [
| By default a setting class is provided for accessing website settings. | By default a setting class is provided for accessing website settings.
| |
*/ */
'setting' => [ "setting" => [
'class' => Plugi\Setting::class "class" => Plugi\Setting::class,
], ],
/* /*
@@ -77,12 +77,12 @@ return [
| By default a PageBuilder is provided based on GrapesJS. | By default a PageBuilder is provided based on GrapesJS.
| |
*/ */
'pagebuilder' => [ "pagebuilder" => [
'class' => Plugi\Modules\GrapesJS\PageBuilder::class, "class" => Plugi\Modules\GrapesJS\PageBuilder::class,
'url' => '/admin/pagebuilder', "url" => "/admin/pagebuilder",
'actions' => [ "actions" => [
'back' => '/admin' "back" => "/admin?tab=pages",
] ],
], ],
/* /*
@@ -93,14 +93,14 @@ return [
| By default a Page class is provided with knowledge about its layout and URL. | By default a Page class is provided with knowledge about its layout and URL.
| |
*/ */
'page' => [ "page" => [
'class' => Plugi\Page::class, "class" => Plugi\Page::class,
'table' => 'pages', "table" => "pages",
'translation' => [ "translation" => [
'class' => Plugi\PageTranslation::class, "class" => Plugi\PageTranslation::class,
'table' => 'page_translations', "table" => "page_translations",
'foreign_key' => 'page_id', "foreign_key" => "page_id",
] ],
], ],
/* /*
@@ -114,10 +114,10 @@ return [
| The cached html is removed if the page is saved again in the page builder. | The cached html is removed if the page is saved again in the page builder.
| |
*/ */
'cache' => [ "cache" => [
'enabled' => false, "enabled" => false,
'folder' => __DIR__ . '/cache', "folder" => __DIR__ . "/cache",
'class' => Plugi\Cache::class "class" => Plugi\Cache::class,
], ],
/* /*
@@ -130,11 +130,11 @@ return [
| containing a view, model (optional) and controller (optional). | containing a view, model (optional) and controller (optional).
| |
*/ */
'theme' => [ "theme" => [
'class' => Plugi\Theme::class, "class" => Plugi\Theme::class,
'folder' => __DIR__ . '/themes', "folder" => __DIR__ . "/themes",
'folder_url' => '/themes', "folder_url" => "/themes",
'active_theme' => 'theme-one' "active_theme" => "theme-one",
], ],
/* /*
@@ -145,8 +145,8 @@ return [
| Settings for resolving pages based on the current URI. | Settings for resolving pages based on the current URI.
| |
*/ */
'router' => [ "router" => [
'class' => Plugi\Modules\Router\DatabasePageRouter::class "class" => Plugi\Modules\Router\DatabasePageRouter::class,
], ],
/* /*
@@ -158,17 +158,17 @@ return [
| blank when the server does not require authentication. | blank when the server does not require authentication.
| |
*/ */
'mail' => [ "mail" => [
'class' => Plugi\Core\Mailer::class, "class" => Plugi\Core\Mailer::class,
'transport' => 'smtp', "transport" => "smtp",
'host' => '', "host" => $_ENV["MAIL_HOST"] ?? "",
'port' => 587, "port" => (int) ($_ENV["MAIL_PORT"] ?? 587),
'encryption' => 'tls', "encryption" => $_ENV["MAIL_ENCRYPTION"] ?? "tls",
'username' => '', "username" => $_ENV["MAIL_USERNAME"] ?? "",
'password' => '', "password" => $_ENV["MAIL_PASSWORD"] ?? "",
'from_address' => '', "from_address" => $_ENV["MAIL_FROM_ADDRESS"] ?? "",
'from_name' => '', "from_name" => $_ENV["MAIL_FROM_NAME"] ?? "",
'timeout' => 10, "timeout" => (int) ($_ENV["MAIL_TIMEOUT"] ?? 10),
], ],
/* /*
@@ -182,6 +182,5 @@ return [
| Important: when overriding a class always extend the original class. | Important: when overriding a class always extend the original class.
| |
*/ */
'class_replacements' => [ "class_replacements" => [],
],
]; ];
+28 -7
View File
@@ -1,3 +1,4 @@
# Development only. Do not use this Compose stack for production deployments.
services: services:
web: web:
build: . build: .
@@ -7,7 +8,28 @@ services:
depends_on: depends_on:
- mysql - mysql
ports: ports:
- '63000:80' - '127.0.0.1:63000:80'
environment:
STAGE: ${STAGE:-production}
BASE_URL: ${BASE_URL:-http://localhost:63000}
DATABASE_DRIVER: ${DATABASE_DRIVER:-mysql}
DATABASE_HOST: ${DATABASE_HOST:-mysql}
DATABASE_DATABASE: ${DATABASE_DATABASE:-plugi}
DATABASE_USERNAME: ${DATABASE_USERNAME:-plugi}
DATABASE_PASSWORD: ${DATABASE_PASSWORD:-change-me}
DATABASE_CHARSET: ${DATABASE_CHARSET:-utf8mb4}
DATABASE_PREFIX: ${DATABASE_PREFIX:-}
USERNAME: ${USERNAME:-admin}
PASSWORD: ${PASSWORD:-}
PASSWORD_HASH: ${PASSWORD_HASH:-}
MAIL_HOST: ${MAIL_HOST:-}
MAIL_PORT: ${MAIL_PORT:-587}
MAIL_ENCRYPTION: ${MAIL_ENCRYPTION:-tls}
MAIL_USERNAME: ${MAIL_USERNAME:-}
MAIL_PASSWORD: ${MAIL_PASSWORD:-}
MAIL_FROM_ADDRESS: ${MAIL_FROM_ADDRESS:-}
MAIL_FROM_NAME: ${MAIL_FROM_NAME:-}
MAIL_TIMEOUT: ${MAIL_TIMEOUT:-10}
links: links:
- mysql - mysql
networks: networks:
@@ -15,7 +37,7 @@ services:
adminer: adminer:
image: adminer image: adminer
ports: ports:
- 63001:8080 - '127.0.0.1:63001:8080'
links: links:
- mysql - mysql
networks: networks:
@@ -24,13 +46,12 @@ services:
image: "mysql:8.0" image: "mysql:8.0"
restart: 'always' restart: 'always'
volumes: volumes:
- '.:/application'
- db:/var/lib/mysql:cached - db:/var/lib/mysql:cached
environment: environment:
- MYSQL_ROOT_PASSWORD=root MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-change-me-root}
- MYSQL_DATABASE=plugi MYSQL_DATABASE: ${DATABASE_DATABASE:-plugi}
- MYSQL_USER=plugi MYSQL_USER: ${DATABASE_USERNAME:-plugi}
- MYSQL_PASSWORD=plugi MYSQL_PASSWORD: ${DATABASE_PASSWORD:-change-me}
# ports: # ports:
# - '63002:3306' # - '63002:3306'
networks: networks:
@@ -7,22 +7,44 @@ use Plugi\Extensions\Form\Finishers\FinishersRepository;
class SubmissionHandler class SubmissionHandler
{ {
public const MAX_REQUEST_BYTES = 65536;
public const MAX_FIELD_BYTES = 16384;
public const MAX_FIELDS = 100;
private $formsRepository; private $formsRepository;
private $finishersRepository; 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->formsRepository = $formsRepository ?? new DefinitionsRepository();
$this->finishersRepository = $finishersRepository ?? new FinishersRepository(); $this->finishersRepository = $finishersRepository ?? new FinishersRepository();
$this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter();
} }
public function handle($formId, string $rawData): array 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); $formId = filter_var($formId, FILTER_VALIDATE_INT);
if ($formId === false || $formId < 1) { if ($formId === false || $formId < 1) {
return $this->failure(400, ['A valid form id is required.']); 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 { try {
$form = $this->formsRepository->findWithId($formId); $form = $this->formsRepository->findWithId($formId);
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
@@ -125,6 +147,10 @@ class SubmissionHandler
$knownFields = []; $knownFields = [];
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select']; $supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
if (count($submittedFields) > self::MAX_FIELDS) {
return ['The submission contains too many fields.'];
}
foreach ($formFields as $field) { 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)) { 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.']; return ['The form contains an invalid field configuration.'];
@@ -160,6 +186,20 @@ class SubmissionHandler
if (!is_string($name) || !array_key_exists($name, $knownFields)) { if (!is_string($name) || !array_key_exists($name, $knownFields)) {
return ['The submission contains an unknown field.']; 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) { 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;
}
}
+11
View File
@@ -35,6 +35,17 @@ return [
], ],
"uniqueKeys" => [], "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" => [ "definitions" => [
"columns" => [ "columns" => [
"name" => "varchar(255) NOT NULL", "name" => "varchar(255) NOT NULL",
+8 -1
View File
@@ -1,7 +1,14 @@
<?php <?php
$handler = new \Plugi\Extensions\Form\SubmissionHandler(); $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']); http_response_code($result['status']);
header('Content-Type: application/json; charset=utf-8'); 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/SendConfirmationEmailToSubmitter.php';
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.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/Finishers/FinishersRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php';
class TestMailer class TestMailer
{ {
@@ -160,6 +161,40 @@ namespace FormExtensionTests {
return ['class' => $this->finishers[$key]]; 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 { namespace Plugi {
@@ -177,6 +212,7 @@ namespace {
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository; use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
use FormExtensionTests\FinishersRepository as TestFinishersRepository; use FormExtensionTests\FinishersRepository as TestFinishersRepository;
use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
use Plugi\Extensions\Form\SubmissionHandler; use Plugi\Extensions\Form\SubmissionHandler;
if (!function_exists('phpb_instance')) { 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 function validForm(array $finishers = []): array
{ {
return [ return [
@@ -223,6 +289,31 @@ namespace {
assertSameValue(true, $result['body']['success'], 'Successful actions must report success'); assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order'); 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['formFinisherCalls'] = [];
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true]; $GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
$result = makeHandler($form)->handle(7, $validPayload); $result = makeHandler($form)->handle(7, $validPayload);
+1 -1
View File
@@ -1,7 +1,7 @@
<?php <?php
require_once __DIR__.'/plugi-core/src/Core/EnvLoader.php'; require_once __DIR__.'/plugi-core/src/Core/EnvLoader.php';
(new Plugi\Core\EnvLoader())->load(); (new Plugi\Core\EnvLoader(__DIR__ . '/.env'))->load();
if ($_ENV['STAGE'] !== 'production') { if ($_ENV['STAGE'] !== 'production') {
ini_set('display_errors', 1); ini_set('display_errors', 1);
+3
View File
@@ -16,6 +16,7 @@ return [
'name' => 'varchar(255)', 'name' => 'varchar(255)',
'layout' => 'varchar(255)', 'layout' => 'varchar(255)',
'data' => 'longtext', 'data' => 'longtext',
'draft_data' => 'longtext NULL',
'type' => 'varchar(63)', 'type' => 'varchar(63)',
'status' => 'varchar(63)', 'status' => 'varchar(63)',
'parent_id' => 'int', 'parent_id' => 'int',
@@ -57,6 +58,8 @@ return [
'original_file' => 'varchar(512)', 'original_file' => 'varchar(512)',
'mime_type' => 'varchar(50)', 'mime_type' => 'varchar(50)',
'server_file' => 'varchar(512)', 'server_file' => 'varchar(512)',
'alt_text' => "varchar(1000) NOT NULL DEFAULT ''",
'folder' => "varchar(255) NOT NULL DEFAULT ''",
], ],
'uniqueKeys' => [ 'uniqueKeys' => [
'public_id' => ['public_id'], 'public_id' => ['public_id'],
+1 -1
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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"}
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.4 MiB

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+8316 -6200
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
+3031 -1255
View File
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
+4505 -3647
View File
File diff suppressed because it is too large Load Diff
+11
View File
@@ -83,6 +83,7 @@ return [
'pagebuilder' => [ 'pagebuilder' => [
'filter-placeholder' => 'Filter', 'filter-placeholder' => 'Filter',
'loading-text' => 'Seiteneditor wird geladen...', 'loading-text' => 'Seiteneditor wird geladen...',
'page-selector' => 'Seite auswählen',
'style-no-element-selected' => 'Wähle ein Element aus um das Aussehen anzupassen.', '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-no-element-selected' => 'Wähle ein Element aus um die Attribute anzupassen',
'trait-settings' => 'Einstellungen', 'trait-settings' => 'Einstellungen',
@@ -91,6 +92,13 @@ return [
'view-settings' => 'Einstellungen', 'view-settings' => 'Einstellungen',
'view-style-manager' => 'Aussehen anpassen', 'view-style-manager' => 'Aussehen anpassen',
'save-page' => 'Speichern', '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', 'view-page' => 'Ansehen',
'go-back' => 'Zurück', 'go-back' => 'Zurück',
'viewport-selector' => 'Vorschauansicht', 'viewport-selector' => 'Vorschauansicht',
@@ -100,7 +108,10 @@ return [
'page' => 'Seite', 'page' => 'Seite',
'page-content' => 'Seiteninhalte', 'page-content' => 'Seiteninhalte',
'toastr-changes-saved' => 'Änderungen gespeichert', '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-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-component-update-failed' => 'Fehler beim Laden',
'toastr-switching-language-failed' => 'Fehler beim Ändern der Sprache', 'toastr-switching-language-failed' => 'Fehler beim Ändern der Sprache',
'yes' => 'Ja', 'yes' => 'Ja',
+11
View File
@@ -83,6 +83,7 @@ return [
'pagebuilder' => [ 'pagebuilder' => [
'filter-placeholder' => 'Filter', 'filter-placeholder' => 'Filter',
'loading-text' => 'Loading pagebuilder..', 'loading-text' => 'Loading pagebuilder..',
'page-selector' => 'Select page',
'style-no-element-selected' => 'Select an element to modify the style.', 'style-no-element-selected' => 'Select an element to modify the style.',
'trait-no-element-selected' => 'Select an element to modify any attributes.', 'trait-no-element-selected' => 'Select an element to modify any attributes.',
'trait-settings' => 'Settings', 'trait-settings' => 'Settings',
@@ -91,6 +92,13 @@ return [
'view-settings' => 'Settings', 'view-settings' => 'Settings',
'view-style-manager' => 'Style Manager', 'view-style-manager' => 'Style Manager',
'save-page' => 'Save', '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', 'view-page' => 'View',
'go-back' => 'Back', 'go-back' => 'Back',
'viewport-selector' => 'Preview viewport', 'viewport-selector' => 'Preview viewport',
@@ -100,7 +108,10 @@ return [
'page' => 'Page', 'page' => 'Page',
'page-content' => 'Page contents', 'page-content' => 'Page contents',
'toastr-changes-saved' => 'Changes saved', '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-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-component-update-failed' => 'Error while reloading component',
'toastr-switching-language-failed' => 'Error while switching language', 'toastr-switching-language-failed' => 'Error while switching language',
'yes' => 'Yes', 'yes' => 'Yes',
+11
View File
@@ -82,6 +82,7 @@ return [
'pagebuilder' => [ 'pagebuilder' => [
'filter-placeholder' => 'Filtrera', 'filter-placeholder' => 'Filtrera',
'loading-text' => 'Laddar sidbyggaren...', 'loading-text' => 'Laddar sidbyggaren...',
'page-selector' => 'Välj sida',
'style-no-element-selected' => 'Välj ett element för att ändra stilen.', '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-no-element-selected' => 'Välj ett element för att ändra dess attribut.',
'trait-settings' => 'Inställningar', 'trait-settings' => 'Inställningar',
@@ -90,6 +91,13 @@ return [
'view-settings' => 'Inställningar', 'view-settings' => 'Inställningar',
'view-style-manager' => 'Stilhanterare', 'view-style-manager' => 'Stilhanterare',
'save-page' => 'Spara', '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', 'view-page' => 'Visa',
'go-back' => 'Tillbaka', 'go-back' => 'Tillbaka',
'viewport-selector' => 'Förhandsgranskningens vy', 'viewport-selector' => 'Förhandsgranskningens vy',
@@ -99,7 +107,10 @@ return [
'page' => 'Sida', 'page' => 'Sida',
'page-content' => 'Sidinnehåll', 'page-content' => 'Sidinnehåll',
'toastr-changes-saved' => 'Ändringarna har sparats', '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-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-component-update-failed' => 'Det gick inte att läsa in komponenten igen',
'toastr-switching-language-failed' => 'Det gick inte att byta språk', 'toastr-switching-language-failed' => 'Det gick inte att byta språk',
'yes' => 'Ja', 'yes' => 'Ja',
+14 -1
View File
@@ -133,6 +133,19 @@ class DB
return $stmt->execute($parameters); 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. * 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); $sanitizedColumn = phpb_remove_non_alpha_numeric($column);
if (empty($sanitizedColumn)) continue; if (empty($sanitizedColumn)) continue;
// Validate column definition against a safe pattern // 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}"); $this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
} }
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) { foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
+234 -82
View File
@@ -9,6 +9,7 @@ use Plugi\Modules\GrapesJS\Block\BlockAdapter;
use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator; use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator;
use Plugi\Modules\GrapesJS\Upload\Uploader; use Plugi\Modules\GrapesJS\Upload\Uploader;
use Plugi\PageTranslationService; use Plugi\PageTranslationService;
use Plugi\Repositories\PageDraftPublishedCacheInvalidationException;
use Plugi\Repositories\PageRepository; use Plugi\Repositories\PageRepository;
use Plugi\Repositories\UploadRepository; use Plugi\Repositories\UploadRepository;
use Exception; use Exception;
@@ -35,9 +36,9 @@ class PageBuilder implements PageBuilderContract
*/ */
public function __construct() public function __construct()
{ {
$this->theme = phpb_instance('theme', [ $this->theme = phpb_instance("theme", [
phpb_config('theme'), phpb_config("theme"),
phpb_config('theme.active_theme') phpb_config("theme.active_theme"),
]); ]);
} }
@@ -64,14 +65,14 @@ class PageBuilder implements PageBuilderContract
{ {
phpb_set_in_editmode(); phpb_set_in_editmode();
if ($route === 'thumb_generator') { if ($route === "thumb_generator") {
$thumbGenerator = new ThumbGenerator($this->theme); $thumbGenerator = new ThumbGenerator($this->theme);
return $thumbGenerator->handleThumbRequest($action); return $thumbGenerator->handleThumbRequest($action);
} }
if (is_null($page)) { if (is_null($page)) {
$pageId = $_GET['page'] ?? null; $pageId = $_GET["page"] ?? null;
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
$page = $pageRepository->findWithId($pageId); $page = $pageRepository->findWithId($pageId);
} }
if (!($page instanceof PageContract)) { if (!($page instanceof PageContract)) {
@@ -80,44 +81,96 @@ class PageBuilder implements PageBuilderContract
switch ($action) { switch ($action) {
case null: case null:
case 'edit': case "edit":
$this->renderPageBuilder($page); $this->renderPageBuilder($page);
exit(); exit();
break; break;
case 'store': case "store":
if (isset($_POST) && isset($_POST['data'])) { if (isset($_POST) && isset($_POST["data"])) {
$data = json_decode($_POST['data'], true); $data = json_decode($_POST["data"], true);
$this->updatePage($page, $data); $this->updatePage($page, $data);
exit(); exit();
} }
break; 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)) { if (isset($_FILES)) {
$this->handleFileUpload(); $this->handleFileUpload();
} }
break; break;
case 'upload_delete': case "upload_delete":
if (isset($_POST['id'])) { if (isset($_POST["id"])) {
$this->handleFileDelete(); $this->handleFileDelete();
} }
break; break;
case 'renderBlock': case "renderBlock":
$language = $this->getValidPostedLanguage(); $language = $this->getValidPostedLanguage();
if ($language === null) { if ($language === null) {
$this->respondToInvalidLanguageRequest(); $this->respondToInvalidLanguageRequest();
} }
if (isset($_POST['data'])) { if (isset($_POST["data"])) {
$this->renderPageBuilderBlock($page, $language, json_decode($_POST['data'], true)); $this->renderPageBuilderBlock(
$page,
$language,
json_decode($_POST["data"], true),
);
exit(); exit();
} }
break; break;
case 'renderLanguageVariant': case "renderLanguageVariant":
$language = $this->getValidPostedLanguage(); $language = $this->getValidPostedLanguage();
if ($language === null) { if ($language === null) {
$this->respondToInvalidLanguageRequest(); $this->respondToInvalidLanguageRequest();
} }
if (isset($_POST['data'])) { if (isset($_POST["data"])) {
$this->renderLanguageVariant($page, $language, json_decode($_POST['data'], true)); $this->renderLanguageVariant(
$page,
$language,
json_decode($_POST["data"], true),
);
exit(); exit();
} }
break; break;
@@ -134,33 +187,65 @@ class PageBuilder implements PageBuilderContract
public function handleFileUpload() public function handleFileUpload()
{ {
$publicId = sha1(uniqid(rand(), true)); $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 $uploader
->file_name($publicId . '/' . str_replace(' ', '-', $uploader->file_src_name)) ->file_name($publicId . "/" . $fileName)
->upload_to(phpb_config('storage.uploads_folder') . '/') ->upload_to(phpb_config("storage.uploads_folder") . "/")
->mime_check()
->run(); ->run();
if (!$uploader->was_uploaded) { if (!$uploader->was_uploaded) {
die("Upload error: {$uploader->error}"); die("Upload error: {$uploader->error}");
} else { } else {
$originalFile = str_replace(' ', '-', $uploader->file_src_name);
$originalMime = $uploader->file_src_mime; $originalMime = $uploader->file_src_mime;
$serverFile = $uploader->final_file_name; $serverFile = $uploader->final_file_name;
$uploadRepository = new UploadRepository; $uploadRepository = new UploadRepository();
$uploadedFile = $uploadRepository->create([ $uploadedFile = $uploadRepository->create([
'public_id' => $publicId, "public_id" => $publicId,
'original_file' => $originalFile, "original_file" => $originalFile,
'mime_type' => $originalMime, "mime_type" => $originalMime,
'server_file' => $serverFile "server_file" => $serverFile,
]); ]);
echo json_encode([ echo json_encode([
'data' => [ "data" => [
'public_id' => $publicId, "public_id" => $publicId,
'src' => $uploadedFile->getUrl(), "src" => $uploadedFile->getUrl(),
'type' => 'image' "type" => "image",
] ],
]); ]);
exit(); exit();
} }
@@ -171,12 +256,15 @@ class PageBuilder implements PageBuilderContract
*/ */
public function handleFileDelete() public function handleFileDelete()
{ {
$uploadRepository = new UploadRepository; $uploadRepository = new UploadRepository();
$uploadedFileResult = $uploadRepository->findWhere('public_id', $_POST['id']); $uploadedFileResult = $uploadRepository->findWhere(
"public_id",
$_POST["id"],
);
if (empty($uploadedFileResult)) { if (empty($uploadedFileResult)) {
echo json_encode([ echo json_encode([
'success' => false, "success" => false,
'message' => 'File not found' "message" => "File not found",
]); ]);
exit(); exit();
} }
@@ -184,18 +272,26 @@ class PageBuilder implements PageBuilderContract
$uploadedFile = $uploadedFileResult[0]; $uploadedFile = $uploadedFileResult[0];
$uploadRepository->destroy($uploadedFile->id); $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) { if ($serverFilePath) {
unlink($serverFilePath); unlink($serverFilePath);
} }
$parentDirectory = realpath(phpb_config('storage.uploads_folder') . '/' . dirname($uploadedFile->server_file)); $parentDirectory = realpath(
if ($parentDirectory && dirname($uploadedFile->server_file) !== '.') { phpb_config("storage.uploads_folder") .
"/" .
dirname($uploadedFile->server_file),
);
if ($parentDirectory && dirname($uploadedFile->server_file) !== ".") {
rmdir($parentDirectory); rmdir($parentDirectory);
} }
echo json_encode([ echo json_encode([
'success' => true "success" => true,
]); ]);
exit(); exit();
} }
@@ -210,16 +306,37 @@ class PageBuilder implements PageBuilderContract
{ {
phpb_set_in_editmode(); 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 // init variables that should be accessible in the view
$pageBuilder = $this; $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()); $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) { if ($currentLanguage !== null) {
$_SESSION['plugi_language'] = $currentLanguage; $_SESSION["plugi_language"] = $currentLanguage;
$pageRenderer->setLanguage($currentLanguage); $pageRenderer->setLanguage($currentLanguage);
} else { } 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 // 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 = []; $blockSettings = [];
foreach ($this->theme->getThemeBlocks() as $themeBlock) { foreach ($this->theme->getThemeBlocks() as $themeBlock) {
$slug = phpb_e($themeBlock->getSlug()); $slug = phpb_e($themeBlock->getSlug());
$adapter = phpb_instance(BlockAdapter::class, [$pageRenderer, $themeBlock]); $adapter = phpb_instance(BlockAdapter::class, [
if ($themeBlock->get('hidden') !== true) { $pageRenderer,
$themeBlock,
]);
if ($themeBlock->get("hidden") !== true) {
$blocks[$slug] = $adapter->getBlockManagerArray(); $blocks[$slug] = $adapter->getBlockManagerArray();
} }
$blockSettings[$slug] = $adapter->getBlockSettingsArray(); $blockSettings[$slug] = $adapter->getBlockSettingsArray();
@@ -236,14 +356,14 @@ class PageBuilder implements PageBuilderContract
// create an array of all uploaded assets // create an array of all uploaded assets
$assets = []; $assets = [];
foreach ((new UploadRepository)->getAll() as $file) { foreach (new UploadRepository()->getAll() as $file) {
$assets[] = [ $assets[] = [
'src' => $file->getUrl(), "src" => $file->getUrl(),
'public_id' => $file->public_id "public_id" => $file->public_id,
]; ];
} }
require __DIR__ . '/resources/views/layout.php'; require __DIR__ . "/resources/views/layout.php";
} }
/** /**
@@ -255,7 +375,10 @@ class PageBuilder implements PageBuilderContract
*/ */
public function renderPage(PageContract $page, $language = null): string public function renderPage(PageContract $page, $language = null): string
{ {
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page]); $pageRenderer = phpb_instance(PageRenderer::class, [
$this->theme,
$page,
]);
if (!is_null($language)) { if (!is_null($language)) {
$pageRenderer->setLanguage($language); $pageRenderer->setLanguage($language);
} }
@@ -270,16 +393,26 @@ class PageBuilder implements PageBuilderContract
* @param array $blockData * @param array $blockData
* @throws Exception * @throws Exception
*/ */
public function renderPageBuilderBlock(PageContract $page, string $language, $blockData = []) public function renderPageBuilderBlock(
{ PageContract $page,
string $language,
$blockData = [],
) {
phpb_set_in_editmode(); phpb_set_in_editmode();
$blockData = is_array($blockData) ? $blockData : []; $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); $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 * @param array $blockData
* @throws Exception * @throws Exception
*/ */
public function renderLanguageVariant(PageContract $page, string $language, $blockData = []) public function renderLanguageVariant(
{ PageContract $page,
string $language,
$blockData = [],
) {
phpb_set_in_editmode(); 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(); $this->respondToInvalidLanguageRequest();
} }
$_SESSION['plugi_language'] = $language; $_SESSION["plugi_language"] = $language;
$blockData = is_array($blockData) ? $blockData : []; $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); $pageRenderer->setLanguage($language);
echo json_encode([ echo json_encode([
'dynamicBlocks' => $pageRenderer->getPageBlocksData()[$language] "dynamicBlocks" => $pageRenderer->getPageBlocksData()[$language],
]); ]);
} }
@@ -315,8 +460,14 @@ class PageBuilder implements PageBuilderContract
*/ */
protected function getValidPostedLanguage(): ?string protected function getValidPostedLanguage(): ?string
{ {
$language = $_POST['language'] ?? null; $language = $_POST["language"] ?? null;
if (! is_string($language) || ! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) { if (
!is_string($language) ||
!new PageTranslationService()->isAvailableLocale(
$language,
array_keys(phpb_active_languages()),
)
) {
return null; return null;
} }
@@ -329,8 +480,8 @@ class PageBuilder implements PageBuilderContract
protected function respondToInvalidLanguageRequest(): void protected function respondToInvalidLanguageRequest(): void
{ {
http_response_code(400); http_response_code(400);
header('Content-Type: application/json'); header("Content-Type: application/json");
echo json_encode(['message' => 'Unsupported language.']); echo json_encode(["message" => "Unsupported language."]);
exit(); exit();
} }
@@ -343,7 +494,7 @@ class PageBuilder implements PageBuilderContract
*/ */
public function updatePage(PageContract $page, $data) public function updatePage(PageContract $page, $data)
{ {
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
return $pageRepository->updatePageData($page, $data); return $pageRepository->updatePageData($page, $data);
} }
@@ -356,12 +507,9 @@ class PageBuilder implements PageBuilderContract
{ {
$pages = []; $pages = [];
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
foreach ($pageRepository->getAll() as $page) { foreach ($pageRepository->getAll() as $page) {
$pages[] = [ $pages[] = [phpb_e($page->getName()), phpb_e($page->getId())];
phpb_e($page->getName()),
phpb_e($page->getId())
];
} }
return $pages; return $pages;
@@ -376,9 +524,13 @@ class PageBuilder implements PageBuilderContract
public function getPageComponents(PageContract $page) public function getPageComponents(PageContract $page)
{ {
$data = $page->getBuilderData(); $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) // 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]; $components = [0 => $components];
} }
return $components; return $components;
@@ -393,8 +545,8 @@ class PageBuilder implements PageBuilderContract
public function getPageStyleComponents(PageContract $page) public function getPageStyleComponents(PageContract $page)
{ {
$data = $page->getBuilderData(); $data = $page->getBuilderData();
if (isset($data['style'])) { if (isset($data["style"])) {
return $data['style']; return $data["style"];
} }
return []; return [];
} }
@@ -408,10 +560,10 @@ class PageBuilder implements PageBuilderContract
public function getPageStyleCss(PageContract $page) public function getPageStyleCss(PageContract $page)
{ {
$data = $page->getBuilderData(); $data = $page->getBuilderData();
if (isset($data['css'])) { if (isset($data["css"])) {
return $data['css']; return $data["css"];
} }
return ''; return "";
} }
/** /**
@@ -440,6 +592,6 @@ class PageBuilder implements PageBuilderContract
if (!is_null($scripts)) { if (!is_null($scripts)) {
$this->scripts[$location] = $scripts; $this->scripts[$location] = $scripts;
} }
return $this->scripts[$location] ?? ''; return $this->scripts[$location] ?? "";
} }
} }
@@ -201,6 +201,113 @@ class PageRenderer
return $pageHtml; 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. * Return the page body for display on the website.
* The body contains all blocks which are put into the selected layout. * The body contains all blocks which are put into the selected layout.
@@ -27,7 +27,6 @@ class Uploader {
$finfo = finfo_open(FILEINFO_MIME_TYPE); $finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo) { if ($finfo) {
$mime = finfo_file($finfo, $filePath); $mime = finfo_file($finfo, $filePath);
finfo_close($finfo);
if (!empty($mime)) { if (!empty($mime)) {
return $mime; return $mime;
} }
@@ -256,6 +255,11 @@ class Uploader {
* @throws Exception * @throws Exception
*/ */
public function run() { public function run() {
$uploadRoot = rtrim($this->upload_to, '/\\');
if ($uploadRoot === '') {
$uploadRoot = DIRECTORY_SEPARATOR;
}
// check whether the final name is in random mode // check whether the final name is in random mode
if ($this->file_name !== true) { if ($this->file_name !== true) {
// preserve file extension if provided // preserve file extension if provided
@@ -264,13 +268,24 @@ class Uploader {
} else { } else {
$file = $this->file_name; $file = $this->file_name;
} }
$path = $this->upload_to . $file;
$this->upload_to = dirname($path);
} else { } else {
$hash = bin2hex(random_bytes(16)); $hash = bin2hex(random_bytes(16));
$file = $hash . '.' . $this->file_src_name_ext; $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; $get_mime = isset($this->mime_check) ? true : false;
@@ -282,6 +297,9 @@ class Uploader {
$this->was_uploaded = false; $this->was_uploaded = false;
$this->error = "Incorrect type of file"; $this->error = "Incorrect type of file";
} }
if (!$this->was_uploaded) {
return false;
}
// check file maximum size // check file maximum size
if ($this->file_src_size > $this->get_file_max_size) { if ($this->file_src_size > $this->get_file_max_size) {
@@ -290,18 +308,6 @@ class Uploader {
return false; 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 // check whether file already exists or if are replacing it
if (file_exists($path)) { if (file_exists($path)) {
if (! $this->get_auto_replace) { if (! $this->get_auto_replace) {
@@ -364,6 +370,60 @@ class Uploader {
return false; 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. * 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. * Switch pagebuilder to another language variant on changing the language selector.
*/ */
document.addEventListener("change", function(e) { bindLanguageSelector(document, window);
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;
}
});
});
/** /**
* Activate the given language variant in the pagebuilder. * 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 sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
const panelsEl = document.querySelector('.gjs-pn-panels'); const panelsEl = document.querySelector('.gjs-pn-panels');
const gjsEl = document.getElementById('gjs'); const gjsEl = document.getElementById('gjs');
const viewportSelector = document.getElementById('viewport-select'); const viewportSelector = document.getElementById('viewport-selector');
if (window.editor) { if (window.editor) {
bindViewportSelector(window.editor, viewportSelector); bindViewportSelector(window.editor, viewportSelector);
@@ -1,4 +1,5 @@
import { bindDraftActions } from './draft-actions.js';
window.pageData = {}; window.pageData = {};
@@ -14,12 +15,13 @@
/** /**
* Save page on clicking save button. * Save page on clicking save button.
*/ */
const savePageBtn = document.getElementById("save-page"); bindDraftActions(
if (savePageBtn) { document.getElementById('save-page'),
savePageBtn.addEventListener('click', function() { document.getElementById('publish-page'),
saveAllTranslationsToServer(); publishAfterSave => saveAllTranslationsToServer(publishAfterSave),
}); () => window.confirm(window.translations['confirm-publish'])
} );
updateDraftStatus(window.draftAvailable);
/** /**
* Save page on Ctrl + S. * Save page on Ctrl + S.
@@ -242,11 +244,14 @@
/** /**
* Save the data of all translation variants on the server. * 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(); toggleSaving();
saveCurrentTranslationLocally(async function() { saveCurrentTranslationLocally(async function() {
try {
// update all language variants with the latest data of the current language we just saved locally // update all language variants with the latest data of the current language we just saved locally
Object.keys(window.languages || {}).forEach(languageCode => { Object.keys(window.languages || {}).forEach(languageCode => {
if (languageCode !== window.currentLanguage) { if (languageCode !== window.currentLanguage) {
@@ -258,14 +263,12 @@
data.style = removeOldStyleSelectors(data.style); data.style = removeOldStyleSelectors(data.style);
data.blocks = window.pageBlocks; data.blocks = window.pageBlocks;
const saveBtn = document.getElementById("save-page"); const saveBtn = document.getElementById('save-page');
const saveUrl = saveBtn ? (saveBtn.dataset.url || saveBtn.getAttribute('data-url')) : ''; const saveUrl = saveBtn ? (saveBtn.dataset.url || saveBtn.getAttribute('data-url')) : '';
const formData = new URLSearchParams(); const formData = new URLSearchParams();
formData.append('data', JSON.stringify(data)); formData.append('data', JSON.stringify(data));
formData.append('_csrf_token', window.csrfToken); formData.append('_csrf_token', window.csrfToken);
try {
const response = await fetch(saveUrl, { const response = await fetch(saveUrl, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -276,32 +279,75 @@
body: formData body: formData
}); });
toggleSaving();
if (!response.ok) { if (!response.ok) {
let errData = {}; throw new Error(response.statusText + ' ' + response.status);
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;
} }
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() { setTimeout(function() {
window.changesOffset = window.editor.getModel().get('changesCount'); window.changesOffset = window.editor.getModel().get('changesCount');
}, 250); }, 250);
} catch(error) { } catch(error) {
toggleSaving();
console.error(error); console.error(error);
window.toastr.error(error.message || '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). * 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() { selector.addEventListener('change', function() {
if (selector.value) { const checkedRadio = selector.querySelector('input[type="radio"]:checked');
editor.setDevice(selector.value); if (checkedRadio && checkedRadio.value) {
editor.setDevice(checkedRadio.value);
} }
}); });
} }
@@ -1,10 +1,11 @@
$sidebar-width: 325px; $sidebar-width: 325px;
$sidebar-bottom-buttons-height: 40px; $sidebar-bottom-buttons-height: 104px;
/* GENERAL */ /* GENERAL */
html, body, #gjs { html,
body,
#gjs {
height: 100% !important; height: 100% !important;
margin: 0; margin: 0;
overflow: hidden; overflow: hidden;
@@ -16,7 +17,8 @@ html, body, #gjs {
box-shadow: none !important; box-shadow: none !important;
} }
.form-control, .form-control:focus { .form-control,
.form-control:focus {
color: #e1e1e1; color: #e1e1e1;
} }
@@ -45,7 +47,9 @@ html, body, #gjs {
width: 100%; width: 100%;
background-color: #fff; background-color: #fff;
z-index: 10000; z-index: 10000;
transition: opacity 0.3s, visibility 0.3s; transition:
opacity 0.3s,
visibility 0.3s;
&.loaded { &.loaded {
visibility: hidden; visibility: hidden;
@@ -77,11 +81,14 @@ html, body, #gjs {
animation: rotate 5s linear infinite; animation: rotate 5s linear infinite;
} }
@keyframes rotate { @keyframes rotate {
100% {transform: rotate(360deg);} 100% {
transform: rotate(360deg);
}
} }
} }
.btn.focus, .btn:focus { .btn.focus,
.btn:focus {
box-shadow: none; box-shadow: none;
} }
@@ -148,7 +155,7 @@ html, body, #gjs {
/* SIDEBAR */ /* SIDEBAR */
.gjs-pn-views { .gjs-pn-views {
top: 40px; top: 80px;
.gjs-pn-btn { .gjs-pn-btn {
width: 33.33%; width: 33.33%;
@@ -228,7 +235,6 @@ html, body, #gjs {
} }
} }
/* SIDEBAR FIELDS */ /* SIDEBAR FIELDS */
.gjs-three-bg { .gjs-three-bg {
@@ -256,21 +262,18 @@ html, body, #gjs {
} }
} }
/* SIDEBAR HEADER */ /* SIDEBAR HEADER */
#sidebar-header { #sidebar-header {
position: absolute; position: absolute;
box-shadow: none; box-shadow: none;
width: $sidebar-width; width: $sidebar-width;
padding: 0 10px; height: 80px;
background: #22272e; background: #22272e;
height: 40px;
z-index: 100; z-index: 100;
display: flex;
align-items: center;
#language-selector, #viewport-selector { #language-selector,
#viewport-selector {
margin-left: auto; margin-left: auto;
select { select {
@@ -299,14 +302,13 @@ html, body, #gjs {
border-radius: 0; border-radius: 0;
border: none; border: none;
cursor: pointer; cursor: pointer;
height: 40px; height: 36px;
width: 40px; width: 40px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
} }
/* BLOCKS PANEL VIEW */ /* BLOCKS PANEL VIEW */
#block-search { #block-search {
@@ -392,7 +394,6 @@ html, body, #gjs {
border-bottom: none !important; border-bottom: none !important;
} }
/* LAYERS PANEL VIEW */ /* LAYERS PANEL VIEW */
.gjs-layer .gjs-layer-title { .gjs-layer .gjs-layer-title {
@@ -402,7 +403,7 @@ html, body, #gjs {
background-color: #0091d1 !important; background-color: #0091d1 !important;
} }
.gjs-layer.gjs-hovered .gjs-layer-title { .gjs-layer.gjs-hovered .gjs-layer-title {
background-color: #0091d170 !important background-color: #0091d170 !important;
} }
.gjs-category-title, .gjs-category-title,
.gjs-sm-sector .gjs-sm-title, .gjs-sm-sector .gjs-sm-title,
@@ -428,17 +429,15 @@ html, body, #gjs {
display: none; display: none;
} }
.gjs-layer-vis { .gjs-layer-vis {
padding-top: 11px padding-top: 11px;
} }
/* LAYERS PANEL VIEW */ /* LAYERS PANEL VIEW */
.gjs-sm-sector.gjs-sm-open { .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 */ /* TRAITS PANEL VIEW */
.gjs-trt-trait { .gjs-trt-trait {
@@ -505,45 +504,18 @@ html, body, #gjs {
} }
} }
/* SIDEBAR BOTTOM BUTTONS */ /* SIDEBAR BOTTOM BUTTONS */
#sidebar-bottom-buttons { #sidebar-bottom-buttons {
position: absolute; position: absolute;
left: 0; left: 0;
bottom: 0; bottom: 0;
height: $sidebar-bottom-buttons-height;
width: $sidebar-width; width: $sidebar-width;
margin: 0; margin: 0;
padding: 0; padding: 4px;
background: #474c57; background: #474c57;
border-top: none; border-top: none;
display: flex; 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;
&:hover {
background: #017eb5;
color: #fff;
}
&:first-child {
border-left: none;
}
}
button.waiting { button.waiting {
background: #0091d1; background: #0091d1;
@@ -562,9 +534,9 @@ html, body, #gjs {
} }
} }
@import 'fields'; @import "fields";
@import 'style-manager'; @import "style-manager";
@import 'asset-manager'; @import "asset-manager";
.gjs-link-modal-form { .gjs-link-modal-form {
color: #d1d5db; color: #d1d5db;
@@ -8,34 +8,52 @@
</div> </div>
</div> </div>
<div class="text"> <div class="text">
<?= phpb_trans('pagebuilder.loading-text') ?> <?= phpb_trans("pagebuilder.loading-text") ?>
</div> </div>
</div> </div>
</div> </div>
<div id="gjs"></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"> <script type="text/javascript">
window.languages = <?= json_encode(phpb_active_languages()) ?>; window.languages = <?= json_encode(phpb_active_languages()) ?>;
window.currentLanguage = <?= json_encode($currentLanguage) ?>; window.currentLanguage = <?= json_encode($currentLanguage) ?>;
window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>; window.translations = <?= json_encode(phpb_trans("pagebuilder")) ?>;
window.contentContainerComponents = <?= json_encode($pageBuilder->getPageComponents($page)) ?>; window.contentContainerComponents = <?= json_encode(
$pageBuilder->getPageComponents($page),
) ?>;
window.themeBlocks = <?= json_encode($blocks) ?>; window.themeBlocks = <?= json_encode($blocks) ?>;
window.blockSettings = <?= json_encode($blockSettings) ?>; window.blockSettings = <?= json_encode($blockSettings) ?>;
window.pageBlocks = <?= json_encode($pageRenderer->getPageBlocksData()) ?>; window.pageBlocks = <?= json_encode($pageRenderer->getPageBlocksData()) ?>;
window.pages = <?= json_encode($pageBuilder->getPages()) ?>; window.pages = <?= json_encode($pageBuilder->getPages()) ?>;
window.renderBlockUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderBlock', 'page' => $page->getId()]) ?>'; window.renderBlockUrl = '<?= phpb_url("pagebuilder", [
window.injectionScriptUrl = '<?= phpb_asset('pagebuilder/page-injection.js') ?>'; "action" => "renderBlock",
window.renderLanguageVariantUrl = '<?= phpb_url('pagebuilder', ['action' => 'renderLanguageVariant', 'page' => $page->getId()]) ?>'; "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()) ?>'; window.csrfToken = '<?= phpb_e(\Plugi\Core\Csrf::getToken()) ?>';
<?php <?php
$config = require __DIR__ . '/grapesjs/config.php'; $config = require __DIR__ . "/grapesjs/config.php";
// Add CSRF token header to GrapesJS file uploads // Add CSRF token header to GrapesJS file uploads
$config['assetManager']['headers'] = [ $config["assetManager"]["headers"] = [
'X-CSRF-Token' => \Plugi\Core\Csrf::getToken() "X-CSRF-Token" => \Plugi\Core\Csrf::getToken(),
]; ];
?> ?>
let config = <?= json_encode($config) ?>; let config = <?= json_encode($config) ?>;
@@ -54,30 +72,38 @@ if (window.customConfig !== undefined) {
} }
window.initialComponents = <?= json_encode($pageRenderer->render()) ?>; 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.initialCss = <?= json_encode($pageBuilder->getPageStyleCss($page)) ?>;
window.grapesJSTranslations = { window.grapesJSTranslations = {
<?= $currentLanguage ?>: { <?= $currentLanguage ?>: {
styleManager: { styleManager: {
empty: '<?= phpb_trans('pagebuilder.style-no-element-selected') ?>' empty: '<?= phpb_trans("pagebuilder.style-no-element-selected") ?>'
}, },
traitManager: { traitManager: {
empty: '<?= phpb_trans('pagebuilder.trait-no-element-selected') ?>', empty: '<?= phpb_trans("pagebuilder.trait-no-element-selected") ?>',
label: '<?= phpb_trans('pagebuilder.trait-settings') ?>', label: '<?= phpb_trans("pagebuilder.trait-settings") ?>',
traits: { traits: {
options: { options: {
target: { target: {
false: '<?= phpb_trans('pagebuilder.no') ?>', false: '<?= phpb_trans("pagebuilder.no") ?>',
_blank: '<?= phpb_trans('pagebuilder.yes') ?>' _blank: '<?= phpb_trans("pagebuilder.yes") ?>'
} }
} }
} }
}, },
assetManager: { assetManager: {
addButton: '<?= phpb_trans('pagebuilder.asset-manager.add-image') ?>', addButton: '<?= phpb_trans(
"pagebuilder.asset-manager.add-image",
) ?>',
inputPlh: 'http://path/to/the/image.jpg', inputPlh: 'http://path/to/the/image.jpg',
modalTitle: '<?= phpb_trans('pagebuilder.asset-manager.modal-title') ?>', modalTitle: '<?= phpb_trans(
uploadTitle: '<?= phpb_trans('pagebuilder.asset-manager.drop-files') ?>' "pagebuilder.asset-manager.modal-title",
) ?>',
uploadTitle: '<?= phpb_trans(
"pagebuilder.asset-manager.drop-files",
) ?>'
} }
} }
}; };
@@ -94,64 +120,133 @@ window.editor.setStyle(window.initialStyle);
</script> </script>
<?php <?php
require __DIR__ . '/grapesjs/asset-manager.php'; require __DIR__ . "/grapesjs/asset-manager.php";
require __DIR__ . '/grapesjs/component-type-manager.php'; require __DIR__ . "/grapesjs/component-type-manager.php";
require __DIR__ . '/grapesjs/style-manager.php'; require __DIR__ . "/grapesjs/style-manager.php";
require __DIR__ . '/grapesjs/trait-manager.php'; require __DIR__ . "/grapesjs/trait-manager.php";
?> ?>
<button id="toggle-sidebar" class="btn btn-sm btn-ghost"> <button id="toggle-sidebar" class="btn btn-sm btn-ghost">
<i class="fa fa-bars"></i> <i class="fa fa-bars"></i>
</button> </button>
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 px-2"> <div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 p-2">
<?php <?php if (sizeof(phpb_active_languages()) > 1): ?>
if (sizeof(phpb_active_languages()) > 1): <div class="flex-grow"></div>
?>
<div id="language-selector"> <div id="language-selector">
<select class="select select-xs w-24 text-xs"> <fieldset>
<?php <legend class="sr-only"><?= phpb_e(
foreach (phpb_active_languages() as $languageCode => $languageTranslation): phpb_trans("website-manager.website-languages"),
?> ) ?></legend>
<option value="<?= phpb_e($languageCode) ?>" <?= $languageCode === $currentLanguage ? 'selected' : '' ?>> <div class="join">
<?= phpb_e(strtoupper($languageCode)) ?> - <?= phpb_e($languageTranslation) ?> <?php foreach (
</option> array_keys(phpb_active_languages())
<?php as $languageCode
endforeach; ): ?>
?> <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">
</select> <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> </div>
<?php </fieldset>
endif; </div>
?> <?php endif; ?>
<div id="viewport-selector" class="ml-auto"> <fieldset id="viewport-selector" class="ml-auto">
<label class="sr-only" for="viewport-select"><?= phpb_trans('pagebuilder.viewport-selector') ?></label> <legend class="sr-only"><?= phpb_e(
<select id="viewport-select" class="select select-xs w-28 text-xs" aria-label="<?= phpb_e(phpb_trans('pagebuilder.viewport-selector')) ?>"> phpb_trans("pagebuilder.viewport-selector"),
<option value="Desktop"><?= phpb_trans('pagebuilder.viewport-desktop') ?></option> ) ?></legend>
<option value="Tablet"><?= phpb_trans('pagebuilder.viewport-tablet') ?></option> <div class="join">
<option value="Mobile"><?= phpb_trans('pagebuilder.viewport-mobile') ?></option> <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> </select>
</div> </div>
</div> </div>
<div id="sidebar-bottom-buttons" class="flex items-center justify-between"> <div id="sidebar-bottom-buttons" class="grid grid-cols-2 gap-1 p-1">
<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 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> <span class="loading loading-spinner loading-xs" style="display: none;" role="status" aria-hidden="true"></span>
<i class="fa fa-save"></i> <i class="fa fa-save"></i>
<span><?= phpb_trans('pagebuilder.save-page') ?></span> <span><?= phpb_trans("pagebuilder.save-draft") ?></span>
</button> </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> <i class="fa fa-external-link"></i>
<span><?= phpb_trans('pagebuilder.view-page') ?></span> <span><?= phpb_trans("pagebuilder.preview-draft") ?></span>
</a> </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> <i class="fa fa-arrow-circle-left"></i>
<span><?= phpb_trans('pagebuilder.go-back') ?></span> <span><?= phpb_trans("pagebuilder.go-back") ?></span>
</a> </a>
</div> </div>
<div id="block-search"> <div id="block-search">
<i class="fa fa-search"></i> <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> </div>
@@ -7,6 +7,7 @@ use Plugi\Contracts\WebsiteManagerContract;
use Plugi\Extensions; use Plugi\Extensions;
use Plugi\PageTranslationService; use Plugi\PageTranslationService;
use Plugi\Repositories\MenuRepository; use Plugi\Repositories\MenuRepository;
use Plugi\Repositories\PageDraftPublishedCacheInvalidationException;
use Plugi\Repositories\PageRepository; use Plugi\Repositories\PageRepository;
use Plugi\Repositories\SettingRepository; use Plugi\Repositories\SettingRepository;
use Plugi\Repositories\UploadRepository; use Plugi\Repositories\UploadRepository;
@@ -26,83 +27,243 @@ class WebsiteManager implements WebsiteManagerContract
exit(); exit();
} }
if ($route === 'quality' && $action === 'scan' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') { if ($route === "media" && $action === "update_metadata") {
if (! function_exists('phpb_validate_csrf') || ! phpb_validate_csrf()) { if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(403); http_response_code(405);
die('Invalid CSRF token. Please refresh the page and try again.'); exit();
} }
$_GET['tab'] = 'quality'; $this->handleUpdateMediaMetadata();
$this->renderQualityChecks((new SiteQualityCheckService())->run());
exit(); exit();
} }
if ($route === 'settings') { if ($route === "drafts" && $action === "publish_all") {
if ($action === 'renderBlockThumbs') { $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(); $this->renderBlockThumbs();
exit(); exit();
} }
if ($action === 'update') { if ($action === "update") {
$this->handleUpdateSettings(); $this->handleUpdateSettings();
exit(); exit();
} }
} }
if ($route === 'menus') { if ($route === "menus") {
if ($action === 'update') { if ($action === "update") {
$this->handleUpdateMenus(); $this->handleUpdateMenus();
exit(); exit();
} }
} }
if ($route === 'database') { if ($route === "database") {
if ($action === 'update') { if ($action === "update") {
$this->handleUpdateDB(); $this->handleUpdateDB();
exit(); exit();
} }
} }
if ($route === 'page_settings') { if ($route === "page_settings") {
if ($action === 'create') { if ($action === "create") {
$this->handleCreate(); $this->handleCreate();
exit(); exit();
} }
$pageId = $_GET['page'] ?? null; $pageId = $_GET["page"] ?? null;
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
$page = $pageRepository->findWithId($pageId); $page = $pageRepository->findWithId($pageId);
if (!($page instanceof PageContract)) { if (!($page instanceof PageContract)) {
phpb_redirect(phpb_url('website_manager')); phpb_redirect(phpb_url("website_manager"));
} }
if ($action === 'edit') { if ($action === "edit") {
$this->handleEdit($page); $this->handleEdit($page);
exit(); exit();
} else if ($action === 'destroy') { } elseif ($action === "destroy") {
$this->handleDestroy($page); $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. * Handle requests for creating a new page.
*/ */
public function handleCreate() public function handleCreate()
{ {
$errorMessage = null; $errorMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER["REQUEST_METHOD"] === "POST") {
try { try {
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
$page = $pageRepository->create($_POST); $page = $pageRepository->create($_POST);
} catch (\Throwable) { } catch (\Throwable) {
$page = false; $page = false;
} }
if ($page) { if ($page) {
phpb_redirect(phpb_url('website_manager'), [ phpb_redirect(phpb_url("website_manager"), [
'message-type' => 'success', "message-type" => "success",
'message' => phpb_trans('website-manager.page-created') "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); $this->renderPageSettings(null, $errorMessage);
@@ -115,13 +276,13 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function handleEdit(PageContract $page) public function handleEdit(PageContract $page)
{ {
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER["REQUEST_METHOD"] === "POST") {
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
$success = $pageRepository->update($page, $_POST); $success = $pageRepository->update($page, $_POST);
if ($success) { if ($success) {
phpb_redirect(phpb_url('website_manager'), [ phpb_redirect(phpb_url("website_manager"), [
'message-type' => 'success', "message-type" => "success",
'message' => phpb_trans('website-manager.page-updated') "message" => phpb_trans("website-manager.page-updated"),
]); ]);
} }
} }
@@ -136,16 +297,16 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function handleDestroy(PageContract $page) public function handleDestroy(PageContract $page)
{ {
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
if (!$pageRepository->destroy($page->getId())) { if (!$pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url('website_manager'), [ phpb_redirect(phpb_url("website_manager"), [
'message-type' => 'error', "message-type" => "error",
'message' => phpb_trans('website-manager.page-delete-failed') "message" => phpb_trans("website-manager.page-delete-failed"),
]); ]);
} }
phpb_redirect(phpb_url('website_manager'), [ phpb_redirect(phpb_url("website_manager"), [
'message-type' => 'success', "message-type" => "success",
'message' => phpb_trans('website-manager.page-deleted') "message" => phpb_trans("website-manager.page-deleted"),
]); ]);
} }
@@ -154,14 +315,19 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function handleUpdateSettings() public function handleUpdateSettings()
{ {
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER["REQUEST_METHOD"] === "POST") {
$settingRepository = new SettingRepository; $settingRepository = new SettingRepository();
$success = $settingRepository->updateSettings($_POST); $success = $settingRepository->updateSettings($_POST);
if ($success) { if ($success) {
phpb_redirect(phpb_url('website_manager', ['tab' => 'settings']), [ phpb_redirect(
'message-type' => 'success', phpb_url("website_manager", ["tab" => "settings"]),
'message' => phpb_trans('website-manager.settings-updated') [
]); "message-type" => "success",
"message" => phpb_trans(
"website-manager.settings-updated",
),
],
);
} }
} }
} }
@@ -171,13 +337,13 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function handleUpdateMenus() public function handleUpdateMenus()
{ {
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER["REQUEST_METHOD"] === "POST") {
$settingRepository = new MenuRepository; $settingRepository = new MenuRepository();
$success = $settingRepository->updateMenus($_POST); $success = $settingRepository->updateMenus($_POST);
if ($success) { if ($success) {
phpb_redirect(phpb_url('website_manager', ['tab' => 'menus']), [ phpb_redirect(phpb_url("website_manager", ["tab" => "menus"]), [
'message-type' => 'success', "message-type" => "success",
'message' => phpb_trans('website-manager.menus-updated') "message" => phpb_trans("website-manager.menus-updated"),
]); ]);
} }
} }
@@ -189,11 +355,11 @@ class WebsiteManager implements WebsiteManagerContract
public function handleUpdateDB() public function handleUpdateDB()
{ {
global $phpb_db; global $phpb_db;
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER["REQUEST_METHOD"] === "POST") {
$phpb_db->resolveDiffDB(); $phpb_db->resolveDiffDB();
phpb_redirect(phpb_url('website_manager', ['tab' => 'info']), [ phpb_redirect(phpb_url("website_manager", ["tab" => "info"]), [
'message-type' => 'success', "message-type" => "success",
'message' => phpb_trans('website-manager.db-updated') "message" => phpb_trans("website-manager.db-updated"),
]); ]);
} }
} }
@@ -203,34 +369,72 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function renderOverview() public function renderOverview()
{ {
$pageRepository = new PageRepository; $pageRepository = new PageRepository();
$pages = $pageRepository->getAll(); $pages = $pageRepository->getAll();
uasort($pages, function ($a, $b) { uasort($pages, function ($a, $b) {
return ($a->getRoute() < $b->getRoute()) ? -1 : 1; return $a->getRoute() < $b->getRoute() ? -1 : 1;
}); });
$activeLanguages = phpb_active_languages(); $draftPages = [];
$pageTranslationCoverage = (new PageTranslationService())->getPageCoverage($pages, $activeLanguages); 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(); $files = $filesRepository->getAll();
$menuRepository = new MenuRepository; $menuRepository = new MenuRepository();
$menus = $menuRepository->getHydratedMenus(); $menus = $menuRepository->getHydratedMenus();
$menusJson = json_encode($menus); $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 = []; $menuPages = [];
foreach ($pages as $page) { foreach ($pages as $page) {
$menuPages[] = [ $menuPages[] = [
'id' => $page->getId(), "id" => $page->getId(),
'title' => $page->getName(), "title" => $page->getName(),
'route' => $page->getRoute() "route" => $page->getRoute(),
]; ];
} }
$menuPagesJson = json_encode($menuPages); $menuPagesJson = json_encode($menuPages);
$viewFile = 'overview'; $viewFile = "overview";
require __DIR__ . '/resources/layouts/master.php'; require __DIR__ . "/resources/layouts/master.php";
} }
/** /**
@@ -238,8 +442,8 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function renderQualityChecks(?array $qualityReport = null) public function renderQualityChecks(?array $qualityReport = null)
{ {
$viewFile = 'overview'; $viewFile = "overview";
require __DIR__ . '/resources/layouts/master.php'; require __DIR__ . "/resources/layouts/master.php";
} }
/** /**
@@ -247,16 +451,18 @@ class WebsiteManager implements WebsiteManagerContract
* *
* @param PageContract $page * @param PageContract $page
*/ */
public function renderPageSettings(?PageContract $page = null, ?string $errorMessage = null) public function renderPageSettings(
{ ?PageContract $page = null,
$action = isset($page) ? 'edit' : 'create'; ?string $errorMessage = null,
$theme = phpb_instance('theme', [ ) {
phpb_config('theme'), $action = isset($page) ? "edit" : "create";
phpb_config('theme.active_theme') $theme = phpb_instance("theme", [
phpb_config("theme"),
phpb_config("theme.active_theme"),
]); ]);
$viewFile = 'page-settings'; $viewFile = "page-settings";
require __DIR__ . '/resources/layouts/master.php'; require __DIR__ . "/resources/layouts/master.php";
} }
/** /**
@@ -264,8 +470,8 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function renderMenuSettings() public function renderMenuSettings()
{ {
$viewFile = 'menu-settings'; $viewFile = "menu-settings";
require __DIR__ . '/resources/layouts/master.php'; require __DIR__ . "/resources/layouts/master.php";
} }
/** /**
@@ -273,8 +479,8 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function renderBlockThumbs() public function renderBlockThumbs()
{ {
$viewFile = 'block-thumbs'; $viewFile = "block-thumbs";
require __DIR__ . '/resources/layouts/master.php'; require __DIR__ . "/resources/layouts/master.php";
} }
/** /**
@@ -282,7 +488,7 @@ class WebsiteManager implements WebsiteManagerContract
*/ */
public function renderWelcomePage() public function renderWelcomePage()
{ {
$viewFile = 'welcome'; $viewFile = "welcome";
require __DIR__ . '/resources/layouts/empty.php'; require __DIR__ . "/resources/layouts/empty.php";
} }
} }
@@ -1,6 +1,11 @@
<?php <?php
return [ return [
'dashboard' => [
'title' => 'Dashboard',
'include' => __DIR__ . '/dashboard.php',
'icon' => '<i class="ph ph-squares-four"></i>',
],
'pages' => [ 'pages' => [
'title' => phpb_trans('website-manager.pages'), 'title' => phpb_trans('website-manager.pages'),
'include' => __DIR__ . '/pages.php', '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"> <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="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"> <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> <p class="mt-1 text-sm text-base-content/60">Your uploaded files will appear here as a visual library.</p>
</div> </div>
<?php else : ?> <?php else : ?>
<ul class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"> <section class="space-y-4" aria-label="Filter media library">
<?php foreach ($files as $file) : ?> <div class="grid gap-3 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] md:items-end">
<li class="card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md"> <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"> <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"> <?php if ($mediaFile['isImage']) : ?>
<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')) ?>"> <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> <i class="ph-duotone ph-trash" aria-hidden="true"></i>
</button> </button>
</figure> </figure>
<div class="card-body gap-1 p-3"> <div class="card-body gap-3 p-3">
<p class="truncate text-sm font-medium" title="<?= phpb_e($file->public_id) ?>"><?= phpb_e($file->public_id) ?></p> <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> </div>
</li> </li>
<?php endforeach; ?> <?php endforeach; ?>
</ul> </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; ?> <?php endif; ?>
</div> </div>
</section> </section>
<script> <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() { async function uploadFile() {
let formData = new FormData(); let formData = new FormData();
const fileupload = document.getElementById('fileupload'); const fileupload = document.getElementById('fileupload');
@@ -4,9 +4,12 @@
<h2 class="text-xl font-bold tracking-tight text-base-content">Your pages</h2> <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> <p class="text-sm text-base-content/60">Review routes and open the page editor or page settings.</p>
</div> </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> <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> </a>
</header> </header>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100"> <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
@@ -14,10 +17,11 @@
<thead> <thead>
<tr> <tr>
<th class="w-16">ID</th> <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>Localized titles and routes</th>
<th>Coverage</th> <th class="w-44"><?= phpb_trans(
<th class="w-44"><?= phpb_trans('website-manager.actions') ?></th> "website-manager.actions",
) ?></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -35,67 +39,137 @@
<?php foreach ($pages as $page): ?> <?php foreach ($pages as $page): ?>
<?php <?php
$pageRoute = $page->getRoute(); $pageRoute = $page->getRoute();
$canViewPage = $page->get('type') !== 'redirect' && is_string($pageRoute) && $pageRoute !== ''; $canViewPage =
$page->get("type") !== "redirect" &&
is_string($pageRoute) &&
$pageRoute !== "";
?> ?>
<tr> <tr>
<td><?= phpb_e($page->getId()) ?></td> <td><?= phpb_e($page->getId()) ?></td>
<td class="font-medium"><?= phpb_e($page->getName()) ?></td>
<td> <td>
<div class="grid gap-2 sm:grid-cols-2"> <div class="flex flex-wrap items-center gap-2">
<?php foreach ($activeLanguages as $languageCode => $languageTranslation): ?> <span class="font-medium"><?= phpb_e(
<?php $page->getName(),
$localeCoverage = $pageTranslationCoverage[$page->getId()]['locales'][$languageCode] ?? null; ) ?></span>
$localeExists = $localeCoverage['exists'] ?? false; <?php if ($page->get("draft_data") !== null): ?>
$localeComplete = $localeCoverage['complete'] ?? false; <div class="tooltip" data-tip="<?= phpb_trans(
$localeStatus = $localeComplete ? 'Complete' : ($localeExists ? 'Needs attention' : 'Missing'); "pagebuilder.draft-available",
$localeBadgeClass = $localeComplete ? 'badge-success' : ($localeExists ? 'badge-warning' : 'badge-error'); ) ?>">
$localeTitle = $localeCoverage['title'] ?? null; <span class="badge badge-sm badge-warning"><i class="ph-bold ph-git-diff"></i></span>
$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>
</span>
<span class="badge badge-sm <?= $localeBadgeClass ?>"><?= $localeStatus ?></span>
</div> </div>
<p class="truncate text-sm font-medium" title="<?= phpb_e($localeTitle) ?>"> <?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");
?>
<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>
</div>
<p class="truncate text-sm font-medium" title="<?= phpb_e(
$localeTitle,
) ?>">
<?= $localeTitleLabel ?> <?= $localeTitleLabel ?>
</p> </p>
<p class="break-all font-mono text-xs text-base-content/60" title="<?= phpb_e($localeRoute) ?>"> <p class="break-all font-mono text-sm text-base-content/60" title="<?= phpb_e(
<?= is_string($localeRoute) && trim($localeRoute) !== '' ? phpb_e($localeRoute) : 'Route not set' ?> $localeRoute,
) ?>">
<?= is_string($localeRoute) &&
trim($localeRoute) !== ""
? phpb_e($localeRoute)
: "Route not set" ?>
</p> </p>
</div> </div>
<?php endforeach; ?> <?php endforeach; ?>
</div> </div>
</td> </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> <td>
<div class="flex items-center gap-1"> <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> <i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i>
</a> </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> <i class="text-xl ph-duotone ph-pencil-line" aria-hidden="true"></i>
</a> </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> <i class="text-xl ph-duotone ph-gear" aria-hidden="true"></i>
</a> </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> <i class="text-xl ph-duotone ph-trash" aria-hidden="true"></i>
</a> </a>
</div> </div>
+61 -14
View File
@@ -26,13 +26,15 @@ class Page implements PageContract
public function setData($data, $fullOverwrite = true) public function setData($data, $fullOverwrite = true)
{ {
// if page builder data is set, try to decode json // if page builder data is set, try to decode json
if (isset($data['data']) && is_string($data['data'])) { if (isset($data["data"]) && is_string($data["data"])) {
$data['data'] = json_decode($data['data'], true); $data["data"] = json_decode($data["data"], true);
} }
if ($fullOverwrite) { if ($fullOverwrite) {
$this->attributes = $data; $this->attributes = $data;
} elseif (is_array($data)) { } elseif (is_array($data)) {
$this->attributes = is_null($this->attributes) ? [] : $this->attributes; $this->attributes = is_null($this->attributes)
? []
: $this->attributes;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$this->attributes[$key] = $value; $this->attributes[$key] = $value;
} }
@@ -66,7 +68,7 @@ class Page implements PageContract
*/ */
public function getBuilderData() public function getBuilderData()
{ {
return $this->attributes['data'] ?? []; return $this->attributes["data"] ?? [];
} }
/** /**
@@ -76,7 +78,7 @@ class Page implements PageContract
*/ */
public function getId() public function getId()
{ {
return $this->get('id'); return $this->get("id");
} }
/** /**
@@ -86,7 +88,7 @@ class Page implements PageContract
*/ */
public function getName() public function getName()
{ {
return $this->get('name'); return $this->get("name");
} }
/** /**
@@ -96,7 +98,7 @@ class Page implements PageContract
*/ */
public function getLayout() public function getLayout()
{ {
return $this->get('layout'); return $this->get("layout");
} }
/** /**
@@ -107,10 +109,18 @@ class Page implements PageContract
public function getTranslations() public function getTranslations()
{ {
if (is_null($this->translations)) { 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 = []; $translations = [];
foreach ($records as $record) { 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; $translations[$record->locale] = (array) $record;
} }
} }
@@ -129,7 +139,11 @@ class Page implements PageContract
public function getTranslation(string $setting, ?string $locale = null) public function getTranslation(string $setting, ?string $locale = null)
{ {
$translations = $this->getTranslations(); $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) public function getRoute(?string $locale = null)
{ {
$routeTranslation = $this->getTranslation('route', $locale); $routeTranslation = $this->getTranslation("route", $locale);
foreach (phpb_route_parameters() as $routeParameter => $value) { foreach (phpb_route_parameters() as $routeParameter => $value) {
$routeTranslation = str_replace('{' . $routeParameter . '}', $value, $routeTranslation); $routeTranslation = str_replace(
"{" . $routeParameter . "}",
$value,
$routeTranslation,
);
} }
return $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. * Get the value of the given property of this Page.
* *
@@ -172,9 +219,9 @@ class Page implements PageContract
public function invalidateCache() public function invalidateCache()
{ {
$routes = array_map(function ($translation) { $routes = array_map(function ($translation) {
return $translation['route'] ?? null; return $translation["route"] ?? null;
}, $this->getTranslations()); }, $this->getTranslations());
(new PageTranslationService())->invalidateRoutes($routes); new PageTranslationService()->invalidateRoutes($routes);
} }
} }
+32 -3
View File
@@ -11,6 +11,7 @@ use Plugi\Contracts\PageBuilderContract;
use Plugi\Contracts\RouterContract; use Plugi\Contracts\RouterContract;
use Plugi\Contracts\ThemeContract; use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\PageRenderer; use Plugi\Modules\GrapesJS\PageRenderer;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\UploadRepository; use Plugi\Repositories\UploadRepository;
use Plugi\Core\DB; use Plugi\Core\DB;
use Plugi\Extensions; 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 // try to find page in cache
$cache = phpb_instance('cache'); $cache = phpb_instance('cache');
if (phpb_config('cache.enabled') && if (! $hasPreviewToken &&
phpb_config('cache.enabled') &&
! isset($_GET['ignore_cache']) && ! isset($_GET['ignore_cache']) &&
! isset($_GET['refresh_cache']) && ! isset($_GET['refresh_cache']) &&
! isset($_COOKIE['ignore_cache']) && ! isset($_COOKIE['ignore_cache']) &&
@@ -504,11 +510,24 @@ class Plugi
// render page if resolved // render page if resolved
if ($page) { if ($page) {
if ($page->get('type') === 'redirect') { 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 // TODO add menu etc
$renderedContent = $this->pageBuilder->renderPage($page, $pageTranslation->locale); $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); $this->cacheRenderedPage($renderedContent);
} }
echo $renderedContent; echo $renderedContent;
@@ -517,6 +536,16 @@ class Plugi
return false; 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. * Resolve a PageTranslation from the given URL.
* *
@@ -0,0 +1,9 @@
<?php
namespace Plugi\Repositories;
use RuntimeException;
class PageDraftPublishedCacheInvalidationException extends RuntimeException
{
}
+161 -42
View File
@@ -28,9 +28,11 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/ */
public function __construct() 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(); parent::__construct();
$this->class = phpb_instance('page'); $this->class = phpb_instance("page");
} }
/** /**
@@ -42,13 +44,21 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/ */
public function create(array $data) public function create(array $data)
{ {
foreach (['name', 'layout'] as $field) { foreach (["name", "layout"] as $field) {
if (! isset($data[$field]) || ! is_string($data[$field]) || trim($data[$field]) === '') { if (
!isset($data[$field]) ||
!is_string($data[$field]) ||
trim($data[$field]) === ""
) {
return false; 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; return false;
} }
@@ -59,9 +69,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return $this->db->transaction(function () use ($data) { return $this->db->transaction(function () use ($data) {
$page = parent::create([ $page = parent::create([
'name' => $data['name'], "name" => $data["name"],
'layout' => $data['layout'], "layout" => $data["layout"],
'type' => $data['type'], "type" => $data["type"],
]); ]);
if (!($page instanceof PageContract)) { if (!($page instanceof PageContract)) {
return false; return false;
@@ -80,7 +90,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/ */
public function update($page, array $data) public function update($page, array $data)
{ {
foreach (['name', 'layout'] as $field) { foreach (["name", "layout"] as $field) {
if (!isset($data[$field]) || !is_string($data[$field])) { if (!isset($data[$field]) || !is_string($data[$field])) {
return false; return false;
} }
@@ -93,20 +103,27 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$translationService = new PageTranslationService(); $translationService = new PageTranslationService();
$oldRoutes = []; $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()); $oldRoutes = $translationService->getPageRoutes($page->getId());
if (!$this->replaceTranslations($page, $data)) { if (!$this->replaceTranslations($page, $data)) {
return false; return false;
} }
return parent::update($page, [ return parent::update($page, [
'name' => $data['name'], "name" => $data["name"],
'layout' => $data['layout'], "layout" => $data["layout"],
'type' => $data['type'], "type" => $data["type"],
]); ]);
}); });
if ($updateResult) { if ($updateResult) {
$translationService->invalidateRoutes(array_merge($oldRoutes, array_values($data['route']))); $translationService->invalidateRoutes(
array_merge($oldRoutes, array_values($data["route"])),
);
} }
return $updateResult; return $updateResult;
} }
@@ -121,24 +138,31 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
protected function replaceTranslations(PageContract $page, array $data) protected function replaceTranslations(PageContract $page, array $data)
{ {
$activeLanguages = phpb_active_languages(); $activeLanguages = phpb_active_languages();
if (! $this->hasValidTranslationData($data, $activeLanguages) if (
|| $this->hasRouteCollision($data, $activeLanguages, $page->getId())) { !$this->hasValidTranslationData($data, $activeLanguages) ||
$this->hasRouteCollision($data, $activeLanguages, $page->getId())
) {
return false; return false;
} }
$pageTranslationRepository = new PageTranslationRepository; $pageTranslationRepository = new PageTranslationRepository();
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $page->getId())) { if (
!$pageTranslationRepository->destroyWhere(
phpb_config("page.translation.foreign_key"),
$page->getId(),
)
) {
return false; return false;
} }
foreach ($activeLanguages as $languageCode => $languageTranslation) { foreach ($activeLanguages as $languageCode => $languageTranslation) {
$translation = $pageTranslationRepository->create([ $translation = $pageTranslationRepository->create([
phpb_config('page.translation.foreign_key') => $page->getId(), phpb_config("page.translation.foreign_key") => $page->getId(),
'locale' => $languageCode, "locale" => $languageCode,
'title' => $data['title'][$languageCode], "title" => $data["title"][$languageCode],
'meta_title' => $data['meta_title'][$languageCode], "meta_title" => $data["meta_title"][$languageCode],
'meta_description' => $data['meta_description'][$languageCode], "meta_description" => $data["meta_description"][$languageCode],
'route' => $data['route'][$languageCode], "route" => $data["route"][$languageCode],
'target' => $data['target'][$languageCode], "target" => $data["target"][$languageCode],
]); ]);
if (!($translation instanceof PageTranslationContract)) { if (!($translation instanceof PageTranslationContract)) {
return false; return false;
@@ -148,28 +172,54 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return true; return true;
} }
protected function hasValidTranslationData(array $data, array $activeLanguages): bool protected function hasValidTranslationData(
{ array $data,
if (empty($activeLanguages) || ! isset($data['type']) || ! is_string($data['type']) array $activeLanguages,
|| ! in_array($data['type'], ['static', 'redirect'], true)) { ): bool {
if (
empty($activeLanguages) ||
!isset($data["type"]) ||
!is_string($data["type"]) ||
!in_array($data["type"], ["static", "redirect"], true)
) {
return false; return false;
} }
foreach (['title', 'meta_title', 'meta_description', 'route', 'target'] as $field) { foreach (
["title", "meta_title", "meta_description", "route", "target"]
as $field
) {
if (!isset($data[$field]) || !is_array($data[$field])) { if (!isset($data[$field]) || !is_array($data[$field])) {
return false; return false;
} }
foreach ($activeLanguages as $languageCode => $languageTranslation) { foreach (
if (! array_key_exists($languageCode, $data[$field]) || ! is_string($data[$field][$languageCode])) { $activeLanguages
as $languageCode => $languageTranslation
) {
if (
!array_key_exists($languageCode, $data[$field]) ||
!is_string($data[$field][$languageCode])
) {
return false; return false;
} }
if ($field === 'route' && trim($data[$field][$languageCode]) === '') { if (
$field === "route" &&
trim($data[$field][$languageCode]) === ""
) {
return false; return false;
} }
if ($field === 'title' && $data['type'] === 'static' && trim($data[$field][$languageCode]) === '') { if (
$field === "title" &&
$data["type"] === "static" &&
trim($data[$field][$languageCode]) === ""
) {
return false; return false;
} }
if ($field === 'target' && $data['type'] === 'redirect' && trim($data[$field][$languageCode]) === '') { if (
$field === "target" &&
$data["type"] === "redirect" &&
trim($data[$field][$languageCode]) === ""
) {
return false; return false;
} }
} }
@@ -178,18 +228,21 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return true; return true;
} }
protected function hasRouteCollision(array $data, array $activeLanguages, $pageId = null): bool protected function hasRouteCollision(
{ array $data,
array $activeLanguages,
$pageId = null,
): bool {
$routes = []; $routes = [];
foreach ($activeLanguages as $languageCode => $languageTranslation) { foreach ($activeLanguages as $languageCode => $languageTranslation) {
$route = $data['route'][$languageCode]; $route = $data["route"][$languageCode];
if (array_key_exists($route, $routes)) { if (array_key_exists($route, $routes)) {
return true; return true;
} }
$routes[$route] = true; $routes[$route] = true;
} }
$pageTranslationRepository = new PageTranslationRepository; $pageTranslationRepository = new PageTranslationRepository();
foreach (array_keys($routes) as $route) { foreach (array_keys($routes) as $route) {
if ($pageTranslationRepository->routeExists($route, $pageId)) { if ($pageTranslationRepository->routeExists($route, $pageId)) {
return true; return true;
@@ -209,7 +262,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
public function updatePageData($page, array $data) public function updatePageData($page, array $data)
{ {
$updateResult = parent::update($page, [ $updateResult = parent::update($page, [
'data' => json_encode($data), "data" => json_encode($data),
]); ]);
if ($updateResult) { if ($updateResult) {
$page->invalidateCache(); $page->invalidateCache();
@@ -217,6 +270,63 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return $updateResult; 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. * Remove the given page from the database.
* *
@@ -227,10 +337,19 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
{ {
$translationService = new PageTranslationService(); $translationService = new PageTranslationService();
$routes = []; $routes = [];
$destroyResult = $this->db->transaction(function () use ($id, $translationService, &$routes) { $destroyResult = $this->db->transaction(function () use (
$id,
$translationService,
&$routes,
) {
$routes = $translationService->getPageRoutes($id); $routes = $translationService->getPageRoutes($id);
$pageTranslationRepository = new PageTranslationRepository(); $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; return false;
} }
@@ -40,6 +40,46 @@ class UploadRepository extends BaseRepository
'original_file' => $data['original_file'], 'original_file' => $data['original_file'],
'mime_type' => $data['mime_type'], 'mime_type' => $data['mime_type'],
'server_file' => $data['server_file'], '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;
}
} }
+394
View File
@@ -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 &quot;test&quot; &amp; results"'), 'The saved alt text should render as an escaped image alt attribute.');
assertMediaLibrary(str_contains($html, 'value="Camera &quot;test&quot; &amp; 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 &quot;photo&quot; &amp; 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);
+400 -3
View File
@@ -3,6 +3,7 @@
use Plugi\Core\DB; use Plugi\Core\DB;
use Plugi\Contracts\PageContract; use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageTranslationContract; use Plugi\Contracts\PageTranslationContract;
use Plugi\Core\Csrf;
use Plugi\Modules\GrapesJS\PageBuilder; use Plugi\Modules\GrapesJS\PageBuilder;
use Plugi\Modules\Router\DatabasePageRouter; use Plugi\Modules\Router\DatabasePageRouter;
use Plugi\Page; 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/ThemeContract.php';
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php'; require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../src/Contracts/SettingContract.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/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php'; require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/SettingRepository.php'; require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.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/PageTranslationService.php';
require_once __DIR__ . '/../src/Page.php'; require_once __DIR__ . '/../src/Page.php';
require_once __DIR__ . '/../src/PageTranslation.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/WebsiteManager/WebsiteManager.php';
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php'; require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.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'; require_once __DIR__ . '/../src/Plugi.php';
class PageCreationRedirectException extends RuntimeException class PageCreationRedirectException extends RuntimeException
@@ -53,6 +58,7 @@ class PageCreationTestDatabase extends DB
public ?string $failOnDeleteTable = null; public ?string $failOnDeleteTable = null;
public bool $throwOnDeleteFailure = false; public bool $throwOnDeleteFailure = false;
public bool $failOnPageUpdate = false; public bool $failOnPageUpdate = false;
public ?int $failOnPageUpdateId = null;
public array $schemaDiffs = []; public array $schemaDiffs = [];
public function __construct() public function __construct()
@@ -73,6 +79,9 @@ class PageCreationTestDatabase extends DB
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) { if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
return false; 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')) { if (str_starts_with($query, 'INSERT INTO page_translations')) {
$this->translationInsertCount++; $this->translationInsertCount++;
@@ -87,6 +96,18 @@ class PageCreationTestDatabase extends DB
return parent::query($query, $parameters); 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 public function all(string $table, array|string $columns = '*'): array
{ {
if ($table === 'page_translations') { if ($table === 'page_translations') {
@@ -112,6 +133,7 @@ class PageCreationTestDatabase extends DB
name TEXT, name TEXT,
layout TEXT, layout TEXT,
data TEXT, data TEXT,
draft_data TEXT,
type TEXT, type TEXT,
status TEXT, status TEXT,
parent_id INTEGER, parent_id INTEGER,
@@ -219,11 +241,90 @@ class PageCreationTestWebsiteManager extends WebsiteManager
class PageCreationTestCache class PageCreationTestCache
{ {
public static array $invalidatedRoutes = []; 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 public function invalidate(string $route): void
{ {
if (self::$throwOnInvalidate) {
throw new RuntimeException('Simulated route cache invalidation failure.');
}
self::$invalidatedRoutes[] = $route; 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&amp;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 function phpb_config(?string $key = null): mixed
@@ -249,6 +350,11 @@ function phpb_active_languages(): array
return $pageCreationLanguages; return $pageCreationLanguages;
} }
function phpb_is_authenticated(): bool
{
return ! empty($_SESSION['phpb_logged_in']);
}
function phpb_route_parameters(): array function phpb_route_parameters(): array
{ {
return []; return [];
@@ -289,13 +395,22 @@ function phpb_on_url(string $module, array $parameters = []): bool
return false; 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 function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{ {
global $pageCreationRedirectFlash;
$pageCreationRedirectFlash = $flashData;
throw new PageCreationRedirectException($url); 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 function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]): void
{ {
global $phpb_db, $pageCreationConfig, $pageCreationLanguages; global $phpb_db, $pageCreationConfig, $pageCreationLanguages;
@@ -316,7 +436,10 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
$pageCreationConfig = [ $pageCreationConfig = [
'general' => [ 'general' => [
'language' => 'en', 'language' => 'en',
'uploads_url' => '/uploads',
'assets_url' => '/assets',
], ],
'cache' => ['enabled' => true],
'page' => [ 'page' => [
'table' => 'pages', 'table' => 'pages',
'translation' => [ 'translation' => [
@@ -327,6 +450,9 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
]; ];
$pageCreationLanguages = $languages; $pageCreationLanguages = $languages;
PageCreationTestCache::$invalidatedRoutes = []; PageCreationTestCache::$invalidatedRoutes = [];
PageCreationTestCache::$cacheReads = [];
PageCreationTestCache::$cacheWrites = [];
PageCreationTestCache::$throwOnInvalidate = false;
$phpb_db = new PageCreationTestDatabase(); $phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema(); $phpb_db->createSchema();
} }
@@ -345,6 +471,25 @@ function pageCreationPayload(array $overrides = []): array
], $overrides); ], $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 function assertPageCreation(bool $condition, string $message): void
{ {
if (! $condition) { if (! $condition) {
@@ -710,13 +855,15 @@ $cases = [
'name' => 'Missing locale page', 'name' => 'Missing locale page',
'route' => ['en' => '/missing-en', 'de' => '/missing-de'], '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(); $pages = $repository->getAll();
$pageRows = []; $pageRows = [];
foreach ($pages as $page) { foreach ($pages as $page) {
$pageRows[$page->getId()] = $page; $pageRows[$page->getId()] = $page;
} }
global $phpb_db;
$pageIds = array_keys($pageRows); $pageIds = array_keys($pageRows);
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']); $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']); $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, '/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, '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, '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 { 'successful route updates invalidate old and new localized routes' => function (): void {
resetPageCreationDatabase(); resetPageCreationDatabase();
@@ -828,6 +976,255 @@ $cases = [
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes) '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 { 'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase(); resetPageCreationDatabase();
global $phpb_db; 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++; saveCalls++;
}, },
}; };
let checkedRadio;
const selector = { const selector = {
value: 'Desktop', querySelector(selector) {
assert.equal(selector, 'input[type="radio"]:checked');
return checkedRadio;
},
addEventListener(eventName, handler) { addEventListener(eventName, handler) {
assert.equal(eventName, 'change'); assert.equal(eventName, 'change');
changeHandler = handler; changeHandler = handler;
@@ -29,7 +33,7 @@ test('viewport changes select a device without changing project data or invoking
bindViewportSelector(editor, selector); bindViewportSelector(editor, selector);
for (const device of ['Desktop', 'Tablet', 'Mobile']) { for (const device of ['Desktop', 'Tablet', 'Mobile']) {
selector.value = device; checkedRadio = { value: device };
changeHandler(); changeHandler();
} }
+67
View File
@@ -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";
+17
View File
@@ -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>