Launch LaySite visual editor and MCP workspace

This commit is contained in:
2026-11-22 23:26:08 +08:00
commit 1bb0554608
159 changed files with 11103 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Assets
{
public static function cdn(string $value): string
{
$value = rtrim(trim($value), '/');
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.example.com。');
}
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
throw new RuntimeException('CDN 端口无效。');
}
return $value;
}
public static function url(string $path, string $cdn): string
{
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
}
public static function rewrite(string $html, string $cdn): string
{
if ($cdn === '') {
return $html;
}
// Match opening tags separately from comments and text-only elements' contents.
$tags = <<<'REGEX'
~<!--.*?(?:-->|\z)|(?<opening><(?:(?<textTag>script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?<tail>.*?(?:</\k<textTag>\s*>|\z)))~is
REGEX;
$attributes = <<<'REGEX'
~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~
REGEX;
return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string {
if (!isset($tag['opening'])) {
return $tag[0];
}
$opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string {
if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) {
return $attribute[0];
}
$value = $attribute[4];
$quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : '';
$path = $quote === '' ? $value : substr($value, 1, -1);
return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote;
}, $tag['opening']) ?? $tag['opening'];
return $opening . ($tag['tail'] ?? '');
}, $html) ?? $html;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class BlockTemplates
{
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
public const NETWORK_FEED = '{"categories":["projects","partners"],"mode":"network","limit":30}';
public const CATALOG_FEED = '{"categories":["catalog"],"mode":"catalog","limit":30}';
public const ELEMENT_GROUPS = [
'text-elements' => ['文字与列表', [
'paragraph' => ['段落', '<p>填写正文。</p>'],
'subheading' => ['小标题', '<h3>填写小标题</h3>'],
'lead' => ['导语', '<p class="studio-lead">填写本节的导语。</p>'],
'blockquote' => ['引用', '<blockquote><p>填写需要引用的内容。</p></blockquote>'],
'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'],
'ordered-list' => ['编号列表', '<ol><li>填写第一项</li><li>填写第二项</li></ol>'],
'heading-kicker' => ['标题眉标', '<p class="overline">填写分类名称</p>'],
'tag' => ['徽标', '<p><span class="studio-badge">填写标签</span></p>'],
'large-number' => ['重点数字', '<p class="price-value">填写数字</p>'],
'definition-list' => ['术语说明', '<dl class="studio-definitions"><dt>填写术语</dt><dd>填写术语说明。</dd></dl>'],
]],
'link-elements' => ['链接与按钮', [
'button' => ['主按钮', '<p><a class="button button-primary" href="#contact">联系站点</a></p>'],
'outline-button' => ['描边按钮', '<p><a class="button button-outline" href="/">查看服务</a></p>'],
'text-link' => ['文字链接', '<p><a href="/articles">阅读文章</a></p>'],
'button-group' => ['按钮组', '<div class="actions studio-button-group"><a class="button button-primary" href="/">查看服务</a><a class="button button-outline" href="#contact">联系团队</a></div>'],
'breadcrumbs' => ['面包屑', '<p class="breadcrumbs"><a href="/">首页</a><span> / </span><span>当前页面</span></p>'],
'download-link' => ['下载入口', '<p><a class="button button-outline" href="/articles">查看下载</a></p>'],
'email-link' => ['邮件链接', '<p><a href="mailto:hello@example.com">发送邮件</a></p>'],
]],
'media-elements' => ['图片与影音', [
'image' => ['图片', '', 'image/'],
'video' => ['视频', '', 'video/'],
'audio' => ['音频', '', 'audio/'],
'qr-image' => ['二维码', '', 'image/'],
'image-link' => ['图片链接', '<p><a href="/"><img src="/assets/system/sample.webp" alt="版式示意" loading="lazy"></a></p>'],
]],
'structure-elements' => ['版式与数据', [
'separator' => ['分割线', '<hr class="studio-divider">'],
'spacer' => ['留白', '<div class="studio-spacer"></div>'],
'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'],
'basic-table' => ['数据表格', '<table><thead><tr><th scope="col">名称</th><th scope="col">数据</th></tr></thead><tbody><tr><td>填写名称</td><td>填写数据</td></tr></tbody></table>'],
'progress' => ['进度条', '<div class="studio-progress"><p>完成进度</p><progress max="100" value="65">65%</progress></div>'],
'alert' => ['提示卡', '<div class="studio-notice"><p><strong>请注意</strong></p><p>填写一条提示信息。</p></div>'],
'simple-card' => ['内容卡片', '<article class="content-card"><h3>填写卡片标题</h3><p>填写卡片内容。</p></article>'],
'link-card' => ['链接卡片', '<article class="content-card"><h3>查看资料</h3><p>填写链接指向的资料说明。</p><a href="/articles">打开资料</a></article>'],
'list-group' => ['列表组', '<ul class="studio-resources"><li><a href="/">产品与服务</a><span>目录</span></li><li><a href="/articles">站点动态</a><span>文章</span></li></ul>'],
'empty-card' => ['空状态', '<div class="studio-empty"><h3>暂无内容</h3><p>填写访客可以执行的下一步。</p><a href="/articles">查看站点动态</a></div>'],
'status-note' => ['状态提示', '<div class="studio-notice studio-success-note"><p><strong>已完成</strong></p><p>填写操作结果或服务状态。</p></div>'],
'disclosure' => ['折叠内容', '<div class="faq"><details><summary>填写折叠标题</summary><div><p>填写展开后的内容。</p></div></details></div>'],
]],
];
public const GROUPS = [
'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'articles' => ['分类文章', '', '', self::ARTICLE_FEED],
'network' => ['按分类分组', '', '', self::NETWORK_FEED],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'],
]],
'cover' => ['封面与横幅', [
'cover' => ['图文封面', '<div class="studio-cover"><img src="/assets/system/sample.webp" alt="" loading="lazy"><div><h3>用一句话介绍你的产品</h3><p>在首段说明访客能获得什么。</p><a class="button button-primary" href="/">查看服务</a></div></div>'],
'banner' => ['横幅', '<div class="studio-banner"><h3>用一句话介绍你的项目</h3><p>简要说明项目能为访客做什么。</p><a class="button button-primary" href="/">了解更多</a></div>'],
'two-actions' => ['双按钮横幅', '<div class="studio-banner studio-banner-two"><div><h3>选择下一步</h3><p>介绍访客可以立即做什么。</p></div><div class="actions"><a class="button button-primary" href="/">查看服务</a><a class="button button-outline" href="/#contact">联系我们</a></div></div>'],
]],
'layout' => ['图文与布局', [
'image' => ['产品图文', '<div class="studio-split"><img src="/assets/system/sample.webp" alt="" loading="lazy"><div><h3>介绍主题</h3><p>在这里说明图片或产品。</p></div></div>'],
'grid' => ['双栏网格', '<div class="studio-two-column"><article class="content-card"><h3>第一栏</h3><p>填写主要内容。</p></article><article class="content-card"><h3>第二栏</h3><p>补充相关信息。</p></article></div>'],
]],
'media' => ['媒体', [
'gallery' => ['三图画廊', '<div class="studio-gallery"><img src="/assets/system/sample.webp" alt="产品界面示意" loading="lazy"><img src="/assets/system/sample.webp" alt="示例作品" loading="lazy"><img src="/assets/system/sample.webp" alt="云端服务插画" loading="lazy"></div>'],
'video-demo' => ['视频演示', '<div class="studio-split"><video controls preload="none" poster="/assets/system/sample.webp"></video><div><h3>演示视频</h3><p>说明视频涵盖的功能与操作。</p></div></div>'],
]],
'features' => ['特性与口碑', [
'features' => ['特性卡片', '<div class="card-grid feature-grid"><article class="content-card feature-card"><h3>特点一</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点二</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点三</h3><p>介绍这个特点。</p></article></div>'],
'quote' => ['引文', '<blockquote><p>在这里填写引用或用户反馈。</p></blockquote>'],
'metrics' => ['关键数据', '<dl class="studio-metrics"><div><dt>累计项目</dt><dd>100</dd></div><div><dt>服务覆盖</dt><dd>12</dd></div><div><dt>合作伙伴</dt><dd>8</dd></div></dl>'],
'testimonials' => ['用户评价', '<div class="studio-two-column studio-testimonials"><blockquote><p>填写用户的评价,并说明他们获得的结果。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote><blockquote><p>填写另一条用户评价。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote></div>'],
]],
'details' => ['表格与问答', [
'table' => ['对比表格', '<table><thead><tr><th scope="col">项目</th><th scope="col">说明</th></tr></thead><tbody><tr><td>项目一</td><td>填写说明</td></tr><tr><td>项目二</td><td>填写说明</td></tr></tbody></table>'],
'faq' => ['常见问题', '<div class="faq"><details><summary>请输入问题</summary><div><p>请输入答案。</p></div></details></div>'],
'timeline' => ['时间线', '<ol class="studio-timeline"><li><h3>确定目标</h3><p>填写这一阶段需要完成的事项。</p></li><li><h3>实施与验收</h3><p>填写交付时间与验收标准。</p></li></ol>'],
'checklist' => ['清单', '<ul class="studio-checklist"><li>填写必备材料</li><li>填写提交条件</li><li>填写确认事项</li></ul>'],
'changelog' => ['更新记录', '<div class="studio-releases"><article><h3>版本 2.0</h3><p>填写主要功能或改进。</p></article><article><h3>版本 1.0</h3><p>填写上一版本的更新内容。</p></article></div>'],
'pricing' => ['双方案报价', '<div class="card-grid price-grid studio-pricing"><article class="content-card price-card"><h3>基础方案</h3><p class="price-value">填写价格</p><p>填写方案包含的服务。</p><a class="button button-outline" href="/#contact">咨询基础方案</a></article><article class="content-card price-card"><h3>进阶方案</h3><p class="price-value">填写价格</p><p>填写扩展服务或权益。</p><a class="button button-primary" href="/#contact">咨询进阶方案</a></article></div>'],
]],
'actions' => ['导航与引导', [
'service-catalog' => ['目录卡片', '', '', self::CATALOG_FEED],
'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系站点</a></li></ul>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系站点</a></p>'],
'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/articles">浏览资料</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'],
'contact-card' => ['联系方式', '<div class="studio-contact"><div><h3>联系团队</h3><p>填写咨询范围与回复时间。</p></div><dl class="studio-definitions"><dt>电子邮件</dt><dd><a href="mailto:hello@example.com">hello@example.com</a></dd><dt>服务时间</dt><dd>填写工作时间</dd></dl></div>'],
]],
];
public static function groups(): array
{
return self::GROUPS;
}
public static function find(string $key): ?array
{
foreach (self::groups() as [, $templates]) {
if (isset($templates[$key])) {
return $templates[$key];
}
}
return null;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Buttons
{
public const STYLES = ['solid' => '纯色填充', 'outline' => '线框', 'underline' => '下划线', 'plain' => '无样式'];
private const CLASSES = ['solid' => 'button-primary', 'outline' => 'button-outline', 'underline' => 'button-underline', 'plain' => 'button-plain'];
public static function validate(mixed $items, int $limit = 8): array
{
if (!is_array($items) || !array_is_list($items) || count($items) > $limit) {
throw new RuntimeException('按钮或链接数量超过限制。');
}
$buttons = [];
foreach ($items as $index => $item) {
$url = $item[0] ?? null;
$label = $item[1] ?? null;
$style = $item[2] ?? ($index === 0 ? 'solid' : 'outline');
$blank = $item[3] ?? false;
if (!is_string($url) || strlen($url) > 1000 || !Html::url($url) || !is_string($label)
|| trim($label) === '' || mb_strlen($label) > 70 || !is_string($style) || !isset(self::STYLES[$style])
|| !is_bool($blank)) {
throw new RuntimeException('请检查按钮文案、链接和样式。');
}
$buttons[] = [$url, $label, $style, $blank];
}
return $buttons;
}
public static function css(string $style): string
{
return 'button ' . (self::CLASSES[$style] ?? self::CLASSES['solid']);
}
public static function target(bool $blank): string
{
return $blank ? ' target="_blank" rel="noopener noreferrer"' : '';
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
use Throwable;
final class Database
{
private const SCHEMA_VERSION = 1;
// 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';
private static ?PDO $connection = null;
public static function connect(): PDO
{
if (self::$connection !== null) {
return self::$connection;
}
$path = getenv('LAYSITE_DB') ?: dirname(__DIR__, 2) . '/storage/laysite.sqlite';
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0750, true) && !is_dir(dirname($path))) {
throw new RuntimeException('无法创建 SQLite 存放目录。');
}
$pdo = new PDO('sqlite:' . $path, options: [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA foreign_keys = ON');
self::$connection = $pdo;
return $pdo;
}
public static function initialize(): void
{
$root = dirname(__DIR__, 2);
$pdo = self::connect();
$pdo->exec('PRAGMA journal_mode = WAL');
self::write(function (PDO $pdo) use ($root): void {
$version = (int) $pdo->query('PRAGMA user_version')->fetchColumn();
if ($version > self::SCHEMA_VERSION) {
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
}
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
$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)
VALUES ('home', '首页', '我的网站', '欢迎访问我的网站。', '我的网站', '', '', '', '', '[]', '[]')")
->execute();
$articles = $pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES ('articles', '文章与动态', '文章与动态', '浏览站点发布的文章。', '文章与动态', '', '', '', '', '[]', '[]')");
$articles->execute();
if ($articles->rowCount() === 1) {
$pdo->prepare("INSERT INTO sections (page_slug, key, title, lead, body, feed, position)
VALUES ('articles', 'posts', '最新文章', '', '', ?, 0)")->execute([BlockTemplates::ARTICLE_FEED]);
}
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]);
}
if ($version < self::SCHEMA_VERSION) {
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
}
});
}
public static function write(callable $operation): mixed
{
$pdo = self::connect();
$pdo->exec('BEGIN IMMEDIATE');
try {
$result = $operation($pdo);
$pdo->exec('COMMIT');
return $result;
} catch (Throwable $error) {
$pdo->exec('ROLLBACK');
throw $error;
}
}
public static function json(array $data): string
{
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class DesignLibrary
{
public const PRESETS = [
'header' => ['inline' => '横排导航', 'center' => '居中品牌', 'member' => '会员导航'],
'footer' => ['columns' => '多栏链接', 'compact' => '简约横栏', 'band' => '全宽深色'],
'palette' => ['custom' => '自定义配色'],
];
public const COMPONENTS = [
'header' => ['brand' => '站点标识', 'links' => '导航链接', 'action' => '行动按钮', 'account' => '用户区'],
'footer' => ['brand' => '站点标识', 'text' => '说明文字', 'links' => '页脚链接', 'legal' => '版权文字'],
];
public const COLORS = [
'white' => ['页面背景', '#ffffff'], 'paper' => ['区块背景', '#f5f7fb'],
'ink' => ['正文', '#111a2e'], 'muted' => ['次要文字', '#505d73'],
'accent' => ['强调色', '#214ed7'], 'accent-deep' => ['强调色悬停', '#173bae'],
'accent-light' => ['强调色浅底', '#e8efff'], 'line' => ['边框', '#dbe3f0'],
'button-ink' => ['填充按钮文字', '#ffffff'],
];
public static function all(?string $kind = null): array
{
$query = Database::connect()->prepare('SELECT id, kind, name, preset, version FROM design_presets'
. ($kind === null ? '' : ' WHERE kind = ?') . ' ORDER BY kind, id');
$query->execute($kind === null ? [] : [$kind]);
return $query->fetchAll();
}
public static function find(int $id, string $kind): ?array
{
if ($id < 1) {
return null;
}
$query = Database::connect()->prepare('SELECT * FROM design_presets WHERE id = ? AND kind = ?');
$query->execute([$id, $kind]);
$row = $query->fetch();
if (!$row) {
return null;
}
$row['payload'] = self::normalize($kind, $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
return $row;
}
public static function defaults(string $kind): array
{
if ($kind === 'palette') {
return array_map(static fn (array $color): string => $color[1], self::COLORS);
}
return [
'components' => array_keys(self::COMPONENTS[$kind]), 'logo' => '', 'brand' => '', 'text' => '',
'legal' => '', 'links' => $kind === 'header' ? [['/', '首页'], ['/articles', '文章']] : [],
'action' => [], 'provider' => [],
];
}
public static function layout(string $kind, array $site, array $page): array
{
$id = (int) ($page[$kind . '_id'] ?? 0) ?: (int) ($site[$kind . '_id'] ?? 0);
return self::find($id, $kind) ?? [
'id' => 0, 'preset' => array_key_first(self::PRESETS[$kind]), 'payload' => self::defaults($kind),
];
}
public static function selection(string $kind, mixed $value): ?int
{
if ($value === '' || $value === null || $value === 0) {
return null;
}
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($id === false || !self::find($id, $kind)) {
throw new RuntimeException('所选页头、页脚或配色方案不存在。');
}
return $id;
}
public static function normalize(string $kind, string $preset, array $data): array
{
if (!isset(self::PRESETS[$kind][$preset])) {
throw new RuntimeException('请选择可用的组件模板。');
}
if ($kind === 'palette') {
$colors = [];
foreach (self::COLORS as $key => [, $default]) {
$color = $data[$key] ?? $default;
if (!is_string($color) || !preg_match('/^#[\da-f]{6}$/iD', $color)) {
throw new RuntimeException('颜色必须使用六位十六进制表示。');
}
$colors[$key] = strtolower($color);
}
return $colors;
}
$clean = self::defaults($kind);
foreach (['brand' => 100, 'text' => 1200, 'legal' => 300, 'logo' => 1000] as $field => $limit) {
$clean[$field] = self::string($data[$field] ?? '', $limit);
}
if ($clean['logo'] !== '' && !Html::url($clean['logo'], true)) {
throw new RuntimeException('请检查站点标识地址。');
}
$components = $data['components'] ?? $clean['components'];
if (!is_array($components) || !array_is_list($components)) {
throw new RuntimeException('组件顺序无效。');
}
foreach ($components as $component) {
if (!is_string($component) || !isset(self::COMPONENTS[$kind][$component])) {
throw new RuntimeException('布局包含未知组件。');
}
}
$clean['components'] = array_values(array_unique($components));
$clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20);
$clean['action'] = Buttons::validate($data['action'] ?? []);
$clean['provider'] = $kind === 'header' && $preset === 'member'
? self::provider($data['provider'] ?? []) : [];
return $clean;
}
public static function provider(array $data): array
{
$mode = $data['mode'] ?? '';
if ($mode === '') {
return [];
}
if (!in_array($mode, ['oidc', 'oauth2'], true)) {
throw new RuntimeException('请选择 OIDC 或 OAuth 2.0。');
}
$result = ['mode' => $mode];
foreach (['client_id', 'secret_env', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
$result[$field] = self::string($data[$field] ?? '', 600);
}
if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) {
throw new RuntimeException('令牌端点认证方式无效。');
}
if ($result['client_id'] === '' || !preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $result['secret_env'])) {
throw new RuntimeException('填写客户端 ID 和以 LAYSITE_OAUTH_ 开头的客户端密钥环境变量名。');
}
foreach ($mode === 'oidc' ? ['issuer'] : ['authorization', 'token', 'userinfo'] as $field) {
$url = parse_url($result[$field]);
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || ($field === 'issuer' && isset($url['query'])) || !Html::url($result[$field], true)) {
throw new RuntimeException('认证端点必须使用完整的 HTTPS 地址。');
}
}
if ($mode === 'oauth2' && $result['subject_field'] === '') {
throw new RuntimeException('OAuth 2.0 用户资料需要指定稳定的用户 ID 字段。');
}
return $result;
}
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default): int
{
$name = self::string($name, 100);
if ($name === '') {
throw new RuntimeException('请填写配置名称。');
}
$payload = Database::json(self::normalize($kind, $preset, $data));
return Database::write(function (PDO $pdo) use ($kind, $id, $name, $preset, $payload, $version, $default): int {
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 !== '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)]);
}
return $id;
});
}
private static function string(mixed $value, int $limit): string
{
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit) {
throw new RuntimeException('配置包含无效或过长的文字。');
}
return trim($value);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMXPath;
final class DirectoryCard
{
public static function links(array $article, string $body): array
{
$detail = self::hasText($article['summary']) || self::hasBody($body) ? '/articles/' . $article['slug'] : '';
$primary = ($article['card']['url'] ?? '') ?: $detail;
return ['primary' => $primary, 'detail' => $primary === $detail ? '' : $detail];
}
private static function hasText(string $text): bool
{
return preg_match('/[^\s\p{Z}\p{Cf}]/u', $text) === 1;
}
private static function hasBody(string $html): bool
{
if (self::hasText(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'))) {
return true;
}
if (!str_contains($html, 'src=')) {
return false;
}
$document = new DOMDocument();
$document->loadHTML('<meta charset="utf-8">' . $html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
return (bool) $xpath->evaluate('boolean(//img[@src] | //audio[@src] | //video[@src] | //audio/source[@src] | //video/source[@src])');
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMNode;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use RuntimeException;
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' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
'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'],
];
public static function url(string $value, bool $media = false): bool
{
if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) {
return false;
}
if (str_starts_with($value, '/')) {
return !str_starts_with($value, '//');
}
if (str_starts_with($value, '#')) {
return !$media && strlen($value) > 1;
}
$scheme = strtolower((string) parse_url($value, PHP_URL_SCHEME));
return in_array($scheme, $media ? ['https'] : ['https', 'http', 'mailto', 'tel'], true);
}
public static function markdown(string $text): string
{
static $converter;
$converter ??= new GithubFlavoredMarkdownConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
$html = $converter->convert($text)->getContent();
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
}
public static function articleBody(array $article): string
{
return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
}
public static function applyCanvasEdits(string $body, array $edits): string
{
if (!array_is_list($edits) || count($edits) > 512) {
throw new RuntimeException('正文增量无效。');
}
$size = strlen($body);
$cursor = 0;
$result = '';
foreach ($edits as $edit) {
if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
throw new RuntimeException('正文增量无效。');
}
[$offset, $remove, $insert] = $edit;
if (!is_int($offset) || !is_int($remove) || !is_string($insert)
|| $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
throw new RuntimeException('正文增量无效。');
}
$result .= substr($body, $cursor, $offset - $cursor) . $insert;
$cursor = $offset + $remove;
if (strlen($result) > 300000) {
throw new RuntimeException('正文太长。');
}
}
$result .= substr($body, $cursor);
if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
throw new RuntimeException('正文太长或编码无效。');
}
return $result;
}
public static function sanitize(string $html, ?string $anchorPrefix = null): 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::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]);
}
}
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)]);
}
}
}
$output = '';
foreach ($body->childNodes as $child) {
$output .= $document->saveHTML($child);
}
return trim($output);
}
private static function sanitizeChildren(DOMNode $parent): void
{
foreach (iterator_to_array($parent->childNodes) as $element) {
if ($element->nodeType === XML_COMMENT_NODE) {
$parent->removeChild($element);
continue;
}
if (!$element instanceof DOMElement) {
continue;
}
if (!array_key_exists($element->tagName, self::TAGS)) {
$parent->removeChild($element);
continue;
}
$allowed = [...self::TAGS[$element->tagName], 'class', 'id'];
foreach (iterator_to_array($element->attributes) as $attribute) {
$name = $attribute->name;
$value = $attribute->value;
if (!in_array($name, $allowed, true)
|| ($name === 'href' && !self::url($value))
|| (in_array($name, ['src', 'poster'], true) && !self::url($value, true))
|| ($name === 'target' && $value !== '_blank')
|| ($name === 'tabindex' && $value !== '0')) {
$element->removeAttribute($name);
}
}
if ($element->tagName === 'a') {
if ($element->getAttribute('target') === '_blank') {
$element->setAttribute('rel', 'noopener noreferrer');
} else {
$element->removeAttribute('rel');
}
}
self::sanitizeChildren($element);
}
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace App\Content;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider;
use League\OAuth2\Client\Provider\GenericProvider;
use RuntimeException;
final class IdentityProvider
{
public readonly GenericProvider $client;
private readonly Client $http;
private array $oidc = [];
public function __construct(private readonly array $config)
{
$secret = getenv($config['secret_env']);
if (!is_string($secret) || $secret === '') {
throw new RuntimeException('身份服务的客户端密钥尚未配置。');
}
$this->http = new Client(['timeout' => 8, 'connect_timeout' => 4, 'allow_redirects' => false]);
$scope = preg_split('/\s+/', trim($config['scope']), -1, PREG_SPLIT_NO_EMPTY);
$authorization = $config['authorization'];
$token = $config['token'];
$userinfo = $config['userinfo'];
if ($config['mode'] === 'oidc') {
$this->oidc = $this->document(rtrim($config['issuer'], '/') . '/.well-known/openid-configuration');
if (($this->oidc['issuer'] ?? null) !== $config['issuer']) {
throw new RuntimeException('OIDC Issuer 与发现文档不一致。');
}
$authorization = $this->endpoint($this->oidc['authorization_endpoint'] ?? '');
$token = $this->endpoint($this->oidc['token_endpoint'] ?? '');
$userinfo = isset($this->oidc['userinfo_endpoint']) ? $this->endpoint($this->oidc['userinfo_endpoint']) : '';
$scope = array_values(array_unique(['openid', 'profile', 'email', ...$scope]));
}
$auth = $config['token_auth'];
if ($auth === '') {
$supported = $this->oidc['token_endpoint_auth_methods_supported'] ?? ['client_secret_basic'];
if ($this->oidc === [] || (!in_array('client_secret_basic', $supported, true) && in_array('client_secret_post', $supported, true))) {
$auth = 'client_secret_post';
} elseif (in_array('client_secret_basic', $supported, true)) {
$auth = 'client_secret_basic';
} else {
throw new RuntimeException('身份服务没有公布受支持的令牌端点认证方式。');
}
}
$this->client = new GenericProvider([
'clientId' => $config['client_id'], 'clientSecret' => $secret,
'redirectUri' => View::absolute('/account/callback'), 'urlAuthorize' => $authorization,
'urlAccessToken' => $token, 'urlResourceOwnerDetails' => $userinfo,
'pkceMethod' => GenericProvider::PKCE_METHOD_S256, 'scopes' => $scope, 'scopeSeparator' => ' ',
], [
'httpClient' => $this->http,
'optionProvider' => $auth === 'client_secret_basic' ? new HttpBasicAuthOptionProvider() : new PostAuthOptionProvider(),
]);
}
public function authorization(string $nonce): string
{
return $this->client->getAuthorizationUrl($this->oidc === [] ? [] : ['nonce' => $nonce]);
}
public function profile(string $code, string $proof, string $nonce): array
{
$this->client->setPkceCode($proof);
$token = $this->client->getAccessToken('authorization_code', ['code' => $code]);
if ($this->oidc === []) {
$claims = $this->client->getResourceOwner($token)->toArray();
} else {
$claims = $this->verifiedClaims($token->getValues()['id_token'] ?? '', $nonce);
if (isset($this->oidc['userinfo_endpoint'])) {
$more = $this->client->getResourceOwner($token)->toArray();
if (($more['sub'] ?? null) !== $claims['sub']) {
throw new RuntimeException('OIDC 用户资料的主体与 ID Token 不一致。');
}
$claims = $more + $claims;
}
}
$subject = $claims[$this->oidc !== [] ? 'sub' : $this->config['subject_field']] ?? null;
if ((!is_string($subject) && !is_int($subject)) || (string) $subject === '' || strlen((string) $subject) > 255) {
throw new RuntimeException('身份服务没有返回有效的用户标识。');
}
$name = $claims[$this->config['name_field'] ?: 'name'] ?? $claims['preferred_username'] ?? (string) $subject;
$avatar = $claims[$this->config['avatar_field'] ?: 'picture'] ?? '';
return [
'subject' => (string) $subject,
'name' => is_string($name) ? mb_substr($name, 0, 100) : (string) $subject,
'avatar' => is_string($avatar) && strlen($avatar) <= 2048 && str_starts_with($avatar, 'https://') && Html::url($avatar, true) ? $avatar : '',
];
}
private function verifiedClaims(mixed $encoded, string $nonce): array
{
if (!is_string($encoded) || strlen($encoded) > 16384 || substr_count($encoded, '.') !== 2) {
throw new RuntimeException('身份服务没有返回有效的 ID Token。');
}
$header = JWT::jsonDecode(JWT::urlsafeB64Decode(explode('.', $encoded, 2)[0]));
$algorithm = $header->alg ?? '';
if (!in_array($algorithm, ['RS256', 'RS384', 'RS512', 'ES256', 'ES384'], true)) {
throw new RuntimeException('身份服务使用了不支持的 ID Token 签名算法。');
}
$keys = $this->document($this->endpoint($this->oidc['jwks_uri'] ?? ''));
$claims = (array) JWT::decode($encoded, JWK::parseKeySet($keys, $algorithm));
$audience = (array) ($claims['aud'] ?? []);
$client = $this->config['client_id'];
if (($claims['iss'] ?? null) !== $this->config['issuer'] || !in_array($client, $audience, true)
|| ((count($audience) > 1 || isset($claims['azp'])) && ($claims['azp'] ?? null) !== $client)
|| ($claims['nonce'] ?? null) !== $nonce || !is_string($claims['sub'] ?? null) || $claims['sub'] === ''
|| !is_int($claims['exp'] ?? null) || $claims['exp'] <= time()
|| !is_int($claims['iat'] ?? null) || $claims['iat'] > time() + 60) {
throw new RuntimeException('OIDC ID Token 声明校验失败。');
}
return $claims;
}
private function document(string $endpoint): array
{
$response = $this->http->get($this->endpoint($endpoint), ['headers' => ['Accept' => 'application/json'], 'stream' => true]);
$body = Utils::copyToString($response->getBody(), 1048577);
if (strlen($body) > 1048576 || $response->getStatusCode() !== 200) {
throw new RuntimeException('身份服务文档超过大小限制。');
}
$data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($data)) {
throw new RuntimeException('身份服务文档格式无效。');
}
return $data;
}
private function endpoint(mixed $endpoint): string
{
$url = is_string($endpoint) ? parse_url($endpoint) : false;
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || !Html::url($endpoint, true)) {
throw new RuntimeException('身份服务端点必须使用 HTTPS。');
}
return $endpoint;
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RuntimeException;
use Throwable;
use Webman\Http\UploadFile;
final class Media
{
public const MAX_BYTES = 64 * 1024 * 1024;
private const EXTENSIONS = [
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
];
public static function all(bool $includeArchived = false): array
{
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
foreach ($files as &$file) {
$file['url'] = '/assets/uploads/' . $file['name'];
}
unset($file);
return $files;
}
public static function upload(UploadFile $file, string $label): void
{
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
}
$source = $file->getPathname();
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
$extension = self::EXTENSIONS[$mime] ?? null;
if ($extension === null) {
throw new RuntimeException('文件类型不受支持。');
}
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$directory = self::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('资源目录无法创建。');
}
$path = $directory . '/' . $name;
try {
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
if (!$written) {
throw new RuntimeException('文件写入失败。');
}
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function find(string $name): ?array
{
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
$query->execute([$name]);
return $query->fetch() ?: null;
}
public static function update(string $name, string $label, bool $archived): void
{
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
->execute([$label, (int) $archived, $name]);
}
public static function directory(): string
{
return rtrim(getenv('LAYSITE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
}
public static function validateBackup(string $path, string $name, string $mime, int $size): void
{
if ((new \finfo(FILEINFO_MIME_TYPE))->file($path) !== $mime
|| !isset(self::EXTENSIONS[$mime]) || self::EXTENSIONS[$mime] !== pathinfo($name, PATHINFO_EXTENSION)) {
throw new RuntimeException('备份资源类型与清单不一致。');
}
if ($mime === 'image/svg+xml') {
self::safeSvg($path, $size);
}
}
private static function safeSvg(string $source, int $size): string
{
if ($size > 512 * 1024) {
throw new RuntimeException('SVG 图标最大支持 512 KB。');
}
$svg = new DOMDocument();
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
throw new RuntimeException('SVG 图标格式无效。');
}
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
foreach ((new DOMXPath($svg))->query('//*') as $element) {
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|| !in_array($element->localName, $tags, true)) {
throw new RuntimeException('SVG 仅支持基础矢量元素。');
}
foreach ($element->attributes as $attribute) {
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
}
}
}
return $svg->saveXML($svg->documentElement);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class PageDraft
{
public const RESERVED = ['admin', 'assets', 'home', 'account', 'mcp', 'palette', 'favicon'];
public static function slug(mixed $value, array $reserved = self::RESERVED): string
{
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('网址标识无效或已保留。');
}
return $value;
}
public static function content(array $input, array $page): array
{
$name = self::text($input['name'] ?? $page['name'] ?? '', 100, true);
$page += ['name' => $name, 'title' => $name, 'heading' => $name, 'description' => '', 'lead' => '',
'accent' => '', 'image' => '', 'alt' => '', 'image_scale' => 0, 'alignments' => [], 'visibility' => [],
'actions' => [], 'quicklinks' => [], 'theme' => '', 'sections' => []];
$page['name'] = $name;
foreach (['title' => 160, 'heading' => 110, 'description' => 300, 'lead' => 600, 'accent' => 110, 'image' => 1000, 'alt' => 200] as $field => $limit) {
$page[$field] = self::text($input[$field] ?? $page[$field], $limit, in_array($field, ['title', 'heading'], true));
}
if (mb_strlen($page['heading'] . $page['accent']) > 110 || ($page['image'] !== '' && !Html::url($page['image'], true))) {
throw new RuntimeException('首屏标题过长或图片地址不正确。');
}
foreach (['header', 'footer', 'palette'] as $kind) {
$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']);
if (array_key_exists('visibility', $input)) {
if (!is_array($input['visibility'])) {
throw new RuntimeException('页面显示选项无效。');
}
foreach ($input['visibility'] as $area => $visible) {
if (!in_array($area, ['hero', 'header', 'footer'], true) || !is_bool($visible)) {
throw new RuntimeException('页面显示选项无效。');
}
$page['visibility'][$area] = $visible;
}
}
$page['status'] = 'draft';
if (array_key_exists('sections', $input)) {
$oldKeys = array_column($page['sections'], 'key');
$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)));
}
$page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20));
}
return $page;
}
private static function sections(mixed $items): array
{
if (!is_array($items) || !array_is_list($items) || count($items) > 50) {
throw new RuntimeException('每页最多可提交 50 个区块。');
}
$sections = [];
foreach ($items as $item) {
if (!is_array($item)) {
throw new RuntimeException('区块必须是对象。');
}
$key = self::slug($item['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (isset($sections[$key])) {
throw new RuntimeException('区块锚点重复。');
}
$preset = null;
if (isset($item['preset'])) {
$preset = is_string($item['preset']) ? BlockTemplates::find($item['preset']) : null;
if (!$preset) {
throw new RuntimeException('区块模板不存在。');
}
}
$style = $item['style'] ?? $preset[4] ?? 'plain';
if (!in_array($style, ['plain', 'tinted'], true)) {
throw new RuntimeException('区块样式无效。');
}
$sections[$key] = [
'key' => $key, 'title' => self::text($item['title'] ?? $preset[0] ?? '', 100, true),
'lead' => self::text($item['lead'] ?? $preset[2] ?? '', 500),
'body' => Html::sanitize(self::text($item['body'] ?? $preset[1] ?? '', 120000)),
'style' => $style, 'feed' => $preset[3] ?? null, 'version' => null,
];
}
return array_values($sections);
}
private static function text(mixed $value, int $limit, bool $required = false): string
{
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit || ($required && trim($value) === '')) {
throw new RuntimeException('请检查页面内容及字段长度。');
}
return trim($value);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class PageTemplates
{
public static function groups(): array
{
static $groups;
return $groups ??= require dirname(__DIR__, 2) . '/resources/page-templates.php';
}
public static function find(string $key): ?array
{
foreach (self::groups() as $theme => $group) {
if (!isset($group['pages'][$key])) {
continue;
}
$template = $group['pages'][$key];
$sections = [];
$quicklinks = [];
foreach ($template['sections'] as [$anchor, $title, $style, $body, $feed]) {
$sections[] = ['key' => $anchor, 'title' => $title, 'style' => $style, 'body' => Html::sanitize($body, $anchor),
'lead' => '', 'feed' => $feed, 'alignments' => '{}', 'version' => 0];
$quicklinks[] = ['#' . $anchor, $title];
}
return array_replace($template, [
'slug' => $key, 'theme' => $theme, 'title' => $template['name'], 'accent' => '',
'lead' => $template['description'], 'quicklinks' => $quicklinks, 'status' => 'draft',
'alignments' => [], 'image_scale' => 0, 'sections' => $sections,
]);
}
return null;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class Passwords
{
public const MIN_LENGTH = 8;
public static function isSupported(string $password): bool
{
return strlen($password) <= 72 && !str_contains($password, "\0") && mb_check_encoding($password, 'UTF-8');
}
public static function isValidNew(string $password): bool
{
return self::isSupported($password) && mb_strlen($password, 'UTF-8') >= self::MIN_LENGTH;
}
}
+403
View File
@@ -0,0 +1,403 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class Repository
{
public const DIRECTORIES = [
'catalog' => '目录', 'projects' => '项目', 'partners' => '合作伙伴',
];
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'] + self::DIRECTORIES;
private const ARTICLE_FIELDS = 'articles.*, (SELECT json_group_object(c.slug, c.name)
FROM article_category_links l JOIN article_categories c ON c.slug = l.category_slug
WHERE l.article_id = articles.id) AS categories';
private PDO $pdo;
public function __construct()
{
$this->pdo = Database::connect();
}
public function site(): array
{
return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
}
public function pages(bool $publishedOnly = false): array
{
$where = $publishedOnly ? " WHERE status = 'published'" : '';
return $this->pdo->query('SELECT slug, name, title, updated_at, status, version FROM pages' . $where . ' ORDER BY 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);
}
});
}
public function page(string $slug): ?array
{
$page = $this->one('SELECT * FROM pages WHERE slug = ?', [$slug]);
if (!$page) {
return null;
}
foreach (['actions', 'quicklinks', 'alignments', 'visibility'] 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');
$query->execute([$slug]);
$page['sections'] = $query->fetchAll();
return $page;
}
public function section(string $page, string $key): ?array
{
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
}
public function publishedFeed(string $page, string $key): ?array
{
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]);
}
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false): void
{
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): 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 = ?');
$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,
]);
self::checkVersion($query->rowCount());
if ($replaceDraftSections) {
$pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]);
}
foreach ($sections as $section) {
if (!empty($section['delete'])) {
self::deleteSection($pdo, $slug, $section['key'], $section['version']);
} elseif ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section);
} else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
}
}
});
}
public function saveSection(string $page, string $key, array $data, int $version): void
{
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
self::updateSection($pdo, $page, $key, $data, $version);
self::touchPage($pdo, $page);
});
}
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
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]);
self::checkVersion($query->rowCount());
}
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = ''): void
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
self::touchPage($pdo, $page, structureChanged: true);
});
}
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]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。');
}
}
private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void
{
$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]);
}
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
{
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
$current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?');
$current->execute([$page]);
$revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') {
self::deleteSection($pdo, $page, $key, $version);
self::touchPage($pdo, $page, structureChanged: true);
return;
}
$query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key");
$query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) {
throw new RuntimeException('找不到该区块。');
}
self::checkVersion((int) $revisions[$key] === $version ? 1 : 0);
$keys = array_map('strval', array_keys($revisions));
$index = array_search($key, $keys, true);
$other = $index + ($operation === 'up' ? -1 : 1);
if (!isset($keys[$other])) {
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::touchPage($pdo, $page, structureChanged: true);
});
}
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
{
$revision = $structureChanged ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
public function categories(): array
{
return $this->pdo->query('SELECT slug, name FROM article_categories ORDER BY rowid')->fetchAll(PDO::FETCH_KEY_PAIR);
}
public function createCategory(string $slug, string $name): void
{
$query = $this->pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
$query->execute([$slug, $name]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此分类网址标识已被使用。');
}
}
public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
{
if ($category === []) {
return [];
}
$sql = 'SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE 1 = 1';
$args = [];
if ($public) {
$sql .= " AND status = 'published'";
}
if ($category !== null) {
$args = (array) $category;
$marks = implode(', ', array_fill(0, count($args), '?'));
$sql .= " AND EXISTS (SELECT 1 FROM article_category_links
WHERE article_id = articles.id AND category_slug IN ($marks))";
}
if ($tag !== null) {
$sql .= ' AND EXISTS (SELECT 1 FROM json_each(articles.tags) WHERE value = ?)';
$args[] = $tag;
}
$order = $public ? 'published_at' : 'updated_at';
$order = $directoryOrder ? "COALESCE(json_extract(card, '$.position'), 0), id" : "$order DESC, id DESC";
$query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' LIMIT ? OFFSET ?');
$query->execute([...$args, $limit, $offset]);
return array_map(self::decodeArticle(...), $query->fetchAll());
}
public function articleById(int $id): ?array
{
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE id = ?', [$id]));
}
public function published(string $slug): ?array
{
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
}
public function articleRedirect(string $slug): ?array
{
return $this->one("SELECT articles.slug FROM article_redirects
JOIN articles ON articles.id = article_redirects.article_id
WHERE article_redirects.slug = ? AND articles.status = 'published'", [$slug]);
}
public function legacyArticle(string $path): ?array
{
return $this->one("SELECT slug FROM articles WHERE legacy_path = ? AND status = 'published'", [$path]);
}
public function saveArticle(?int $id, array $data, int $version): int
{
return Database::write(function (PDO $pdo) use ($id, $data, $version): int {
$old = $id !== null ? $this->articleById($id) : null;
if ($id !== null && (!$old || $old['version'] !== $version)) {
self::checkVersion(0);
}
$existing = $this->one('SELECT id FROM articles WHERE slug = ?', [$data['slug']]);
$redirect = $this->one('SELECT article_id FROM article_redirects WHERE slug = ?', [$data['slug']]);
if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) {
throw new RuntimeException('此网址标识已被使用。');
}
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null);
$values = [
$data['slug'], $data['title'], $data['summary'], $data['body'],
$data['body_format'], Database::json($data['card']),
Database::json($data['tags']), $data['status'], $publishedAt, self::now(),
];
if ($id === null) {
$query = $pdo->prepare('INSERT INTO articles
(id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
VALUES (' . Database::NEXT_ARTICLE_ID . ', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$query->execute($values);
$id = (int) $pdo->lastInsertId();
} else {
if ($old['slug'] !== $data['slug']) {
$pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]);
$pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]);
}
$query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, summary = ?, body = ?,
body_format = ?, card = ?, tags = ?, status = ?, published_at = ?, updated_at = ?, version = version + 1
WHERE id = ? AND version = ?');
$query->execute([...$values, $id, $version]);
self::checkVersion($query->rowCount());
$pdo->prepare('DELETE FROM article_category_links WHERE article_id = ?')->execute([$id]);
}
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
foreach ($data['categories'] as $category) {
$link->execute([$id, $category]);
}
return $id;
});
}
public function deleteArticle(int $id, int $version): void
{
Database::write(function (PDO $pdo) use ($id, $version): void {
// Keep the original seed slug even if the article has been renamed.
$deletions = $pdo->prepare('INSERT INTO article_deletions (slug, article_id)
SELECT slug, id FROM articles WHERE id = :id
UNION ALL SELECT slug, article_id FROM article_redirects WHERE article_id = :id
ON CONFLICT (slug) DO UPDATE SET article_id = excluded.article_id');
$deletions->execute(['id' => $id]);
$delete = $pdo->prepare('DELETE FROM articles WHERE id = ? AND version = ?');
$delete->execute([$id, $version]);
self::checkVersion($delete->rowCount());
});
}
public function sitemapArticles(): iterable
{
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'
AND (trim(body) <> '' OR trim(summary) <> '' OR json_extract(card, '$.image') <> '' OR json_extract(card, '$.url') <> '')
ORDER BY slug");
yield from $query;
}
public function administrator(string $email): ?array
{
return $this->one('SELECT id, email, password_hash FROM users WHERE email = ?', [$email]);
}
public function administratorById(int $id): ?array
{
return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]);
}
public function changePassword(array $user, string $newHash): bool
{
$query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?');
$query->execute([$newHash, $user['id'], $user['password_hash']]);
return $query->rowCount() === 1;
}
public function recordFailedLogin(string $address): int
{
$now = time();
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) {
return $current['expires_at'] - $now;
}
return Database::write(function (PDO $pdo) use ($address, $now): int {
$pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]);
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12) {
return $current['expires_at'] - $now;
}
$query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?)
ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1');
$query->execute([$address, $now + 900]);
return 0;
});
}
private function one(string $sql, array $args): ?array
{
$query = $this->pdo->prepare($sql);
$query->execute($args);
return $query->fetch() ?: null;
}
private static function decodeArticle(?array $article): ?array
{
if ($article !== null) {
foreach (['tags', 'categories', 'card'] as $field) {
$article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR);
}
}
return $article;
}
private static function now(): string
{
return date('Y-m-d H:i:s');
}
private static function checkVersion(int $count): void
{
if ($count !== 1) {
throw new RuntimeException('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
}
}
}
+289
View File
@@ -0,0 +1,289 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use PharData;
use RuntimeException;
use Throwable;
final class SiteBackup
{
private const FORMAT = 'laysite-site';
private const VERSION = 2;
private const TABLES = [
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
'article_category_links', 'article_redirects', 'article_deletions', 'media',
];
private const MANIFEST_LIMIT = 32 * 1024 * 1024;
public static function export(string $path): void
{
if (!str_ends_with($path, '.tar') || file_exists($path)) {
throw new RuntimeException('请选择尚不存在的 .tar 备份路径。');
}
try {
Database::write(function (PDO $pdo) use ($path): void {
$tables = [];
foreach (self::TABLES as $table) {
$tables[$table] = $pdo->query('SELECT * FROM ' . $table)->fetchAll();
}
$files = [];
$archive = new PharData($path);
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name']);
$file = Media::directory() . '/' . $name;
if (!is_file($file) || is_link($file) || filesize($file) !== (int) $asset['size']) {
throw new RuntimeException('资源文件缺失或大小已变更:' . $name);
}
$files[$name] = hash_file('sha256', $file);
$archive->addFile($file, 'media/' . $name);
}
$manifest = Database::json(['format' => self::FORMAT, 'version' => self::VERSION, 'exported_at' => gmdate('c'), 'tables' => $tables, 'files' => $files]);
if (strlen($manifest) > self::MANIFEST_LIMIT) {
throw new RuntimeException('站点内容超过当前备份格式的大小上限。');
}
$archive->addFromString('site.json', $manifest);
});
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function import(string $path): void
{
$archive = new PharData($path);
if (!isset($archive['site.json']) || $archive['site.json']->isLink() || $archive['site.json']->getSize() > self::MANIFEST_LIMIT) {
throw new RuntimeException('备份清单缺失或过大。');
}
$manifest = json_decode($archive['site.json']->getContent(), true, 48, JSON_THROW_ON_ERROR);
$tables = self::prepare($manifest);
$files = $manifest['files'] ?? [];
if (!is_array($files) || count($files) !== count($tables['media'])) {
throw new RuntimeException('备份资源清单不完整。');
}
$directory = Media::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('不能写入资源目录。');
}
$stage = $directory . '/.restore-' . bin2hex(random_bytes(12));
if (!mkdir($stage, 0700)) {
throw new RuntimeException('不能创建临时资源目录。');
}
$staged = [];
$installed = [];
try {
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name'] ?? null);
$size = $asset['size'] ?? 0;
if (!is_int($size) || $size < 1 || $size > Media::MAX_BYTES || isset($staged[$name])
|| !is_string($files[$name] ?? null) || !isset($archive['media/' . $name])
|| $archive['media/' . $name]->isLink() || !$archive['media/' . $name]->isFile() || $archive['media/' . $name]->getSize() !== $size) {
throw new RuntimeException('备份资源不完整:' . $name);
}
$staged[$name] = $stage . '/' . $name;
$source = fopen('phar://' . $path . '/media/' . $name, 'rb');
if ($source === false) {
throw new RuntimeException('不能读取备份资源。');
}
try {
$destination = fopen($staged[$name], 'xb');
if ($destination === false) {
throw new RuntimeException('不能暂存备份资源。');
}
try {
$written = stream_copy_to_stream($source, $destination, $size + 1);
} finally {
fclose($destination);
}
} finally {
fclose($source);
}
if ($written !== $size || !hash_equals($files[$name], hash_file('sha256', $staged[$name]))) {
throw new RuntimeException('备份资源校验失败:' . $name);
}
Media::validateBackup($staged[$name], $name, $asset['mime'] ?? '', $size);
}
Database::write(function (PDO $pdo) use ($tables, $staged, $directory, &$installed): void {
self::replaceTables($pdo, $tables);
foreach ($staged as $name => $source) {
$target = $directory . '/' . $name;
if (is_file($target) && !is_link($target) && hash_file('sha256', $target) === hash_file('sha256', $source)) {
continue;
}
if (file_exists($target) || is_link($target) || !link($source, $target)) {
throw new RuntimeException('资源名称冲突:' . $name);
}
$installed[] = $target;
}
});
} catch (Throwable $error) {
foreach ($installed as $file) {
unlink($file);
}
throw $error;
} finally {
foreach ($staged as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($stage);
}
}
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)) {
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
}
$tables = $manifest['tables'];
if ($manifest['version'] === 1) {
$tables += ['design_presets' => [], 'article_deletions' => []];
}
foreach (self::TABLES as $table) {
if (!is_array($tables[$table] ?? null) || !array_is_list($tables[$table])) {
throw new RuntimeException('备份数据表不完整。');
}
foreach ($tables[$table] as $row) {
if (!is_array($row) || array_is_list($row)) {
throw new RuntimeException('备份数据行格式无效。');
}
}
}
if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
throw new RuntimeException('备份缺少站点身份或首页。');
}
$designs = [];
foreach ($tables['design_presets'] as &$row) {
$payload = self::decode($row['payload'] ?? '');
$row['payload'] = Database::json(DesignLibrary::normalize($row['kind'] ?? '', $row['preset'] ?? '', $payload));
$designs[$row['id']] = $row['kind'];
}
unset($row);
$settings = self::decode($tables['site_settings'][0]['payload'] ?? '');
if (!is_string($settings['name'] ?? null) || trim($settings['name']) === '' || mb_strlen($settings['name']) > 100) {
throw new RuntimeException('备份的站点名称无效。');
}
$site = ['name' => $settings['name'], 'cdn' => ['origin' => Assets::cdn($settings['cdn']['origin'] ?? '')], 'revisions' => ['general' => time()]];
foreach (['header', 'footer'] as $kind) {
if (isset($settings[$kind . '_id'])) {
$site[$kind . '_id'] = self::selection($designs, $kind, $settings[$kind . '_id']);
}
}
$tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
foreach ($tables['pages'] as &$row) {
PageDraft::slug($row['slug'] ?? null, ['admin', 'assets', 'account', 'mcp', 'palette', 'favicon']);
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'] ?? '{}'));
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = '';
}
foreach (['header', 'footer', 'palette'] as $kind) {
$row[$kind . '_id'] = self::selection($designs, $kind, $row[$kind . '_id'] ?? null);
}
}
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)) {
throw new RuntimeException('备份包含未知区块样式。');
}
$row['body'] = Html::sanitize($row['body'] ?? '');
if (isset($row['feed'])) {
$feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|| !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
|| array_diff($feed['categories'], array_column($tables['article_categories'], 'slug'))
|| !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
throw new RuntimeException('备份的动态区块配置无效。');
}
}
}
unset($row);
foreach ($tables['articles'] as &$row) {
if (($row['body_format'] ?? '') === 'html') {
$row['body'] = Html::sanitize($row['body'] ?? '');
}
$card = self::decode($row['card'] ?? '{}');
foreach (['url', 'extra_url', 'image'] as $field) {
self::validateAssetUrl($card[$field] ?? '', $field === 'image');
}
$row['tags'] = Database::json(self::decode($row['tags'] ?? '[]'));
}
unset($row);
return $tables;
}
private static function replaceTables(PDO $pdo, array $tables): void
{
$revisions = [];
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
$revisions[$table] = in_array('version', $columns, true) ? max(1, (int) $pdo->query('SELECT MAX(version) FROM ' . $table)->fetchColumn() + 1) : 0;
}
foreach (array_reverse(self::TABLES) as $table) {
$pdo->exec('DELETE FROM ' . $table);
}
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
foreach ($tables[$table] as $row) {
$row = array_intersect_key($row, array_flip($columns));
if ($revisions[$table]) {
$row['version'] = $revisions[$table];
}
if (!$row) {
throw new RuntimeException('备份缺少必要的数据列。');
}
$keys = array_keys($row);
$query = $pdo->prepare('INSERT INTO ' . $table . ' ("' . implode('","', $keys) . '") VALUES (' . implode(',', array_fill(0, count($row), '?')) . ')');
$query->execute(array_values($row));
}
}
}
private static function selection(array $designs, string $kind, mixed $id): ?int
{
if ($id === null) {
return null;
}
if (!is_int($id) || ($designs[$id] ?? '') !== $kind) {
throw new RuntimeException('备份引用了缺失的设计方案。');
}
return $id;
}
private static function decode(mixed $value): array
{
$data = is_string($value) ? json_decode($value, true, 32, JSON_THROW_ON_ERROR) : null;
if (!is_array($data)) {
throw new RuntimeException('备份中的配置格式无效。');
}
return $data;
}
private static function validateAssetUrl(mixed $url, bool $media): void
{
if (!is_string($url) || ($url !== '' && !Html::url($url, $media))) {
throw new RuntimeException('备份含有无效的资源地址。');
}
}
private static function mediaName(mixed $name): string
{
if (!is_string($name) || !preg_match('/^[a-f0-9]{32}\.[a-z0-9]+$/D', $name)) {
throw new RuntimeException('备份含有无效的资源名称。');
}
return $name;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class SiteDesign
{
public static function parseLinks(string $value): array
{
$links = [];
foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) {
if (trim($line) === '') {
continue;
}
[$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, ''));
if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
}
$links[] = [$url, $label];
}
return $links;
}
public static function linkText(array $links): string
{
return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
}
public static function saveGeneral(string $name, string $origin, int $version): void
{
Database::write(function (PDO $pdo) use ($name, $origin, $version): void {
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if (($site['revisions']['general'] ?? 0) !== $version) {
throw new RuntimeException('站点设置已更新,请重新打开后再保存。');
}
$site['name'] = $name;
$site['cdn'] = ['origin' => $origin];
$site['revisions']['general'] = $version + 1;
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
});
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace App\Content;
use App\Http\VisitorSession;
use support\Response;
final class View
{
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
{
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
$data['cdn'] = $cdn;
$personalized = false;
if (!$admin) {
$page = $data['page'] ?? [];
$data['header'] = DesignLibrary::layout('header', $data['site'], $page);
$data['footer'] = DesignLibrary::layout('footer', $data['site'], $page);
$data['visitor'] = null;
$provider = $data['header']['payload']['provider'];
$personalized = $provider !== [] && in_array('account', $data['header']['payload']['components'], true)
&& ($page['visibility']['header'] ?? true) && empty($data['previewMode']);
if ($personalized) {
$profile = VisitorSession::profile(request());
if (($profile['layout'] ?? null) === $data['header']['id']
&& ($profile['config'] ?? null) === hash('sha256', json_encode($provider, JSON_THROW_ON_ERROR))) {
$data['visitor'] = $profile;
}
}
}
$html = self::fragment($template, $data);
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
$articleEditor = $admin && !empty($data['articleEditor']);
$editorImages = $articleEditor ? ' data:' : '';
$editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
$headers = [
'Content-Type' => 'text/html; charset=utf-8',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin',
'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:$editorImages; media-src 'self' https:; "
. "style-src $assetSources; {$editorStyles}script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
];
if ($admin || !empty($data['previewMode'])) {
$headers['Cache-Control'] = 'no-store';
$headers['X-Robots-Tag'] = 'noindex, nofollow';
} elseif (($data['noindex'] ?? false) || $status >= 400) {
$headers['X-Robots-Tag'] = 'noindex';
}
if ($personalized) {
$headers['Cache-Control'] = 'private, no-store';
$headers['Vary'] = 'Cookie';
}
return new Response($status, $headers, $page);
}
public static function fragment(string $template, array $data = []): string
{
extract($data, EXTR_SKIP);
ob_start();
try {
require dirname(__DIR__) . '/view/' . $template . '.php';
return (string) ob_get_contents();
} finally {
ob_end_clean();
}
}
public static function escape(string|int|null $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
public static function absolute(string $path): string
{
return rtrim(getenv('LAYSITE_SITE_URL') ?: 'http://127.0.0.1:8787', '/') . $path;
}
public static function date(?string $value, string $format = 'Y年n月j日'): string
{
return $value ? date($format, strtotime($value)) : '';
}
public static function alignmentClass(?string $alignment): string
{
return in_array($alignment, Html::ALIGNMENTS, true) ? ' studio-align-' . $alignment : '';
}
public static function archivePage(string $path, int $page): string
{
if ($page === 1) {
return $path;
}
return $path . (str_contains($path, '?') ? '&' : '?') . 'page=' . $page;
}
public static function redirect(string $path, int $status = 303): Response
{
return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], '');
}
}