Add page publication history and reusable blocks

This commit is contained in:
2026-11-28 18:12:30 +08:00
parent 1c927d360c
commit 3b13f6533d
40 changed files with 1239 additions and 165 deletions
+175 -38
View File
@@ -12,11 +12,12 @@ use Throwable;
final class SiteBackup
{
private const FORMAT = 'laysite-site';
private const VERSION = 6;
private const VERSION = 7;
private const TABLES = [
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
'article_category_links', 'article_redirects', 'article_deletions', 'media',
];
private const REVISION_TABLES = ['page_revisions', 'page_publications', 'section_reuse', 'published_blocks', 'layout_draft_settings'];
private const MANIFEST_LIMIT = 32 * 1024 * 1024;
public static function export(string $path): void
@@ -27,8 +28,9 @@ final class SiteBackup
try {
Database::write(function (PDO $pdo) use ($path): void {
$tables = [];
foreach (self::TABLES as $table) {
$tables[$table] = $pdo->query('SELECT * FROM ' . $table)->fetchAll();
foreach ([...self::TABLES, ...self::REVISION_TABLES] as $table) {
$columns = $table === 'layout_draft_settings' ? 'layout_id, payload' : '*';
$tables[$table] = $pdo->query('SELECT ' . $columns . ' FROM ' . $table)->fetchAll();
}
$files = [];
$archive = new PharData($path);
@@ -141,14 +143,15 @@ final class SiteBackup
private static function prepare(mixed $manifest): array
{
if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT
|| !in_array($manifest['version'] ?? null, [1, 2, 3, 4, 5, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
|| !in_array($manifest['version'] ?? null, [1, 2, 3, 4, 5, 6, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
}
$tables = $manifest['tables'];
if ($manifest['version'] === 1) {
$tables += ['design_presets' => [], 'article_deletions' => []];
}
foreach (self::TABLES as $table) {
$hasRevisions = $manifest['version'] >= 7;
foreach ($hasRevisions ? [...self::TABLES, ...self::REVISION_TABLES] : self::TABLES as $table) {
if (!is_array($tables[$table] ?? null) || !array_is_list($tables[$table])) {
throw new RuntimeException('备份数据表不完整。');
}
@@ -206,7 +209,9 @@ final class SiteBackup
if (!in_array($kind, ['header', 'footer'], true) || $row['page_type'] !== 'page') {
throw new RuntimeException('备份包含无效的页头或页脚页面。');
}
$row['status'] = 'published';
if (!$hasRevisions) {
$row['status'] = 'published';
}
} elseif (isset(SystemPage::TYPES[$row['page_type']])) {
if (($row['status'] ?? null) === 'published') {
$publishedSystemPages[$row['slug']] = $row['page_type'];
@@ -214,21 +219,12 @@ final class SiteBackup
} elseif (!in_array($row['page_type'], ['page', 'home'], true)) {
throw new RuntimeException('备份包含无效的页面类型。');
}
self::validateAssetUrl($row['image'] ?? '', true);
$row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
$row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
$row['presentation'] = CanvasStyle::encode(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::PAGE));
$row['head_html'] = $layout === null ? PageHead::normalize($row['head_html'] ?? '') : '';
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = '';
}
foreach (['header', 'footer', 'palette'] as $kind) {
$row[$kind . '_id'] = self::selection($designs, $kind, $row[$kind . '_id'] ?? null);
}
$row = self::normalizePage($row, $designs);
}
unset($row);
if ($hasRevisions) {
$publishedSystemPages = self::normalizeRevisions($tables, $designs);
}
$systemPages = $settings['system_pages'] ?? [];
$maintenance = $settings['maintenance_enabled'] ?? false;
if (!is_array($systemPages) || !is_bool($maintenance) || ($maintenance && !isset($systemPages['maintenance']))) {
@@ -242,22 +238,9 @@ final class SiteBackup
$site['system_pages'] = $systemPages;
$site['maintenance_enabled'] = $maintenance;
$tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
$categories = array_column($tables['article_categories'], 'slug');
foreach ($tables['sections'] as &$row) {
PageDraft::slug($row['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links', 'layout'], true)) {
throw new RuntimeException('备份包含未知区块样式。');
}
$row['body'] = Html::sanitize($row['body'] ?? '');
$row['presentation'] = CanvasStyle::encode(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::SECTION));
if (isset($row['feed'])) {
$feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|| !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
|| array_diff($feed['categories'], array_column($tables['article_categories'], 'slug'))
|| !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
throw new RuntimeException('备份的动态区块配置无效。');
}
}
$row = self::normalizeSection($row, $categories);
}
unset($row);
foreach ($tables['articles'] as &$row) {
@@ -275,22 +258,169 @@ final class SiteBackup
return $tables;
}
private static function normalizePage(array $row, array $designs, bool $historical = false): array
{
self::validateAssetUrl($row['image'] ?? '', true);
$row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
$row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
$row['presentation'] = CanvasStyle::encode(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::PAGE));
$row['head_html'] = empty($row['layout_id']) ? PageHead::normalize($row['head_html'] ?? '') : '';
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = '';
}
foreach (['header', 'footer', 'palette'] as $kind) {
$id = $row[$kind . '_id'] ?? null;
$row[$kind . '_id'] = $historical && is_int($id) && !isset($designs[$id])
? null : self::selection($designs, $kind, $id);
}
return $row;
}
private static function normalizeSection(array $row, array $categories, bool $historical = false): array
{
PageDraft::slug($row['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links', 'layout'], true)) {
throw new RuntimeException('备份包含未知区块样式。');
}
$row['body'] = Html::sanitize($row['body'] ?? '');
$row['presentation'] = CanvasStyle::encode(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::SECTION));
if (isset($row['feed'])) {
$feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|| !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
|| (!$historical && array_diff($feed['categories'], $categories))
|| !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
throw new RuntimeException('备份的动态区块配置无效。');
}
}
return $row;
}
private static function normalizeRevisions(array &$tables, array $designs): array
{
$categories = array_column($tables['article_categories'], 'slug');
$pages = array_column($tables['pages'], null, 'slug');
$revisions = [];
foreach ($tables['page_revisions'] as &$row) {
$page = self::decode($row['payload'] ?? '');
PageDraft::slug($page['slug'] ?? null, includeSpecial: true);
if (!isset($pages[$row['draft_slug'] ?? '']) || !is_int($row['id'] ?? null) || $row['id'] <= 0
|| !in_array($page['page_type'] ?? '', array_keys(LayoutPage::TYPES + SystemPage::TYPES), true)
|| !in_array($page['layout_kind'] ?? null, [null, 'header', 'footer'], true)
|| !is_array($page['sections'] ?? null) || !array_is_list($page['sections'])) {
throw new RuntimeException('备份包含无效的页面历史。');
}
$fields = ['actions', 'quicklinks', 'alignments', 'visibility', 'presentation'];
foreach ($fields as $field) {
$page[$field] = Database::json($page[$field] ?? []);
}
$page = self::normalizePage($page, $designs, historical: true);
foreach ($fields as $field) {
$page[$field] = self::decode($page[$field]);
}
foreach ($page['sections'] as &$section) {
$section = self::normalizeSection($section, $categories, historical: true);
self::validateReuseIds($section);
unset($section['mirror_source']);
}
unset($section);
$row['payload'] = Database::json($page);
$revisions[$row['id']] = [$row['draft_slug'], $row['kind'], $page['slug'], $page['page_type']];
}
unset($row);
$live = [];
$systemPages = [];
foreach ($tables['page_publications'] as $row) {
$revision = $revisions[$row['revision_id'] ?? 0] ?? null;
if (!$revision || $revision[0] !== ($row['draft_slug'] ?? null) || $revision[1] !== 'published'
|| $revision[2] !== ($row['route_slug'] ?? null)) {
throw new RuntimeException('备份包含无效的发布快照。');
}
$live[$row['draft_slug']] = true;
if (isset(SystemPage::TYPES[$revision[3]])) {
$systemPages[$row['route_slug']] = $revision[3];
}
}
foreach ($tables['pages'] as &$page) {
$page['status'] = isset($live[$page['slug']]) ? 'published' : 'draft';
}
unset($page);
foreach ($tables['section_reuse'] as $row) {
self::validateReuseIds($row);
}
foreach ($tables['published_blocks'] as &$row) {
self::validateReuseIds($row);
$section = self::normalizeSection(self::decode($row['payload'] ?? ''), $categories, historical: true);
if (($section['main_id'] ?? null) !== $row['main_id'] || isset($section['mirror_id'])) {
throw new RuntimeException('备份包含无效的主区块快照。');
}
$row['payload'] = Database::json($section);
}
unset($row);
foreach ($tables['layout_draft_settings'] as &$row) {
$kind = $designs[$row['layout_id'] ?? 0] ?? '';
$config = self::decode($row['payload'] ?? '');
if (!in_array($kind, ['header', 'footer'], true) || !is_bool($config['default'] ?? null)
|| (isset($config['provider']) && ($kind !== 'header' || !is_array($config['provider'])))) {
throw new RuntimeException('备份包含无效的页头页脚草稿设置。');
}
if (isset($config['provider'])) {
DesignLibrary::normalize('header', 'member', ['provider' => $config['provider']]);
}
$row = ['layout_id' => $row['layout_id'], 'payload' => Database::json([
'default' => $config['default'], 'provider' => $config['provider'] ?? null,
])];
}
unset($row);
return $systemPages;
}
private static function validateReuseIds(array $row): void
{
foreach (['main_id', 'mirror_id'] as $field) {
if (isset($row[$field]) && (!is_string($row[$field]) || !preg_match('/^[a-f0-9]{32}$/D', $row[$field]))) {
throw new RuntimeException('备份包含无效的区块关联。');
}
}
}
private static function replaceTables(PDO $pdo, array $tables): void
{
$credentials = array_column($pdo->query("SELECT layout_id, revision, encrypted_secret, payload
FROM layout_oauth_credentials JOIN design_presets ON id = layout_id
WHERE kind = 'header' AND preset = 'member'")->fetchAll(), null, 'layout_id');
$clean = [];
if (isset($tables['page_revisions'])) {
$draftVersions = array_column($tables['pages'], 'version', 'slug');
$publishedIds = array_fill_keys(array_column($tables['page_publications'], 'revision_id'), true);
foreach ($tables['page_revisions'] as $revision) {
if (isset($publishedIds[$revision['id']])
&& ($draftVersions[$revision['draft_slug']] ?? null) === self::decode($revision['payload'])['version']) {
$clean[$revision['id']] = $revision['draft_slug'];
}
}
}
$tableNames = [...self::TABLES, ...self::REVISION_TABLES];
$revisions = [];
foreach (self::TABLES as $table) {
foreach ($tableNames as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
$revisions[$table] = in_array('version', $columns, true) ? max(1, (int) $pdo->query('SELECT MAX(version) FROM ' . $table)->fetchColumn() + 1) : 0;
}
foreach (array_reverse(self::TABLES) as $table) {
foreach (array_reverse($tableNames) as $table) {
$pdo->exec('DELETE FROM ' . $table);
}
foreach (self::TABLES as $table) {
foreach ($tableNames as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
foreach ($tables[$table] as $row) {
if ($revisions[$table] && !empty($tables[$table])) {
$revisions[$table] = max($revisions[$table], 1 + max(array_column($tables[$table], 'version') ?: [0]));
}
foreach ($tables[$table] ?? [] as $row) {
$row = array_intersect_key($row, array_flip($columns));
if ($revisions[$table]) {
$row['version'] = $revisions[$table];
@@ -316,6 +446,13 @@ final class SiteBackup
}
}
LayoutPage::migrate($pdo);
// Advance the matching published revision so a clean draft stays clean after restore.
$snapshot = $pdo->prepare("UPDATE page_revisions SET payload = json_set(payload, '$.version',
(SELECT version FROM pages WHERE slug = ?)) WHERE id = ?");
foreach ($clean as $id => $slug) {
$snapshot->execute([$slug, $id]);
}
PageRevisions::seed($pdo);
}
private static function selection(array $designs, string $kind, mixed $id): ?int