forked from laysense/laysite
Edit shared headers and footers as page types
This commit is contained in:
@@ -104,7 +104,9 @@ final class BlockTemplates
|
||||
|
||||
public static function groups(): array
|
||||
{
|
||||
return self::GROUPS;
|
||||
static $groups;
|
||||
|
||||
return $groups ??= self::GROUPS + LayoutPage::groups();
|
||||
}
|
||||
|
||||
public static function find(string $key): ?array
|
||||
|
||||
@@ -11,7 +11,7 @@ use Throwable;
|
||||
|
||||
final class Database
|
||||
{
|
||||
private const SCHEMA_VERSION = 3;
|
||||
private const SCHEMA_VERSION = 4;
|
||||
// Avoid reusing a deleted ID that may still be open in an editing form.
|
||||
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
|
||||
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
|
||||
@@ -82,6 +82,14 @@ final class Database
|
||||
if ($version < 2) {
|
||||
OAuthCredentials::migrateLegacy($pdo);
|
||||
}
|
||||
if ($version < 4) {
|
||||
$columns = $pdo->query('PRAGMA table_info(pages)')->fetchAll();
|
||||
if (!in_array('layout_id', array_column($columns, 'name'), true)) {
|
||||
$pdo->exec('ALTER TABLE pages ADD COLUMN layout_id INTEGER REFERENCES design_presets(id)');
|
||||
}
|
||||
$pdo->exec('CREATE UNIQUE INDEX IF NOT EXISTS pages_layout_id ON pages(layout_id)');
|
||||
LayoutPage::migrate($pdo);
|
||||
}
|
||||
if ($version < self::SCHEMA_VERSION) {
|
||||
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ final class DesignLibrary
|
||||
'accent-light' => ['强调色浅底', '#e8efff'], 'line' => ['边框', '#dbe3f0'],
|
||||
'button-ink' => ['填充按钮文字', '#ffffff'],
|
||||
];
|
||||
public const PROVIDER_FIELDS = ['mode', 'client_id', 'scope', 'issuer', 'authorization', 'token', 'userinfo',
|
||||
'subject_field', 'name_field', 'avatar_field', 'token_auth'];
|
||||
|
||||
public static function all(?string $kind = null): array
|
||||
{
|
||||
@@ -151,7 +153,7 @@ final class DesignLibrary
|
||||
throw new DesignFieldError('provider_mode', '请选择 OIDC 或 OAuth 2.0。');
|
||||
}
|
||||
$result = ['mode' => $mode];
|
||||
foreach (['client_id', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
|
||||
foreach (array_slice(self::PROVIDER_FIELDS, 1) as $field) {
|
||||
$result[$field] = self::string($data[$field] ?? '', 600, 'provider_' . $field);
|
||||
}
|
||||
if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) {
|
||||
@@ -186,10 +188,20 @@ final class DesignLibrary
|
||||
return null;
|
||||
}
|
||||
|
||||
$page = (new Repository())->layoutPage((int) $layout['id']);
|
||||
if ($page !== null && !LayoutPage::hasMember($page['sections'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return hash('sha256', Database::json([$layout['payload']['provider'], $layout['credential_revision']]));
|
||||
}
|
||||
|
||||
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int
|
||||
{
|
||||
return Database::write(static fn (PDO $pdo): int => self::saveIn($pdo, $kind, $id, $name, $preset, $data, $version, $default, $secret));
|
||||
}
|
||||
|
||||
public static function saveIn(PDO $pdo, string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default, string $secret = ''): int
|
||||
{
|
||||
$name = self::string($name, 100, 'name');
|
||||
if ($name === '') {
|
||||
@@ -200,44 +212,50 @@ final class DesignLibrary
|
||||
$provider = $clean['provider'] ?? [];
|
||||
$active = $provider !== [] && self::hasAccount($preset, $clean['components']);
|
||||
|
||||
return Database::write(function (PDO $pdo) use ($kind, $id, $name, $preset, $payload, $version, $default, $provider, $active, $secret): int {
|
||||
if ($active && $secret === '') {
|
||||
$saved = $id === null ? null : self::find($id, $kind);
|
||||
$fields = array_flip(['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id']);
|
||||
if (empty($saved['credential_revision'])
|
||||
|| array_intersect_key($provider, $fields) !== array_intersect_key($saved['payload']['provider'], $fields)) {
|
||||
throw new DesignFieldError('provider_secret', '启用登录或变更身份提供商时,请填写客户端密钥。');
|
||||
}
|
||||
if ($active && $secret === '') {
|
||||
$saved = $id === null ? null : self::find($id, $kind);
|
||||
$fields = array_flip(['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id']);
|
||||
if (empty($saved['credential_revision'])
|
||||
|| array_intersect_key($provider, $fields) !== array_intersect_key($saved['payload']['provider'], $fields)) {
|
||||
throw new DesignFieldError('provider_secret', '启用登录或变更身份提供商时,请填写客户端密钥。');
|
||||
}
|
||||
if ($id === null) {
|
||||
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')->execute([$kind, $name, $preset, $payload]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
} else {
|
||||
$query = $pdo->prepare('UPDATE design_presets SET name = ?, preset = ?, payload = ?, version = version + 1 WHERE id = ? AND kind = ? AND version = ?');
|
||||
$query->execute([$name, $preset, $payload, $id, $kind, $version]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('配置已更新,请重新打开后再保存。');
|
||||
}
|
||||
}
|
||||
if ($id === null) {
|
||||
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')->execute([$kind, $name, $preset, $payload]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
} else {
|
||||
$query = $pdo->prepare('UPDATE design_presets SET name = ?, preset = ?, payload = ?, version = version + 1 WHERE id = ? AND kind = ? AND version = ?');
|
||||
$query->execute([$name, $preset, $payload, $id, $kind, $version]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('配置已更新,请重新打开后再保存。');
|
||||
}
|
||||
if ($kind === 'header') {
|
||||
if ($provider === []) {
|
||||
$pdo->prepare('DELETE FROM layout_oauth_credentials WHERE layout_id = ?')->execute([$id]);
|
||||
} elseif ($active && $secret !== '') {
|
||||
OAuthCredentials::store($pdo, $id, $secret);
|
||||
}
|
||||
}
|
||||
if ($kind !== 'palette') {
|
||||
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if ($default) {
|
||||
$site[$kind . '_id'] = $id;
|
||||
} elseif (($site[$kind . '_id'] ?? null) === $id) {
|
||||
unset($site[$kind . '_id']);
|
||||
}
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
}
|
||||
if ($kind === 'header') {
|
||||
if ($provider === []) {
|
||||
$pdo->prepare('DELETE FROM layout_oauth_credentials WHERE layout_id = ?')->execute([$id]);
|
||||
} elseif ($active && $secret !== '') {
|
||||
OAuthCredentials::store($pdo, $id, $secret);
|
||||
}
|
||||
}
|
||||
if ($kind !== 'palette') {
|
||||
self::setDefault($pdo, $kind, $id, $default);
|
||||
}
|
||||
|
||||
return $id;
|
||||
});
|
||||
return $id;
|
||||
}
|
||||
|
||||
public static function setDefault(PDO $pdo, string $kind, int $id, bool $default): void
|
||||
{
|
||||
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
$field = $kind . '_id';
|
||||
if ($default) {
|
||||
$site[$field] = $id;
|
||||
} elseif (($site[$field] ?? null) === $id) {
|
||||
unset($site[$field]);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
}
|
||||
|
||||
private static function string(mixed $value, int $limit, string $field): string
|
||||
|
||||
+61
-17
@@ -15,12 +15,13 @@ final class Html
|
||||
public const ALIGNMENTS = ['left', 'center', 'right'];
|
||||
|
||||
private const TAGS = [
|
||||
'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'button' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'figure' => [], 'figcaption' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
|
||||
'a' => ['href', 'target', 'rel', 'aria-label'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
|
||||
'button' => ['aria-expanded', 'aria-controls', 'hidden'], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
||||
'dl' => [], 'dt' => [], 'em' => [], 'figure' => [], 'figcaption' => [], 'footer' => [],
|
||||
'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'header' => [], 'hr' => [], 'i' => [],
|
||||
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
|
||||
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
|
||||
'section' => [], 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
|
||||
'li' => [], 'nav' => ['aria-label'], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
|
||||
'section' => ['aria-labelledby'], 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
|
||||
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
|
||||
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
|
||||
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
|
||||
@@ -98,24 +99,67 @@ final class Html
|
||||
}
|
||||
self::sanitizeChildren($body);
|
||||
if ($anchorPrefix !== null) {
|
||||
$ids = [];
|
||||
foreach ($body->getElementsByTagName('*') as $element) {
|
||||
$id = $element->getAttribute('id');
|
||||
if ($id !== '') {
|
||||
$ids[$id] = $anchorPrefix . '-' . $id;
|
||||
$element->setAttribute('id', $ids[$id]);
|
||||
}
|
||||
self::scopeIds($body, $anchorPrefix);
|
||||
}
|
||||
|
||||
return self::bodyMarkup($body);
|
||||
}
|
||||
|
||||
public static function sharedFragment(string $html, string $scope, string $account): string
|
||||
{
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$document->loadHTML('<!doctype html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$body = $document->getElementsByTagName('body')->item(0);
|
||||
if (!$body) {
|
||||
return '';
|
||||
}
|
||||
self::scopeIds($body, $scope);
|
||||
foreach (iterator_to_array($body->getElementsByTagName('a')) as $node) {
|
||||
if (!in_array('studio-member-slot', preg_split('/\s+/', $node->getAttribute('class')), true)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($body->getElementsByTagName('a') as $link) {
|
||||
$href = $link->getAttribute('href');
|
||||
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
|
||||
$link->setAttribute('href', '#' . $ids[substr($href, 1)]);
|
||||
if ($account !== '') {
|
||||
$fragment = new DOMDocument('1.0', 'UTF-8');
|
||||
$fragment->loadHTML('<!doctype html><html><head><meta charset="UTF-8"></head><body>' . $account . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
||||
$replacement = $fragment->getElementsByTagName('a')->item(0);
|
||||
$node->parentNode->replaceChild($document->importNode($replacement, true), $node);
|
||||
} else {
|
||||
$node->parentNode->removeChild($node);
|
||||
}
|
||||
}
|
||||
|
||||
return self::bodyMarkup($body);
|
||||
}
|
||||
|
||||
private static function scopeIds(DOMElement $body, string $prefix): void
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($body->getElementsByTagName('*') as $element) {
|
||||
$id = $element->getAttribute('id');
|
||||
if ($id !== '') {
|
||||
$ids[$id] = $prefix . '-' . $id;
|
||||
$element->setAttribute('id', $ids[$id]);
|
||||
}
|
||||
}
|
||||
foreach ($body->getElementsByTagName('*') as $element) {
|
||||
$href = $element->getAttribute('href');
|
||||
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
|
||||
$element->setAttribute('href', '#' . $ids[substr($href, 1)]);
|
||||
}
|
||||
foreach (['for', 'aria-labelledby', 'aria-controls'] as $attribute) {
|
||||
if ($element->hasAttribute($attribute)) {
|
||||
$tokens = preg_split('/\s+/', $element->getAttribute($attribute));
|
||||
$element->setAttribute($attribute, implode(' ', array_map(static fn ($id) => $ids[$id] ?? $id, $tokens)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function bodyMarkup(DOMElement $body): string
|
||||
{
|
||||
$output = '';
|
||||
foreach ($body->childNodes as $child) {
|
||||
$output .= $document->saveHTML($child);
|
||||
$output .= $body->ownerDocument->saveHTML($child);
|
||||
}
|
||||
|
||||
return trim($output);
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use PDO;
|
||||
use RuntimeException;
|
||||
|
||||
final class LayoutPage
|
||||
{
|
||||
public const TYPES = ['page' => '普通页面', 'header' => '页头', 'footer' => '页脚'];
|
||||
|
||||
public static function slug(string $kind, int $id): string
|
||||
{
|
||||
return "layout--$kind-$id";
|
||||
}
|
||||
|
||||
public static function create(string $kind, string $name): string
|
||||
{
|
||||
return Database::write(static function (PDO $pdo) use ($kind, $name): string {
|
||||
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')
|
||||
->execute([$kind, $name, array_key_first(DesignLibrary::PRESETS[$kind]), Database::json(DesignLibrary::defaults($kind))]);
|
||||
$id = (int) $pdo->lastInsertId();
|
||||
$slug = self::slug($kind, $id);
|
||||
Repository::insertPage($pdo, $slug, $name, ['visibility' => ['hero' => false]], $id);
|
||||
|
||||
return $slug;
|
||||
});
|
||||
}
|
||||
|
||||
public static function migrate(PDO $pdo): void
|
||||
{
|
||||
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
$rows = $pdo->query("SELECT d.* FROM design_presets d LEFT JOIN pages p ON p.layout_id = d.id
|
||||
WHERE d.kind IN ('header', 'footer') AND p.slug IS NULL")->fetchAll();
|
||||
foreach ($rows as $row) {
|
||||
$kind = $row['kind'];
|
||||
$layout = $row;
|
||||
$layout['payload'] = DesignLibrary::normalize($kind, $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
|
||||
$body = self::component($kind, $layout, $site['name']);
|
||||
Repository::insertPage($pdo, self::slug($kind, $row['id']), $row['name'], [
|
||||
'visibility' => ['hero' => false],
|
||||
'sections' => [[
|
||||
'key' => 'layout-content', 'title' => DesignLibrary::PRESETS[$kind][$row['preset']], 'lead' => '',
|
||||
'body' => Html::sanitize($body), 'style' => 'layout',
|
||||
]],
|
||||
], $row['id']);
|
||||
}
|
||||
}
|
||||
|
||||
public static function groups(): array
|
||||
{
|
||||
$groups = [];
|
||||
foreach (['header', 'footer'] as $kind) {
|
||||
$items = [];
|
||||
foreach (DesignLibrary::PRESETS[$kind] as $preset => $label) {
|
||||
$body = self::sample($kind, $preset);
|
||||
$items[$kind . '-' . $preset] = [$label, Html::sanitize($body), '', null, 'layout'];
|
||||
}
|
||||
$groups[$kind . 's'] = [self::TYPES[$kind], $items];
|
||||
}
|
||||
|
||||
return $groups;
|
||||
}
|
||||
|
||||
public static function sample(string $kind, string $preset): string
|
||||
{
|
||||
$layout = ['id' => 0, 'preset' => $preset, 'payload' => array_replace(DesignLibrary::defaults($kind), [
|
||||
'brand' => '品牌名称', 'links' => [['/', '首页'], ['/articles', '文章']],
|
||||
'action' => [['/articles', '了解更多', 'solid', false]], 'text' => '关于网站的一句话介绍。', 'legal' => '© 品牌名称',
|
||||
])];
|
||||
|
||||
return self::component($kind, $layout, '品牌名称');
|
||||
}
|
||||
|
||||
private static function component(string $kind, array $layout, string $name): string
|
||||
{
|
||||
return View::fragment($kind, [
|
||||
$kind => $layout, 'site' => ['name' => $name], 'showHeader' => true, 'showFooter' => true,
|
||||
'path' => null, 'visitor' => null, 'member' => false, 'layoutTemplate' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public static function hasMember(array $sections): bool
|
||||
{
|
||||
foreach ($sections as $section) {
|
||||
if (str_contains($section['body'], 'studio-member-slot')
|
||||
&& preg_match_all('~<a\b[^>]*\sclass="([^"]*)"~i', $section['body'], $matches)) {
|
||||
foreach ($matches[1] as $classes) {
|
||||
if (in_array('studio-member-slot', preg_split('/\s+/', $classes), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function saveSettings(PDO $pdo, array $page, array $config): void
|
||||
{
|
||||
$kind = $page['layout_kind'];
|
||||
$id = $page['layout_id'];
|
||||
if ($kind === 'header' && $config['provider'] !== null) {
|
||||
if (!self::hasMember($page['sections'])) {
|
||||
throw new RuntimeException('请先在画布中添加会员导航。');
|
||||
}
|
||||
$layout = DesignLibrary::find($id, $kind);
|
||||
$payload = $layout['payload'];
|
||||
$payload['provider'] = $config['provider'];
|
||||
$payload['components'] = array_values(array_unique([...$payload['components'], 'account']));
|
||||
DesignLibrary::saveIn($pdo, $kind, $id, $page['name'], 'member', $payload, $layout['version'], $config['default'], $config['secret']);
|
||||
} else {
|
||||
$pdo->prepare('UPDATE design_presets SET name = ?, version = version + 1 WHERE id = ?')->execute([$page['name'], $id]);
|
||||
DesignLibrary::setDefault($pdo, $kind, $id, $config['default']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,11 @@ final class PageDraft
|
||||
{
|
||||
public const RESERVED = ['admin', 'assets', 'home', 'account', 'mcp', 'palette'];
|
||||
|
||||
public static function slug(mixed $value, array $reserved = self::RESERVED): string
|
||||
public static function slug(mixed $value, array $reserved = self::RESERVED, bool $includeLayouts = false): string
|
||||
{
|
||||
if ($includeLayouts && is_string($value) && preg_match('/^layout--(?:header|footer)-[1-9][0-9]{0,18}$/D', $value)) {
|
||||
return $value;
|
||||
}
|
||||
if (!is_string($value) || strlen($value) > 70 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value)
|
||||
|| in_array($value, $reserved, true)) {
|
||||
throw new RuntimeException('网址标识无效或已保留。');
|
||||
@@ -92,7 +95,7 @@ final class PageDraft
|
||||
}
|
||||
}
|
||||
$style = $item['style'] ?? $preset[4] ?? 'plain';
|
||||
if (!in_array($style, ['plain', 'tinted'], true)) {
|
||||
if (!in_array($style, ['plain', 'tinted', 'layout'], true)) {
|
||||
throw new RuntimeException('区块样式无效。');
|
||||
}
|
||||
$sections[$key] = [
|
||||
|
||||
+68
-21
@@ -30,35 +30,41 @@ final class Repository
|
||||
|
||||
public function pages(bool $publishedOnly = false): array
|
||||
{
|
||||
$where = $publishedOnly ? " WHERE status = 'published'" : '';
|
||||
$where = $publishedOnly ? " WHERE pages.status = 'published' AND pages.layout_id IS NULL" : '';
|
||||
|
||||
return $this->pdo->query('SELECT slug, name, title, updated_at, status, version FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
|
||||
return $this->pdo->query('SELECT pages.slug, pages.name, pages.title, pages.updated_at, pages.status, pages.version, d.kind AS layout_kind
|
||||
FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id' . $where . ' ORDER BY pages.rowid')->fetchAll();
|
||||
}
|
||||
|
||||
public function createPage(string $slug, string $name, array $template = []): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($slug, $name, $template): void {
|
||||
$query = $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
|
||||
lead, image, alt, actions, quicklinks, theme, visibility, header_id, footer_id, palette_id, status, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?)");
|
||||
$query->execute([
|
||||
$slug, $name, $template['title'] ?? $name, $template['description'] ?? '', $template['heading'] ?? $name,
|
||||
$template['accent'] ?? '', $template['lead'] ?? '', $template['image'] ?? '', $template['alt'] ?? '',
|
||||
Database::json($template['actions'] ?? []), Database::json($template['quicklinks'] ?? []),
|
||||
$template['theme'] ?? '', Database::json($template['visibility'] ?? []), $template['header_id'] ?? null, $template['footer_id'] ?? null, $template['palette_id'] ?? null, self::now(),
|
||||
]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此页面地址已存在。');
|
||||
}
|
||||
foreach ($template['sections'] ?? [] as $section) {
|
||||
self::insertSection($pdo, $slug, $section['key'], $section);
|
||||
}
|
||||
});
|
||||
Database::write(static fn (PDO $pdo) => self::insertPage($pdo, $slug, $name, $template));
|
||||
}
|
||||
|
||||
public static function insertPage(PDO $pdo, string $slug, string $name, array $template = [], ?int $layoutId = null): void
|
||||
{
|
||||
$query = $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
|
||||
lead, image, alt, actions, quicklinks, theme, visibility, header_id, footer_id, palette_id, layout_id, status, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
||||
$query->execute([
|
||||
$slug, $name, $template['title'] ?? $name, $template['description'] ?? '', $template['heading'] ?? $name,
|
||||
$template['accent'] ?? '', $template['lead'] ?? '', $template['image'] ?? '', $template['alt'] ?? '',
|
||||
Database::json($template['actions'] ?? []), Database::json($template['quicklinks'] ?? []),
|
||||
$template['theme'] ?? '', Database::json($template['visibility'] ?? []), $template['header_id'] ?? null,
|
||||
$template['footer_id'] ?? null, $template['palette_id'] ?? null, $layoutId, $layoutId === null ? 'draft' : 'published', self::now(),
|
||||
]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此页面地址已存在。');
|
||||
}
|
||||
foreach ($template['sections'] ?? [] as $section) {
|
||||
self::insertSection($pdo, $slug, $section['key'], $section);
|
||||
}
|
||||
}
|
||||
|
||||
public function page(string $slug): ?array
|
||||
{
|
||||
$page = $this->one('SELECT * FROM pages WHERE slug = ?', [$slug]);
|
||||
$page = $this->one('SELECT pages.*, d.kind AS layout_kind FROM pages
|
||||
LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]);
|
||||
if (!$page) {
|
||||
return null;
|
||||
}
|
||||
@@ -72,6 +78,44 @@ final class Repository
|
||||
return $page;
|
||||
}
|
||||
|
||||
public function layoutPage(int $id): ?array
|
||||
{
|
||||
$row = $this->one('SELECT slug FROM pages WHERE layout_id = ?', [$id]);
|
||||
|
||||
return $row ? $this->page($row['slug']) : null;
|
||||
}
|
||||
|
||||
public function withSectionFeeds(array $page): array
|
||||
{
|
||||
$categories = null;
|
||||
foreach ($page['sections'] as &$section) {
|
||||
if (!$section['feed']) {
|
||||
continue;
|
||||
}
|
||||
$categories ??= $this->categories();
|
||||
$feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
|
||||
$network = $feed['mode'] === 'network';
|
||||
$catalog = $feed['mode'] === 'catalog';
|
||||
$grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1);
|
||||
$archivePath = '/articles/feed/' . $page['slug'] . '/' . $section['key'];
|
||||
$section['archivePath'] = empty($page['layout_kind']) && $page['status'] === 'published' ? $archivePath : null;
|
||||
$section['articleFeed'] = [];
|
||||
$section['networkFeed'] = $network;
|
||||
$section['catalogFeed'] = $catalog;
|
||||
$section['feedLimit'] = $feed['limit'];
|
||||
foreach ($grouped ? $feed['categories'] : [''] as $category) {
|
||||
$selected = $category === '' ? $feed['categories'] : [$category];
|
||||
$section['articleFeed'][] = [
|
||||
'categories' => $selected, 'label' => $categories[$category] ?? '',
|
||||
'articles' => $this->articles($selected, limit: $feed['limit'], directoryOrder: $network || $catalog),
|
||||
];
|
||||
}
|
||||
}
|
||||
unset($section);
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
public function section(string $page, string $key): ?array
|
||||
{
|
||||
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
|
||||
@@ -81,7 +125,7 @@ final class Repository
|
||||
{
|
||||
return $this->one("SELECT sections.title, sections.feed FROM sections
|
||||
JOIN pages ON pages.slug = sections.page_slug
|
||||
WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
|
||||
WHERE pages.slug = ? AND pages.status = 'published' AND pages.layout_id IS NULL AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
|
||||
}
|
||||
|
||||
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
|
||||
@@ -111,6 +155,9 @@ final class Repository
|
||||
if ($sectionOrder !== null) {
|
||||
self::writeSectionOrder($pdo, $slug, $sectionOrder);
|
||||
}
|
||||
if (isset($data['layoutConfig'])) {
|
||||
LayoutPage::saveSettings($pdo, $this->page($slug), $data['layoutConfig']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use Throwable;
|
||||
final class SiteBackup
|
||||
{
|
||||
private const FORMAT = 'laysite-site';
|
||||
private const VERSION = 2;
|
||||
private const VERSION = 3;
|
||||
private const TABLES = [
|
||||
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
|
||||
'article_category_links', 'article_redirects', 'article_deletions', 'media',
|
||||
@@ -140,7 +140,7 @@ final class SiteBackup
|
||||
private static function prepare(mixed $manifest): array
|
||||
{
|
||||
if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT
|
||||
|| !in_array($manifest['version'] ?? null, [1, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
|
||||
|| !in_array($manifest['version'] ?? null, [1, 2, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
|
||||
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
|
||||
}
|
||||
$tables = $manifest['tables'];
|
||||
@@ -179,7 +179,16 @@ final class SiteBackup
|
||||
}
|
||||
$tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
|
||||
foreach ($tables['pages'] as &$row) {
|
||||
PageDraft::slug($row['slug'] ?? null, array_diff(PageDraft::RESERVED, ['home']));
|
||||
$layout = $row['layout_id'] ?? null;
|
||||
if ($layout === null) {
|
||||
PageDraft::slug($row['slug'] ?? null, array_diff(PageDraft::RESERVED, ['home']));
|
||||
} else {
|
||||
$kind = is_int($layout) ? ($designs[$layout] ?? null) : null;
|
||||
if (!in_array($kind, ['header', 'footer'], true) || ($row['slug'] ?? null) !== LayoutPage::slug($kind, $layout)) {
|
||||
throw new RuntimeException('备份包含无效的页头或页脚页面。');
|
||||
}
|
||||
$row['status'] = 'published';
|
||||
}
|
||||
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));
|
||||
@@ -196,7 +205,7 @@ final class SiteBackup
|
||||
unset($row);
|
||||
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'], true)) {
|
||||
if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links', 'layout'], true)) {
|
||||
throw new RuntimeException('备份包含未知区块样式。');
|
||||
}
|
||||
$row['body'] = Html::sanitize($row['body'] ?? '');
|
||||
@@ -267,6 +276,7 @@ final class SiteBackup
|
||||
$insert->execute([$layout['id'], $saved['revision'], $saved['encrypted_secret']]);
|
||||
}
|
||||
}
|
||||
LayoutPage::migrate($pdo);
|
||||
}
|
||||
|
||||
private static function selection(array $designs, string $kind, mixed $id): ?int
|
||||
|
||||
+17
-1
@@ -15,8 +15,9 @@ final class View
|
||||
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
|
||||
$data['cdn'] = $cdn;
|
||||
$personalized = false;
|
||||
if (!$admin) {
|
||||
if (!$admin && empty($data['page']['layout_kind'])) {
|
||||
$page = $data['page'] ?? [];
|
||||
$repo = new Repository();
|
||||
$data['header'] = DesignLibrary::layout('header', $data['site'], $page);
|
||||
$data['footer'] = DesignLibrary::layout('footer', $data['site'], $page);
|
||||
$data['visitor'] = null;
|
||||
@@ -31,6 +32,21 @@ final class View
|
||||
$data['visitor'] = $profile;
|
||||
}
|
||||
}
|
||||
foreach (['header', 'footer'] as $kind) {
|
||||
$id = $data[$kind]['id'];
|
||||
if ($id === 0 || (!($page['visibility'][$kind] ?? true) && empty($data['canvas']))) {
|
||||
continue;
|
||||
}
|
||||
$region = $repo->layoutPage($id);
|
||||
if ($region) {
|
||||
$account = $kind === 'header' && $data['member']
|
||||
? self::fragment('member-account', ['layoutId' => $id, 'visitor' => $data['visitor']]) : '';
|
||||
$markup = self::fragment('page', [
|
||||
'page' => $repo->withSectionFeeds($region), 'site' => $data['site'], 'canvas' => false,
|
||||
]);
|
||||
$data[$kind . 'Markup'] = Html::sharedFragment($markup, $region['slug'], $account);
|
||||
}
|
||||
}
|
||||
}
|
||||
$html = self::fragment($template, $data);
|
||||
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
|
||||
|
||||
Reference in New Issue
Block a user