diff --git a/README.md b/README.md index 1158240..a5ad97c 100644 --- a/README.md +++ b/README.md @@ -32,14 +32,20 @@ php start.php start ## 页面与站点设计 - 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。 +- 「图层」可定位或移除首屏,也可调整独立区块的顺序。保存页面后生效。移除的首屏可通过撤销或「页面设置 → 页面显示」恢复。 +- 选中元素可编辑四边的内外边距。选中文字后可修改字号、粗体、斜体和删除线。Enter 或 Shift+Enter 在当前元素内换行。正文用 Ctrl+Enter(macOS 上为 ⌘+Enter)或工具栏「换段」新建段落,列表中则新增列表项。 +- 画布支持 Ctrl/⌘+Z 撤销和 Ctrl/⌘+Shift+Z 重做。页面设置的输入框保留浏览器原生撤销。 - 选中按钮后可复制。在「属性」中选择纯色填充、线框、下划线或无样式,并选择是否在新标签页打开。首屏支持最多八个按钮。 -- 「站点设计」中可以保存多套页头、页脚和配色。选择布局模板后,可以勾选并排序标识、导航、按钮、文字、版权或用户区组件,填入各组件内容。页头和页脚可以设为站点默认。每页可覆盖这两个默认项、选择配色,或独立隐藏页头和页脚。 +- 在「网站页面 → 新建页面」选择普通页面、页头或页脚。三种页面共用同一个画布。页头页脚版式在「组件 → 页头/页脚」,也可添加封面、视频、文章等常规区块,或在页面设置中显示首屏。 +- 页头和页脚可设为站点默认。普通页面各用一个下拉框选择隐藏、站点默认或指定方案。页头页脚作为共享区域显示,无独立公开网址。配色方案在「站点设计」管理。 - 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。 - 发布后的站点具备独立标题、描述、canonical、Open Graph、站点地图和 robots.txt。可在「站点设置」配置站点名称和静态资源 CDN。 +画布样式以白名单 CSS 类保存。间距与字号使用限定范围内的整数,服务端生成带版本指纹的样式表,画布和使用这些类的公开页按需加载。内容经过 HTML 清理,内联 `style` 属性会被移除。 + ### 会员页头 -在「站点设计 → 页头」选择「会员导航」并勾选「用户区」,即可设置认证。将配置好的页头用作默认,或应用于需要登录的页面。 +在页头画布的「组件 → 页头」添加「会员导航」,即可打开「会员登录设置」。将配置好的页头用作默认,或应用于需要登录的页面。 | 模式 | 填写内容 | | --- | --- | @@ -81,7 +87,7 @@ Agent 可以编辑草稿,管理员在画布里检查、细改及发布。草 「站点设计 → 站点备份」支持导出和确认后覆盖导入。备份包是包含版本化 JSON 清单和校验和的 TAR,包含页面、区块、文章、站点设置、布局、配色和媒体数据。管理员密码、OAuth 客户端密钥、运行环境密钥和登录会话由目标安装独立管理。导入到原站点时,身份提供商配置一致的同一套页头会保留客户端密钥。导入到新站点后,在对应会员页头重新填写。备份存放在站点公开目录外。 -当前导出格式为 v2,导入兼容 v1 的基础内容备份并补齐空的设计库。未来格式会保留迁移入口,遇到较新的不兼容格式时提示升级。上传大小受 Webman 与外层代理限制,较大站点可使用 CLI。 +当前导出格式为 v3,导入兼容 v1 和 v2。导入 v2 后,原有页头和页脚会转换成共享页面,原有引用继续有效。遇到较新的不兼容格式时会提示升级。上传大小受 Webman 与外层代理限制,较大站点可使用 CLI。 ```sh php bin/backup.php export /srv/backups/laysite-2026-11.tar @@ -97,6 +103,8 @@ bin/update.sh v1.1.0 /srv/backups/pre-update.tar 从 v1.0.0 升级时,让执行迁移的进程能读到原先填写的 `LAYSITE_OAUTH_*` 值。升级会将这些密钥转存到 SQLite,成功后即可移除旧变量。若迁移时缺少某个旧值,在对应会员页头补填密钥即可启用登录。 +从 v1.1.0 更新画布功能时,更新脚本会添加样式字段,并将已有页头和页脚迁到「网站页面」,保留页面引用和已有认证配置。手动更新源码后,运行 `php bin/install.php` 再启动 Webman。 + ## 生产反代 在 `.env` 配置 `LAYSITE_SITE_URL=https://example.com` 和 `LAYSITE_SECURE_COOKIES=1`。下列示例假定代理和 Webman 在同一主机。代理应以实际访客来源覆盖 `X-Real-IP`,并将项目文件、数据库和媒体存储保持在公开根目录之外。 diff --git a/VERSION b/VERSION index 9084fa2..26aaba0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.0 +1.2.0 diff --git a/app/Content/BlockTemplates.php b/app/Content/BlockTemplates.php index 68dd5c9..49bd894 100644 --- a/app/Content/BlockTemplates.php +++ b/app/Content/BlockTemplates.php @@ -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 diff --git a/app/Content/CanvasStyle.php b/app/Content/CanvasStyle.php new file mode 100644 index 0000000..a28bfaa --- /dev/null +++ b/app/Content/CanvasStyle.php @@ -0,0 +1,148 @@ + ['padding-top', 0, 128], 'pr' => ['padding-right', 0, 128], + 'pb' => ['padding-bottom', 0, 128], 'pl' => ['padding-left', 0, 128], + 'mt' => ['margin-top', -128, 128], 'mr' => ['margin-right', -128, 128], + 'mb' => ['margin-bottom', -128, 128], 'ml' => ['margin-left', -128, 128], + 'size' => ['font-size', 8, 144], + ]; + private const TYPOGRAPHY = [ + 'weight-bold' => 'font-weight:700', 'weight-normal' => 'font-weight:400', + 'slant-italic' => 'font-style:italic', 'slant-normal' => 'font-style:normal', + 'strike-on' => 'text-decoration-line:line-through', 'strike-off' => 'text-decoration-line:none', + ]; + private const PREFIX = 'studio-style-'; + + public static function encode(array $presentation): string + { + return $presentation === [] ? '{}' : Database::json($presentation); + } + + public static function stylesheetUrl(): string + { + static $version; + $version ??= hash_file('xxh64', __FILE__); + + return '/canvas-style.css?v=' . $version; + } + + public static function normalize(mixed $input, array $roles): array + { + if (!is_array($input) || count($input) > count($roles) + 28) { + throw new RuntimeException('画布样式无效。'); + } + $styles = []; + foreach ($input as $role => $style) { + if ((!in_array($role, $roles, true) && !($roles === self::PAGE && is_string($role) + && preg_match('/^(?:action-[0-7]|nav-(?:[0-9]|1[0-9]))$/D', $role))) || !is_array($style)) { + throw new RuntimeException('画布样式无效。'); + } + $classes = self::classList($style['classes'] ?? ''); + $runs = $style['runs'] ?? []; + if (!is_array($runs) || !array_is_list($runs) || count($runs) > 1024) { + throw new RuntimeException('文字格式过多。'); + } + $textLength = 0; + $cleanRuns = []; + foreach ($runs as $run) { + if (!is_array($run) || !array_is_list($run) || count($run) !== 2 || !is_string($run[0]) + || ($textLength += strlen($run[0])) > 2400 || !mb_check_encoding($run[0], 'UTF-8')) { + throw new RuntimeException('文字格式无效。'); + } + $cleanRuns[] = [$run[0], self::classList($run[1], textOnly: true)]; + } + if ($classes !== '' || $cleanRuns !== []) { + $styles[$role] = ['classes' => $classes, 'runs' => $cleanRuns]; + } + } + + return $styles; + } + + private static function classList(mixed $value, bool $textOnly = false): string + { + if (!is_string($value) || strlen($value) > 320) { + throw new RuntimeException('画布样式无效。'); + } + $classes = []; + foreach (explode(' ', $value) as $class) { + if (!str_starts_with($class, self::PREFIX)) { + continue; + } + $token = substr($class, strlen(self::PREFIX)); + [$property, $size] = array_pad(explode('-', $token, 2), 2, ''); + if (isset(self::TYPOGRAPHY[$token])) { + $classes[$property] = $class; + } elseif ((!$textOnly || $property === 'size') && isset(self::PROPERTIES[$property]) + && preg_match('/^(?:0|-?[1-9]\d{0,2})$/D', $size)) { + [, $min, $max] = self::PROPERTIES[$property]; + if ((int) $size >= $min && (int) $size <= $max) { + $classes[$property] = $class; + } + } + } + + return implode(' ', $classes); + } + + public static function classes(array $styles, string $role): string + { + $classes = $styles[$role]['classes'] ?? ''; + + return $classes === '' ? '' : ' ' . View::escape($classes); + } + + public static function remapSlots(array $styles, string $prefix, array $indexes): array + { + $result = array_filter($styles, static fn (string $key): bool => !str_starts_with($key, $prefix), ARRAY_FILTER_USE_KEY); + foreach ($indexes as $next => $previous) { + if (isset($styles[$prefix . $previous])) { + $result[$prefix . $next] = $styles[$prefix . $previous]; + } + } + + return $result; + } + + public static function text(array $styles, string $role, string $plain): string + { + $runs = $styles[$role]['runs'] ?? []; + if ($runs === [] || trim(implode('', array_column($runs, 0))) !== $plain) { + return str_replace(["\r\n", "\r", "\n"], '
', View::escape($plain)); + } + $markup = ''; + foreach ($runs as [$text, $class]) { + $escaped = str_replace("\n", '
', View::escape($text)); + $markup .= $class === '' ? $escaped : '' . $escaped . ''; + } + + return $markup; + } + + public static function stylesheet(): string + { + $css = ''; + foreach (self::PROPERTIES as $key => [$property, $min, $max]) { + for ($value = $min; $value <= $max; $value++) { + $css .= '.' . self::PREFIX . "$key-$value{{$property}:{$value}px!important}\n"; + } + } + foreach (self::TYPOGRAPHY as $key => $value) { + $css .= '.' . self::PREFIX . "$key{{$value}!important}\n"; + } + + return $css . 'span.studio-style-strike-off {display:inline-block}'; + } +} diff --git a/app/Content/Database.php b/app/Content/Database.php index 0685cea..01195ba 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -11,7 +11,7 @@ use Throwable; final class Database { - private const SCHEMA_VERSION = 2; + 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'; @@ -54,6 +54,14 @@ final class Database throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。'); } $pdo->exec(file_get_contents($root . '/resources/schema.sql')); + if ($version < 3) { + foreach (['pages', 'sections'] as $table) { + $columns = $pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(); + if (!in_array('presentation', array_column($columns, 'name'), true)) { + $pdo->exec("ALTER TABLE $table ADD COLUMN presentation TEXT NOT NULL DEFAULT '{}'"); + } + } + } $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]); $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks) @@ -74,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); } diff --git a/app/Content/DesignLibrary.php b/app/Content/DesignLibrary.php index 7da8d52..c1f3c6d 100644 --- a/app/Content/DesignLibrary.php +++ b/app/Content/DesignLibrary.php @@ -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 { @@ -125,7 +127,11 @@ final class DesignLibrary } } $clean['components'] = array_values(array_unique($components)); - $clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20); + try { + $clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20); + } catch (RuntimeException $error) { + throw new DesignFieldError('links', $error->getMessage()); + } try { $clean['action'] = Buttons::validate($data['action'] ?? []); } catch (RuntimeException $error) { @@ -147,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)) { @@ -182,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 === '') { @@ -196,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 diff --git a/app/Content/Html.php b/app/Content/Html.php index 9706127..cae9f36 100644 --- a/app/Content/Html.php +++ b/app/Content/Html.php @@ -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' => [], - 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], - 'dl' => [], 'dt' => [], 'em' => [], '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' => [], - '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('' . $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('' . $account . '', 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); @@ -154,6 +198,9 @@ final class Html $element->removeAttribute('rel'); } } + if ($element->tagName === 'button') { + $element->setAttribute('type', 'button'); + } self::sanitizeChildren($element); } } diff --git a/app/Content/LayoutPage.php b/app/Content/LayoutPage.php new file mode 100644 index 0000000..64030a7 --- /dev/null +++ b/app/Content/LayoutPage.php @@ -0,0 +1,119 @@ + '普通页面', '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('~]*\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']); + } + } +} diff --git a/app/Content/PageDraft.php b/app/Content/PageDraft.php index 347cb9c..f36b746 100644 --- a/app/Content/PageDraft.php +++ b/app/Content/PageDraft.php @@ -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('网址标识无效或已保留。'); @@ -37,7 +40,11 @@ final class PageDraft $key = $kind . '_id'; $page[$key] = array_key_exists($key, $input) ? DesignLibrary::selection($kind, $input[$key]) : ($page[$key] ?? null); } - $page['actions'] = Buttons::validate($input['actions'] ?? $page['actions']); + $actions = Buttons::validate($input['actions'] ?? $page['actions']); + if (array_key_exists('actions', $input) && $actions !== Buttons::validate($page['actions'])) { + $page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'action-', []); + } + $page['actions'] = $actions; if (array_key_exists('visibility', $input)) { if (!is_array($input['visibility'])) { throw new RuntimeException('页面显示选项无效。'); @@ -55,8 +62,11 @@ final class PageDraft $page['sections'] = self::sections($input['sections']); if (!array_key_exists('actions', $input)) { $removed = array_map(static fn (string $key): string => '#' . $key, array_diff($oldKeys, array_column($page['sections'], 'key'))); - $page['actions'] = array_values(array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true))); + $kept = array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true)); + $page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'action-', array_keys($kept)); + $page['actions'] = array_values($kept); } + $page['presentation'] = CanvasStyle::remapSlots($page['presentation'] ?? [], 'nav-', []); $page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20)); } @@ -85,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] = [ diff --git a/app/Content/Repository.php b/app/Content/Repository.php index ed6227f..977e1ff 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -30,39 +30,45 @@ 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; } - foreach (['actions', 'quicklinks', 'alignments', 'visibility'] as $key) { + foreach (['actions', 'quicklinks', 'alignments', 'visibility', 'presentation'] as $key) { $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR); } $query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key'); @@ -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,18 +125,19 @@ 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): void + public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void { - Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): void { + Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void { $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, - image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); + image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, presentation = COALESCE(?, presentation), version = version + 1 WHERE slug = ? AND version = ?'); $query->execute([ $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']), - Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), $slug, $version, + Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), + isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, $slug, $version, ]); self::checkVersion($query->rowCount()); if ($replaceDraftSections) { @@ -107,6 +152,12 @@ final class Repository self::updateSection($pdo, $slug, $section['key'], $section, $section['version']); } } + if ($sectionOrder !== null) { + self::writeSectionOrder($pdo, $slug, $sectionOrder); + } + if (isset($data['layoutConfig'])) { + LayoutPage::saveSettings($pdo, $this->page($slug), $data['layoutConfig']); + } }); } @@ -120,9 +171,9 @@ final class Repository private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void { - $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1 + $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), presentation = COALESCE(?, presentation), version = version + 1 WHERE page_slug = ? AND key = ? AND version = ?'); - $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]); + $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $data['presentation'] ?? null, $page, $key, $version]); self::checkVersion($query->rowCount()); } @@ -136,9 +187,9 @@ final class Repository private static function insertSection(PDO $pdo, string $page, string $key, array $data): void { - $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); - $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]); + $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, presentation, position) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); + $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]); if ($query->rowCount() !== 1) { throw new RuntimeException('此区块锚点已被使用。'); } @@ -149,10 +200,20 @@ final class Repository $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); $query->execute([$page, $key, $version]); self::checkVersion($query->rowCount()); - $pdo->prepare("UPDATE pages SET - quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor), - actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor) - WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $page]); + $query = $pdo->prepare('SELECT actions, quicklinks, presentation FROM pages WHERE slug = ?'); + $query->execute([$page]); + $row = $query->fetch(); + $styles = json_decode($row['presentation'], true, flags: JSON_THROW_ON_ERROR); + foreach (['actions' => 'action-', 'quicklinks' => 'nav-'] as $column => $prefix) { + $links = json_decode($row[$column], true, flags: JSON_THROW_ON_ERROR); + $kept = array_filter($links, static fn (array $link): bool => $link[0] !== '#' . $key); + if (count($kept) !== count($links)) { + $row[$column] = Database::json(array_values($kept)); + $styles = CanvasStyle::remapSlots($styles, $prefix, array_keys($kept)); + } + } + $pdo->prepare('UPDATE pages SET actions = ?, quicklinks = ?, presentation = ? WHERE slug = ?') + ->execute([$row['actions'], $row['quicklinks'], CanvasStyle::encode($styles), $page]); } public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void @@ -182,14 +243,25 @@ final class Repository return; } [$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]]; - $query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?'); - foreach ($keys as $position => $section) { - $query->execute([$position, $page, $section]); - } + self::writeSectionOrder($pdo, $page, $keys); self::touchPage($pdo, $page, structureChanged: true); }); } + private static function writeSectionOrder(PDO $pdo, string $slug, array $keys): void + { + $query = $pdo->prepare("SELECT key FROM sections WHERE page_slug = ? AND style <> 'hero-links'"); + $query->execute([$slug]); + $available = $query->fetchAll(PDO::FETCH_COLUMN); + if (count($available) !== count($keys) || array_diff($available, $keys)) { + throw new RuntimeException('区块顺序已变更,请重新打开编辑页。'); + } + $query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?'); + foreach ($keys as $position => $key) { + $query->execute([$position, $slug, $key]); + } + } + private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void { $revision = $structureChanged ? ', version = version + 1' : ''; diff --git a/app/Content/SiteBackup.php b/app/Content/SiteBackup.php index dcf35e0..c83431d 100644 --- a/app/Content/SiteBackup.php +++ b/app/Content/SiteBackup.php @@ -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,12 +179,22 @@ 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)); $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)); if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) { $row['theme'] = ''; } @@ -195,10 +205,11 @@ 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'] ?? ''); + $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) @@ -265,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 diff --git a/app/Content/View.php b/app/Content/View.php index 4250710..18c0e54 100644 --- a/app/Content/View.php +++ b/app/Content/View.php @@ -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); diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index ce7d97c..c563797 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -6,9 +6,11 @@ namespace App\Controller; use App\Content\BlockTemplates; use App\Content\Buttons; +use App\Content\CanvasStyle; use App\Content\DesignLibrary; use App\Content\Database; use App\Content\Html; +use App\Content\LayoutPage; use App\Content\Passwords; use App\Content\Repository; use App\Content\SiteDesign; @@ -250,6 +252,10 @@ class AdminController if (!$page) { return $this->error($request, '找不到此页面。', 404); } + $site = $repo->site(); + $layoutKind = $page['layout_kind']; + $layout = $layoutKind === null ? null : DesignLibrary::find($page['layout_id'], $layoutKind); + $default = $layout && ($site[$layoutKind . '_id'] ?? null) === $layout['id']; $error = ''; if ($request->method() === 'POST') { $data = []; @@ -257,7 +263,10 @@ class AdminController $data[$field] = $this->input($request, $field); } $data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name'); - $data['status'] = $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status'); + if ($layout) { + $data['title'] = $data['name']; + } + $data['status'] = $layout || $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status'); $scale = $this->input($request, 'image_scale'); $data['image_scale'] = $request->post('image_scale') === null ? (int) $page['image_scale'] : (ctype_digit($scale) ? (int) $scale : -1); @@ -281,14 +290,39 @@ class AdminController } $data['visibility'][$area] = $value === '1'; } + if ($layout) { + $default = $request->post('make_default') === '1'; + $provider = null; + if ($layoutKind === 'header' && $request->post('provider_mode') !== null) { + foreach (DesignLibrary::PROVIDER_FIELDS as $name) { + $provider[$name] = $this->input($request, 'provider_' . $name); + } + } + $data['layoutConfig'] = ['default' => $default, 'provider' => $provider, 'secret' => $this->input($request, 'provider_secret', trimValue: false)]; + } else { + foreach (['header', 'footer'] as $area) { + $choice = $request->post($area . '_choice'); + if ($choice === null) { + continue; + } + $data['visibility'][$area] = $choice !== 'hidden'; + if ($choice !== 'hidden') { + $data[$area . '_id'] = DesignLibrary::selection($area, $choice); + } + } + $page = array_replace($page, array_intersect_key($data, ['header_id' => true, 'footer_id' => true])); + } $page['visibility'] = $data['visibility']; $data['alignments'] = $request->post('alignments') === null ? $page['alignments'] : $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']); $page['alignments'] = $data['alignments']; + $data['presentation'] = $request->post('canvas_presentation') === null ? $page['presentation'] + : CanvasStyle::normalize(json_decode($this->input($request, 'canvas_presentation'), true), CanvasStyle::PAGE); + $page['presentation'] = $data['presentation']; $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks')); if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true) || $data['title'] === '' || mb_strlen($data['title']) > 160 || - ($data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 || + (!$layout && $data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 || (($data['visibility']['hero'] ?? true) && $data['heading'] === '') || mb_strlen($data['heading'] . $data['accent']) > 110 || mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 || ($data['image_scale'] !== 0 && ($data['image_scale'] < 10 || $data['image_scale'] > 100)) || @@ -296,7 +330,15 @@ class AdminController throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。'); } $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories()); - $repo->savePage($slug, $data, $this->version($request), $sections); + $order = $request->post('canvas_order', ''); + if ($order !== '') { + $order = is_string($order) ? json_decode($order, true) : null; + if (!is_array($order) || !array_is_list($order) || count($order) > count($page['sections']) + 50 + || count(array_filter($order, 'is_string')) !== count($order)) { + throw new RuntimeException('区块顺序无效。'); + } + } + $repo->savePage($slug, $data, $this->version($request), $sections, sectionOrder: $order === '' ? null : $order); return $this->success($request, '/admin/pages/' . $slug . '?saved=1'); } catch (RuntimeException $exception) { @@ -306,7 +348,9 @@ class AdminController return $this->render($request, 'admin-page', [ 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1', - 'pageTemplateDrawer' => true, 'designs' => DesignLibrary::all(), + 'pageTemplateDrawer' => !$layout, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default, + 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']), + 'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]), ], $error !== '' ? 422 : 200); } @@ -366,10 +410,12 @@ class AdminController $version = $change['version'] ?? null; $fields = $change['fields'] ?? []; $alignments = $change['alignments'] ?? null; + $presentation = $change['presentation'] ?? null; $feed = $change['feed'] ?? null; $delete = ($change['delete'] ?? false) === true; $isNew = is_array($change) && array_key_exists('version', $change) && $version === null; - if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || (!$delete && $fields === [] && $alignments === null && $feed === null) + if (!is_string($key) || isset($updates[$key]) || !is_array($fields) + || (!$delete && $fields === [] && $alignments === null && $presentation === null && $feed === null) || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key)) : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) { throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。'); @@ -419,6 +465,9 @@ class AdminController if ($alignments !== null) { $section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead'])); } + if ($presentation !== null) { + $section['presentation'] = CanvasStyle::encode(CanvasStyle::normalize($presentation, CanvasStyle::SECTION)); + } $this->checkSection($section, $section['style']); if (isset($fields['body'])) { $section['body'] = Html::sanitize($section['body']); diff --git a/app/Controller/DesignController.php b/app/Controller/DesignController.php index 8570e3d..49cb6ad 100644 --- a/app/Controller/DesignController.php +++ b/app/Controller/DesignController.php @@ -22,7 +22,7 @@ final class DesignController extends AdminController } return $this->render($request, 'admin-design', [ - 'title' => '站点设计', 'items' => DesignLibrary::all(), 'site' => (new Repository())->site(), + 'title' => '站点设计', 'items' => DesignLibrary::all('palette'), ]); } @@ -31,73 +31,42 @@ final class DesignController extends AdminController if ($failure = $this->guard($request)) { return $failure; } + if ($kind !== 'palette') { + if ($key === 'new') { + return View::redirect('/admin/new-page?type=' . $kind); + } + $page = (new Repository())->layoutPage((int) $key); + + return $page && $page['layout_kind'] === $kind + ? View::redirect('/admin/pages/' . $page['slug']) : $this->error($request, '找不到这项设计配置。', 404); + } $id = $key === 'new' ? null : (int) $key; $item = $id === null ? [ - 'name' => '', 'preset' => array_key_first(DesignLibrary::PRESETS[$kind]), - 'payload' => DesignLibrary::defaults($kind), 'version' => 0, - ] : DesignLibrary::find($id, $kind); + 'name' => '', 'preset' => 'custom', 'payload' => DesignLibrary::defaults('palette'), 'version' => 0, + ] : DesignLibrary::find($id, 'palette'); if (!$item) { - return $this->error($request, '找不到这项设计配置。', 404); + return $this->error($request, '找不到这项配色方案。', 404); } $error = ''; $field = ''; - $secret = ''; - $links = SiteDesign::linkText($item['payload']['links'] ?? []); - $default = $id !== null && ((new Repository())->site()[$kind . '_id'] ?? null) === $id; if ($request->method() === 'POST') { + $item['name'] = $this->input($request, 'name'); + $item['version'] = $this->version($request); + foreach (array_keys(DesignLibrary::COLORS) as $color) { + $item['payload'][$color] = $this->input($request, $color); + } try { - $savedProvider = $item['payload']['provider'] ?? []; - $item['name'] = $this->input($request, 'name'); - $item['preset'] = $this->input($request, 'preset'); - $item['version'] = $this->version($request); - $default = $request->post('make_default') === '1'; - if ($kind === 'palette') { - foreach (DesignLibrary::COLORS as $color => $definition) { - $item['payload'][$color] = $this->input($request, $color); - } - } else { - $url = $this->input($request, 'action_url'); - $label = $this->input($request, 'action_label'); - $links = $this->input($request, 'links', trimValue: false); - $item['payload'] = [ - 'components' => $request->post('components', []), - 'brand' => $this->input($request, 'brand'), 'logo' => $this->input($request, 'logo'), - 'text' => $this->input($request, 'text'), 'legal' => $this->input($request, 'legal'), - 'action' => $url === '' && $label === '' ? [] : [[$url, $label, $this->input($request, 'action_style'), $request->post('action_blank') === '1']], - 'provider' => $savedProvider, - ]; - $components = $item['payload']['components']; - if ($kind === 'header' && is_array($components) && DesignLibrary::hasAccount($item['preset'], $components)) { - foreach (['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id', 'scope', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) { - $item['payload']['provider'][$field] = $this->input($request, 'provider_' . $field); - } - $secret = $this->input($request, 'provider_secret', trimValue: false); - } - try { - $item['payload']['links'] = SiteDesign::parseLinks($links); - } catch (RuntimeException $ex) { - throw new DesignFieldError('links', $ex->getMessage()); - } - } - $id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $item['version'], $default, $secret); + $id = DesignLibrary::save($kind, $id, $item['name'], 'custom', $item['payload'], $item['version'], false); - return $this->success($request, "/admin/design/$kind/$id?saved=1"); - } catch (RuntimeException $ex) { - $error = $this->validationMessage($ex); - $field = $ex instanceof DesignFieldError ? $ex->field : ''; + return $this->success($request, "/admin/design/palette/$id?saved=1"); + } catch (RuntimeException $exception) { + $error = $this->validationMessage($exception); + $field = $exception instanceof DesignFieldError ? $exception->field : ''; } } - if ($kind !== 'palette') { - $components = $item['payload']['components']; - $item['payload']['components'] = is_array($components) ? array_values(array_intersect( - array_filter($components, 'is_string'), array_keys(DesignLibrary::COMPONENTS[$kind]) - )) : []; - } - return $this->render($request, 'admin-design-edit', [ - 'title' => '设计配置', 'kind' => $kind, 'key' => $key, 'item' => $item, 'default' => $default, - 'error' => $error, 'field' => $field, 'links' => $links, 'reenterSecret' => $error !== '' && $secret !== '', + 'title' => '配色方案', 'key' => $key, 'item' => $item, 'error' => $error, 'field' => $field, 'saved' => $error === '' && $request->get('saved') === '1', ], $error === '' ? 200 : 422); } @@ -138,15 +107,18 @@ final class DesignController extends AdminController if ($failure = $this->guard($request)) { return $failure; } + if ($kind !== 'palette') { + $layout = (new Repository())->layoutPage((int) $id); + + return $layout && $layout['layout_kind'] === $kind ? View::redirect('/admin/pages/' . $layout['slug'] . '/preview') + : $this->error($request, '找不到这项设计配置。', 404); + } if (!DesignLibrary::find((int) $id, $kind)) { return $this->error($request, '找不到这项设计配置。', 404); } $repo = new Repository(); $page = $repo->page('home'); $page[$kind . '_id'] = (int) $id; - if ($kind !== 'palette') { - $page['visibility'][$kind] = true; - } return (new SiteController())->renderPage($repo, $page, true); } diff --git a/app/Controller/McpController.php b/app/Controller/McpController.php index a75c8ae..326754a 100644 --- a/app/Controller/McpController.php +++ b/app/Controller/McpController.php @@ -122,7 +122,7 @@ final class McpController try { $data = match ($name) { 'list_pages' => $repo->pages(), - 'get_page' => $this->read($repo, PageDraft::slug($args['slug'] ?? null, [])), + 'get_page' => $this->read($repo, PageDraft::slug($args['slug'] ?? null, [], includeLayouts: true)), 'list_templates' => $this->templates(), 'list_designs' => DesignLibrary::all(), 'create_draft' => $this->create($repo, $args), diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php index abb1b30..7931bd4 100644 --- a/app/Controller/SiteController.php +++ b/app/Controller/SiteController.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Controller; use App\Content\Assets; +use App\Content\CanvasStyle; use App\Content\Html; use App\Content\Repository; use App\Content\View; @@ -24,7 +25,7 @@ final class SiteController { $repo = new Repository(); $page = $repo->page($slug); - if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') { + if (!$page || $page['layout_kind'] !== null || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') { return $this->missing($request); } if ($slug === 'articles' && $request->get('page') !== null) { @@ -45,30 +46,7 @@ final class SiteController $slug = $page['slug']; $isHome = $slug === 'home'; $showHero = $page['visibility']['hero'] ?? true; - $categories = $repo->categories(); - foreach ($page['sections'] as &$section) { - if (!$section['feed']) { - continue; - } - $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/' . $slug . '/' . $section['key']; - $section['archivePath'] = $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' => $repo->articles($selected, limit: $feed['limit'], directoryOrder: $network || $catalog), - ]; - } - } - unset($section); + $page = $repo->withSectionFeeds($page); return View::render('page', [ 'site' => $repo->site(), @@ -223,6 +201,15 @@ final class SiteController return View::redirect(Assets::DEFAULT_ICON, 301); } + public function canvasStyle(Request $request): Response + { + static $css; + $css ??= CanvasStyle::stylesheet(); + + return new Response(200, ['Content-Type' => 'text/css; charset=utf-8', + 'Cache-Control' => 'public, max-age=3600', 'X-Content-Type-Options' => 'nosniff'], $css); + } + public function missing(Request $request): Response { $path = $request->path(); @@ -230,7 +217,7 @@ final class SiteController $normal = rtrim($path, '/'); $entry = preg_match('~^/(?:admin|account)(?:/|$)~D', $normal) && Route::dispatch($request->method(), $normal)[0] === Dispatcher::FOUND; - $single = preg_match('~^/[a-z0-9-]+$~D', $normal); + $single = preg_match('~^/[a-z0-9]+(?:-[a-z0-9]+)*$~D', $normal); if ($entry || ($single && $normal !== '/home' && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published') || preg_match('~^/articles(?:/[a-z0-9-]+){1,2}$~D', $normal)) { $query = $request->queryString(); diff --git a/app/Controller/StudioController.php b/app/Controller/StudioController.php index 9723fd9..9457dae 100644 --- a/app/Controller/StudioController.php +++ b/app/Controller/StudioController.php @@ -5,7 +5,9 @@ declare(strict_types=1); namespace App\Controller; use App\Content\BlockTemplates; +use App\Content\DesignLibrary; use App\Content\Html; +use App\Content\LayoutPage; use App\Content\Media; use App\Content\PageDraft; use App\Content\PageTemplates; @@ -22,16 +24,26 @@ final class StudioController extends AdminController if ($failure = $this->guard($request)) { return $failure; } + $type = $request->get('type'); $data = [ 'title' => '新建页面', 'name' => '', 'slug' => '', 'error' => '', 'pageTemplateDrawer' => true, 'openTemplates' => $request->get('templates') === '1', + 'type' => is_string($type) && isset(LayoutPage::TYPES[$type]) ? $type : 'page', ]; if ($request->method() === 'POST') { $data['name'] = $this->input($request, 'name'); $data['slug'] = $this->input($request, 'slug'); + $data['type'] = $request->post('type') === null ? 'page' : $this->input($request, 'type'); try { - if (!$this->slug($data['slug']) || in_array($data['slug'], PageDraft::RESERVED, true) - || $data['name'] === '' || mb_strlen($data['name']) > 100) { + if (!isset(LayoutPage::TYPES[$data['type']]) || $data['name'] === '' || mb_strlen($data['name']) > 100) { + throw new RuntimeException('请填写页面名称并选择页面类型。'); + } + if ($data['type'] !== 'page') { + $slug = LayoutPage::create($data['type'], $data['name']); + + return $this->success($request, '/admin/pages/' . $slug); + } + if (!$this->slug($data['slug']) || in_array($data['slug'], PageDraft::RESERVED, true)) { throw new RuntimeException('请填写页面名称及可用的网址标识。'); } $key = $this->input($request, 'template'); @@ -69,6 +81,15 @@ final class StudioController extends AdminController } $repo = new Repository(); $page = $repo->page($slug); + $area = $request->get('area'); + if ($page && $page['layout_kind'] === null && in_array($area, ['header', 'footer'], true)) { + try { + $page[$area . '_id'] = DesignLibrary::selection($area, $request->get('choice')); + $page['visibility'][$area] = true; + } catch (RuntimeException $error) { + return $this->error($request, $this->validationMessage($error), 422); + } + } return $page ? (new SiteController())->renderPage($repo, $page, true, $request->get('canvas') === '1') : $this->error($request, '找不到此页面。', 404); } diff --git a/app/view/admin-dashboard.php b/app/view/admin-dashboard.php index cbc5f6c..f2c55f0 100644 --- a/app/view/admin-dashboard.php +++ b/app/view/admin-dashboard.php @@ -1,8 +1,10 @@ $page['status'] === 'published')); +$regular = array_filter($pages, static fn (array $page): bool => $page['layout_kind'] === null); +$live = count(array_filter($regular, static fn (array $page): bool => $page['status'] === 'published')); ?>

网站后台

@@ -16,7 +18,7 @@ $live = count(array_filter($pages, static fn (array $page): bool => $page['statu

网站页面

-

个已发布 · 个草稿

+

个已发布 · 个草稿 · 个页头页脚

>