pdo = new PDO('sqlite::memory:'); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->databaseName = 'page_creation_test'; } public function query(string $query, array $parameters = []) { if (str_starts_with($query, 'INSERT INTO settings') || str_starts_with($query, 'UPDATE settings SET')) { $this->settingWriteCount++; if ($this->settingWriteCount === $this->failOnSettingWrite) { return false; } } if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) { if ($this->throwOnDeleteFailure) { throw new PDOException('Simulated page deletion failure.'); } return 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; } if (str_starts_with($query, 'INSERT INTO page_translations')) { $this->translationInsertCount++; if ($this->translationInsertCount === $this->failOnTranslationInsert) { if ($this->throwOnTranslationFailure) { throw new PDOException('Simulated page translation write failure.'); } return false; } } if ($this->failOnTranslationUpdate && str_starts_with($query, 'UPDATE page_translations SET')) { return false; } return parent::query($query, $parameters); } public function queryAffectedRows(string $query, array $parameters = []): int|false { if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) { return false; } if ($this->failOnPageUpdateId !== null && str_starts_with($query, 'UPDATE pages SET') && (int) end($parameters) === $this->failOnPageUpdateId) { return false; } return parent::queryAffectedRows($query, $parameters); } public function all(string $table, array|string $columns = '*'): array { if ($table === 'page_translations') { $this->pageTranslationAllCallCount++; } return parent::all($table, $columns); } public function select(string $query, array $parameters): array { if (str_starts_with($query, 'SELECT * FROM page_translations WHERE page_id IN (')) { $this->pageTranslationBatchSelectCount++; } return parent::select($query, $parameters); } public function createSchema(): void { $this->pdo->exec('CREATE TABLE settings ( id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT NOT NULL UNIQUE, value TEXT NOT NULL, is_array INTEGER NOT NULL )'); $this->pdo->exec('CREATE TABLE pages ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, layout TEXT, data TEXT, draft_data TEXT, type TEXT, status TEXT, parent_id INTEGER, updated_at TEXT DEFAULT CURRENT_TIMESTAMP, created_at TEXT DEFAULT CURRENT_TIMESTAMP )'); $this->pdo->exec('CREATE TABLE page_translations ( id INTEGER PRIMARY KEY AUTOINCREMENT, page_id INTEGER NOT NULL, locale TEXT NOT NULL, title TEXT, meta_title TEXT, meta_description TEXT, route TEXT, target TEXT, updated_at TEXT DEFAULT CURRENT_TIMESTAMP, created_at TEXT DEFAULT CURRENT_TIMESTAMP, UNIQUE (page_id, locale) )'); } public function diffDB(): array { return $this->schemaDiffs; } public function getDBDefinitionHash(): string { return 'test-schema-hash'; } public function rows(string $table): array { return $this->select("SELECT * FROM {$table}", []); } } class PageCreationSchemaMigrationTestDatabase extends DB { public array $queries = []; public function __construct() { } public function diffDB(): array { return [ 'pages' => [ 'columns' => ['type' => 'varchar(63)'], 'uniqueKeys' => [], ], 'page_translations' => [ 'columns' => ['target' => 'varchar(255)'], 'uniqueKeys' => [], ], 'missing_table' => false, ]; } public function getDBDefinition(): array { return [ 'pages' => ['columns' => ['type' => 'varchar(63)'], 'uniqueKeys' => []], 'page_translations' => ['columns' => ['target' => 'varchar(255)'], 'uniqueKeys' => []], 'missing_table' => [ 'columns' => ['label' => 'varchar(255)'], 'uniqueKeys' => ['label' => ['label']], ], ]; } public function query(string $query, array $parameters = []) { $this->queries[] = $query; return true; } public function transaction(callable $callback): mixed { return $callback(); } public function select(string $query, array $parameters): array { return []; } public function findWithId(string $table, $id): array { return [['id' => $id]]; } public function lastInsertId(): string { return '1'; } public function getDBDefinitionHash(): string { return 'test-schema-hash'; } } class PageCreationTestWebsiteManager extends WebsiteManager { public ?string $renderedErrorMessage = null; public function renderPageSettings(?PageContract $page = null, ?string $errorMessage = null) { $this->renderedErrorMessage = $errorMessage; } } class PageCreationTestCache { public static array $invalidatedRoutes = []; public static array $cacheReads = []; public static array $cacheWrites = []; public static ?string $cachedContent = null; public static bool $throwOnInvalidate = false; public function invalidate(string $route): void { if (self::$throwOnInvalidate) { throw new RuntimeException('Simulated route cache invalidation failure.'); } self::$invalidatedRoutes[] = $route; } public function getForUrl(string $url): ?string { self::$cacheReads[] = $url; return self::$cachedContent; } public function storeForUrl(string $url, string $content, int $lifetime): void { self::$cacheWrites[] = [$url, $content, $lifetime]; } } class PageCreationTestPublicRouter { public function __construct(private ?PageTranslationContract $translation) { } public function resolve(string $url): ?PageTranslationContract { return $this->translation; } } class PageCreationTestPublicPageBuilder { public array $renderedData = []; public ?string $renderedLanguage = null; public function renderPage(PageContract $page, ?string $language = null): string { $this->renderedData = $page->getBuilderData(); $this->renderedLanguage = $language; return '
Draft
']])) { throw new RuntimeException('Could not save a draft for the batch publishing test.'); } return $page; } function assertPageCreation(bool $condition, string $message): void { if (! $condition) { throw new RuntimeException($message); } } function runPageCreationCase(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; } } $cases = [ 'startup prompts for database updates when schema drifts despite a matching hash' => function (): void { resetPageCreationDatabase(); global $phpb_db, $pageCreationConfig; $pageCreationConfig['auth'] = ['url' => '/auth']; $phpb_db->schemaDiffs = [ 'pages' => [ 'columns' => ['type' => 'varchar(63)'], 'uniqueKeys' => [], ], ]; $settings = new ReflectionProperty(Setting::class, 'settings'); $settings->setValue(null, ['db-definition' => $phpb_db->getDBDefinitionHash()]); try { (new \Plugi\Plugi())->checkDatabaseDefinition(); } catch (PageCreationRedirectException $exception) { assertPageCreation( $exception->redirectUrl === '/website_manager', 'Schema drift redirected to an unexpected page.' ); return; } throw new RuntimeException('Schema drift with a matching hash did not prompt for a database update.'); }, 'database updates apply lowercase schema definitions needed to create pages' => function (): void { $_ENV['DATABASE_PREFIX'] = ''; $database = new PageCreationSchemaMigrationTestDatabase(); global $phpb_db; $phpb_db = $database; $database->resolveDiffDB(); assertPageCreation( in_array('ALTER TABLE pages ADD type varchar(63)', $database->queries, true), 'Database update skipped the lowercase pages.type definition.' ); assertPageCreation( in_array('ALTER TABLE page_translations ADD target varchar(255)', $database->queries, true), 'Database update skipped the lowercase page_translations.target definition.' ); assertPageCreation( in_array('ALTER TABLE missing_table ADD label varchar(255)', $database->queries, true), 'Database update did not add configured columns to a newly created table.' ); assertPageCreation( in_array('ALTER TABLE missing_table ADD UNIQUE KEY label (`label`)', $database->queries, true), 'Database update skipped a lowercase unique-key definition.' ); }, 'configured locale is preferred over the first available translation' => function (): void { resetPageCreationDatabase(['de' => [], 'fr' => []]); global $pageCreationConfig; $pageCreationConfig['general']['language'] = 'fr'; $page = new Page(); $page->setTranslations([ 'de' => ['title' => 'Deutscher Titel'], 'fr' => ['title' => 'Titre français'], ]); assertPageCreation( $page->getTranslation('title', 'it') === 'Titre français', 'Missing requested locale should fall back to the configured default, not the first saved locale.' ); }, 'locked generated routes do not leave a base page without translations' => function (): void { resetPageCreationDatabase(); $payload = pageCreationPayload(); unset($payload['route']); $result = (new PageRepository())->create($payload); assertPageCreation($result === false, 'An omitted disabled route should be rejected.'); global $phpb_db; assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Invalid create left a base page row.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Invalid create left translation rows.'); }, 'create handler reports validation failure and retains submitted values' => function (): void { resetPageCreationDatabase(); $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = pageCreationPayload(); unset($_POST['route']); $submittedValues = $_POST; $manager = new PageCreationTestWebsiteManager(); $manager->handleCreate(); global $phpb_db; assertPageCreation($manager->renderedErrorMessage === 'website-manager.page-create-failed', 'Create failure message was not supplied to the form.'); assertPageCreation($_POST === $submittedValues, 'Create handler did not retain submitted field values.'); assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Rejected create left a base page row.'); $_POST = []; }, 'create handler reports database failures and retains submitted values' => function (): void { resetPageCreationDatabase(); global $phpb_db; $phpb_db->failOnTranslationInsert = 2; $phpb_db->throwOnTranslationFailure = true; $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST = pageCreationPayload(); $submittedValues = $_POST; $manager = new PageCreationTestWebsiteManager(); $manager->handleCreate(); assertPageCreation($manager->renderedErrorMessage === 'website-manager.page-create-failed', 'Database failure message was not supplied to the form.'); assertPageCreation($_POST === $submittedValues, 'Database failure discarded submitted values.'); assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Database failure left a base page row.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Database failure left translations.'); $_POST = []; }, 'page form retains submitted values and submits locked routes' => function (): void { resetPageCreationDatabase(); $_POST = [ 'name' => 'Retained & page', 'type' => 'static', 'layout' => 'default', 'title' => ['en' => 'English title', 'de' => 'Deutscher Titel'], 'meta_title' => ['en' => 'English meta', 'de' => 'Deutscher Meta'], 'meta_description' => ['en' => 'English description', 'de' => 'Deutsche Beschreibung'], 'route' => ['en' => '/custom', 'de' => '/de/custom'], 'target' => ['en' => '', 'de' => ''], ]; $page = null; $action = 'create'; $errorMessage = 'Page creation failed.'; $theme = new class { public function getThemeLayouts(): array { return [new class { public function getSlug(): string { return 'default'; } public function getTitle(): string { return 'Default'; } }]; } }; ob_start(); include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php'; $html = ob_get_clean(); assertPageCreation(str_contains($html, 'role="alert"'), 'Create failure message was not rendered.'); assertPageCreation(str_contains($html, 'Page creation failed.'), 'Create failure message was not retained.'); assertPageCreation(str_contains($html, 'value="Retained & page"'), 'Page name was not retained safely.'); assertPageCreation(str_contains($html, 'value="English title"'), 'English title was not retained.'); assertPageCreation(str_contains($html, 'route: "/custom"'), 'Submitted route value was not retained safely.'); assertPageCreation(str_contains($html, 'name="route[en]" x-model="route" :readonly="disabled && type !== \'redirect\'"'), 'Locked route is not a successful form control.'); assertPageCreation(str_contains($html, 'disabled=!disabled'), 'Manual route editing toggle was removed.'); $_POST['title'] = 'malformed localized payload'; $_POST['route']['en'] = "'Saved draft
']]); $pages = $repository->getAll(); $pageRows = []; foreach ($pages as $page) { $pageRows[$page->getId()] = $page; } $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']); $missingPage = new Page(); $missingPage->setData(['id' => 999, 'type' => 'static']); $pages[] = $missingPage; $phpb_db->pageTranslationBatchSelectCount = 0; $coverage = (new Plugi\PageTranslationService())->getPageCoverage($pages, phpb_active_languages()); assertPageCreation($coverage[$pageIds[0]]['completeCount'] === 2, 'A complete page did not report all active locales complete.'); assertPageCreation($coverage[$pageIds[1]]['completeCount'] === 1, 'A partially complete page reported the wrong coverage count.'); assertPageCreation($coverage[$pageIds[1]]['locales']['de']['exists'] === true, 'An incomplete saved locale was reported as missing.'); assertPageCreation($coverage[$pageIds[1]]['locales']['de']['complete'] === false, 'An incomplete saved locale was reported as complete.'); assertPageCreation($coverage[$pageIds[2]]['locales']['de']['exists'] === false, 'An absent locale was reported as saved.'); assertPageCreation($coverage[999]['completeCount'] === 0, 'A page without translation records reported complete locales.'); assertPageCreation($phpb_db->pageTranslationBatchSelectCount === 1, 'Translation coverage used more than one batched repository query.'); $activeLanguages = phpb_active_languages(); $pageTranslationCoverage = $coverage; ob_start(); include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/pages.php'; $html = ob_get_clean(); assertPageCreation(str_contains($html, '/complete-en'), 'The page overview did not render the saved English 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, '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(); $repository = new PageRepository(); $repository->create(pageCreationPayload()); global $phpb_db; $page = $repository->findWithId($phpb_db->rows('pages')[0]['id']); $result = $repository->update($page, pageCreationPayload([ 'route' => ['en' => '/changed-en', 'de' => '/changed-de'], ])); assertPageCreation($result === true, 'A valid route update failed.'); assertPageCreation( PageCreationTestCache::$invalidatedRoutes === ['/changed-de', '/changed-en', '/de/new-page', '/new-page'], 'A successful route update did not invalidate both old and new localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes) ); }, 'page deletion removes translations and invalidates routes after commit' => function (): void { resetPageCreationDatabase(); $repository = new PageRepository(); $repository->create(pageCreationPayload([ 'route' => ['en' => '/delete-en', 'de' => '/delete-de'], ])); global $phpb_db; $pageId = $phpb_db->rows('pages')[0]['id']; assertPageCreation($repository->destroy($pageId) === true, 'Page deletion failed.'); assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Page deletion left the base page.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Page deletion left translation rows.'); assertPageCreation( PageCreationTestCache::$invalidatedRoutes === ['/delete-de', '/delete-en'], 'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes) ); }, 'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void { resetPageCreationDatabase(); $repository = new PageRepository(); $repository->create(pageCreationPayload()); global $phpb_db; $pageId = $phpb_db->rows('pages')[0]['id']; $phpb_db->failOnDeleteTable = 'pages'; assertPageCreation($repository->destroy($pageId) === false, 'A failed base-row deletion was reported as successful.'); assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Failed deletion removed the base page.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Failed deletion did not roll back translation cleanup.'); assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed deletion invalidated route caches.'); }, 'exception during page deletion rolls back rows and leaves caches intact' => function (): void { resetPageCreationDatabase(); $repository = new PageRepository(); $repository->create(pageCreationPayload()); global $phpb_db; $pageId = $phpb_db->rows('pages')[0]['id']; $phpb_db->failOnDeleteTable = 'pages'; $phpb_db->throwOnDeleteFailure = true; try { $repository->destroy($pageId); } catch (PDOException) { } assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Deletion exception removed the base page.'); assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Deletion exception did not roll back translation cleanup.'); assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Deletion exception invalidated route caches.'); }, 'page content cache invalidation occurs only after successful writes' => function (): void { resetPageCreationDatabase(); $repository = new PageRepository(); $repository->create(pageCreationPayload()); global $phpb_db; $page = $repository->findWithId($phpb_db->rows('pages')[0]['id']); $phpb_db->failOnPageUpdate = true; assertPageCreation($repository->updatePageData($page, ['html' => []]) === false, 'A failed page-data update was reported as successful.'); assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A failed page-data update invalidated route caches.'); $phpb_db->failOnPageUpdate = false; assertPageCreation($repository->updatePageData($page, ['html' => []]) === true, 'A valid page-data update failed.'); assertPageCreation( PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'], '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' => ['Published
']]; $draftData = ['html' => ['Draft
']]; 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' => ['Newer draft
']]; 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' => ['Draft
']], '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' => ['Draft
']], '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); }, 'settings writes roll back when a create or update fails' => function (): void { resetPageCreationDatabase(); global $phpb_db; $settingRepository = new \Plugi\Repositories\SettingRepository(); $phpb_db->failOnSettingWrite = 2; assertPageCreation( ! $settingRepository->updateSettings(['first' => 'one', 'second' => 'two']) && $phpb_db->rows('settings') === [], 'A failed settings create reported success or retained earlier writes.' ); resetPageCreationDatabase(); $phpb_db->query('INSERT INTO settings (setting, value, is_array) VALUES (?, ?, ?)', ['existing', 'old', 0]); $phpb_db->settingWriteCount = 0; $phpb_db->failOnSettingWrite = 2; $settingRepository = new \Plugi\Repositories\SettingRepository(); $updateSucceeded = $settingRepository->updateSettings(['first' => 'one', 'existing' => 'new']); $savedSettings = array_column($phpb_db->rows('settings'), 'value', 'setting'); assertPageCreation( ! $updateSucceeded && $savedSettings === ['existing' => 'old'], 'A failed settings update reported success or retained earlier writes.' ); resetPageCreationDatabase(); $settingRepository = new \Plugi\Repositories\SettingRepository(); assertPageCreation( $settingRepository->updateSettings(['first' => 'one', 'second' => ['two', 'three']]) && array_column($phpb_db->rows('settings'), 'value', 'setting') === ['first' => 'one', 'second' => 'two,three'], 'Successful settings writes were not committed.' ); }, 'cached public pages require a currently resolved route' => function (): void { resetPageCreationDatabase(); $translation = new PageTranslation(); $translation->locale = 'en'; $translation->route = '/new-page'; [$handled, $html] = runPageCreationPublicRequest($translation, [], false, '', 'cached page
'); assertPageCreation($handled && $html === 'cached page
', 'An active route did not serve its cached response.'); assertPageCreation(count(PageCreationTestCache::$cacheReads) === 1, 'An active route did not check its cache.'); [$handled, $html] = runPageCreationPublicRequest(null, [], false, '', 'cached disabled route
'); assertPageCreation(! $handled && $html === '', 'A cached response was served after the router rejected the route.'); assertPageCreation(PageCreationTestCache::$cacheReads === [], 'A rejected route accessed the page cache.'); }, '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' => ['Published
']]; $draftData = ['html' => ['Draft
']]; $repository->updatePageData($page, $publishedData); $repository->updatePageDraftData($page, $draftData); $translation = new PageTranslation(); $translation->page_id = $pageId; $translation->locale = 'de'; $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->renderedLanguage === 'de' && $GLOBALS['phpb_request_language'] === 'de', 'A resolved translation locale did not control page rendering and request language state.'); assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.'); assertPageCreation(str_contains(strtolower($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 = '