Migrate Laysense to unmodified LaySite 1.5.2
This commit is contained in:
@@ -12,6 +12,8 @@ final class BlockTemplates
|
||||
|
||||
public const CATALOG_FEED = '{"categories":["catalog"],"mode":"catalog","limit":30}';
|
||||
|
||||
public const DESIGN_STUDIO_IMAGE = '/assets/system/design-studio.webp';
|
||||
|
||||
public const ELEMENT_GROUPS = [
|
||||
'text-elements' => ['文字与列表', [
|
||||
'paragraph' => ['段落', '<p>填写正文。</p>'],
|
||||
@@ -88,6 +90,7 @@ final class BlockTemplates
|
||||
'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>'],
|
||||
'plan-comparison' => ['两种方案对比', '<div class="studio-two-column studio-comparison"><article class="content-card"><p class="overline">适合个人</p><h3>轻量方案</h3><ul><li>核心功能</li><li>按需使用</li></ul></article><article class="content-card"><p class="overline">适合团队</p><h3>协作方案</h3><ul><li>共享工作空间</li><li>团队支持</li></ul></article></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>'],
|
||||
@@ -96,6 +99,7 @@ final class BlockTemplates
|
||||
'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>'],
|
||||
'reference-code' => ['说明与代码示例', '<div class="studio-split"><div><p class="overline">操作示例</p><h3>运行一次检查</h3><p>说明命令的适用环境和执行后的结果。</p></div><pre class="studio-code"><code>curl -I https://example.com</code></pre></div>'],
|
||||
]],
|
||||
'actions' => ['导航与引导', [
|
||||
'service-catalog' => ['目录卡片', '', '', self::CATALOG_FEED],
|
||||
@@ -103,11 +107,13 @@ final class BlockTemplates
|
||||
'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>'],
|
||||
'support-channels' => ['支持渠道', '<div class="studio-two-column"><article class="content-card"><h3>查找自助资料</h3><p>按问题类型查阅文档与最新公告。</p><a href="/articles">查看帮助文章</a></article><article class="content-card"><h3>联系支持团队</h3><p>请注明当前情况、操作步骤及希望得到的帮助。</p><a href="mailto:hello@example.com">发送邮件</a></article></div>'],
|
||||
]],
|
||||
'events' => ['活动与场地', [
|
||||
'event-agenda' => ['当日议程', '<ol class="studio-agenda"><li><p>09:30</p><div><h3>签到与开场</h3><p>开放入口并介绍当天安排。</p></div><span>主会场</span></li><li><p>10:30</p><div><h3>专题工作坊</h3><p>跟随主持人完成一次实践。</p></div><span>工作区</span></li><li><p>14:00</p><div><h3>圆桌交流</h3><p>分享实践经验并回答问题。</p></div><span>交流区</span></li></ol>'],
|
||||
'speaker-lineup' => ['嘉宾阵容', '<div class="card-grid studio-speakers"><article class="content-card"><p class="overline">主题分享</p><h3>嘉宾姓名</h3><p>填写嘉宾的角色和主题。</p></article><article class="content-card"><p class="overline">工作坊</p><h3>主持人姓名</h3><p>介绍实践主题和适合的听众。</p></article><article class="content-card"><p class="overline">圆桌交流</p><h3>主持人姓名</h3><p>介绍本场将讨论的议题。</p></article></div>'],
|
||||
'venue-guide' => ['到场指南', '<div class="studio-two-column"><article class="content-card"><h3>开放与入场</h3><p>填写开放时间、预约方式和入口位置。</p></article><article class="content-card"><h3>交通与无障碍</h3><p>填写推荐交通方式和无障碍通道位置。</p></article></div>'],
|
||||
'event-registration' => ['活动报名', '<div class="studio-banner studio-banner-two"><div><p class="overline">参加活动</p><h3>预留你的席位</h3><p>报名时请附上姓名和到场人数。</p></div><a class="button button-primary" href="mailto:hello@example.com">邮件报名</a></div>'],
|
||||
]],
|
||||
'commerce' => ['商品与服务', [
|
||||
'product-spotlight' => ['商品展示', '<div class="studio-split studio-product"><img src="/assets/system/sample.webp" alt="商品展示示例" loading="lazy"><div><p class="overline">系列名称</p><h3>填写商品名称</h3><p>说明规格、适用场景与供货信息。</p><a class="button button-primary" href="#contact">联系订购</a></div></div>'],
|
||||
@@ -123,8 +129,48 @@ final class BlockTemplates
|
||||
public static function groups(): array
|
||||
{
|
||||
static $groups;
|
||||
if ($groups === null) {
|
||||
$groups = self::GROUPS + LayoutPage::groups();
|
||||
foreach (self::splitLayouts() as $group => $layouts) {
|
||||
$groups[$group][1] += $layouts;
|
||||
}
|
||||
}
|
||||
|
||||
return $groups ??= self::GROUPS + LayoutPage::groups();
|
||||
return $groups;
|
||||
}
|
||||
|
||||
private static function splitLayouts(): array
|
||||
{
|
||||
$sample = '<img src="/assets/system/sample.webp" alt="示例界面" loading="lazy">';
|
||||
$photo = '<img src="' . self::DESIGN_STUDIO_IMAGE . '" alt="工作台上的陶器、笔记本与亚麻布" loading="lazy">';
|
||||
$split = static fn (string $class, string $first, string $second): string => '<div class="studio-split ' . $class . '">' . $first . $second . '</div>';
|
||||
$intro = '<div><h3>看见使用场景</h3><p>用图片展示工作场景,并解释访客能在其中完成什么。</p></div>';
|
||||
$cover = '<div><p class="overline">工作室</p><h3>把想法做成可以使用的作品</h3><p>介绍你的团队、服务以及下一步。</p><a class="button button-primary" href="/articles">探索作品</a></div>';
|
||||
$guide = '<div><h3>准备开始</h3><p>在图片旁说明操作条件和完成目标。</p><ul class="studio-checklist"><li>准备工作环境</li><li>打开操作入口</li><li>确认初次运行结果</li></ul></div>';
|
||||
$story = '<div><p class="overline">幕后故事</p><h3>从材料开始做决定</h3><p>把一个细节讲清楚,让读者了解作品的背景和过程。</p><a href="/articles">阅读完整故事</a></div>';
|
||||
$captioned = '<figure class="studio-captioned">' . $photo . '<figcaption>设计工作台与选材样本</figcaption></figure>';
|
||||
$features = '<div><h3>从日常使用开始</h3><p>说明这项功能在真实工作流程里怎么使用。</p></div>';
|
||||
$video = '<video controls preload="none" poster="/assets/system/sample.webp"></video>';
|
||||
|
||||
return [
|
||||
'cover' => [
|
||||
'cover-photo-left' => ['大图封面 · 图左', $split('studio-split-cover studio-split-media-left', $photo, $cover)],
|
||||
'cover-photo-right' => ['大图封面 · 图右', $split('studio-split-cover studio-split-media-right', $cover, $photo)],
|
||||
],
|
||||
'layout' => [
|
||||
'split-balanced-left' => ['均分图文 · 图左', $split('studio-split-balanced', $sample, $intro)],
|
||||
'split-balanced-right' => ['均分图文 · 图右', $split('studio-split-balanced', $intro, $sample)],
|
||||
'split-guide-left' => ['大图与清单 · 图左', $split('studio-split-guide studio-split-media-left', $sample, $guide)],
|
||||
'split-guide-right' => ['大图与清单 · 图右', $split('studio-split-guide studio-split-media-right', $guide, $sample)],
|
||||
'split-story-left' => ['故事与图注 · 图左', $split('studio-split-story', $captioned, $story)],
|
||||
'split-story-right' => ['故事与图注 · 图右', $split('studio-split-story', $story, $captioned)],
|
||||
'split-alternating' => ['双行交错图文', '<div class="studio-alternating">' . $split('studio-split-balanced', $sample, $features)
|
||||
. $split('studio-split-balanced', $story, $photo) . '</div>'],
|
||||
],
|
||||
'media' => [
|
||||
'video-demo-right' => ['视频演示 · 视频右', $split('studio-split-balanced', '<div><h3>观看演示</h3><p>说明视频包含的功能和观看顺序。</p></div>', $video)],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function find(string $key): ?array
|
||||
|
||||
+101
-8
@@ -18,6 +18,8 @@ final class CanvasStyle
|
||||
'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],
|
||||
'letter' => ['letter-spacing', -5, 24],
|
||||
'line' => ['line-height', 8, 30],
|
||||
];
|
||||
private const TYPOGRAPHY = [
|
||||
'weight-bold' => 'font-weight:700', 'weight-normal' => 'font-weight:400',
|
||||
@@ -25,6 +27,13 @@ final class CanvasStyle
|
||||
'strike-on' => 'text-decoration-line:line-through', 'strike-off' => 'text-decoration-line:none',
|
||||
];
|
||||
private const PREFIX = 'studio-style-';
|
||||
private const IMAGE_SIZES = [
|
||||
'cover' => 'cover', 'contain' => 'contain', 'stretch' => '100% 100%', 'original' => 'auto', 'tile' => 'auto',
|
||||
];
|
||||
private const IMAGE_POSITIONS = [
|
||||
'c' => 'center', 'tl' => 'left top', 'tc' => 'center top', 'tr' => 'right top',
|
||||
'ml' => 'left center', 'mr' => 'right center', 'bl' => 'left bottom', 'bc' => 'center bottom', 'br' => 'right bottom',
|
||||
];
|
||||
|
||||
public static function encode(array $presentation): string
|
||||
{
|
||||
@@ -95,7 +104,7 @@ final class CanvasStyle
|
||||
|
||||
private static function classList(mixed $value, bool $textOnly = false): string
|
||||
{
|
||||
if (!is_string($value) || strlen($value) > 320) {
|
||||
if (!is_string($value) || strlen($value) > 1800) {
|
||||
throw new RuntimeException('画布样式无效。');
|
||||
}
|
||||
$classes = [];
|
||||
@@ -109,9 +118,11 @@ final class CanvasStyle
|
||||
$classes[$property] = $class;
|
||||
} elseif ($property === 'color' && ($size === 'theme' || preg_match('/^[a-f0-9]{6}$/D', $size))) {
|
||||
$classes[$property] = $class;
|
||||
} elseif (!$textOnly && $property === 'fill' && self::fill($size) !== null) {
|
||||
$classes[$property] = $class;
|
||||
} elseif (!$textOnly && $property === 'display' && in_array($size, ['block', 'inline', 'inline-block'], true)) {
|
||||
$classes[$property] = $class;
|
||||
} elseif ((!$textOnly || $property === 'size') && isset(self::PROPERTIES[$property])
|
||||
} elseif ((!$textOnly || in_array($property, ['size', 'letter', 'line'], true)) && 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) {
|
||||
@@ -163,12 +174,92 @@ final class CanvasStyle
|
||||
return $markup;
|
||||
}
|
||||
|
||||
public static function colorRules(string $markup): string
|
||||
private static function fill(string $token): ?string
|
||||
{
|
||||
preg_match_all('/\bstudio-style-color-([a-f0-9]{6})(?![\w-])/', $markup, $matches);
|
||||
if (preg_match('/^solid-([a-f0-9]{6})$/D', $token, $parts)) {
|
||||
return 'background:#' . $parts[1] . '!important';
|
||||
}
|
||||
if (preg_match('/^gradient-(0|[1-9]\d{0,2})-([a-f0-9]{6})-([a-f0-9]{6})$/D', $token, $parts) && (int) $parts[1] <= 360) {
|
||||
return "background:linear-gradient({$parts[1]}deg,#{$parts[2]},#{$parts[3]})!important";
|
||||
}
|
||||
if (str_starts_with($token, 'gradient-')) {
|
||||
return self::gradient(substr($token, strlen('gradient-')));
|
||||
}
|
||||
$size = 'cover';
|
||||
$position = 'c';
|
||||
if (preg_match('/^image-v2-([a-z]+)-([a-z]+)-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
|
||||
[, $size, $position, $encoded] = $parts;
|
||||
} elseif (preg_match('/^image-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) {
|
||||
$encoded = $parts[1];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (!isset(self::IMAGE_SIZES[$size], self::IMAGE_POSITIONS[$position])) {
|
||||
return null;
|
||||
}
|
||||
$url = base64_decode(strtr($encoded, '-_', '+/'), true);
|
||||
if ($url === false || strlen($url) > 1000 || !mb_check_encoding($url, 'UTF-8') || !Html::url($url, true)
|
||||
|| rtrim(strtr(base64_encode($url), '+/', '-_'), '=') !== $encoded) {
|
||||
return null;
|
||||
}
|
||||
// Quote the URL for CSS and keep the result safe inside a raw-text HTML style element.
|
||||
$escaped = str_replace(['"', '<', '>'], ['\\22 ', '\\3c ', '\\3e '], $url);
|
||||
|
||||
$repeat = $size === 'tile' ? 'repeat' : 'no-repeat';
|
||||
|
||||
return 'background-image:url("' . $escaped . '")!important;background-position:' . self::IMAGE_POSITIONS[$position]
|
||||
. '!important;background-size:' . self::IMAGE_SIZES[$size] . '!important;background-repeat:' . $repeat . '!important';
|
||||
}
|
||||
|
||||
private static function gradient(string $token): ?string
|
||||
{
|
||||
$parts = explode('-', $token, 15);
|
||||
$type = array_shift($parts);
|
||||
if ($type === 'linear') {
|
||||
$angle = array_shift($parts);
|
||||
if ($angle === null || !preg_match('/^(0|[1-9]\d{0,2})$/D', $angle) || (int) $angle > 360) {
|
||||
return null;
|
||||
}
|
||||
$direction = $angle . 'deg';
|
||||
} elseif ($type === 'radial') {
|
||||
$direction = 'circle at center';
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (count($parts) < 2 || count($parts) > 12) {
|
||||
return null;
|
||||
}
|
||||
$last = 0;
|
||||
$stops = [];
|
||||
foreach ($parts as $stop) {
|
||||
if (!preg_match('/^(0|[1-9]\d?|100)_([a-f0-9]{6})$/D', $stop, $color) || (int) $color[1] < $last) {
|
||||
return null;
|
||||
}
|
||||
$last = (int) $color[1];
|
||||
$stops[] = "#{$color[2]} {$last}%";
|
||||
}
|
||||
|
||||
return "background:{$type}-gradient($direction," . implode(',', $stops) . ')!important';
|
||||
}
|
||||
|
||||
public static function dynamicRules(string $markup): string
|
||||
{
|
||||
preg_match_all('/\bstudio-style-(color|fill)-([A-Za-z0-9_-]+)(?![\w-])/', $markup, $matches, PREG_SET_ORDER);
|
||||
$css = '';
|
||||
foreach (array_unique($matches[1]) as $hex) {
|
||||
$css .= ".studio-style-color-{$hex}{color:#{$hex}!important}\n";
|
||||
$seen = [];
|
||||
foreach ($matches as [$class, $property, $value]) {
|
||||
if (isset($seen[$class])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$class] = true;
|
||||
if ($property === 'color') {
|
||||
$rule = preg_match('/^[a-f0-9]{6}$/D', $value) ? "color:#{$value}!important" : null;
|
||||
} else {
|
||||
$rule = self::fill($value);
|
||||
}
|
||||
if ($rule !== null) {
|
||||
$css .= ".$class" . '{' . $rule . "}\n";
|
||||
}
|
||||
}
|
||||
|
||||
return $css;
|
||||
@@ -177,9 +268,11 @@ final class CanvasStyle
|
||||
public static function stylesheet(): string
|
||||
{
|
||||
$css = '';
|
||||
foreach (self::PROPERTIES as $key => [$property, $min, $max]) {
|
||||
foreach (self::PROPERTIES as $key => $definition) {
|
||||
[$property, $min, $max] = $definition;
|
||||
for ($value = $min; $value <= $max; $value++) {
|
||||
$css .= '.' . self::PREFIX . "$key-$value{{$property}:{$value}px!important}\n";
|
||||
$length = $key === 'line' ? $value / 10 : $value . 'px';
|
||||
$css .= '.' . self::PREFIX . "$key-$value{{$property}:{$length}!important}\n";
|
||||
}
|
||||
}
|
||||
for ($width = self::MIN_MEDIA_SCALE; $width <= 100; $width++) {
|
||||
|
||||
+44
-17
@@ -11,7 +11,8 @@ use Throwable;
|
||||
|
||||
final class Database
|
||||
{
|
||||
private const SCHEMA_VERSION = 6;
|
||||
public const MIGRATION_REQUIRED = '数据库尚未完成升级。请在站点目录运行 php bin/install.php。';
|
||||
private const SCHEMA_VERSION = 9;
|
||||
// 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';
|
||||
@@ -53,7 +54,8 @@ final class Database
|
||||
if ($version > self::SCHEMA_VERSION) {
|
||||
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
|
||||
}
|
||||
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
|
||||
$schema = file_get_contents($root . '/resources/schema.sql');
|
||||
$pdo->exec($schema);
|
||||
if ($version < 3) {
|
||||
foreach (['pages', 'sections'] as $table) {
|
||||
$columns = $pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
|
||||
@@ -63,21 +65,23 @@ final class Database
|
||||
}
|
||||
}
|
||||
$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 === 0) {
|
||||
$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 < 2) {
|
||||
OAuthCredentials::migrateLegacy($pdo);
|
||||
@@ -92,15 +96,38 @@ final class Database
|
||||
if ($version < 6 && !in_array('page_type', array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'), true)) {
|
||||
$pdo->exec("ALTER TABLE pages ADD COLUMN page_type TEXT NOT NULL DEFAULT 'page' CHECK (page_type IN ('page', 'maintenance', 'not-found'))");
|
||||
}
|
||||
if ($version < 8 && !in_array('head_html', array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'), true)) {
|
||||
$pdo->exec("ALTER TABLE pages ADD COLUMN head_html TEXT NOT NULL DEFAULT ''");
|
||||
}
|
||||
if ($version < 5) {
|
||||
LayoutPage::migrate($pdo);
|
||||
}
|
||||
if ($version < 9) {
|
||||
self::migratePageRoutes($pdo, $schema);
|
||||
DesignLibrary::ensureDefaultPalette($pdo);
|
||||
}
|
||||
if ($version < self::SCHEMA_VERSION) {
|
||||
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function migratePageRoutes(PDO $pdo, string $schema): void
|
||||
{
|
||||
// Renaming the parent also retargets the old child table's foreign key.
|
||||
$pdo->exec('ALTER TABLE pages RENAME TO pages_before_routes');
|
||||
$pdo->exec('ALTER TABLE sections RENAME TO sections_before_routes');
|
||||
$pdo->exec($schema);
|
||||
foreach (['pages', 'sections'] as $table) {
|
||||
$columns = implode(', ', array_column($pdo->query("PRAGMA table_info($table)")->fetchAll(), 'name'));
|
||||
$pdo->exec("INSERT INTO $table (rowid, $columns) SELECT rowid, $columns FROM {$table}_before_routes");
|
||||
}
|
||||
$pdo->exec('DROP TABLE sections_before_routes');
|
||||
$pdo->exec('DROP TABLE pages_before_routes');
|
||||
$pdo->exec('CREATE UNIQUE INDEX pages_layout_id ON pages(layout_id)');
|
||||
$pdo->exec("UPDATE pages SET page_type = 'home' WHERE slug = 'home' AND page_type = 'page' AND layout_id IS NULL");
|
||||
}
|
||||
|
||||
public static function write(callable $operation): mixed
|
||||
{
|
||||
$pdo = self::connect();
|
||||
|
||||
@@ -39,6 +39,68 @@ final class DesignLibrary
|
||||
return $query->fetchAll();
|
||||
}
|
||||
|
||||
public static function ensureDefaultPalette(PDO $pdo): void
|
||||
{
|
||||
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if (array_key_exists('palette_id', $site)) {
|
||||
return;
|
||||
}
|
||||
$pdo->prepare("INSERT INTO design_presets (kind, name, preset, payload) VALUES ('palette', ?, 'custom', ?)")
|
||||
->execute(['默认配色', Database::json(self::defaults('palette'))]);
|
||||
$site['palette_id'] = (int) $pdo->lastInsertId();
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
}
|
||||
|
||||
public static function layouts(): array
|
||||
{
|
||||
return Database::connect()->query("SELECT d.id, d.kind, d.name, pages.slug FROM design_presets d
|
||||
JOIN pages ON pages.layout_id = d.id WHERE d.kind IN ('header', 'footer') ORDER BY d.kind, d.id")->fetchAll();
|
||||
}
|
||||
|
||||
public static function palettes(): array
|
||||
{
|
||||
$rows = Database::connect()->query("SELECT id, name, preset, payload, version FROM design_presets
|
||||
WHERE kind = 'palette' ORDER BY id")->fetchAll();
|
||||
foreach ($rows as &$row) {
|
||||
$row['colors'] = self::normalize('palette', $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
|
||||
unset($row['payload'], $row['preset']);
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function paletteUrl(int $id, int $version, bool $region = false): string
|
||||
{
|
||||
return '/palette/' . $id . ($region ? '/region' : '') . '.css?v=' . $version;
|
||||
}
|
||||
|
||||
public static function deletePalette(int $id, int $version): bool
|
||||
{
|
||||
return Database::write(static function (PDO $pdo) use ($id, $version): bool {
|
||||
$query = $pdo->prepare("SELECT version FROM design_presets WHERE id = ? AND kind = 'palette'");
|
||||
$query->execute([$id]);
|
||||
$currentVersion = $query->fetchColumn();
|
||||
$query->closeCursor();
|
||||
if ($currentVersion === false) {
|
||||
return false;
|
||||
}
|
||||
if ((int) $currentVersion !== $version) {
|
||||
throw new RuntimeException('配色方案已更新,请刷新后再删除。');
|
||||
}
|
||||
|
||||
$pdo->prepare('UPDATE pages SET palette_id = NULL, version = version + 1 WHERE palette_id = ?')->execute([$id]);
|
||||
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if (($site['palette_id'] ?? null) === $id) {
|
||||
$site['palette_id'] = null;
|
||||
$site['revisions']['general'] = ($site['revisions']['general'] ?? 0) + 1;
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
}
|
||||
$pdo->prepare("DELETE FROM design_presets WHERE id = ? AND kind = 'palette'")->execute([$id]);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static function find(int $id, string $kind): ?array
|
||||
{
|
||||
if ($id < 1) {
|
||||
@@ -86,7 +148,12 @@ final class DesignLibrary
|
||||
}
|
||||
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if ($id === false || !self::find($id, $kind)) {
|
||||
throw new RuntimeException('所选页头、页脚或配色方案不存在。');
|
||||
$label = match ($kind) {
|
||||
'header' => '页头',
|
||||
'footer' => '页脚',
|
||||
default => '配色方案',
|
||||
};
|
||||
throw new RuntimeException('所选' . $label . '已不可用。请保留修改,重新打开页面后再选择。');
|
||||
}
|
||||
|
||||
return $id;
|
||||
|
||||
+18
-19
@@ -9,25 +9,9 @@ use RuntimeException;
|
||||
|
||||
final class LayoutPage
|
||||
{
|
||||
public const TYPES = ['page' => '普通页面', 'header' => '页头', 'footer' => '页脚'];
|
||||
public const TYPES = ['page' => '普通页面', 'home' => '首页', '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 {
|
||||
$id = self::insertPreset($pdo, $kind, $name);
|
||||
$slug = self::slug($kind, $id);
|
||||
Repository::insertPage($pdo, $slug, $name, ['visibility' => ['hero' => false]], $id);
|
||||
|
||||
return $slug;
|
||||
});
|
||||
}
|
||||
|
||||
private static function insertPreset(PDO $pdo, string $kind, string $name): int
|
||||
public static function insertPreset(PDO $pdo, string $kind, string $name): int
|
||||
{
|
||||
$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))]);
|
||||
@@ -51,7 +35,7 @@ final class LayoutPage
|
||||
$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'], [
|
||||
Repository::insertPage($pdo, 'layout--' . $kind . '-' . $row['id'], $row['name'], [
|
||||
'visibility' => ['hero' => false],
|
||||
'sections' => [[
|
||||
'key' => 'layout-content', 'title' => DesignLibrary::PRESETS[$kind][$row['preset']], 'lead' => '',
|
||||
@@ -128,4 +112,19 @@ final class LayoutPage
|
||||
DesignLibrary::setDefault($pdo, $kind, $id, $config['default']);
|
||||
}
|
||||
}
|
||||
|
||||
public static function deletePreset(PDO $pdo, string $kind, int $id): void
|
||||
{
|
||||
$field = $kind . '_id';
|
||||
$pdo->prepare("UPDATE pages SET $field = NULL, version = version + 1 WHERE $field = ?")->execute([$id]);
|
||||
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
if (($site['layout_defaults'][$kind] ?? null) === $id) {
|
||||
unset($site['layout_defaults'][$kind]);
|
||||
}
|
||||
if (($site[$field] ?? null) === $id) {
|
||||
$site[$field] = $site['layout_defaults'][$kind] ?? null;
|
||||
}
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
$pdo->prepare('DELETE FROM design_presets WHERE id = ?')->execute([$id]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ final class Licenses
|
||||
'url' => 'https://github.com/codemirror/codemirror5', 'file' => $root . '/public/assets/vendor/codemirror/LICENSE'],
|
||||
'js-beautify' => ['name' => 'JS Beautifier', 'version' => '1.15.4', 'license' => 'MIT',
|
||||
'url' => 'https://github.com/beautifier/js-beautify', 'file' => $root . '/public/assets/vendor/js-beautify/LICENSE'],
|
||||
'grapick' => ['name' => 'Grapick', 'version' => '0.1.13', 'license' => 'MIT',
|
||||
'url' => 'https://github.com/artf/grapick', 'file' => $root . '/public/assets/vendor/grapick/LICENSE'],
|
||||
'geist' => ['name' => 'Geist', 'license' => 'OFL-1.1',
|
||||
'url' => 'https://github.com/vercel/geist-font', 'file' => $root . '/public/assets/geist-OFL.txt'],
|
||||
'dompurify' => ['name' => 'DOMPurify', 'version' => self::declaredVersion($editor, '~@license DOMPurify\h+' . $version . '~'), 'license' => 'Apache-2.0 / MPL-2.0',
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use App\Config\Environment;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use RuntimeException;
|
||||
|
||||
final class McpSettings
|
||||
{
|
||||
private const CONTEXT = 'laysite-mcp';
|
||||
public const PATH = '/mcp';
|
||||
|
||||
public static function read(): array
|
||||
{
|
||||
$row = self::stored(Database::connect());
|
||||
$migrationRequired = $row === false;
|
||||
$keyError = '';
|
||||
if (!is_array($row)) {
|
||||
$token = $migrationRequired ? null : self::legacyToken();
|
||||
|
||||
return ['enabled' => $token !== null, 'version' => 0, 'legacy' => $token !== null]
|
||||
+ compact('token', 'migrationRequired', 'keyError');
|
||||
}
|
||||
|
||||
$enabled = (bool) $row['enabled'];
|
||||
$token = null;
|
||||
if ($enabled && $row['encrypted_secret'] !== null) {
|
||||
try {
|
||||
$token = SiteSecrets::decrypt($row['encrypted_secret'], self::CONTEXT);
|
||||
} catch (SiteKeyFileError $error) {
|
||||
$keyError = $error->getMessage();
|
||||
} catch (RuntimeException) {
|
||||
// Keep the settings accessible so an administrator can replace an unreadable key.
|
||||
}
|
||||
}
|
||||
|
||||
return ['version' => (int) $row['version'], 'legacy' => false] + compact('enabled', 'token', 'migrationRequired', 'keyError');
|
||||
}
|
||||
|
||||
public static function save(bool $enabled, bool $rotate, int $version): void
|
||||
{
|
||||
if ($rotate && !$enabled) {
|
||||
throw new RuntimeException('启用 MCP 后才能生成新密钥。');
|
||||
}
|
||||
Database::write(static function (PDO $pdo) use ($enabled, $rotate, $version): void {
|
||||
$row = self::stored($pdo);
|
||||
if ($row === false) {
|
||||
throw new RuntimeException(Database::MIGRATION_REQUIRED);
|
||||
}
|
||||
if ($version !== (int) ($row['version'] ?? 0)) {
|
||||
throw new RuntimeException('MCP 设置已更新,请刷新后再保存。');
|
||||
}
|
||||
$encrypted = $row['encrypted_secret'] ?? null;
|
||||
$legacy = $row === null ? self::legacyToken() : null;
|
||||
if ($rotate || ($enabled && $encrypted === null && $legacy === null)) {
|
||||
$encrypted = SiteSecrets::encrypt(bin2hex(random_bytes(32)), self::CONTEXT);
|
||||
} elseif ($legacy !== null) {
|
||||
$encrypted = SiteSecrets::encrypt($legacy, self::CONTEXT);
|
||||
}
|
||||
$pdo->prepare('INSERT INTO mcp_settings (id, enabled, encrypted_secret, version) VALUES (1, ?, ?, 1)
|
||||
ON CONFLICT (id) DO UPDATE SET enabled = excluded.enabled, encrypted_secret = excluded.encrypted_secret,
|
||||
version = mcp_settings.version + 1')->execute([(int) $enabled, $encrypted]);
|
||||
});
|
||||
}
|
||||
|
||||
private static function stored(PDO $pdo): array|false|null
|
||||
{
|
||||
try {
|
||||
return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: null;
|
||||
} catch (PDOException $error) {
|
||||
if (($error->errorInfo[2] ?? '') === 'no such table: mcp_settings') {
|
||||
return false;
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
private static function legacyToken(): ?string
|
||||
{
|
||||
$value = Environment::get('LAYSITE_MCP_TOKEN');
|
||||
|
||||
return is_string($value) && strlen($value) >= 32 ? $value : null;
|
||||
}
|
||||
}
|
||||
+24
-2
@@ -15,6 +15,8 @@ use Webman\Http\UploadFile;
|
||||
final class Media
|
||||
{
|
||||
public const MAX_BYTES = 64 * 1024 * 1024;
|
||||
private const MAX_CODE_BYTES = 2 * 1024 * 1024;
|
||||
private const CODE_TYPES = ['css' => 'text/css', 'js' => 'text/javascript'];
|
||||
|
||||
private const EXTENSIONS = [
|
||||
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
|
||||
@@ -22,6 +24,7 @@ final class Media
|
||||
'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',
|
||||
'text/css' => 'css', 'text/javascript' => 'js',
|
||||
];
|
||||
|
||||
public static function all(bool $includeArchived = false): array
|
||||
@@ -42,7 +45,7 @@ final class Media
|
||||
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
|
||||
}
|
||||
$source = $file->getPathname();
|
||||
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
|
||||
$mime = self::mime($source, (string) $file->getUploadName(), $size);
|
||||
$extension = self::EXTENSIONS[$mime] ?? null;
|
||||
if ($extension === null) {
|
||||
throw new RuntimeException('文件类型不受支持。');
|
||||
@@ -105,7 +108,7 @@ final class Media
|
||||
|
||||
public static function validateBackup(string $path, string $name, string $mime, int $size): void
|
||||
{
|
||||
if ((new \finfo(FILEINFO_MIME_TYPE))->file($path) !== $mime
|
||||
if (self::mime($path, $name, $size) !== $mime
|
||||
|| !isset(self::EXTENSIONS[$mime]) || self::EXTENSIONS[$mime] !== pathinfo($name, PATHINFO_EXTENSION)) {
|
||||
throw new RuntimeException('备份资源类型与清单不一致。');
|
||||
}
|
||||
@@ -114,6 +117,25 @@ final class Media
|
||||
}
|
||||
}
|
||||
|
||||
private static function mime(string $path, string $name, int $size): string|false
|
||||
{
|
||||
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($path);
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
if (!isset(self::CODE_TYPES[$extension])) {
|
||||
return in_array($mime, self::CODE_TYPES, true) ? false : $mime;
|
||||
}
|
||||
if ($size > self::MAX_CODE_BYTES || !is_string($mime)
|
||||
|| (!str_starts_with($mime, 'text/') && !in_array($mime, ['application/javascript', 'application/json'], true))) {
|
||||
throw new RuntimeException('CSS 或 JavaScript 文件须为有效的 UTF-8 文本,且不超过 2 MB。');
|
||||
}
|
||||
$source = file_get_contents($path, length: self::MAX_CODE_BYTES + 1);
|
||||
if (!is_string($source) || strlen($source) !== $size || !mb_check_encoding($source, 'UTF-8') || str_contains($source, "\0")) {
|
||||
throw new RuntimeException('CSS 或 JavaScript 文件须为有效的 UTF-8 文本,且不超过 2 MB。');
|
||||
}
|
||||
|
||||
return self::CODE_TYPES[$extension];
|
||||
}
|
||||
|
||||
private static function safeSvg(string $source, int $size): string
|
||||
{
|
||||
if ($size > 512 * 1024) {
|
||||
|
||||
@@ -10,26 +10,16 @@ use RuntimeException;
|
||||
|
||||
final class OAuthCredentials
|
||||
{
|
||||
private const CIPHER = 'aes-256-gcm';
|
||||
private const KEY_BYTES = 32;
|
||||
private const NONCE_BYTES = 12;
|
||||
private const TAG_BYTES = 16;
|
||||
|
||||
public static function store(PDO $pdo, int $layout, string $secret): void
|
||||
{
|
||||
if ($secret === '' || strlen($secret) > 4096 || str_contains($secret, "\0")) {
|
||||
throw new DesignFieldError('provider_secret', '客户端密钥为空或格式无效。');
|
||||
}
|
||||
$revision = bin2hex(random_bytes(16));
|
||||
$nonce = random_bytes(self::NONCE_BYTES);
|
||||
$ciphertext = openssl_encrypt($secret, self::CIPHER, self::key(create: true), OPENSSL_RAW_DATA, $nonce,
|
||||
$tag, self::context($layout, $revision), self::TAG_BYTES);
|
||||
if ($ciphertext === false) {
|
||||
throw new RuntimeException('无法加密客户端密钥。');
|
||||
}
|
||||
$encrypted = SiteSecrets::encrypt($secret, self::context($layout, $revision));
|
||||
$pdo->prepare('INSERT INTO layout_oauth_credentials (layout_id, revision, encrypted_secret) VALUES (?, ?, ?)
|
||||
ON CONFLICT (layout_id) DO UPDATE SET revision = excluded.revision, encrypted_secret = excluded.encrypted_secret')
|
||||
->execute([$layout, $revision, base64_encode($nonce . $tag . $ciphertext)]);
|
||||
->execute([$layout, $revision, $encrypted]);
|
||||
}
|
||||
|
||||
public static function read(int $layout, string $revision): string
|
||||
@@ -37,18 +27,11 @@ final class OAuthCredentials
|
||||
$query = Database::connect()->prepare('SELECT encrypted_secret FROM layout_oauth_credentials WHERE layout_id = ? AND revision = ?');
|
||||
$query->execute([$layout, $revision]);
|
||||
$value = $query->fetchColumn();
|
||||
$encrypted = is_string($value) ? base64_decode($value, true) : false;
|
||||
if ($encrypted === false || strlen($encrypted) <= self::NONCE_BYTES + self::TAG_BYTES) {
|
||||
if (!is_string($value)) {
|
||||
throw new RuntimeException('客户端密钥尚未配置或已更新。');
|
||||
}
|
||||
$secret = openssl_decrypt(substr($encrypted, self::NONCE_BYTES + self::TAG_BYTES), self::CIPHER, self::key(),
|
||||
OPENSSL_RAW_DATA, substr($encrypted, 0, self::NONCE_BYTES), substr($encrypted, self::NONCE_BYTES, self::TAG_BYTES),
|
||||
self::context($layout, $revision));
|
||||
if ($secret === false) {
|
||||
throw new RuntimeException('无法解密客户端密钥。');
|
||||
}
|
||||
|
||||
return $secret;
|
||||
return SiteSecrets::decrypt($value, self::context($layout, $revision));
|
||||
}
|
||||
|
||||
public static function migrateLegacy(PDO $pdo): void
|
||||
@@ -76,41 +59,4 @@ final class OAuthCredentials
|
||||
{
|
||||
return 'laysite-oauth:' . $layout . ':' . $revision;
|
||||
}
|
||||
|
||||
private static function key(bool $create = false): string
|
||||
{
|
||||
$path = Database::path() . '.key';
|
||||
if (is_link($path)) {
|
||||
throw new RuntimeException('密钥文件不能使用符号链接。');
|
||||
}
|
||||
$mask = umask(0077);
|
||||
try {
|
||||
$file = is_file($path) || $create ? @fopen($path, $create ? 'c+b' : 'rb') : false;
|
||||
} finally {
|
||||
umask($mask);
|
||||
}
|
||||
if ($file === false) {
|
||||
throw new RuntimeException('无法打开站点密钥文件。');
|
||||
}
|
||||
try {
|
||||
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
|
||||
throw new RuntimeException('站点密钥文件需能上锁,并且只能由运行用户访问。');
|
||||
}
|
||||
$key = stream_get_contents($file, self::KEY_BYTES + 1);
|
||||
if ($create && $key === '') {
|
||||
$key = random_bytes(self::KEY_BYTES);
|
||||
if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) {
|
||||
ftruncate($file, 0);
|
||||
throw new RuntimeException('无法写入站点密钥文件。');
|
||||
}
|
||||
}
|
||||
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
|
||||
throw new RuntimeException('站点密钥文件格式无效。');
|
||||
}
|
||||
|
||||
return $key;
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use RuntimeException;
|
||||
|
||||
final class PageDraft
|
||||
{
|
||||
public const RESERVED = ['.', '.laysite', 'admin', 'assets', 'home', 'account', 'mcp', 'palette'];
|
||||
public const RESERVED = ['.', '.laysite', 'admin', 'assets', 'account', 'mcp', 'palette'];
|
||||
|
||||
public static function slug(mixed $value, array $reserved = self::RESERVED, bool $includeSpecial = false): string
|
||||
{
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use RuntimeException;
|
||||
|
||||
final class PageHead
|
||||
{
|
||||
public const MAX_LENGTH = 32768;
|
||||
private const ATTRIBUTES = [
|
||||
'meta' => ['name', 'property', 'content'],
|
||||
'link' => ['rel', 'href', 'media', 'integrity', 'crossorigin', 'referrerpolicy'],
|
||||
'style' => ['media'],
|
||||
'script' => ['src', 'type', 'async', 'defer', 'integrity', 'crossorigin', 'referrerpolicy'],
|
||||
];
|
||||
|
||||
public static function normalize(mixed $value): string
|
||||
{
|
||||
if (!is_string($value) || strlen($value) > self::MAX_LENGTH || !mb_check_encoding($value, 'UTF-8') || str_contains($value, "\0")) {
|
||||
throw new RuntimeException('Head 代码须使用 UTF-8,最多 32 KB。');
|
||||
}
|
||||
$value = trim($value);
|
||||
self::parse($value);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function render(array $sources, string $nonce, bool $canvas): array
|
||||
{
|
||||
$result = ['markup' => '', 'styles' => [], 'scripts' => [], 'inlineScript' => false, 'hasScript' => false];
|
||||
foreach ($sources as $source) {
|
||||
foreach (self::parse($source) as [$tag, $attributes, $text, $origin]) {
|
||||
if ($canvas && $tag === 'script') {
|
||||
continue;
|
||||
}
|
||||
if ($tag === 'script') {
|
||||
if (strtolower($attributes['type'] ?? '') !== 'application/ld+json') {
|
||||
$result['hasScript'] = true;
|
||||
}
|
||||
if (!isset($attributes['src'])) {
|
||||
$result['inlineScript'] = true;
|
||||
$attributes['nonce'] = $nonce;
|
||||
} elseif ($origin !== null) {
|
||||
$result['scripts'][$origin] = true;
|
||||
}
|
||||
}
|
||||
if ($tag === 'style') {
|
||||
$attributes['nonce'] = $nonce;
|
||||
} elseif ($tag === 'link' && $origin !== null) {
|
||||
$result['styles'][$origin] = true;
|
||||
}
|
||||
$markup = '<' . $tag;
|
||||
foreach ($attributes as $name => $value) {
|
||||
$markup .= " $name" . (in_array($name, ['async', 'defer'], true) ? '' : '="' . View::escape($value) . '"');
|
||||
}
|
||||
$result['markup'] .= $markup . '>' . ($text === null ? '' : $text . '</' . $tag . '>') . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function parse(string $source): array
|
||||
{
|
||||
if ($source === '') {
|
||||
return [];
|
||||
}
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$document->loadHTML('<!doctype html><html><head><meta charset="utf-8">' . $source . '</head><body></body></html>',
|
||||
LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
|
||||
$head = $document->getElementsByTagName('head')->item(0);
|
||||
$body = $document->getElementsByTagName('body')->item(0);
|
||||
if ($head === null || ($body !== null && ($body->childElementCount > 0 || trim($body->textContent) !== ''))) {
|
||||
throw new RuntimeException('Head 中只能填写文档头部的标签。');
|
||||
}
|
||||
|
||||
$entries = [];
|
||||
$origins = [];
|
||||
foreach ($head->childNodes as $node) {
|
||||
if ($node === $head->firstChild || $node->nodeType === XML_COMMENT_NODE
|
||||
|| ($node->nodeType === XML_TEXT_NODE && trim($node->textContent) === '')) {
|
||||
continue;
|
||||
}
|
||||
if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName])) {
|
||||
throw new RuntimeException('Head 仅支持 meta、样式表(link)、style 和 script 标签。');
|
||||
}
|
||||
if (count($entries) >= 40) {
|
||||
throw new RuntimeException('Head 最多允许 40 个标签。');
|
||||
}
|
||||
$tag = $node->tagName;
|
||||
$attributes = [];
|
||||
foreach ($node->attributes as $attribute) {
|
||||
if (!in_array($attribute->name, self::ATTRIBUTES[$tag], true)) {
|
||||
throw new RuntimeException('Head 标签包含不支持的属性:' . $attribute->name . '。');
|
||||
}
|
||||
$attributes[$attribute->name] = $attribute->value;
|
||||
}
|
||||
$text = in_array($tag, ['script', 'style'], true) ? $node->textContent : null;
|
||||
if ($text !== null && preg_match('~<(?:!--|/?\s*(?:script|style)\b)~i', $text)) {
|
||||
throw new RuntimeException('内联代码含有可能中断 HTML 解析的标记,请将代码放到独立文件中。');
|
||||
}
|
||||
$origin = null;
|
||||
if ($tag === 'meta' && ((!isset($attributes['name']) && !isset($attributes['property'])) || !isset($attributes['content']))) {
|
||||
throw new RuntimeException('meta 标签须填写 name 或 property,以及 content。');
|
||||
}
|
||||
if ($tag === 'link') {
|
||||
if (strtolower($attributes['rel'] ?? '') !== 'stylesheet') {
|
||||
throw new RuntimeException('Head 中的 link 标签仅用于加载样式表。');
|
||||
}
|
||||
$origin = self::origin($attributes['href'] ?? '');
|
||||
} elseif ($tag === 'script') {
|
||||
if (!in_array(strtolower($attributes['type'] ?? ''), ['', 'text/javascript', 'module', 'application/ld+json'], true)) {
|
||||
throw new RuntimeException('script 类型须为 JavaScript、module 或 application/ld+json。');
|
||||
}
|
||||
if (isset($attributes['src'])) {
|
||||
if (trim($text) !== '') {
|
||||
throw new RuntimeException('有 src 的 script 标签应留空内容。');
|
||||
}
|
||||
$origin = self::origin($attributes['src']);
|
||||
}
|
||||
}
|
||||
if ($origin !== null) {
|
||||
$origins[$origin] = true;
|
||||
if (count($origins) > 8) {
|
||||
throw new RuntimeException('一处 Head 设置最多可以引用 8 个 HTTPS 来源。');
|
||||
}
|
||||
}
|
||||
$entries[] = [$tag, $attributes, $text, $origin];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
private static function origin(string $url): ?string
|
||||
{
|
||||
if (strlen($url) <= 2048 && Html::url($url, true)) {
|
||||
if (str_starts_with($url, '/')) {
|
||||
return null;
|
||||
}
|
||||
$parts = parse_url($url);
|
||||
if (filter_var($url, FILTER_VALIDATE_URL) && isset($parts['host']) && !isset($parts['user']) && !isset($parts['pass'])
|
||||
&& preg_match('/^[a-z0-9.-]+$/iD', $parts['host'])) {
|
||||
return 'https://' . strtolower($parts['host']) . (isset($parts['port']) ? ':' . $parts['port'] : '');
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException('样式表和脚本地址须使用以 / 开头的站内路径或完整 HTTPS 网址。');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class PageTemplates
|
||||
{
|
||||
public static function groups(): array
|
||||
@@ -13,6 +15,23 @@ final class PageTemplates
|
||||
return $groups ??= require dirname(__DIR__, 2) . '/resources/page-templates.php';
|
||||
}
|
||||
|
||||
public static function palette(string $theme): array
|
||||
{
|
||||
static $css;
|
||||
$css ??= file_get_contents(dirname(__DIR__, 2) . '/public/assets/page-themes.css');
|
||||
// The opening rule for each theme is the same palette used in the live template preview.
|
||||
if ($css === false || !preg_match('/^\.theme-' . preg_quote($theme, '/') . '\s*\{([^{}]*)\}/m', $css, $rule)) {
|
||||
throw new RuntimeException('找不到整页模板的配色。');
|
||||
}
|
||||
preg_match_all('/--([a-z-]+):\s*(#[a-f0-9]{6})\s*;/i', $rule[1], $matches);
|
||||
$colors = array_intersect_key(array_combine($matches[1], $matches[2]), DesignLibrary::COLORS);
|
||||
if (count($colors) !== count(DesignLibrary::COLORS)) {
|
||||
throw new RuntimeException('整页模板的配色不完整。');
|
||||
}
|
||||
|
||||
return $colors;
|
||||
}
|
||||
|
||||
public static function find(string $key): ?array
|
||||
{
|
||||
foreach (self::groups() as $theme => $group) {
|
||||
|
||||
+138
-22
@@ -30,15 +30,32 @@ final class Repository
|
||||
|
||||
public function pages(bool $publishedOnly = false): array
|
||||
{
|
||||
$where = $publishedOnly ? " WHERE pages.status = 'published' AND pages.layout_id IS NULL AND pages.page_type = 'page'" : '';
|
||||
$where = $publishedOnly ? " WHERE pages.status = 'published' AND pages.layout_id IS NULL AND pages.page_type IN ('page', 'home')" : '';
|
||||
|
||||
return $this->pdo->query('SELECT pages.slug, pages.name, pages.title, pages.updated_at, pages.status, pages.version, pages.page_type, d.kind AS layout_kind
|
||||
return $this->pdo->query('SELECT pages.slug, pages.name, pages.title, pages.updated_at, pages.status, pages.version, pages.page_type, pages.layout_id, 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 homepage(): ?array
|
||||
{
|
||||
$result = $this->one("SELECT slug FROM pages WHERE page_type = 'home'
|
||||
AND layout_id IS NULL AND status = 'published' ORDER BY RANDOM() LIMIT 1", []);
|
||||
|
||||
return $result ? $this->page($result['slug']) : null;
|
||||
}
|
||||
|
||||
public function createPage(string $slug, string $name, array $template = [], string $type = 'page'): void
|
||||
{
|
||||
Database::write(static fn (PDO $pdo) => self::insertPage($pdo, $slug, $name, $template, type: $type));
|
||||
Database::write(static function (PDO $pdo) use ($slug, $name, $template, $type): void {
|
||||
if (($template['palette_id'] ?? null) === null && ($template['theme'] ?? '') !== '') {
|
||||
$suffix = ' · 模板配色';
|
||||
$paletteName = mb_substr($name, 0, 100 - mb_strlen($suffix)) . $suffix;
|
||||
$template['palette_id'] = DesignLibrary::saveIn($pdo, 'palette', null, $paletteName, 'custom',
|
||||
PageTemplates::palette($template['theme']), 0, false);
|
||||
}
|
||||
$layout = in_array($type, ['header', 'footer'], true) ? LayoutPage::insertPreset($pdo, $type, $name) : null;
|
||||
self::insertPage($pdo, $slug, $name, $template, $layout, $layout === null ? $type : 'page');
|
||||
});
|
||||
}
|
||||
|
||||
public static function insertPage(PDO $pdo, string $slug, string $name, array $template = [], ?int $layoutId = null, string $type = 'page'): void
|
||||
@@ -98,7 +115,7 @@ final class Repository
|
||||
$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['page_type'] ?? 'page') === 'page' && $page['status'] === 'published' ? $archivePath : null;
|
||||
$section['archivePath'] = $feed['categories'] && empty($page['layout_kind']) && in_array($page['page_type'] ?? 'page', ['page', 'home'], true) && $page['status'] === 'published' ? $archivePath : null;
|
||||
$section['articleFeed'] = [];
|
||||
$section['networkFeed'] = $network;
|
||||
$section['catalogFeed'] = $catalog;
|
||||
@@ -125,25 +142,53 @@ 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 pages.layout_id IS NULL AND pages.page_type = 'page'
|
||||
WHERE pages.slug = ? AND pages.status = 'published' AND pages.layout_id IS NULL AND pages.page_type IN ('page', 'home')
|
||||
AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
|
||||
}
|
||||
|
||||
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
|
||||
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): array
|
||||
{
|
||||
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 = ?, presentation = COALESCE(?, presentation), version = version + 1 WHERE slug = ? AND version = ?');
|
||||
return Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): array {
|
||||
$existing = $this->one('SELECT pages.version, pages.page_type, pages.layout_id, pages.header_id, pages.footer_id, d.kind AS layout_kind
|
||||
FROM pages LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]);
|
||||
if ($existing !== null && $existing['version'] !== $version) {
|
||||
$this->checkRemovedPageLayouts($existing, $data['originalLayoutIds'] ?? []);
|
||||
}
|
||||
self::checkVersion($existing !== null && $existing['version'] === $version ? 1 : 0);
|
||||
$target = $data['slug'] ?? $slug;
|
||||
if ($target !== $slug && $this->one('SELECT 1 FROM pages WHERE slug = ?', [$target])) {
|
||||
throw new RuntimeException('此页面地址已存在。');
|
||||
}
|
||||
$previousType = $existing['layout_kind'] ?? $existing['page_type'];
|
||||
$type = $data['type'] ?? $previousType;
|
||||
$layout = $existing['layout_id'];
|
||||
if ($type !== $previousType) {
|
||||
$layout = in_array($type, ['header', 'footer'], true) ? LayoutPage::insertPreset($pdo, $type, $data['name']) : null;
|
||||
}
|
||||
$head = $data['head_html'] ?? null;
|
||||
$query = $pdo->prepare('UPDATE pages SET slug = ?, page_type = ?, layout_id = ?, name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
|
||||
image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?,
|
||||
presentation = COALESCE(?, presentation), ' . ($head === null ? '' : 'head_html = ?, ')
|
||||
. 'version = version + 1 WHERE slug = ? AND version = ?');
|
||||
$query->execute([
|
||||
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
|
||||
$target, $layout === null ? $type : 'page', $layout, $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(),
|
||||
isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null, $slug, $version,
|
||||
isset($data['presentation']) ? CanvasStyle::encode($data['presentation']) : null,
|
||||
...($head === null ? [] : [$head]), $slug, $version,
|
||||
]);
|
||||
self::checkVersion($query->rowCount());
|
||||
if ($data['status'] === 'draft' && str_starts_with($slug, 'system--')) {
|
||||
SiteDesign::unsetSystemPage($pdo, $slug);
|
||||
if (isset(SystemPage::TYPES[$previousType])) {
|
||||
if ($data['status'] === 'draft' || $previousType !== $type) {
|
||||
SiteDesign::replaceSystemPage($pdo, $slug);
|
||||
} elseif ($target !== $slug) {
|
||||
SiteDesign::replaceSystemPage($pdo, $slug, replacement: $target);
|
||||
}
|
||||
}
|
||||
if ($existing['layout_id'] !== null && $layout !== $existing['layout_id']) {
|
||||
LayoutPage::deletePreset($pdo, $existing['layout_kind'], $existing['layout_id']);
|
||||
}
|
||||
$slug = $target;
|
||||
if ($replaceDraftSections) {
|
||||
$pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]);
|
||||
}
|
||||
@@ -159,9 +204,43 @@ final class Repository
|
||||
if ($sectionOrder !== null) {
|
||||
self::writeSectionOrder($pdo, $slug, $sectionOrder);
|
||||
}
|
||||
if (isset($data['layoutConfig'])) {
|
||||
LayoutPage::saveSettings($pdo, $this->page($slug), $data['layoutConfig']);
|
||||
$page = $this->page($slug);
|
||||
if ($type === $previousType && $layout !== null && isset($data['layoutConfig'])) {
|
||||
LayoutPage::saveSettings($pdo, $page, $data['layoutConfig']);
|
||||
}
|
||||
|
||||
return $page;
|
||||
});
|
||||
}
|
||||
|
||||
private function checkRemovedPageLayouts(array $page, array $originalIds): void
|
||||
{
|
||||
foreach (['header' => '页头', 'footer' => '页脚'] as $kind => $label) {
|
||||
$id = $originalIds[$kind] ?? 0;
|
||||
if ($id > 0 && $page[$kind . '_id'] === null
|
||||
&& !$this->one('SELECT 1 FROM design_presets WHERE id = ? AND kind = ?', [$id, $kind])) {
|
||||
throw new RuntimeException('此页面引用的' . $label . '已被移除。请保留修改,重新打开编辑器后再保存。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function deletePage(string $slug, int $version): bool
|
||||
{
|
||||
return Database::write(function (PDO $pdo) use ($slug, $version): bool {
|
||||
$page = $this->one('SELECT pages.layout_id, d.kind AS layout_kind FROM pages
|
||||
LEFT JOIN design_presets d ON pages.layout_id = d.id WHERE pages.slug = ?', [$slug]);
|
||||
if ($page === null) {
|
||||
return false;
|
||||
}
|
||||
$delete = $pdo->prepare('DELETE FROM pages WHERE slug = ? AND version = ?');
|
||||
$delete->execute([$slug, $version]);
|
||||
self::checkVersion($delete->rowCount());
|
||||
if ($page['layout_id'] !== null) {
|
||||
LayoutPage::deletePreset($pdo, $page['layout_kind'], $page['layout_id']);
|
||||
}
|
||||
SiteDesign::replaceSystemPage($pdo, $slug);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -169,7 +248,7 @@ final class Repository
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
|
||||
self::updateSection($pdo, $page, $key, $data, $version);
|
||||
self::touchPage($pdo, $page);
|
||||
self::touchPage($pdo, $page, bumpVersion: false);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -185,7 +264,7 @@ final class Repository
|
||||
{
|
||||
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);
|
||||
self::touchPage($pdo, $page);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -193,7 +272,14 @@ final class Repository
|
||||
{
|
||||
$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]);
|
||||
$feed = $data['feed'] ?? null;
|
||||
if ($feed !== null) {
|
||||
$config = json_decode($feed, true, flags: JSON_THROW_ON_ERROR);
|
||||
$available = $pdo->query('SELECT slug FROM article_categories')->fetchAll(PDO::FETCH_COLUMN);
|
||||
$config['categories'] = array_values(array_intersect($config['categories'], $available));
|
||||
$feed = Database::json($config);
|
||||
}
|
||||
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $feed, $data['alignments'] ?? '{}', $data['presentation'] ?? '{}', $page]);
|
||||
if ($query->rowCount() !== 1) {
|
||||
throw new RuntimeException('此区块锚点已被使用。');
|
||||
}
|
||||
@@ -229,7 +315,7 @@ final class Repository
|
||||
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
|
||||
if ($operation === 'delete') {
|
||||
self::deleteSection($pdo, $page, $key, $version);
|
||||
self::touchPage($pdo, $page, structureChanged: true);
|
||||
self::touchPage($pdo, $page);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -248,7 +334,7 @@ final class Repository
|
||||
}
|
||||
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
|
||||
self::writeSectionOrder($pdo, $page, $keys);
|
||||
self::touchPage($pdo, $page, structureChanged: true);
|
||||
self::touchPage($pdo, $page);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -266,9 +352,9 @@ final class Repository
|
||||
}
|
||||
}
|
||||
|
||||
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
|
||||
private static function touchPage(PDO $pdo, string $slug, bool $bumpVersion = true): void
|
||||
{
|
||||
$revision = $structureChanged ? ', version = version + 1' : '';
|
||||
$revision = $bumpVersion ? ', version = version + 1' : '';
|
||||
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
|
||||
}
|
||||
|
||||
@@ -286,6 +372,36 @@ final class Repository
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteCategory(string $slug): bool
|
||||
{
|
||||
return Database::write(function (PDO $pdo) use ($slug): bool {
|
||||
if ($this->one('SELECT 1 FROM article_categories WHERE slug = ?', [$slug]) === null) {
|
||||
return false;
|
||||
}
|
||||
$pdo->prepare('UPDATE articles SET version = version + 1 WHERE id IN
|
||||
(SELECT article_id FROM article_category_links WHERE category_slug = ?)')->execute([$slug]);
|
||||
$pdo->prepare('DELETE FROM article_category_links WHERE category_slug = ?')->execute([$slug]);
|
||||
$pdo->prepare('DELETE FROM article_categories WHERE slug = ?')->execute([$slug]);
|
||||
|
||||
$sections = $pdo->prepare("SELECT page_slug, key, feed FROM sections WHERE EXISTS
|
||||
(SELECT 1 FROM json_each(sections.feed, '$.categories') WHERE value = ?)");
|
||||
$sections->execute([$slug]);
|
||||
$update = $pdo->prepare('UPDATE sections SET feed = ?, version = version + 1 WHERE page_slug = ? AND key = ?');
|
||||
$affected = [];
|
||||
foreach ($sections->fetchAll() as $section) {
|
||||
$feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
|
||||
$feed['categories'] = array_values(array_diff($feed['categories'], [$slug]));
|
||||
$update->execute([Database::json($feed), $section['page_slug'], $section['key']]);
|
||||
$affected[$section['page_slug']] = true;
|
||||
}
|
||||
foreach (array_keys($affected) as $page) {
|
||||
self::touchPage($pdo, $page);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
|
||||
int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
|
||||
{
|
||||
|
||||
+26
-15
@@ -12,7 +12,7 @@ use Throwable;
|
||||
final class SiteBackup
|
||||
{
|
||||
private const FORMAT = 'laysite-site';
|
||||
private const VERSION = 4;
|
||||
private const VERSION = 6;
|
||||
private const TABLES = [
|
||||
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
|
||||
'article_category_links', 'article_redirects', 'article_deletions', 'media',
|
||||
@@ -111,6 +111,7 @@ final class SiteBackup
|
||||
}
|
||||
Database::write(function (PDO $pdo) use ($tables, $staged, $directory, &$installed): void {
|
||||
self::replaceTables($pdo, $tables);
|
||||
DesignLibrary::ensureDefaultPalette($pdo);
|
||||
foreach ($staged as $name => $source) {
|
||||
$target = $directory . '/' . $name;
|
||||
if (is_file($target) && !is_link($target) && hash_file('sha256', $target) === hash_file('sha256', $source)) {
|
||||
@@ -140,7 +141,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, 2, 3, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
|
||||
|| !in_array($manifest['version'] ?? null, [1, 2, 3, 4, 5, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
|
||||
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
|
||||
}
|
||||
$tables = $manifest['tables'];
|
||||
@@ -157,8 +158,8 @@ final class SiteBackup
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
|
||||
throw new RuntimeException('备份缺少站点身份或首页。');
|
||||
if (count($tables['site_settings']) !== 1) {
|
||||
throw new RuntimeException('备份缺少站点身份。');
|
||||
}
|
||||
$designs = [];
|
||||
foreach ($tables['design_presets'] as &$row) {
|
||||
@@ -172,6 +173,11 @@ final class SiteBackup
|
||||
throw new RuntimeException('备份的站点名称无效。');
|
||||
}
|
||||
$site = ['name' => $settings['name'], 'cdn' => ['origin' => Assets::cdn($settings['cdn']['origin'] ?? '')], 'revisions' => ['general' => time()]];
|
||||
$site['head_html'] = PageHead::normalize($settings['head_html'] ?? '');
|
||||
$site['favicon'] = SiteIcon::normalize($settings['favicon'] ?? '');
|
||||
if (array_key_exists('palette_id', $settings)) {
|
||||
$site['palette_id'] = self::selection($designs, 'palette', $settings['palette_id']);
|
||||
}
|
||||
$layoutDefaults = $settings['layout_defaults'] ?? [];
|
||||
if (!is_array($layoutDefaults)) {
|
||||
throw new RuntimeException('备份的基础页头页脚配置无效。');
|
||||
@@ -188,21 +194,25 @@ final class SiteBackup
|
||||
foreach ($tables['pages'] as &$row) {
|
||||
$layout = $row['layout_id'] ?? null;
|
||||
$row['page_type'] ??= 'page';
|
||||
if ($row['page_type'] !== 'page') {
|
||||
if ($layout !== null || !is_string($row['page_type']) || !SystemPage::slugMatches($row['page_type'], $row['slug'] ?? null)) {
|
||||
throw new RuntimeException('备份包含无效的系统页面。');
|
||||
}
|
||||
if (($row['status'] ?? null) === 'published') {
|
||||
$publishedSystemPages[$row['slug']] = $row['page_type'];
|
||||
}
|
||||
} elseif ($layout === null) {
|
||||
PageDraft::slug($row['slug'] ?? null, array_diff(PageDraft::RESERVED, ['home']));
|
||||
} else {
|
||||
PageDraft::slug($row['slug'] ?? null, includeSpecial: true);
|
||||
if ($manifest['version'] < 6 && $layout === null && $row['slug'] === 'home' && $row['page_type'] === 'page') {
|
||||
$row['page_type'] = 'home';
|
||||
}
|
||||
if (!is_string($row['page_type'])) {
|
||||
throw new RuntimeException('备份包含无效的页面类型。');
|
||||
}
|
||||
if ($layout !== null) {
|
||||
$kind = is_int($layout) ? ($designs[$layout] ?? null) : null;
|
||||
if (!in_array($kind, ['header', 'footer'], true) || ($row['slug'] ?? null) !== LayoutPage::slug($kind, $layout)) {
|
||||
if (!in_array($kind, ['header', 'footer'], true) || $row['page_type'] !== 'page') {
|
||||
throw new RuntimeException('备份包含无效的页头或页脚页面。');
|
||||
}
|
||||
$row['status'] = 'published';
|
||||
} elseif (isset(SystemPage::TYPES[$row['page_type']])) {
|
||||
if (($row['status'] ?? null) === 'published') {
|
||||
$publishedSystemPages[$row['slug']] = $row['page_type'];
|
||||
}
|
||||
} elseif (!in_array($row['page_type'], ['page', 'home'], true)) {
|
||||
throw new RuntimeException('备份包含无效的页面类型。');
|
||||
}
|
||||
self::validateAssetUrl($row['image'] ?? '', true);
|
||||
$row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
|
||||
@@ -210,6 +220,7 @@ final class SiteBackup
|
||||
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
|
||||
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
|
||||
$row['presentation'] = CanvasStyle::encode(CanvasStyle::normalize(self::decode($row['presentation'] ?? '{}'), CanvasStyle::PAGE));
|
||||
$row['head_html'] = $layout === null ? PageHead::normalize($row['head_html'] ?? '') : '';
|
||||
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
|
||||
$row['theme'] = '';
|
||||
}
|
||||
|
||||
@@ -31,9 +31,10 @@ final class SiteDesign
|
||||
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, array $systemPages, bool $maintenance): void
|
||||
public static function saveGeneral(string $name, string $origin, int $version, array $systemPages, bool $maintenance,
|
||||
?string $head = null, ?string $icon = null, mixed $palette = null): void
|
||||
{
|
||||
Database::write(function (PDO $pdo) use ($name, $origin, $version, $systemPages, $maintenance): void {
|
||||
Database::write(function (PDO $pdo) use ($name, $origin, $version, $systemPages, $maintenance, $head, $icon, $palette): 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('站点设置已更新,请重新打开后再保存。');
|
||||
@@ -47,25 +48,38 @@ final class SiteDesign
|
||||
if ($maintenance && !isset($systemPages['maintenance'])) {
|
||||
throw new RuntimeException('请先发布并选择维护页,再开启维护模式。');
|
||||
}
|
||||
if ($palette !== null) {
|
||||
$site['palette_id'] = DesignLibrary::selection('palette', $palette);
|
||||
}
|
||||
$site['name'] = $name;
|
||||
$site['cdn'] = ['origin' => $origin];
|
||||
$site['system_pages'] = $systemPages;
|
||||
$site['maintenance_enabled'] = $maintenance;
|
||||
if ($head !== null) {
|
||||
$site['head_html'] = $head;
|
||||
}
|
||||
if ($icon !== null) {
|
||||
$site['favicon'] = $icon;
|
||||
}
|
||||
$site['revisions']['general'] = $version + 1;
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
});
|
||||
}
|
||||
|
||||
public static function unsetSystemPage(PDO $pdo, string $slug): void
|
||||
public static function replaceSystemPage(PDO $pdo, string $slug, ?string $replacement = null): void
|
||||
{
|
||||
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
|
||||
$type = array_search($slug, $site['system_pages'] ?? [], true);
|
||||
if ($type === false) {
|
||||
return;
|
||||
}
|
||||
unset($site['system_pages'][$type]);
|
||||
if ($type === 'maintenance') {
|
||||
$site['maintenance_enabled'] = false;
|
||||
if ($replacement !== null) {
|
||||
$site['system_pages'][$type] = $replacement;
|
||||
} else {
|
||||
unset($site['system_pages'][$type]);
|
||||
if ($type === 'maintenance') {
|
||||
$site['maintenance_enabled'] = false;
|
||||
}
|
||||
}
|
||||
$site['revisions']['general'] = ($site['revisions']['general'] ?? 0) + 1;
|
||||
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use RuntimeException;
|
||||
use support\Response;
|
||||
|
||||
final class SiteIcon
|
||||
{
|
||||
public const SIZE = 64;
|
||||
public const PATH = '/.laysite/favicon.png';
|
||||
|
||||
public static function normalize(mixed $value): string
|
||||
{
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
$bytes = is_string($value) && strlen($value) <= 44000 ? base64_decode($value, true) : false;
|
||||
$size = $bytes === false || $bytes === '' ? false : @getimagesizefromstring($bytes);
|
||||
if (!$size || $size[2] !== IMAGETYPE_PNG || $size[0] !== self::SIZE || $size[1] !== self::SIZE) {
|
||||
throw new RuntimeException('请裁剪并生成一个 64 × 64 的 PNG 图标。');
|
||||
}
|
||||
|
||||
return base64_encode($bytes);
|
||||
}
|
||||
|
||||
public static function url(string $icon): string
|
||||
{
|
||||
return $icon === '' ? Assets::DEFAULT_ICON : self::PATH . '?v=' . substr(hash('sha256', $icon), 0, 16);
|
||||
}
|
||||
|
||||
public static function response(string $icon, bool $ico): Response
|
||||
{
|
||||
if ($icon === '') {
|
||||
return View::redirect(Assets::DEFAULT_ICON, 301);
|
||||
}
|
||||
$bytes = base64_decode($icon, true);
|
||||
if ($bytes === false) {
|
||||
return View::redirect(Assets::DEFAULT_ICON, 302);
|
||||
}
|
||||
if ($ico) {
|
||||
$bytes = pack('vvvCCCCvvVV', 0, 1, 1, self::SIZE, self::SIZE, 0, 0, 1, 32, strlen($bytes), 22) . $bytes;
|
||||
}
|
||||
|
||||
return new Response(200, [
|
||||
'Content-Type' => $ico ? 'image/x-icon' : 'image/png',
|
||||
'Cache-Control' => 'public, max-age=300',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
], $bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
final class SiteKeyFileError extends \RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
final class SiteSecrets
|
||||
{
|
||||
private const CIPHER = 'aes-256-gcm';
|
||||
private const KEY_BYTES = 32;
|
||||
private const NONCE_BYTES = 12;
|
||||
private const TAG_BYTES = 16;
|
||||
|
||||
public static function encrypt(string $secret, string $context): string
|
||||
{
|
||||
$nonce = random_bytes(self::NONCE_BYTES);
|
||||
$ciphertext = openssl_encrypt($secret, self::CIPHER, self::key(create: true), OPENSSL_RAW_DATA, $nonce,
|
||||
$tag, $context, self::TAG_BYTES);
|
||||
if ($ciphertext === false) {
|
||||
throw new RuntimeException('无法加密站点密钥。');
|
||||
}
|
||||
|
||||
return base64_encode($nonce . $tag . $ciphertext);
|
||||
}
|
||||
|
||||
public static function decrypt(string $value, string $context): string
|
||||
{
|
||||
$encrypted = base64_decode($value, true);
|
||||
if ($encrypted === false || strlen($encrypted) <= self::NONCE_BYTES + self::TAG_BYTES) {
|
||||
throw new RuntimeException('站点密钥格式无效。');
|
||||
}
|
||||
$secret = openssl_decrypt(substr($encrypted, self::NONCE_BYTES + self::TAG_BYTES), self::CIPHER, self::key(),
|
||||
OPENSSL_RAW_DATA, substr($encrypted, 0, self::NONCE_BYTES), substr($encrypted, self::NONCE_BYTES, self::TAG_BYTES),
|
||||
$context);
|
||||
if ($secret === false) {
|
||||
throw new RuntimeException('无法解密站点密钥。');
|
||||
}
|
||||
|
||||
return $secret;
|
||||
}
|
||||
|
||||
private static function key(bool $create = false): string
|
||||
{
|
||||
$path = Database::path() . '.key';
|
||||
clearstatcache(true, $path);
|
||||
if (is_link($path)) {
|
||||
throw new SiteKeyFileError('密钥文件不能使用符号链接。');
|
||||
}
|
||||
if (!$create && !file_exists($path)) {
|
||||
throw new RuntimeException('站点密钥文件缺失。');
|
||||
}
|
||||
$mask = umask(0077);
|
||||
try {
|
||||
$file = is_file($path) || $create ? @fopen($path, $create ? 'c+b' : 'rb') : false;
|
||||
} finally {
|
||||
umask($mask);
|
||||
}
|
||||
if ($file === false) {
|
||||
throw new SiteKeyFileError('无法打开站点密钥文件。');
|
||||
}
|
||||
try {
|
||||
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
|
||||
throw new SiteKeyFileError('站点密钥文件需能上锁,并且只能由运行用户访问。');
|
||||
}
|
||||
$key = stream_get_contents($file, self::KEY_BYTES + 1);
|
||||
if ($create && $key === '') {
|
||||
$key = random_bytes(self::KEY_BYTES);
|
||||
if (fwrite($file, $key) !== self::KEY_BYTES || !fflush($file)) {
|
||||
ftruncate($file, 0);
|
||||
throw new SiteKeyFileError('无法写入站点密钥文件。');
|
||||
}
|
||||
}
|
||||
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
|
||||
throw new SiteKeyFileError('站点密钥文件格式无效。');
|
||||
}
|
||||
|
||||
return $key;
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ final class SystemPage
|
||||
|
||||
public static function published(Repository $repo, string $type, mixed $slug): ?array
|
||||
{
|
||||
if (!self::slugMatches($type, $slug)) {
|
||||
if (!isset(self::TYPES[$type]) || !is_string($slug) || $slug === '') {
|
||||
return null;
|
||||
}
|
||||
$page = $repo->page($slug);
|
||||
|
||||
+21
-6
@@ -44,18 +44,32 @@ final class View
|
||||
$markup = self::fragment('page', [
|
||||
'page' => $repo->withSectionFeeds($region), 'site' => $data['site'], 'canvas' => false,
|
||||
]);
|
||||
$data[$kind . 'Markup'] = Html::sharedFragment($markup, $region['slug'], $account, $data['path'] ?? null);
|
||||
$data[$kind . 'Markup'] = self::fragment('shared-layout', [
|
||||
'kind' => $kind, 'visible' => $page['visibility'][$kind] ?? true,
|
||||
'content' => Html::sharedFragment($markup, $region['slug'], $account, $data['path'] ?? null),
|
||||
'palette' => DesignLibrary::find((int) ($region['palette_id'] ?? 0), 'palette'),
|
||||
'theme' => $region['theme'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
$html = self::fragment($template, $data);
|
||||
$data['canvasColors'] = $admin ? '' : CanvasStyle::colorRules($html . ($data['headerMarkup'] ?? '') . ($data['footerMarkup'] ?? ''));
|
||||
$data['styleNonce'] = $data['canvasColors'] !== '' || !empty($data['canvas']) ? base64_encode(random_bytes(18)) : '';
|
||||
$data['canvasColors'] = $admin ? '' : CanvasStyle::dynamicRules($html . ($data['headerMarkup'] ?? '') . ($data['footerMarkup'] ?? ''));
|
||||
$headSources = $admin ? [] : array_filter([$data['site']['head_html'] ?? '', $data['page']['head_html'] ?? '']);
|
||||
$data['styleNonce'] = $data['canvasColors'] !== '' || !empty($data['canvas']) || $headSources !== []
|
||||
? base64_encode(random_bytes(18)) : '';
|
||||
$head = PageHead::render($headSources, $data['styleNonce'], !empty($data['canvas']));
|
||||
$data['headMarkup'] = $head['markup'];
|
||||
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
|
||||
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
|
||||
$styleSources = $assetSources . ($data['styleNonce'] === '' ? '' : " 'nonce-{$data['styleNonce']}'");
|
||||
$styleSources .= $head['styles'] === [] ? '' : ' ' . implode(' ', array_keys($head['styles']));
|
||||
$scriptSources = $assetSources . ($head['scripts'] === [] ? '' : ' ' . implode(' ', array_keys($head['scripts'])));
|
||||
if ($head['inlineScript']) {
|
||||
$scriptSources .= " 'nonce-{$data['styleNonce']}'";
|
||||
}
|
||||
$articleEditor = $admin && !empty($data['articleEditor']);
|
||||
$editorImages = $articleEditor ? ' data:' : '';
|
||||
$editorImages = ($articleEditor ? ' data:' : '') . ($admin && !empty($data['faviconEditor']) ? ' blob:' : '');
|
||||
$editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
|
||||
$headers = [
|
||||
'Content-Type' => 'text/html; charset=utf-8',
|
||||
@@ -63,8 +77,9 @@ final class View
|
||||
'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 $styleSources; {$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'",
|
||||
. "style-src $styleSources; {$editorStyles}script-src $scriptSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
|
||||
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'"
|
||||
. ($head['hasScript'] && !empty($data['previewMode']) ? '; sandbox allow-scripts allow-popups' : ''),
|
||||
];
|
||||
if ($admin || !empty($data['previewMode'])) {
|
||||
$headers['Cache-Control'] = 'no-store';
|
||||
|
||||
Reference in New Issue
Block a user