Address LaySite 1.4.5 editor and release review suggestions

This commit is contained in:
2026-11-27 22:14:02 +08:00
parent 00e8a70e06
commit 074591d34f
16 changed files with 159 additions and 48 deletions
+1
View File
@@ -11,6 +11,7 @@ use Throwable;
final class Database
{
public const MIGRATION_REQUIRED = '数据库尚未完成升级。请在站点目录运行 php bin/install.php。';
private const SCHEMA_VERSION = 8;
// 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),
+22 -6
View File
@@ -6,6 +6,7 @@ namespace App\Content;
use App\Config\Environment;
use PDO;
use PDOException;
use RuntimeException;
final class McpSettings
@@ -16,10 +17,13 @@ final class McpSettings
public static function read(): array
{
$row = self::stored(Database::connect());
if ($row === null) {
$token = self::legacyToken();
$migrationRequired = $row === false;
$keyError = '';
if (!is_array($row)) {
$token = $migrationRequired ? null : self::legacyToken();
return ['enabled' => $token !== null, 'version' => 0, 'token' => $token, 'legacy' => $token !== null];
return ['enabled' => $token !== null, 'version' => 0, 'legacy' => $token !== null]
+ compact('token', 'migrationRequired', 'keyError');
}
$enabled = (bool) $row['enabled'];
@@ -27,12 +31,14 @@ final class McpSettings
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 ['enabled' => $enabled, 'version' => (int) $row['version'], 'token' => $token, 'legacy' => false];
return ['version' => (int) $row['version'], 'legacy' => false] + compact('enabled', 'token', 'migrationRequired', 'keyError');
}
public static function save(bool $enabled, bool $rotate, int $version): void
@@ -42,6 +48,9 @@ final class McpSettings
}
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 设置已更新,请刷新后再保存。');
}
@@ -58,9 +67,16 @@ final class McpSettings
});
}
private static function stored(PDO $pdo): ?array
private static function stored(PDO $pdo): array|false|null
{
return $pdo->query('SELECT enabled, encrypted_secret, version FROM mcp_settings WHERE id = 1')->fetch() ?: 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
+8 -3
View File
@@ -38,7 +38,9 @@ final class PageHead
continue;
}
if ($tag === 'script') {
$result['hasScript'] = true;
if (strtolower($attributes['type'] ?? '') !== 'application/ld+json') {
$result['hasScript'] = true;
}
if (!isset($attributes['src'])) {
$result['inlineScript'] = true;
$attributes['nonce'] = $nonce;
@@ -83,8 +85,11 @@ final class PageHead
|| ($node->nodeType === XML_TEXT_NODE && trim($node->textContent) === '')) {
continue;
}
if (!$node instanceof DOMElement || !isset(self::ATTRIBUTES[$node->tagName]) || count($entries) >= 40) {
throw new RuntimeException('Head 最多支持 40 个 meta、样式表、style 或 script 标签。');
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 = [];
+5 -2
View File
@@ -132,14 +132,17 @@ final class Repository
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false, ?array $sectionOrder = null): void
{
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections, $sectionOrder): void {
$head = $data['head_html'] ?? null;
$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), head_html = COALESCE(?, head_html), version = version + 1 WHERE slug = ? AND version = ?');
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'],
$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, $data['head_html'] ?? 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--')) {
+9
View File
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class SiteKeyFileError extends \RuntimeException
{
}
+9 -5
View File
@@ -44,8 +44,12 @@ final class SiteSecrets
private static function key(bool $create = false): string
{
$path = Database::path() . '.key';
clearstatcache(true, $path);
if (is_link($path)) {
throw new RuntimeException('密钥文件不能使用符号链接。');
throw new SiteKeyFileError('密钥文件不能使用符号链接。');
}
if (!$create && !file_exists($path)) {
throw new RuntimeException('站点密钥文件缺失。');
}
$mask = umask(0077);
try {
@@ -54,22 +58,22 @@ final class SiteSecrets
umask($mask);
}
if ($file === false) {
throw new RuntimeException('无法打开站点密钥文件。');
throw new SiteKeyFileError('无法打开站点密钥文件。');
}
try {
if (!flock($file, $create ? LOCK_EX : LOCK_SH) || (fstat($file)['mode'] & 0077) !== 0) {
throw new RuntimeException('站点密钥文件需能上锁,并且只能由运行用户访问。');
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 RuntimeException('无法写入站点密钥文件。');
throw new SiteKeyFileError('无法写入站点密钥文件。');
}
}
if (!is_string($key) || strlen($key) !== self::KEY_BYTES) {
throw new RuntimeException('站点密钥文件格式无效。');
throw new SiteKeyFileError('站点密钥文件格式无效。');
}
return $key;
+5 -1
View File
@@ -324,6 +324,7 @@ class AdminController
$layoutKind = $page['layout_kind'];
$layout = $layoutKind === null ? null : DesignLibrary::find($page['layout_id'], $layoutKind);
$default = $layout && ($site[$layoutKind . '_id'] ?? null) === $layout['id'];
$headEditor = !$layout && array_key_exists('head_html', $page);
$error = '';
if ($request->method() === 'POST') {
$data = [];
@@ -348,6 +349,9 @@ class AdminController
}
try {
if ($head !== null) {
if (!$headEditor) {
throw new RuntimeException(Database::MIGRATION_REQUIRED);
}
$data['head_html'] = PageHead::normalize($head);
}
$data['actions'] = $request->post('hero_actions') === null ? $page['actions']
@@ -426,7 +430,7 @@ class AdminController
return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'canvasSourceEditor' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
'pageTemplateDrawer' => !$layout, 'headEditor' => !$layout, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default,
'pageTemplateDrawer' => !$layout, 'headEditor' => $headEditor, 'designs' => DesignLibrary::all(), 'layout' => $layout, 'layoutDefault' => $default,
'layoutBase' => $layout && ($site['layout_defaults'][$layoutKind] ?? null) === $layout['id'],
'siteName' => $site['name'], 'layoutHasMember' => $layoutKind === 'header' && LayoutPage::hasMember($page['sections']),
'layoutDefaults' => array_intersect_key($site, ['header_id' => true, 'footer_id' => true]),
+1 -1
View File
@@ -34,7 +34,7 @@ final class McpController
return new Response(503, ['Cache-Control' => 'no-store']);
}
$secret = $settings['token'];
if ($settings['enabled'] && $secret === null) {
if ($settings['migrationRequired'] || ($settings['enabled'] && $secret === null)) {
return new Response(503, ['Cache-Control' => 'no-store']);
}
$header = $request->header('authorization', '');
+8 -5
View File
@@ -70,8 +70,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<div class="canvas-font-combo">
<input id="canvas-font-size" type="number" data-canvas-font-size min="8" max="144" step="1" placeholder="px" disabled>
<select data-font-preset aria-label="常用字号(px)" title="常用字号" disabled>
<option value="" hidden>▾</option>
<?php foreach ($fontSizes as $size): ?><option value="<?= $size ?>"><?= $size ?> px</option><?php endforeach ?>
<option value="" hidden>—</option>
<?php foreach ($fontSizes as $size): ?><option value="<?= $size ?>"><?= $size ?></option><?php endforeach ?>
</select>
</div>
</div>
@@ -134,8 +134,8 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<fieldset class="admin-options canvas-spacing-fields"><legend id="spacing-<?= $prefix ?>-legend"><?= $label ?>(px)</legend>
<div class="canvas-spacing-preset">
<label id="spacing-preset-<?= $prefix ?>-label" for="spacing-preset-<?= $prefix ?>">四边预设</label>
<input id="spacing-preset-<?= $prefix ?>" type="range" min="0" max="<?= count($spacingPresets) - 1 ?>" step="1"
value="<?= array_search(16, $spacingPresets, true) ?>" data-spacing-preset="<?= $e(Database::json($spacingPresets)) ?>"
<input id="spacing-preset-<?= $prefix ?>" type="range" min="-1" max="<?= count($spacingPresets) - 1 ?>" step="1"
value="-1" data-spacing-preset="<?= $e(Database::json($spacingPresets)) ?>"
list="spacing-preset-ticks" aria-labelledby="spacing-<?= $prefix ?>-legend spacing-preset-<?= $prefix ?>-label">
<output for="spacing-preset-<?= $prefix ?>" data-spacing-readout aria-live="off">默认</output>
<button class="button button-outline" type="button" data-spacing-reset>恢复默认</button>
@@ -146,6 +146,7 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
</fieldset>
<?php endforeach ?>
<datalist id="spacing-preset-ticks">
<option value="-1"></option>
<?php foreach (array_keys($spacingPresets) as $index): ?><option value="<?= $index ?>"></option><?php endforeach ?>
</datalist>
<div class="actions">
@@ -281,8 +282,10 @@ $spacingPresets = [0, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128];
<label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label>
<?php endif ?>
<?php if (!$layout): ?>
<?php if ($headEditor): ?>
<?= View::fragment('head-settings', ['label' => '本页 Head', 'head' => $page['head_html']]) ?>
<?php elseif (!$layout): ?>
<p class="field-note">本页 Head 尚不可用。<?= $e(Database::MIGRATION_REQUIRED) ?></p>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit"><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存页面</button></div>
</form>
+2
View File
@@ -12,6 +12,8 @@ $e = View::escape(...);
<textarea id="head-source" name="head_html" data-head-source rows="10" spellcheck="false"
autocapitalize="off" maxlength="<?= PageHead::MAX_LENGTH ?>"><?= $e($head) ?></textarea>
<p class="field-note">可添加 meta、样式表、style 和 script。全站代码先加载,本页代码随后加载。保存后,画布载入样式,脚本在独立预览和公开页面运行。</p>
<p class="field-note">需要使用 jQuery 时,请插入带 defer 的外部脚本,或让内联脚本等待 DOMContentLoaded。</p>
<p class="feedback error" data-head-limit role="status" hidden>Head 代码最多 32 KB(UTF-8)。请删减代码,或改用外部文件。</p>
<div class="actions">
<button class="button button-outline" type="button" data-head-asset="text/css"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入样式表</button>
<button class="button button-outline" type="button" data-head-asset="text/javascript"><?= View::fragment('studio-icon', ['icon' => 'add']) ?>插入脚本</button>
+12 -6
View File
@@ -1,4 +1,5 @@
<?php
use App\Content\Database;
use App\Content\McpSettings;
use App\Content\View;
@@ -37,16 +38,21 @@ $e = View::escape(...);
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="settings_section" value="mcp">
<input type="hidden" name="version" value="<?= $e($mcp['version']) ?>">
<label><input type="checkbox" name="mcp_enabled" value="1"<?= $mcp['enabled'] ? ' checked' : '' ?>> 开放 MCP</label>
<label><input type="checkbox" name="mcp_enabled" value="1"<?= $mcp['enabled'] ? ' checked' : '' ?><?= $mcp['migrationRequired'] ? ' disabled' : '' ?>> 开放 MCP</label>
<p class="field-note">允许持有密钥的 AI 客户端通过 Streamable HTTP 新建和编辑草稿。</p>
<?php if ($mcp['migrationRequired']): ?>
<p class="feedback error"><?= $e(Database::MIGRATION_REQUIRED) ?></p>
<?php endif ?>
<?php if ($mcp['enabled']): ?>
<label>连接网址<input type="url" readonly value="<?= $e(View::absolute(McpSettings::PATH)) ?>"></label>
<?php if ($mcp['token'] === null): ?>
<p class="feedback error">当前密钥无法读取。生成新密钥后即可重新连接。</p>
<?php if ($mcp['keyError'] !== ''): ?>
<p class="feedback error"><?= $e($mcp['keyError']) ?> 请检查数据库旁的 <code>.key</code> 文件及运行账户的权限。</p>
<?php elseif ($mcp['token'] === null): ?>
<p class="feedback error">当前密钥无法读取。可以生成新密钥并重新连接。</p>
<?php else: ?>
<details class="settings-stack">
<summary>查看连接密钥</summary>
<label>Bearer 密钥<input type="text" readonly spellcheck="false" autocomplete="off" value="<?= $e($mcp['token']) ?>"></label>
<label>Bearer 密钥<input type="text" class="mcp-token" readonly spellcheck="false" autocomplete="off" value="<?= $e($mcp['token']) ?>"></label>
<p class="field-note">在客户端设置 Authorization 请求头,格式为 Bearer 后加一个空格和密钥。</p>
</details>
<?php endif ?>
@@ -55,8 +61,8 @@ $e = View::escape(...);
<p class="field-note">当前密钥来自环境变量 LAYSITE_MCP_TOKEN。保存后由后台管理。</p>
<?php endif ?>
<div class="actions">
<button type="submit" class="button button-primary"><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存 MCP 设置</button>
<?php if ($mcp['enabled']): ?>
<button type="submit" class="button button-primary"<?= $mcp['migrationRequired'] ? ' disabled' : '' ?>><?= View::fragment('studio-icon', ['icon' => 'save']) ?>保存 MCP 设置</button>
<?php if ($mcp['enabled'] && $mcp['keyError'] === ''): ?>
<button type="submit" class="button button-outline" name="rotate_mcp_token" value="1" data-confirm="生成新密钥后,原有的 MCP 连接需要更换密钥。继续吗?"><?= View::fragment('studio-icon', ['icon' => 'refresh']) ?>生成新密钥</button>
<?php endif ?>
</div>