add draft/publishing workflow

This commit is contained in:
2026-11-29 09:31:09 +01:00
parent 345a99cf32
commit 45535204a2
20 changed files with 660 additions and 60 deletions
+234 -3
View File
@@ -33,6 +33,8 @@ require_once __DIR__ . '/../src/Repositories/PageRepository.php';
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
require_once __DIR__ . '/../src/Modules/GrapesJS/PageRenderer.php';
require_once __DIR__ . '/../src/Extensions.php';
require_once __DIR__ . '/../src/Plugi.php';
class PageCreationRedirectException extends RuntimeException
@@ -112,6 +114,7 @@ class PageCreationTestDatabase extends DB
name TEXT,
layout TEXT,
data TEXT,
draft_data TEXT,
type TEXT,
status TEXT,
parent_id INTEGER,
@@ -219,11 +222,86 @@ class PageCreationTestWebsiteManager extends WebsiteManager
class PageCreationTestCache
{
public static array $invalidatedRoutes = [];
public static array $cacheReads = [];
public static array $cacheWrites = [];
public static ?string $cachedContent = null;
public function invalidate(string $route): void
{
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
@@ -249,6 +327,11 @@ function phpb_active_languages(): array
return $pageCreationLanguages;
}
function phpb_is_authenticated(): bool
{
return ! empty($_SESSION['phpb_logged_in']);
}
function phpb_route_parameters(): array
{
return [];
@@ -289,9 +372,16 @@ function phpb_on_url(string $module, array $parameters = []): bool
return false;
}
function phpb_current_relative_url(): string
function phpb_current_relative_url(bool $removeParameters = false): string
{
return '/admin/page_settings';
global $pageCreationCurrentUrl;
$url = $pageCreationCurrentUrl ?? '/admin/page_settings';
return $removeParameters ? explode('?', $url, 2)[0] : $url;
}
function phpb_static(string $name): string
{
return $name;
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
@@ -316,7 +406,10 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
$pageCreationConfig = [
'general' => [
'language' => 'en',
'uploads_url' => '/uploads',
'assets_url' => '/assets',
],
'cache' => ['enabled' => true],
'page' => [
'table' => 'pages',
'translation' => [
@@ -327,6 +420,8 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
];
$pageCreationLanguages = $languages;
PageCreationTestCache::$invalidatedRoutes = [];
PageCreationTestCache::$cacheReads = [];
PageCreationTestCache::$cacheWrites = [];
$phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema();
}
@@ -710,13 +805,15 @@ $cases = [
'name' => 'Missing locale page',
'route' => ['en' => '/missing-en', 'de' => '/missing-de'],
]));
global $phpb_db;
$draftPage = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$repository->updatePageDraftData($draftPage, ['html' => ['<p>Saved draft</p>']]);
$pages = $repository->getAll();
$pageRows = [];
foreach ($pages as $page) {
$pageRows[$page->getId()] = $page;
}
global $phpb_db;
$pageIds = array_keys($pageRows);
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']);
$phpb_db->query('DELETE FROM page_translations WHERE page_id = ? AND locale = ?', [$pageIds[2], 'de']);
@@ -744,6 +841,7 @@ $cases = [
assertPageCreation(str_contains($html, '/complete-de'), 'The page overview did not render the saved German route.');
assertPageCreation(str_contains($html, 'New page'), 'The page overview did not render a saved localized title.');
assertPageCreation(str_contains($html, '2 / 2 complete'), 'The page overview did not render the translation coverage summary.');
assertPageCreation(str_contains($html, 'pagebuilder.draft-available'), 'The page overview did not indicate that a saved draft exists.');
},
'successful route updates invalidate old and new localized routes' => function (): void {
resetPageCreationDatabase();
@@ -828,6 +926,139 @@ $cases = [
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'page drafts stay unpublished until promoted and publishing requires a draft' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$publishedData = ['html' => ['<p>Published</p>']];
$draftData = ['html' => ['<p>Draft</p>']];
assertPageCreation($repository->updatePageData($page, $publishedData) === true, 'Initial published data could not be saved.');
PageCreationTestCache::$invalidatedRoutes = [];
assertPageCreation($repository->updatePageDraftData($page, $draftData) === true, 'Draft data could not be saved.');
assertPageCreation($repository->getPageDraftData($page) === $draftData, 'Saved draft data could not be read back.');
assertPageCreation(json_decode($phpb_db->rows('pages')[0]['data'], true) === $publishedData, 'Saving a draft changed the published page data.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Saving a draft invalidated published page caches.');
assertPageCreation($repository->publishPageDraft($page) === true, 'A saved draft could not be published.');
$pageRow = $phpb_db->rows('pages')[0];
assertPageCreation(json_decode($pageRow['data'], true) === $draftData, 'Publishing did not promote the draft into published data.');
assertPageCreation($pageRow['draft_data'] === null, 'Publishing did not clear the draft.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'],
'Publishing did not invalidate the localized page caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
PageCreationTestCache::$invalidatedRoutes = [];
assertPageCreation($repository->publishPageDraft($page) === false, 'Publishing a page without a draft was reported as successful.');
assertPageCreation(json_decode($phpb_db->rows('pages')[0]['data'], true) === $draftData, 'Publishing without a draft changed the published data.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Publishing without a draft invalidated page caches.');
$schema = require __DIR__ . '/../config/tables.php';
assertPageCreation(
isset($schema['pages']['columns']['draft_data']) && str_contains(strtoupper($schema['pages']['columns']['draft_data']), 'NULL'),
'The pages schema does not declare a nullable draft_data column.'
);
},
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/new-page', 'de' => '/de/new-page'],
]));
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$page = $repository->findWithId($pageId);
$publishedData = ['html' => ['<p>Published</p>']];
$draftData = ['html' => ['<p>Draft</p>']];
$repository->updatePageData($page, $publishedData);
$repository->updatePageDraftData($page, $draftData);
$translation = new PageTranslation();
$translation->page_id = $pageId;
$translation->locale = 'en';
$translation->route = '/new-page';
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
$document = new DOMDocument();
@$document->loadHTML($html);
$links = [];
foreach ($document->getElementsByTagName('a') as $link) {
$links[] = $link->getAttribute('href');
}
assertPageCreation($links[0] === '/about?locale=de&previewToken=valid-token#intro', 'Relative internal link lost its query or fragment while carrying preview mode.');
assertPageCreation($links[1] === 'https://example.test/contact?next=1&previewToken=valid-token', 'Absolute same-site link did not carry preview mode.');
assertPageCreation($links[2] === 'https://external.test/page?x=1#fragment', 'External link was modified for preview mode.');
assertPageCreation($links[3] === '#section', 'Fragment-only link was modified for preview mode.');
assertPageCreation($links[4] === '?search=one&previewToken=valid-token', 'Query-only link did not preserve its query while carrying preview mode.');
assertPageCreation($links[5] === '/already?x=1&previewToken=valid-token', 'Existing preview token was not replaced while preserving other parameters.');
assertPageCreation($links[6] === '\\\\evil.example/path', 'A backslash-prefixed external URL changed during preview serialization.');
assertPageCreation($links[7] === '//evil.example/path', 'A tab-prefixed external URL received the preview token or changed destination during serialization.');
assertPageCreation($links[8] === '//evil.example/path', 'A space-prefixed external URL received the preview token or changed destination during serialization.');
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Preview request accessed the public page cache.');
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'invalid-token'], true, 'valid-token');
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'An invalid preview token exposed the saved draft.');
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Invalid-token request accessed the public page cache.');
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], false, 'valid-token');
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'An unauthenticated preview request exposed the saved draft.');
assertPageCreation(PageCreationTestCache::$cacheReads === [] && PageCreationTestCache::$cacheWrites === [], 'Unauthenticated preview request accessed the public page cache.');
[$handled, , $pageBuilder] = runPageCreationPublicRequest($translation, [], false, 'valid-token');
assertPageCreation($handled === true && $pageBuilder->renderedData === $publishedData, 'A public request did not render the published page.');
assertPageCreation(count(PageCreationTestCache::$cacheReads) === 1, 'Ordinary published request no longer reads the public cache.');
assertPageCreation(count(PageCreationTestCache::$cacheWrites) === 1, 'Ordinary published request no longer stores rendered output.');
},
'preview link rewriting does not leak tokens through an external base URL' => function (): void {
$html = '<!doctype html><html><head><base href="https://external.test/"></head><body>'
. '<a href="/relative-link">Relative</a>'
. '<a href="https://example.test/absolute-link">Same-site absolute</a>'
. '</body></html>';
$rewritten = \Plugi\Modules\GrapesJS\PageRenderer::appendPreviewTokenToLinks($html, 'valid-token');
$document = new DOMDocument();
@$document->loadHTML($rewritten);
$links = [];
foreach ($document->getElementsByTagName('a') as $link) {
$links[] = $link->getAttribute('href');
}
assertPageCreation($links[0] === '/relative-link', 'A relative link under an external base URL received the preview token.');
assertPageCreation($links[1] === 'https://example.test/absolute-link?previewToken=valid-token', 'An explicit same-site URL was not preserved as a preview link.');
},
'authenticated preview redirects preserve tokens only for same-site targets' => function (): void {
$checkRedirect = static function (string $target, string $expected): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'type' => 'redirect',
'target' => ['en' => $target, 'de' => $target],
]));
global $phpb_db;
$translation = new PageTranslation();
$translation->page_id = $phpb_db->rows('pages')[0]['id'];
$translation->locale = 'en';
$translation->route = '/redirect';
$translation->target = $target;
try {
runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
throw new RuntimeException('Redirect page did not redirect.');
} catch (PageCreationRedirectException $exception) {
assertPageCreation($exception->redirectUrl === $expected, 'Redirect target did not preserve authenticated preview mode correctly.');
}
};
$checkRedirect('/about?locale=de#intro', '/about?locale=de&previewToken=valid-token#intro');
$checkRedirect('https://external.test/about?locale=de#intro', 'https://external.test/about?locale=de#intro');
},
'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase();
global $phpb_db;
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindDraftActions } from '../src/Modules/GrapesJS/resources/assets/js/draft-actions.js';
function button() {
let clickHandler;
return {
addEventListener(eventName, handler) {
assert.equal(eventName, 'click');
clickHandler = handler;
},
click() {
clickHandler();
},
};
}
test('draft action saves edits and publishes only after confirmation', () => {
const saveButton = button();
const publishButton = button();
const actions = [];
let confirmation = false;
bindDraftActions(saveButton, publishButton, publishAfterSave => actions.push(publishAfterSave), () => confirmation);
saveButton.click();
publishButton.click();
confirmation = true;
publishButton.click();
assert.deepEqual(actions, [false, true]);
});