此文章的原文暂不可用。
+ +填写卡片标题
填写卡片内容。
commit 1bb05546080b69cd23d4c82fd77c62f086feab42
Author: ChatGPT 填写正文。 填写本节的导语。 填写需要引用的内容。 填写分类名称 填写标签 填写数字 完成进度 请注意 填写一条提示信息。 填写卡片内容。 填写链接指向的资料说明。 已完成 填写操作结果或服务状态。 填写展开后的内容。 用一句话补充背景或说明。 在这里输入区块内容。 说明访客需要知悉的事项、条件或时间。 在这里说明图片或产品。 填写主要内容。 补充相关信息。 说明视频涵盖的功能与操作。 介绍这个特点。 介绍这个特点。 介绍这个特点。 在这里填写引用或用户反馈。 填写用户的评价,并说明他们获得的结果。 用户姓名 · 公司或角色 填写另一条用户评价。 用户姓名 · 公司或角色 请输入答案。 填写这一阶段需要完成的事项。 填写交付时间与验收标准。 填写主要功能或改进。 填写上一版本的更新内容。 说明下一步。 填写咨询范围与回复时间。 暂无文章。 文章已删除。 站点已还原。 还原会替换现有页面、文章、设计配置及媒体目录记录。先导出当前站点,再选择需要还原的文件。 = $live ?> 个已发布 · = count($pages) - $live ?> 个草稿 >= $pages ? '没有匹配的页面。' : '暂无页面。' ?> 暂无自定义配置。 可以直接编辑文字,插入链接、图片、音视频。复杂区块可切换到 HTML 源码调整。 = View::escape($error) ?> 已保存。 管理网站页面、媒体和文章。 = $e($error) ?> 忘记密码时,可请服务器管理员通过命令行重设。 = $e($slug) ?> · #= $e($key) ?> 暂无已发布的动态。 = $e($article['summary']) ?> 此文章的原文暂不可用。 = $e($site['name']) ?> = $alignField('lead') ?>>= $e($page['lead']) ?>填写小标题
'],
+ 'lead' => ['导语', '
'],
+ 'bullet-list' => ['项目列表', '
'],
+ 'ordered-list' => ['编号列表', '
'],
+ 'heading-kicker' => ['标题眉标', '
'],
+ ]],
+ 'link-elements' => ['链接与按钮', [
+ 'button' => ['主按钮', ''],
+ 'outline-button' => ['描边按钮', ''],
+ 'text-link' => ['文字链接', ''],
+ 'button-group' => ['按钮组', ''],
+ 'breadcrumbs' => ['面包屑', ''],
+ 'download-link' => ['下载入口', ''],
+ 'email-link' => ['邮件链接', ''],
+ ]],
+ 'media-elements' => ['图片与影音', [
+ 'image' => ['图片', '', 'image/'],
+ 'video' => ['视频', '', 'video/'],
+ 'audio' => ['音频', '', 'audio/'],
+ 'qr-image' => ['二维码', '', 'image/'],
+ 'image-link' => ['图片链接', ''],
+ ]],
+ 'structure-elements' => ['版式与数据', [
+ 'separator' => ['分割线', '
'],
+ 'spacer' => ['留白', ''],
+ 'code' => ['代码块', '
'],
+ 'basic-table' => ['数据表格', '填写代码
'],
+ 'progress' => ['进度条', '名称 数据 填写名称 填写数据 填写卡片标题
查看资料
填写折叠标题
填写区块标题
'],
+ 'notice' => ['重点提示', '填写重要提示


介绍主题
第一栏
第二栏



演示视频
特点一
特点二
特点三
'],
+ 'metrics' => ['关键数据', '
'],
+ 'testimonials' => ['用户评价', '
'],
+ 'faq' => ['常见问题', '项目 说明 项目一 填写说明 项目二 填写说明 请输入问题
'],
+ 'checklist' => ['清单', '确定目标
实施与验收
'],
+ 'changelog' => ['更新记录', '版本 2.0
版本 1.0
联系团队
', '
'], ['', '
'], $html);
+ }
+
+ public static function articleBody(array $article): string
+ {
+ return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
+ }
+
+ public static function applyCanvasEdits(string $body, array $edits): string
+ {
+ if (!array_is_list($edits) || count($edits) > 512) {
+ throw new RuntimeException('正文增量无效。');
+ }
+ $size = strlen($body);
+ $cursor = 0;
+ $result = '';
+ foreach ($edits as $edit) {
+ if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
+ throw new RuntimeException('正文增量无效。');
+ }
+ [$offset, $remove, $insert] = $edit;
+ if (!is_int($offset) || !is_int($remove) || !is_string($insert)
+ || $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
+ throw new RuntimeException('正文增量无效。');
+ }
+ $result .= substr($body, $cursor, $offset - $cursor) . $insert;
+ $cursor = $offset + $remove;
+ if (strlen($result) > 300000) {
+ throw new RuntimeException('正文太长。');
+ }
+ }
+ $result .= substr($body, $cursor);
+ if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
+ throw new RuntimeException('正文太长或编码无效。');
+ }
+
+ return $result;
+ }
+
+ public static function sanitize(string $html, ?string $anchorPrefix = null): string
+ {
+ $document = new DOMDocument('1.0', 'UTF-8');
+ $document->loadHTML('' . $html . '', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
+ $body = $document->getElementsByTagName('body')->item(0);
+ if (!$body) {
+ return '';
+ }
+ self::sanitizeChildren($body);
+ if ($anchorPrefix !== null) {
+ $ids = [];
+ foreach ($body->getElementsByTagName('*') as $element) {
+ $id = $element->getAttribute('id');
+ if ($id !== '') {
+ $ids[$id] = $anchorPrefix . '-' . $id;
+ $element->setAttribute('id', $ids[$id]);
+ }
+ }
+ foreach ($body->getElementsByTagName('a') as $link) {
+ $href = $link->getAttribute('href');
+ if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
+ $link->setAttribute('href', '#' . $ids[substr($href, 1)]);
+ }
+ }
+ }
+ $output = '';
+ foreach ($body->childNodes as $child) {
+ $output .= $document->saveHTML($child);
+ }
+
+ return trim($output);
+ }
+
+ private static function sanitizeChildren(DOMNode $parent): void
+ {
+ foreach (iterator_to_array($parent->childNodes) as $element) {
+ if ($element->nodeType === XML_COMMENT_NODE) {
+ $parent->removeChild($element);
+ continue;
+ }
+ if (!$element instanceof DOMElement) {
+ continue;
+ }
+ if (!array_key_exists($element->tagName, self::TAGS)) {
+ $parent->removeChild($element);
+ continue;
+ }
+ $allowed = [...self::TAGS[$element->tagName], 'class', 'id'];
+ foreach (iterator_to_array($element->attributes) as $attribute) {
+ $name = $attribute->name;
+ $value = $attribute->value;
+ if (!in_array($name, $allowed, true)
+ || ($name === 'href' && !self::url($value))
+ || (in_array($name, ['src', 'poster'], true) && !self::url($value, true))
+ || ($name === 'target' && $value !== '_blank')
+ || ($name === 'tabindex' && $value !== '0')) {
+ $element->removeAttribute($name);
+ }
+ }
+ if ($element->tagName === 'a') {
+ if ($element->getAttribute('target') === '_blank') {
+ $element->setAttribute('rel', 'noopener noreferrer');
+ } else {
+ $element->removeAttribute('rel');
+ }
+ }
+ self::sanitizeChildren($element);
+ }
+ }
+}
diff --git a/app/Content/IdentityProvider.php b/app/Content/IdentityProvider.php
new file mode 100644
index 0000000..c271d60
--- /dev/null
+++ b/app/Content/IdentityProvider.php
@@ -0,0 +1,148 @@
+http = new Client(['timeout' => 8, 'connect_timeout' => 4, 'allow_redirects' => false]);
+ $scope = preg_split('/\s+/', trim($config['scope']), -1, PREG_SPLIT_NO_EMPTY);
+ $authorization = $config['authorization'];
+ $token = $config['token'];
+ $userinfo = $config['userinfo'];
+ if ($config['mode'] === 'oidc') {
+ $this->oidc = $this->document(rtrim($config['issuer'], '/') . '/.well-known/openid-configuration');
+ if (($this->oidc['issuer'] ?? null) !== $config['issuer']) {
+ throw new RuntimeException('OIDC Issuer 与发现文档不一致。');
+ }
+ $authorization = $this->endpoint($this->oidc['authorization_endpoint'] ?? '');
+ $token = $this->endpoint($this->oidc['token_endpoint'] ?? '');
+ $userinfo = isset($this->oidc['userinfo_endpoint']) ? $this->endpoint($this->oidc['userinfo_endpoint']) : '';
+ $scope = array_values(array_unique(['openid', 'profile', 'email', ...$scope]));
+ }
+ $auth = $config['token_auth'];
+ if ($auth === '') {
+ $supported = $this->oidc['token_endpoint_auth_methods_supported'] ?? ['client_secret_basic'];
+ if ($this->oidc === [] || (!in_array('client_secret_basic', $supported, true) && in_array('client_secret_post', $supported, true))) {
+ $auth = 'client_secret_post';
+ } elseif (in_array('client_secret_basic', $supported, true)) {
+ $auth = 'client_secret_basic';
+ } else {
+ throw new RuntimeException('身份服务没有公布受支持的令牌端点认证方式。');
+ }
+ }
+ $this->client = new GenericProvider([
+ 'clientId' => $config['client_id'], 'clientSecret' => $secret,
+ 'redirectUri' => View::absolute('/account/callback'), 'urlAuthorize' => $authorization,
+ 'urlAccessToken' => $token, 'urlResourceOwnerDetails' => $userinfo,
+ 'pkceMethod' => GenericProvider::PKCE_METHOD_S256, 'scopes' => $scope, 'scopeSeparator' => ' ',
+ ], [
+ 'httpClient' => $this->http,
+ 'optionProvider' => $auth === 'client_secret_basic' ? new HttpBasicAuthOptionProvider() : new PostAuthOptionProvider(),
+ ]);
+ }
+
+ public function authorization(string $nonce): string
+ {
+ return $this->client->getAuthorizationUrl($this->oidc === [] ? [] : ['nonce' => $nonce]);
+ }
+
+ public function profile(string $code, string $proof, string $nonce): array
+ {
+ $this->client->setPkceCode($proof);
+ $token = $this->client->getAccessToken('authorization_code', ['code' => $code]);
+ if ($this->oidc === []) {
+ $claims = $this->client->getResourceOwner($token)->toArray();
+ } else {
+ $claims = $this->verifiedClaims($token->getValues()['id_token'] ?? '', $nonce);
+ if (isset($this->oidc['userinfo_endpoint'])) {
+ $more = $this->client->getResourceOwner($token)->toArray();
+ if (($more['sub'] ?? null) !== $claims['sub']) {
+ throw new RuntimeException('OIDC 用户资料的主体与 ID Token 不一致。');
+ }
+ $claims = $more + $claims;
+ }
+ }
+ $subject = $claims[$this->oidc !== [] ? 'sub' : $this->config['subject_field']] ?? null;
+ if ((!is_string($subject) && !is_int($subject)) || (string) $subject === '' || strlen((string) $subject) > 255) {
+ throw new RuntimeException('身份服务没有返回有效的用户标识。');
+ }
+ $name = $claims[$this->config['name_field'] ?: 'name'] ?? $claims['preferred_username'] ?? (string) $subject;
+ $avatar = $claims[$this->config['avatar_field'] ?: 'picture'] ?? '';
+ return [
+ 'subject' => (string) $subject,
+ 'name' => is_string($name) ? mb_substr($name, 0, 100) : (string) $subject,
+ 'avatar' => is_string($avatar) && strlen($avatar) <= 2048 && str_starts_with($avatar, 'https://') && Html::url($avatar, true) ? $avatar : '',
+ ];
+ }
+
+ private function verifiedClaims(mixed $encoded, string $nonce): array
+ {
+ if (!is_string($encoded) || strlen($encoded) > 16384 || substr_count($encoded, '.') !== 2) {
+ throw new RuntimeException('身份服务没有返回有效的 ID Token。');
+ }
+ $header = JWT::jsonDecode(JWT::urlsafeB64Decode(explode('.', $encoded, 2)[0]));
+ $algorithm = $header->alg ?? '';
+ if (!in_array($algorithm, ['RS256', 'RS384', 'RS512', 'ES256', 'ES384'], true)) {
+ throw new RuntimeException('身份服务使用了不支持的 ID Token 签名算法。');
+ }
+ $keys = $this->document($this->endpoint($this->oidc['jwks_uri'] ?? ''));
+ $claims = (array) JWT::decode($encoded, JWK::parseKeySet($keys, $algorithm));
+ $audience = (array) ($claims['aud'] ?? []);
+ $client = $this->config['client_id'];
+ if (($claims['iss'] ?? null) !== $this->config['issuer'] || !in_array($client, $audience, true)
+ || ((count($audience) > 1 || isset($claims['azp'])) && ($claims['azp'] ?? null) !== $client)
+ || ($claims['nonce'] ?? null) !== $nonce || !is_string($claims['sub'] ?? null) || $claims['sub'] === ''
+ || !is_int($claims['exp'] ?? null) || $claims['exp'] <= time()
+ || !is_int($claims['iat'] ?? null) || $claims['iat'] > time() + 60) {
+ throw new RuntimeException('OIDC ID Token 声明校验失败。');
+ }
+
+ return $claims;
+ }
+
+ private function document(string $endpoint): array
+ {
+ $response = $this->http->get($this->endpoint($endpoint), ['headers' => ['Accept' => 'application/json'], 'stream' => true]);
+ $body = Utils::copyToString($response->getBody(), 1048577);
+ if (strlen($body) > 1048576 || $response->getStatusCode() !== 200) {
+ throw new RuntimeException('身份服务文档超过大小限制。');
+ }
+ $data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
+ if (!is_array($data)) {
+ throw new RuntimeException('身份服务文档格式无效。');
+ }
+ return $data;
+ }
+
+ private function endpoint(mixed $endpoint): string
+ {
+ $url = is_string($endpoint) ? parse_url($endpoint) : false;
+ if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
+ || isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || !Html::url($endpoint, true)) {
+ throw new RuntimeException('身份服务端点必须使用 HTTPS。');
+ }
+
+ return $endpoint;
+ }
+}
diff --git a/app/Content/Media.php b/app/Content/Media.php
new file mode 100644
index 0000000..8b2e253
--- /dev/null
+++ b/app/Content/Media.php
@@ -0,0 +1,130 @@
+ 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
+ 'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
+ 'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
+ 'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
+ 'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
+ ];
+
+ public static function all(bool $includeArchived = false): array
+ {
+ $query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
+ $files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
+ foreach ($files as &$file) {
+ $file['url'] = '/assets/uploads/' . $file['name'];
+ }
+ unset($file);
+
+ return $files;
+ }
+
+ public static function upload(UploadFile $file, string $label): void
+ {
+ if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
+ throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
+ }
+ $source = $file->getPathname();
+ $mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
+ $extension = self::EXTENSIONS[$mime] ?? null;
+ if ($extension === null) {
+ throw new RuntimeException('文件类型不受支持。');
+ }
+ $content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
+ $name = bin2hex(random_bytes(16)) . '.' . $extension;
+ $directory = self::directory();
+ if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
+ throw new RuntimeException('资源目录无法创建。');
+ }
+ $path = $directory . '/' . $name;
+ try {
+ $written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
+ if (!$written) {
+ throw new RuntimeException('文件写入失败。');
+ }
+ $query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
+ $query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
+ } catch (Throwable $error) {
+ if (is_file($path)) {
+ unlink($path);
+ }
+ throw $error;
+ }
+ }
+
+ public static function find(string $name): ?array
+ {
+ $query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
+ $query->execute([$name]);
+
+ return $query->fetch() ?: null;
+ }
+
+ public static function update(string $name, string $label, bool $archived): void
+ {
+ Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
+ ->execute([$label, (int) $archived, $name]);
+ }
+
+ public static function directory(): string
+ {
+ return rtrim(getenv('LAYSITE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
+ }
+
+ public static function validateBackup(string $path, string $name, string $mime, int $size): void
+ {
+ if ((new \finfo(FILEINFO_MIME_TYPE))->file($path) !== $mime
+ || !isset(self::EXTENSIONS[$mime]) || self::EXTENSIONS[$mime] !== pathinfo($name, PATHINFO_EXTENSION)) {
+ throw new RuntimeException('备份资源类型与清单不一致。');
+ }
+ if ($mime === 'image/svg+xml') {
+ self::safeSvg($path, $size);
+ }
+ }
+
+ private static function safeSvg(string $source, int $size): string
+ {
+ if ($size > 512 * 1024) {
+ throw new RuntimeException('SVG 图标最大支持 512 KB。');
+ }
+ $svg = new DOMDocument();
+ if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
+ || $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
+ throw new RuntimeException('SVG 图标格式无效。');
+ }
+ $tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
+ $attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
+ 'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
+ 'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
+ foreach ((new DOMXPath($svg))->query('//*') as $element) {
+ if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
+ || !in_array($element->localName, $tags, true)) {
+ throw new RuntimeException('SVG 仅支持基础矢量元素。');
+ }
+ foreach ($element->attributes as $attribute) {
+ if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
+ || !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
+ throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
+ }
+ }
+ }
+
+ return $svg->saveXML($svg->documentElement);
+ }
+}
diff --git a/app/Content/PageDraft.php b/app/Content/PageDraft.php
new file mode 100644
index 0000000..f8f01da
--- /dev/null
+++ b/app/Content/PageDraft.php
@@ -0,0 +1,109 @@
+ 70 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value)
+ || in_array($value, $reserved, true)) {
+ throw new RuntimeException('网址标识无效或已保留。');
+ }
+
+ return $value;
+ }
+
+ public static function content(array $input, array $page): array
+ {
+ $name = self::text($input['name'] ?? $page['name'] ?? '', 100, true);
+ $page += ['name' => $name, 'title' => $name, 'heading' => $name, 'description' => '', 'lead' => '',
+ 'accent' => '', 'image' => '', 'alt' => '', 'image_scale' => 0, 'alignments' => [], 'visibility' => [],
+ 'actions' => [], 'quicklinks' => [], 'theme' => '', 'sections' => []];
+ $page['name'] = $name;
+ foreach (['title' => 160, 'heading' => 110, 'description' => 300, 'lead' => 600, 'accent' => 110, 'image' => 1000, 'alt' => 200] as $field => $limit) {
+ $page[$field] = self::text($input[$field] ?? $page[$field], $limit, in_array($field, ['title', 'heading'], true));
+ }
+ if (mb_strlen($page['heading'] . $page['accent']) > 110 || ($page['image'] !== '' && !Html::url($page['image'], true))) {
+ throw new RuntimeException('首屏标题过长或图片地址不正确。');
+ }
+ foreach (['header', 'footer', 'palette'] as $kind) {
+ $key = $kind . '_id';
+ $page[$key] = array_key_exists($key, $input) ? DesignLibrary::selection($kind, $input[$key]) : ($page[$key] ?? null);
+ }
+ $page['actions'] = Buttons::validate($input['actions'] ?? $page['actions']);
+ if (array_key_exists('visibility', $input)) {
+ if (!is_array($input['visibility'])) {
+ throw new RuntimeException('页面显示选项无效。');
+ }
+ foreach ($input['visibility'] as $area => $visible) {
+ if (!in_array($area, ['hero', 'header', 'footer'], true) || !is_bool($visible)) {
+ throw new RuntimeException('页面显示选项无效。');
+ }
+ $page['visibility'][$area] = $visible;
+ }
+ }
+ $page['status'] = 'draft';
+ if (array_key_exists('sections', $input)) {
+ $oldKeys = array_column($page['sections'], 'key');
+ $page['sections'] = self::sections($input['sections']);
+ if (!array_key_exists('actions', $input)) {
+ $removed = array_map(static fn (string $key): string => '#' . $key, array_diff($oldKeys, array_column($page['sections'], 'key')));
+ $page['actions'] = array_values(array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true)));
+ }
+ $page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20));
+ }
+
+ return $page;
+ }
+
+ private static function sections(mixed $items): array
+ {
+ if (!is_array($items) || !array_is_list($items) || count($items) > 50) {
+ throw new RuntimeException('每页最多可提交 50 个区块。');
+ }
+ $sections = [];
+ foreach ($items as $item) {
+ if (!is_array($item)) {
+ throw new RuntimeException('区块必须是对象。');
+ }
+ $key = self::slug($item['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
+ if (isset($sections[$key])) {
+ throw new RuntimeException('区块锚点重复。');
+ }
+ $preset = null;
+ if (isset($item['preset'])) {
+ $preset = is_string($item['preset']) ? BlockTemplates::find($item['preset']) : null;
+ if (!$preset) {
+ throw new RuntimeException('区块模板不存在。');
+ }
+ }
+ $style = $item['style'] ?? $preset[4] ?? 'plain';
+ if (!in_array($style, ['plain', 'tinted'], true)) {
+ throw new RuntimeException('区块样式无效。');
+ }
+ $sections[$key] = [
+ 'key' => $key, 'title' => self::text($item['title'] ?? $preset[0] ?? '', 100, true),
+ 'lead' => self::text($item['lead'] ?? $preset[2] ?? '', 500),
+ 'body' => Html::sanitize(self::text($item['body'] ?? $preset[1] ?? '', 120000)),
+ 'style' => $style, 'feed' => $preset[3] ?? null, 'version' => null,
+ ];
+ }
+ return array_values($sections);
+ }
+
+ private static function text(mixed $value, int $limit, bool $required = false): string
+ {
+ if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit || ($required && trim($value) === '')) {
+ throw new RuntimeException('请检查页面内容及字段长度。');
+ }
+
+ return trim($value);
+ }
+}
diff --git a/app/Content/PageTemplates.php b/app/Content/PageTemplates.php
new file mode 100644
index 0000000..b80d396
--- /dev/null
+++ b/app/Content/PageTemplates.php
@@ -0,0 +1,40 @@
+ $group) {
+ if (!isset($group['pages'][$key])) {
+ continue;
+ }
+ $template = $group['pages'][$key];
+ $sections = [];
+ $quicklinks = [];
+ foreach ($template['sections'] as [$anchor, $title, $style, $body, $feed]) {
+ $sections[] = ['key' => $anchor, 'title' => $title, 'style' => $style, 'body' => Html::sanitize($body, $anchor),
+ 'lead' => '', 'feed' => $feed, 'alignments' => '{}', 'version' => 0];
+ $quicklinks[] = ['#' . $anchor, $title];
+ }
+
+ return array_replace($template, [
+ 'slug' => $key, 'theme' => $theme, 'title' => $template['name'], 'accent' => '',
+ 'lead' => $template['description'], 'quicklinks' => $quicklinks, 'status' => 'draft',
+ 'alignments' => [], 'image_scale' => 0, 'sections' => $sections,
+ ]);
+ }
+
+ return null;
+ }
+}
diff --git a/app/Content/Passwords.php b/app/Content/Passwords.php
new file mode 100644
index 0000000..9d7a076
--- /dev/null
+++ b/app/Content/Passwords.php
@@ -0,0 +1,20 @@
+= self::MIN_LENGTH;
+ }
+}
diff --git a/app/Content/Repository.php b/app/Content/Repository.php
new file mode 100644
index 0000000..ed6227f
--- /dev/null
+++ b/app/Content/Repository.php
@@ -0,0 +1,403 @@
+ '目录', 'projects' => '项目', 'partners' => '合作伙伴',
+ ];
+ public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'] + self::DIRECTORIES;
+ private const ARTICLE_FIELDS = 'articles.*, (SELECT json_group_object(c.slug, c.name)
+ FROM article_category_links l JOIN article_categories c ON c.slug = l.category_slug
+ WHERE l.article_id = articles.id) AS categories';
+ private PDO $pdo;
+
+ public function __construct()
+ {
+ $this->pdo = Database::connect();
+ }
+
+ public function site(): array
+ {
+ return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
+ }
+
+ public function pages(bool $publishedOnly = false): array
+ {
+ $where = $publishedOnly ? " WHERE status = 'published'" : '';
+
+ return $this->pdo->query('SELECT slug, name, title, updated_at, status, version FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
+ }
+
+ public function createPage(string $slug, string $name, array $template = []): void
+ {
+ Database::write(function (PDO $pdo) use ($slug, $name, $template): void {
+ $query = $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
+ lead, image, alt, actions, quicklinks, theme, visibility, header_id, footer_id, palette_id, status, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?)");
+ $query->execute([
+ $slug, $name, $template['title'] ?? $name, $template['description'] ?? '', $template['heading'] ?? $name,
+ $template['accent'] ?? '', $template['lead'] ?? '', $template['image'] ?? '', $template['alt'] ?? '',
+ Database::json($template['actions'] ?? []), Database::json($template['quicklinks'] ?? []),
+ $template['theme'] ?? '', Database::json($template['visibility'] ?? []), $template['header_id'] ?? null, $template['footer_id'] ?? null, $template['palette_id'] ?? null, self::now(),
+ ]);
+ if ($query->rowCount() !== 1) {
+ throw new RuntimeException('此页面地址已存在。');
+ }
+ foreach ($template['sections'] ?? [] as $section) {
+ self::insertSection($pdo, $slug, $section['key'], $section);
+ }
+ });
+ }
+
+ public function page(string $slug): ?array
+ {
+ $page = $this->one('SELECT * FROM pages WHERE slug = ?', [$slug]);
+ if (!$page) {
+ return null;
+ }
+ foreach (['actions', 'quicklinks', 'alignments', 'visibility'] as $key) {
+ $page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR);
+ }
+ $query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key');
+ $query->execute([$slug]);
+ $page['sections'] = $query->fetchAll();
+
+ return $page;
+ }
+
+ public function section(string $page, string $key): ?array
+ {
+ return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
+ }
+
+ public function publishedFeed(string $page, string $key): ?array
+ {
+ return $this->one("SELECT sections.title, sections.feed FROM sections
+ JOIN pages ON pages.slug = sections.page_slug
+ WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
+ }
+
+ public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false): void
+ {
+ Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): void {
+ $query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
+ image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
+ $query->execute([
+ $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
+ $data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
+ Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), $slug, $version,
+ ]);
+ self::checkVersion($query->rowCount());
+ if ($replaceDraftSections) {
+ $pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]);
+ }
+ foreach ($sections as $section) {
+ if (!empty($section['delete'])) {
+ self::deleteSection($pdo, $slug, $section['key'], $section['version']);
+ } elseif ($section['version'] === null) {
+ self::insertSection($pdo, $slug, $section['key'], $section);
+ } else {
+ self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
+ }
+ }
+ });
+ }
+
+ public function saveSection(string $page, string $key, array $data, int $version): void
+ {
+ Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
+ self::updateSection($pdo, $page, $key, $data, $version);
+ self::touchPage($pdo, $page);
+ });
+ }
+
+ private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
+ {
+ $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1
+ WHERE page_slug = ? AND key = ? AND version = ?');
+ $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]);
+ self::checkVersion($query->rowCount());
+ }
+
+ public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = ''): void
+ {
+ Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
+ self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
+ self::touchPage($pdo, $page, structureChanged: true);
+ });
+ }
+
+ private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
+ {
+ $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position)
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
+ $query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]);
+ if ($query->rowCount() !== 1) {
+ throw new RuntimeException('此区块锚点已被使用。');
+ }
+ }
+
+ private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void
+ {
+ $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
+ $query->execute([$page, $key, $version]);
+ self::checkVersion($query->rowCount());
+ $pdo->prepare("UPDATE pages SET
+ quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor),
+ actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor)
+ WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $page]);
+ }
+
+ public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
+ {
+ Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
+ $current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?');
+ $current->execute([$page]);
+ $revision = $current->fetchColumn();
+ self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
+ if ($operation === 'delete') {
+ self::deleteSection($pdo, $page, $key, $version);
+ self::touchPage($pdo, $page, structureChanged: true);
+
+ return;
+ }
+ $query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key");
+ $query->execute([$page]);
+ $revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
+ if (!array_key_exists($key, $revisions)) {
+ throw new RuntimeException('找不到该区块。');
+ }
+ self::checkVersion((int) $revisions[$key] === $version ? 1 : 0);
+ $keys = array_map('strval', array_keys($revisions));
+ $index = array_search($key, $keys, true);
+ $other = $index + ($operation === 'up' ? -1 : 1);
+ if (!isset($keys[$other])) {
+ return;
+ }
+ [$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
+ $query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
+ foreach ($keys as $position => $section) {
+ $query->execute([$position, $page, $section]);
+ }
+ self::touchPage($pdo, $page, structureChanged: true);
+ });
+ }
+
+ private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
+ {
+ $revision = $structureChanged ? ', version = version + 1' : '';
+ $pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
+ }
+
+ public function categories(): array
+ {
+ return $this->pdo->query('SELECT slug, name FROM article_categories ORDER BY rowid')->fetchAll(PDO::FETCH_KEY_PAIR);
+ }
+
+ public function createCategory(string $slug, string $name): void
+ {
+ $query = $this->pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
+ $query->execute([$slug, $name]);
+ if ($query->rowCount() !== 1) {
+ throw new RuntimeException('此分类网址标识已被使用。');
+ }
+ }
+
+ public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
+ int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
+ {
+ if ($category === []) {
+ return [];
+ }
+ $sql = 'SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE 1 = 1';
+ $args = [];
+ if ($public) {
+ $sql .= " AND status = 'published'";
+ }
+ if ($category !== null) {
+ $args = (array) $category;
+ $marks = implode(', ', array_fill(0, count($args), '?'));
+ $sql .= " AND EXISTS (SELECT 1 FROM article_category_links
+ WHERE article_id = articles.id AND category_slug IN ($marks))";
+ }
+ if ($tag !== null) {
+ $sql .= ' AND EXISTS (SELECT 1 FROM json_each(articles.tags) WHERE value = ?)';
+ $args[] = $tag;
+ }
+ $order = $public ? 'published_at' : 'updated_at';
+ $order = $directoryOrder ? "COALESCE(json_extract(card, '$.position'), 0), id" : "$order DESC, id DESC";
+ $query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' LIMIT ? OFFSET ?');
+ $query->execute([...$args, $limit, $offset]);
+
+ return array_map(self::decodeArticle(...), $query->fetchAll());
+ }
+
+ public function articleById(int $id): ?array
+ {
+ return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE id = ?', [$id]));
+ }
+
+ public function published(string $slug): ?array
+ {
+ return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
+ }
+
+ public function articleRedirect(string $slug): ?array
+ {
+ return $this->one("SELECT articles.slug FROM article_redirects
+ JOIN articles ON articles.id = article_redirects.article_id
+ WHERE article_redirects.slug = ? AND articles.status = 'published'", [$slug]);
+ }
+
+ public function legacyArticle(string $path): ?array
+ {
+ return $this->one("SELECT slug FROM articles WHERE legacy_path = ? AND status = 'published'", [$path]);
+ }
+
+ public function saveArticle(?int $id, array $data, int $version): int
+ {
+ return Database::write(function (PDO $pdo) use ($id, $data, $version): int {
+ $old = $id !== null ? $this->articleById($id) : null;
+ if ($id !== null && (!$old || $old['version'] !== $version)) {
+ self::checkVersion(0);
+ }
+ $existing = $this->one('SELECT id FROM articles WHERE slug = ?', [$data['slug']]);
+ $redirect = $this->one('SELECT article_id FROM article_redirects WHERE slug = ?', [$data['slug']]);
+ if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) {
+ throw new RuntimeException('此网址标识已被使用。');
+ }
+ $publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null);
+ $values = [
+ $data['slug'], $data['title'], $data['summary'], $data['body'],
+ $data['body_format'], Database::json($data['card']),
+ Database::json($data['tags']), $data['status'], $publishedAt, self::now(),
+ ];
+ if ($id === null) {
+ $query = $pdo->prepare('INSERT INTO articles
+ (id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
+ VALUES (' . Database::NEXT_ARTICLE_ID . ', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
+ $query->execute($values);
+ $id = (int) $pdo->lastInsertId();
+ } else {
+ if ($old['slug'] !== $data['slug']) {
+ $pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]);
+ $pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]);
+ }
+ $query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, summary = ?, body = ?,
+ body_format = ?, card = ?, tags = ?, status = ?, published_at = ?, updated_at = ?, version = version + 1
+ WHERE id = ? AND version = ?');
+ $query->execute([...$values, $id, $version]);
+ self::checkVersion($query->rowCount());
+ $pdo->prepare('DELETE FROM article_category_links WHERE article_id = ?')->execute([$id]);
+ }
+ $link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
+ foreach ($data['categories'] as $category) {
+ $link->execute([$id, $category]);
+ }
+
+ return $id;
+ });
+ }
+
+ public function deleteArticle(int $id, int $version): void
+ {
+ Database::write(function (PDO $pdo) use ($id, $version): void {
+ // Keep the original seed slug even if the article has been renamed.
+ $deletions = $pdo->prepare('INSERT INTO article_deletions (slug, article_id)
+ SELECT slug, id FROM articles WHERE id = :id
+ UNION ALL SELECT slug, article_id FROM article_redirects WHERE article_id = :id
+ ON CONFLICT (slug) DO UPDATE SET article_id = excluded.article_id');
+ $deletions->execute(['id' => $id]);
+
+ $delete = $pdo->prepare('DELETE FROM articles WHERE id = ? AND version = ?');
+ $delete->execute([$id, $version]);
+ self::checkVersion($delete->rowCount());
+ });
+ }
+
+ public function sitemapArticles(): iterable
+ {
+ $query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'
+ AND (trim(body) <> '' OR trim(summary) <> '' OR json_extract(card, '$.image') <> '' OR json_extract(card, '$.url') <> '')
+ ORDER BY slug");
+ yield from $query;
+ }
+
+ public function administrator(string $email): ?array
+ {
+ return $this->one('SELECT id, email, password_hash FROM users WHERE email = ?', [$email]);
+ }
+
+ public function administratorById(int $id): ?array
+ {
+ return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]);
+ }
+
+ public function changePassword(array $user, string $newHash): bool
+ {
+ $query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?');
+ $query->execute([$newHash, $user['id'], $user['password_hash']]);
+
+ return $query->rowCount() === 1;
+ }
+
+ public function recordFailedLogin(string $address): int
+ {
+ $now = time();
+ $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
+ if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) {
+ return $current['expires_at'] - $now;
+ }
+
+ return Database::write(function (PDO $pdo) use ($address, $now): int {
+ $pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]);
+ $current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
+ if ($current && $current['attempts'] >= 12) {
+ return $current['expires_at'] - $now;
+ }
+ $query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?)
+ ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1');
+ $query->execute([$address, $now + 900]);
+
+ return 0;
+ });
+ }
+
+ private function one(string $sql, array $args): ?array
+ {
+ $query = $this->pdo->prepare($sql);
+ $query->execute($args);
+
+ return $query->fetch() ?: null;
+ }
+
+ private static function decodeArticle(?array $article): ?array
+ {
+ if ($article !== null) {
+ foreach (['tags', 'categories', 'card'] as $field) {
+ $article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR);
+ }
+ }
+
+ return $article;
+ }
+
+ private static function now(): string
+ {
+ return date('Y-m-d H:i:s');
+ }
+
+ private static function checkVersion(int $count): void
+ {
+ if ($count !== 1) {
+ throw new RuntimeException('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
+ }
+ }
+}
diff --git a/app/Content/SiteBackup.php b/app/Content/SiteBackup.php
new file mode 100644
index 0000000..cd1ceb0
--- /dev/null
+++ b/app/Content/SiteBackup.php
@@ -0,0 +1,289 @@
+query('SELECT * FROM ' . $table)->fetchAll();
+ }
+ $files = [];
+ $archive = new PharData($path);
+ foreach ($tables['media'] as $asset) {
+ $name = self::mediaName($asset['name']);
+ $file = Media::directory() . '/' . $name;
+ if (!is_file($file) || is_link($file) || filesize($file) !== (int) $asset['size']) {
+ throw new RuntimeException('资源文件缺失或大小已变更:' . $name);
+ }
+ $files[$name] = hash_file('sha256', $file);
+ $archive->addFile($file, 'media/' . $name);
+ }
+ $manifest = Database::json(['format' => self::FORMAT, 'version' => self::VERSION, 'exported_at' => gmdate('c'), 'tables' => $tables, 'files' => $files]);
+ if (strlen($manifest) > self::MANIFEST_LIMIT) {
+ throw new RuntimeException('站点内容超过当前备份格式的大小上限。');
+ }
+ $archive->addFromString('site.json', $manifest);
+ });
+ } catch (Throwable $error) {
+ if (is_file($path)) {
+ unlink($path);
+ }
+ throw $error;
+ }
+ }
+
+ public static function import(string $path): void
+ {
+ $archive = new PharData($path);
+ if (!isset($archive['site.json']) || $archive['site.json']->isLink() || $archive['site.json']->getSize() > self::MANIFEST_LIMIT) {
+ throw new RuntimeException('备份清单缺失或过大。');
+ }
+ $manifest = json_decode($archive['site.json']->getContent(), true, 48, JSON_THROW_ON_ERROR);
+ $tables = self::prepare($manifest);
+ $files = $manifest['files'] ?? [];
+ if (!is_array($files) || count($files) !== count($tables['media'])) {
+ throw new RuntimeException('备份资源清单不完整。');
+ }
+ $directory = Media::directory();
+ if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
+ throw new RuntimeException('不能写入资源目录。');
+ }
+ $stage = $directory . '/.restore-' . bin2hex(random_bytes(12));
+ if (!mkdir($stage, 0700)) {
+ throw new RuntimeException('不能创建临时资源目录。');
+ }
+ $staged = [];
+ $installed = [];
+ try {
+ foreach ($tables['media'] as $asset) {
+ $name = self::mediaName($asset['name'] ?? null);
+ $size = $asset['size'] ?? 0;
+ if (!is_int($size) || $size < 1 || $size > Media::MAX_BYTES || isset($staged[$name])
+ || !is_string($files[$name] ?? null) || !isset($archive['media/' . $name])
+ || $archive['media/' . $name]->isLink() || !$archive['media/' . $name]->isFile() || $archive['media/' . $name]->getSize() !== $size) {
+ throw new RuntimeException('备份资源不完整:' . $name);
+ }
+ $staged[$name] = $stage . '/' . $name;
+ $source = fopen('phar://' . $path . '/media/' . $name, 'rb');
+ if ($source === false) {
+ throw new RuntimeException('不能读取备份资源。');
+ }
+ try {
+ $destination = fopen($staged[$name], 'xb');
+ if ($destination === false) {
+ throw new RuntimeException('不能暂存备份资源。');
+ }
+ try {
+ $written = stream_copy_to_stream($source, $destination, $size + 1);
+ } finally {
+ fclose($destination);
+ }
+ } finally {
+ fclose($source);
+ }
+ if ($written !== $size || !hash_equals($files[$name], hash_file('sha256', $staged[$name]))) {
+ throw new RuntimeException('备份资源校验失败:' . $name);
+ }
+ Media::validateBackup($staged[$name], $name, $asset['mime'] ?? '', $size);
+ }
+ Database::write(function (PDO $pdo) use ($tables, $staged, $directory, &$installed): void {
+ self::replaceTables($pdo, $tables);
+ foreach ($staged as $name => $source) {
+ $target = $directory . '/' . $name;
+ if (is_file($target) && !is_link($target) && hash_file('sha256', $target) === hash_file('sha256', $source)) {
+ continue;
+ }
+ if (file_exists($target) || is_link($target) || !link($source, $target)) {
+ throw new RuntimeException('资源名称冲突:' . $name);
+ }
+ $installed[] = $target;
+ }
+ });
+ } catch (Throwable $error) {
+ foreach ($installed as $file) {
+ unlink($file);
+ }
+ throw $error;
+ } finally {
+ foreach ($staged as $file) {
+ if (is_file($file)) {
+ unlink($file);
+ }
+ }
+ rmdir($stage);
+ }
+ }
+
+ private static function prepare(mixed $manifest): array
+ {
+ if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT
+ || !in_array($manifest['version'] ?? null, [1, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
+ throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
+ }
+ $tables = $manifest['tables'];
+ if ($manifest['version'] === 1) {
+ $tables += ['design_presets' => [], 'article_deletions' => []];
+ }
+ foreach (self::TABLES as $table) {
+ if (!is_array($tables[$table] ?? null) || !array_is_list($tables[$table])) {
+ throw new RuntimeException('备份数据表不完整。');
+ }
+ foreach ($tables[$table] as $row) {
+ if (!is_array($row) || array_is_list($row)) {
+ throw new RuntimeException('备份数据行格式无效。');
+ }
+ }
+ }
+ if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
+ throw new RuntimeException('备份缺少站点身份或首页。');
+ }
+ $designs = [];
+ foreach ($tables['design_presets'] as &$row) {
+ $payload = self::decode($row['payload'] ?? '');
+ $row['payload'] = Database::json(DesignLibrary::normalize($row['kind'] ?? '', $row['preset'] ?? '', $payload));
+ $designs[$row['id']] = $row['kind'];
+ }
+ unset($row);
+ $settings = self::decode($tables['site_settings'][0]['payload'] ?? '');
+ if (!is_string($settings['name'] ?? null) || trim($settings['name']) === '' || mb_strlen($settings['name']) > 100) {
+ throw new RuntimeException('备份的站点名称无效。');
+ }
+ $site = ['name' => $settings['name'], 'cdn' => ['origin' => Assets::cdn($settings['cdn']['origin'] ?? '')], 'revisions' => ['general' => time()]];
+ foreach (['header', 'footer'] as $kind) {
+ if (isset($settings[$kind . '_id'])) {
+ $site[$kind . '_id'] = self::selection($designs, $kind, $settings[$kind . '_id']);
+ }
+ }
+ $tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
+ foreach ($tables['pages'] as &$row) {
+ PageDraft::slug($row['slug'] ?? null, ['admin', 'assets', 'account', 'mcp', 'palette', 'favicon']);
+ self::validateAssetUrl($row['image'] ?? '', true);
+ $row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
+ $row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
+ $row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
+ $row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
+ if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
+ $row['theme'] = '';
+ }
+ foreach (['header', 'footer', 'palette'] as $kind) {
+ $row[$kind . '_id'] = self::selection($designs, $kind, $row[$kind . '_id'] ?? null);
+ }
+ }
+ unset($row);
+ foreach ($tables['sections'] as &$row) {
+ PageDraft::slug($row['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
+ if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links'], true)) {
+ throw new RuntimeException('备份包含未知区块样式。');
+ }
+ $row['body'] = Html::sanitize($row['body'] ?? '');
+ if (isset($row['feed'])) {
+ $feed = self::decode($row['feed']);
+ if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
+ || !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
+ || array_diff($feed['categories'], array_column($tables['article_categories'], 'slug'))
+ || !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
+ throw new RuntimeException('备份的动态区块配置无效。');
+ }
+ }
+ }
+ unset($row);
+ foreach ($tables['articles'] as &$row) {
+ if (($row['body_format'] ?? '') === 'html') {
+ $row['body'] = Html::sanitize($row['body'] ?? '');
+ }
+ $card = self::decode($row['card'] ?? '{}');
+ foreach (['url', 'extra_url', 'image'] as $field) {
+ self::validateAssetUrl($card[$field] ?? '', $field === 'image');
+ }
+ $row['tags'] = Database::json(self::decode($row['tags'] ?? '[]'));
+ }
+ unset($row);
+
+ return $tables;
+ }
+
+ private static function replaceTables(PDO $pdo, array $tables): void
+ {
+ $revisions = [];
+ foreach (self::TABLES as $table) {
+ $columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
+ $revisions[$table] = in_array('version', $columns, true) ? max(1, (int) $pdo->query('SELECT MAX(version) FROM ' . $table)->fetchColumn() + 1) : 0;
+ }
+ foreach (array_reverse(self::TABLES) as $table) {
+ $pdo->exec('DELETE FROM ' . $table);
+ }
+ foreach (self::TABLES as $table) {
+ $columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
+ foreach ($tables[$table] as $row) {
+ $row = array_intersect_key($row, array_flip($columns));
+ if ($revisions[$table]) {
+ $row['version'] = $revisions[$table];
+ }
+ if (!$row) {
+ throw new RuntimeException('备份缺少必要的数据列。');
+ }
+ $keys = array_keys($row);
+ $query = $pdo->prepare('INSERT INTO ' . $table . ' ("' . implode('","', $keys) . '") VALUES (' . implode(',', array_fill(0, count($row), '?')) . ')');
+ $query->execute(array_values($row));
+ }
+ }
+ }
+
+ private static function selection(array $designs, string $kind, mixed $id): ?int
+ {
+ if ($id === null) {
+ return null;
+ }
+ if (!is_int($id) || ($designs[$id] ?? '') !== $kind) {
+ throw new RuntimeException('备份引用了缺失的设计方案。');
+ }
+ return $id;
+ }
+
+ private static function decode(mixed $value): array
+ {
+ $data = is_string($value) ? json_decode($value, true, 32, JSON_THROW_ON_ERROR) : null;
+ if (!is_array($data)) {
+ throw new RuntimeException('备份中的配置格式无效。');
+ }
+ return $data;
+ }
+
+ private static function validateAssetUrl(mixed $url, bool $media): void
+ {
+ if (!is_string($url) || ($url !== '' && !Html::url($url, $media))) {
+ throw new RuntimeException('备份含有无效的资源地址。');
+ }
+ }
+
+ private static function mediaName(mixed $name): string
+ {
+ if (!is_string($name) || !preg_match('/^[a-f0-9]{32}\.[a-z0-9]+$/D', $name)) {
+ throw new RuntimeException('备份含有无效的资源名称。');
+ }
+ return $name;
+ }
+}
diff --git a/app/Content/SiteDesign.php b/app/Content/SiteDesign.php
new file mode 100644
index 0000000..c519090
--- /dev/null
+++ b/app/Content/SiteDesign.php
@@ -0,0 +1,47 @@
+ 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
+ throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
+ }
+ $links[] = [$url, $label];
+ }
+
+ return $links;
+ }
+
+ public static function linkText(array $links): string
+ {
+ return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
+ }
+
+ public static function saveGeneral(string $name, string $origin, int $version): void
+ {
+ Database::write(function (PDO $pdo) use ($name, $origin, $version): void {
+ $site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
+ if (($site['revisions']['general'] ?? 0) !== $version) {
+ throw new RuntimeException('站点设置已更新,请重新打开后再保存。');
+ }
+ $site['name'] = $name;
+ $site['cdn'] = ['origin' => $origin];
+ $site['revisions']['general'] = $version + 1;
+ $pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
+ });
+ }
+}
diff --git a/app/Content/View.php b/app/Content/View.php
new file mode 100644
index 0000000..90abdff
--- /dev/null
+++ b/app/Content/View.php
@@ -0,0 +1,108 @@
+ $html]), $cdn);
+ $assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
+ $articleEditor = $admin && !empty($data['articleEditor']);
+ $editorImages = $articleEditor ? ' data:' : '';
+ $editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
+ $headers = [
+ 'Content-Type' => 'text/html; charset=utf-8',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'Referrer-Policy' => 'strict-origin-when-cross-origin',
+ 'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
+ 'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:$editorImages; media-src 'self' https:; "
+ . "style-src $assetSources; {$editorStyles}script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
+ . (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
+ ];
+ if ($admin || !empty($data['previewMode'])) {
+ $headers['Cache-Control'] = 'no-store';
+ $headers['X-Robots-Tag'] = 'noindex, nofollow';
+ } elseif (($data['noindex'] ?? false) || $status >= 400) {
+ $headers['X-Robots-Tag'] = 'noindex';
+ }
+
+ if ($personalized) {
+ $headers['Cache-Control'] = 'private, no-store';
+ $headers['Vary'] = 'Cookie';
+ }
+ return new Response($status, $headers, $page);
+ }
+
+ public static function fragment(string $template, array $data = []): string
+ {
+ extract($data, EXTR_SKIP);
+ ob_start();
+ try {
+ require dirname(__DIR__) . '/view/' . $template . '.php';
+
+ return (string) ob_get_contents();
+ } finally {
+ ob_end_clean();
+ }
+ }
+
+ public static function escape(string|int|null $value): string
+ {
+ return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
+ }
+
+ public static function absolute(string $path): string
+ {
+ return rtrim(getenv('LAYSITE_SITE_URL') ?: 'http://127.0.0.1:8787', '/') . $path;
+ }
+
+ public static function date(?string $value, string $format = 'Y年n月j日'): string
+ {
+ return $value ? date($format, strtotime($value)) : '';
+ }
+
+ public static function alignmentClass(?string $alignment): string
+ {
+ return in_array($alignment, Html::ALIGNMENTS, true) ? ' studio-align-' . $alignment : '';
+ }
+
+ public static function archivePage(string $path, int $page): string
+ {
+ if ($page === 1) {
+ return $path;
+ }
+
+ return $path . (str_contains($path, '?') ? '&' : '?') . 'page=' . $page;
+ }
+
+ public static function redirect(string $path, int $status = 303): Response
+ {
+ return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], '');
+ }
+}
diff --git a/app/Controller/AccountController.php b/app/Controller/AccountController.php
new file mode 100644
index 0000000..3db9d14
--- /dev/null
+++ b/app/Controller/AccountController.php
@@ -0,0 +1,110 @@
+provider((int) $id);
+ if ($config === []) {
+ return $this->page($request, '该用户区尚未配置登录。', 404);
+ }
+ try {
+ $provider = new IdentityProvider($config);
+ $nonce = bin2hex(random_bytes(32));
+ $url = $provider->authorization($nonce);
+ $session = VisitorSession::create();
+ $session->set('flow', [
+ 'layout' => (int) $id, 'config' => $this->fingerprint($config), 'nonce' => $nonce,
+ 'state' => $provider->client->getState(), 'proof' => $provider->client->getPkceCode(), 'expires' => time() + 600,
+ ]);
+ $session->save();
+ return VisitorSession::cookie(View::redirect($url), $session, 600);
+ } catch (Throwable $error) {
+ error_log('LaySite account login: ' . get_class($error));
+ return $this->page($request, '无法连接身份服务,请联系站点管理员。', 502);
+ }
+ }
+
+ public function callback(Request $request): Response
+ {
+ $session = VisitorSession::open($request);
+ $flow = $session?->get('flow');
+ $state = $request->get('state');
+ $code = $request->get('code');
+ if (!is_array($flow) || $flow['expires'] < time() || !is_string($state) || !hash_equals($flow['state'], $state)
+ || !is_string($code) || $code === '' || strlen($code) > 4096) {
+ return $this->page($request, '登录请求已过期或未完成,请重新登录。', 400);
+ }
+ $session->flush();
+ $session->save();
+ try {
+ $config = $this->provider($flow['layout']);
+ if (!$config || $this->fingerprint($config) !== $flow['config']) {
+ return $this->page($request, '登录配置已变更,请重新登录。', 409);
+ }
+ $profile = (new IdentityProvider($config))->profile($code, $flow['proof'], $flow['nonce']);
+ $current = VisitorSession::create();
+ $current->set('profile', $profile + [
+ 'layout' => $flow['layout'], 'config' => $flow['config'], 'expires' => time() + 28800, 'logout' => bin2hex(random_bytes(32)),
+ ]);
+ $current->save();
+ return VisitorSession::cookie(View::redirect('/account'), $current, 28800);
+ } catch (Throwable $error) {
+ error_log('LaySite account callback: ' . get_class($error));
+ return $this->page($request, '身份验证失败,请重新登录。', 502);
+ }
+ }
+
+ public function index(Request $request): Response
+ {
+ return $this->page($request);
+ }
+
+ public function logout(Request $request): Response
+ {
+ $profile = VisitorSession::profile($request);
+ $token = $request->post('token');
+ if (!$profile || !is_string($token) || !hash_equals($profile['logout'], $token)) {
+ return $this->page($request, '退出请求已过期。', 403);
+ }
+ $session = VisitorSession::open($request);
+ $session->flush();
+ $session->save();
+
+ return VisitorSession::cookie(View::redirect('/'), null, 0);
+ }
+
+ private function page(Request $request, string $error = '', int $status = 200): Response
+ {
+ return View::render('account', [
+ 'site' => (new Repository())->site(), 'title' => '用户中心', 'description' => '', 'path' => '/account',
+ 'error' => $error, 'profile' => VisitorSession::profile($request), 'noindex' => true,
+ ], $status)->withHeader('Cache-Control', 'private, no-store');
+ }
+
+ private function provider(int $id): array
+ {
+ $row = DesignLibrary::find($id, 'header');
+
+ return ($row['preset'] ?? '') === 'member' && in_array('account', $row['payload']['components'], true)
+ ? $row['payload']['provider'] : [];
+ }
+
+ private function fingerprint(array $config): string
+ {
+ return hash('sha256', json_encode($config, JSON_THROW_ON_ERROR));
+ }
+}
diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php
new file mode 100644
index 0000000..3e1f7b7
--- /dev/null
+++ b/app/Controller/AdminController.php
@@ -0,0 +1,662 @@
+signedIn($request)) {
+ return $this->success($request, '/admin');
+ }
+
+ $data = ['title' => '登录内容管理', 'error' => '', 'email' => ''];
+ if ($request->method() !== 'POST') {
+ return $this->render($request, 'admin-login', $data);
+ }
+
+ $data['email'] = strtolower($this->input($request, 'email'));
+ if (!$this->validToken($request)) {
+ $data['error'] = '登录表单已更新,请重新提交。若反复出现此提示,请确认浏览器允许本站 Cookie。';
+
+ return $this->render($request, 'admin-login', $data, 403);
+ }
+
+ $password = $this->input($request, 'password', trimValue: false);
+ $repo = new Repository();
+ $user = strlen($data['email']) <= 254 ? $repo->administrator($data['email']) : null;
+ $hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG';
+ if (Passwords::isSupported($password) && password_verify($password, $hash) && $user) {
+ $this->openSession($request, $user);
+
+ return $this->success($request, '/admin');
+ }
+
+ $retryAfter = $repo->recordFailedLogin($request->clientAddress());
+ if ($retryAfter > 0) {
+ $data['error'] = '当前来源的密码验证失败次数过多,请核对密码或稍后再试。';
+
+ return $this->render($request, 'admin-login', $data, 429)->withHeader('Retry-After', (string) $retryAfter);
+ }
+
+ $data['error'] = '邮箱或密码有误。';
+
+ return $this->render($request, 'admin-login', $data, 422);
+ }
+
+ public function logout(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $request->session()->flush();
+ $request->session()->save();
+ $request->sessionRegenerateId(true);
+
+ return $this->success($request, '/admin/login');
+ }
+
+ public function password(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+
+ $error = '';
+ if ($request->method() === 'POST') {
+ $current = $this->input($request, 'current_password', trimValue: false);
+ $password = $this->input($request, 'new_password', trimValue: false);
+ $confirmation = $this->input($request, 'confirm_password', trimValue: false);
+ if (!Passwords::isSupported($current) || !password_verify($current, $this->user['password_hash'])) {
+ $error = '当前密码有误。';
+ } elseif (!Passwords::isValidNew($password)) {
+ $error = '新密码至少 8 个字符,最多 72 字节。';
+ } elseif ($password !== $confirmation) {
+ $error = '两次输入的新密码不一致。';
+ } else {
+ try {
+ $newHash = password_hash($password, PASSWORD_DEFAULT);
+ if (!(new Repository())->changePassword($this->user, $newHash)) {
+ throw new RuntimeException('密码已在其他会话中更新,请重新登录。');
+ }
+ $this->openSession($request, array_replace($this->user, ['password_hash' => $newHash]));
+
+ return $this->success($request, '/admin/password?saved=1');
+ } catch (RuntimeException $exception) {
+ $error = $this->validationMessage($exception);
+ }
+ }
+ }
+
+ return $this->render($request, 'admin-password', [
+ 'title' => '修改密码', 'error' => $error, 'saved' => $request->get('saved') === '1',
+ ], $error !== '' ? 422 : 200);
+ }
+
+ public function dashboard(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $repo = new Repository();
+
+ return $this->render($request, 'admin-dashboard', [
+ 'title' => '内容管理', 'pages' => $repo->pages(), 'articles' => $repo->articles(public: false, limit: 5),
+ 'pageTemplateDrawer' => true,
+ ]);
+ }
+
+ public function articles(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $page = max(1, min(10000, (int) $request->get('page', 1)));
+ $repo = new Repository();
+ $categories = $repo->categories();
+ $category = $request->get('category');
+ $category = is_string($category) && isset($categories[$category]) ? $category : null;
+ $articles = $repo->articles($category, public: false, limit: 31, offset: ($page - 1) * 30);
+
+ return $this->render($request, 'admin-articles', [
+ 'title' => '文章与动态', 'articles' => array_slice($articles, 0, 30), 'pageNumber' => $page,
+ 'hasNext' => count($articles) > 30, 'categories' => $categories, 'category' => $category,
+ 'deleted' => $request->get('deleted') === '1',
+ ]);
+ }
+
+ public function articleCategories(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $repo = new Repository();
+ $name = $slug = $error = '';
+ if ($request->method() === 'POST') {
+ $slug = $this->input($request, 'slug');
+ $name = $this->input($request, 'name');
+ try {
+ if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $slug) || strlen($slug) > 60 || $name === '' || mb_strlen($name) > 60) {
+ throw new RuntimeException('请填写分类名称及网址标识。');
+ }
+ $repo->createCategory($slug, $name);
+
+ return $this->success($request, '/admin/article-categories?saved=1');
+ } catch (RuntimeException $exception) {
+ $error = $this->validationMessage($exception);
+ }
+ }
+
+ return $this->render($request, 'admin-article-categories', [
+ 'title' => '文章分类', 'categories' => $repo->categories(), 'name' => $name, 'slug' => $slug,
+ 'error' => $error, 'saved' => $request->get('saved') === '1',
+ ], $error === '' ? 200 : 422);
+ }
+
+ public function article(Request $request, ?string $id = null): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $repo = new Repository();
+ $categories = $repo->categories();
+ $preset = $request->get('category');
+ $preset = is_string($preset) && isset($categories[$preset]) ? $preset : 'news';
+ $article = $id !== null ? $repo->articleById((int) $id) : [
+ 'title' => '', 'slug' => '', 'summary' => '', 'body' => '', 'body_format' => 'markdown',
+ 'categories' => [$preset => $categories[$preset]], 'card' => [], 'tags' => [], 'status' => 'draft', 'version' => 0,
+ ];
+ if (!$article) {
+ return $this->error($request, '找不到这篇文章。', 404);
+ }
+ $error = '';
+ if ($request->method() === 'POST') {
+ $data = $this->articleInput($request);
+ $article = array_replace($article, $data, [
+ 'categories' => array_intersect_key($categories, array_flip($data['categories'])),
+ 'version' => $this->version($request),
+ ]);
+ try {
+ if (mb_strlen($data['title']) < 1 || mb_strlen($data['title']) > 120
+ || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $data['slug']) || strlen($data['slug']) > 100
+ || mb_strlen($data['summary']) > 250 || strlen($data['body']) > 200000
+ || $data['categories'] === [] || array_diff($data['categories'], array_keys($categories))
+ || !in_array($data['body_format'], ['markdown', 'html'], true)
+ || !in_array($data['status'], ['draft', 'published'], true)) {
+ throw new RuntimeException('请检查标题、网址标识、分类、摘要和正文长度。');
+ }
+ $this->checkArticleCard($data['card']);
+ if ($data['body_format'] === 'html') {
+ $data['body'] = Html::sanitize($data['body']);
+ }
+ if ($data['status'] === 'published' && trim(Html::articleBody($data)) === ''
+ && (!array_intersect($data['categories'], array_keys(Repository::DIRECTORIES))
+ || ($data['summary'] === '' && empty($data['card']['url']) && empty($data['card']['image'])))) {
+ throw new RuntimeException('发布前请填写文章正文。');
+ }
+ $saved = $repo->saveArticle($id === null ? null : (int) $id, $data, $this->version($request));
+
+ return $this->success($request, '/admin/articles/' . $saved . '?saved=1');
+ } catch (RuntimeException $exception) {
+ $error = $this->validationMessage($exception);
+ }
+ }
+
+ return $this->render($request, 'admin-article', [
+ 'title' => $id === null ? '新建文章' : '编辑文章', 'article' => $article, 'error' => $error,
+ 'articleId' => $id, 'categories' => $categories, 'articleEditor' => true, 'saved' => $request->get('saved') === '1',
+ ], $error !== '' ? 422 : 200);
+ }
+
+ public function deleteArticle(Request $request, string $id): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+
+ try {
+ (new Repository())->deleteArticle((int) $id, $this->version($request));
+ } catch (RuntimeException $exception) {
+ return $this->error($request, $this->validationMessage($exception), $exception instanceof \PDOException ? 500 : 409);
+ }
+
+ return $this->success($request, '/admin/articles?deleted=1');
+ }
+
+ public function page(Request $request, string $slug): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $repo = new Repository();
+ $page = $repo->page($slug);
+ if (!$page) {
+ return $this->error($request, '找不到此页面。', 404);
+ }
+ $error = '';
+ if ($request->method() === 'POST') {
+ $data = [];
+ foreach (['title', 'description', 'heading', 'accent', 'lead', 'image', 'alt'] as $field) {
+ $data[$field] = $this->input($request, $field);
+ }
+ $data['name'] = $request->post('name') === null ? $page['name'] : $this->input($request, 'name');
+ $data['status'] = $request->post('status') === null || $slug === 'home' ? $page['status'] : $this->input($request, 'status');
+ $scale = $this->input($request, 'image_scale');
+ $data['image_scale'] = $request->post('image_scale') === null ? (int) $page['image_scale']
+ : (ctype_digit($scale) ? (int) $scale : -1);
+ $page = array_replace($page, $data, ['version' => $this->version($request)]);
+ try {
+ $data['actions'] = $request->post('hero_actions') === null ? $page['actions']
+ : Buttons::validate(json_decode($this->input($request, 'hero_actions'), true));
+ foreach (['header', 'footer', 'palette'] as $kind) {
+ $key = $kind . '_id';
+ $data[$key] = $request->post($key) === null ? $page[$key] : DesignLibrary::selection($kind, $request->post($key));
+ }
+ $page = array_replace($page, $data);
+ $data['visibility'] = $page['visibility'];
+ foreach (['hero', 'header', 'footer'] as $area) {
+ $value = $request->post('show_' . $area);
+ if ($value === null) {
+ continue;
+ }
+ if (!in_array($value, ['0', '1'], true)) {
+ throw new RuntimeException('页面显示选项不正确。');
+ }
+ $data['visibility'][$area] = $value === '1';
+ }
+ $page['visibility'] = $data['visibility'];
+ $data['alignments'] = $request->post('alignments') === null ? $page['alignments']
+ : $this->alignmentMap(json_decode($this->input($request, 'alignments'), true), ['heading', 'lead', 'actions', 'image']);
+ $page['alignments'] = $data['alignments'];
+ $data['quicklinks'] = $request->post('quicklinks') === null ? $page['quicklinks'] : SiteDesign::parseLinks($this->input($request, 'quicklinks'));
+ if ($data['name'] === '' || mb_strlen($data['name']) > 100 || !in_array($data['status'], ['draft', 'published'], true)
+ || $data['title'] === '' || mb_strlen($data['title']) > 160 ||
+ ($data['status'] === 'published' && $data['description'] === '') || mb_strlen($data['description']) > 300 ||
+ (($data['visibility']['hero'] ?? true) && $data['heading'] === '') || mb_strlen($data['heading'] . $data['accent']) > 110 ||
+ mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 ||
+ ($data['image_scale'] !== 0 && ($data['image_scale'] < 10 || $data['image_scale'] > 100)) ||
+ strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true))) {
+ throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
+ }
+ $sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections'], $repo->categories());
+ $repo->savePage($slug, $data, $this->version($request), $sections);
+
+ return $this->success($request, '/admin/pages/' . $slug . '?saved=1');
+ } catch (RuntimeException $exception) {
+ $error = $this->validationMessage($exception);
+ }
+ }
+
+ return $this->render($request, 'admin-page', [
+ 'title' => '编辑 ' . $page['name'], 'page' => $page, 'categories' => $repo->categories(), 'wideAdmin' => true, 'error' => $error, 'saved' => $request->get('saved') === '1',
+ 'pageTemplateDrawer' => true, 'designs' => DesignLibrary::all(),
+ ], $error !== '' ? 422 : 200);
+ }
+
+ public function section(Request $request, string $slug, string $key): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $repo = new Repository();
+ $section = $repo->section($slug, $key);
+ if (!$section) {
+ return $this->error($request, '找不到此区块。', 404);
+ }
+ $savedStyle = $section['style'];
+ $categories = $repo->categories();
+ $error = '';
+ if ($request->method() === 'POST') {
+ $data = [
+ 'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
+ 'body' => $this->input($request, 'body'),
+ 'style' => $savedStyle === 'hero-links' || $request->post('style') === null ? $savedStyle : $this->input($request, 'style'),
+ 'feed' => $section['feed'],
+ ];
+ $section = array_replace($section, $data, ['version' => $this->version($request)]);
+ try {
+ if ($savedStyle !== 'hero-links' && $request->post('feed_mode') !== null) {
+ $data['feed'] = $section['feed'] = $this->feedInput($request, $categories);
+ }
+ $this->checkSection($data, $savedStyle);
+ $data['body'] = Html::sanitize($data['body']);
+ $repo->saveSection($slug, $key, $data, $this->version($request));
+
+ return $this->success($request, '/admin/pages/' . $slug . '/' . $key . '?saved=1');
+ } catch (RuntimeException $exception) {
+ $error = $this->validationMessage($exception);
+ }
+ }
+
+ return $this->render($request, 'admin-section', [
+ 'title' => '编辑区块', 'section' => $section, 'categories' => $categories, 'savedStyle' => $savedStyle, 'error' => $error, 'saved' => $request->get('saved') === '1',
+ ], $error !== '' ? 422 : 200);
+ }
+
+ private function canvasSections(mixed $payload, array $sections, array $categories): array
+ {
+ if ($payload === '') {
+ return [];
+ }
+ $changes = is_string($payload) ? json_decode($payload, true) : null;
+ if (!is_array($changes) || !array_is_list($changes) || count($changes) > count($sections) + 50) {
+ throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
+ }
+ $available = array_column($sections, null, 'key');
+ $updates = [];
+ foreach ($changes as $change) {
+ $key = $change['key'] ?? null;
+ $version = $change['version'] ?? null;
+ $fields = $change['fields'] ?? [];
+ $alignments = $change['alignments'] ?? null;
+ $feed = $change['feed'] ?? null;
+ $delete = ($change['delete'] ?? false) === true;
+ $isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
+ if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || (!$delete && $fields === [] && $alignments === null && $feed === null)
+ || ($isNew ? (isset($available[$key]) || !preg_match('/^block-[a-f0-9]{32}$/D', $key))
+ : (!isset($available[$key]) || !is_int($version) || $version !== (int) $available[$key]['version']))) {
+ throw new RuntimeException('区块已变更或画布内容无效,请重新打开编辑页。');
+ }
+ if ($delete) {
+ if ($isNew) {
+ throw new RuntimeException('未保存的区块无需提交删除。');
+ }
+ $updates[$key] = compact('key', 'version', 'delete');
+ continue;
+ }
+ $section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
+ if ($isNew && isset($change['template'])) {
+ $preset = is_string($change['template']) ? BlockTemplates::find($change['template']) : null;
+ if ($preset === null) {
+ throw new RuntimeException('区块模板已失效。');
+ }
+ $section['feed'] = $preset[3] ?? null;
+ $section['style'] = $preset[4] ?? 'plain';
+ }
+ if ($isNew && isset($change['copyOf'])) {
+ $source = $change['copyOf']['key'] ?? null;
+ $sourceVersion = $change['copyOf']['version'] ?? null;
+ if (!is_string($source) || empty($available[$source]['feed']) || $sourceVersion !== (int) $available[$source]['version']) {
+ throw new RuntimeException('原模块已变更,请刷新画布后再复制。');
+ }
+ $section = array_replace($available[$source], ['key' => $key]);
+ }
+ if ($feed !== null) {
+ if (!is_array($feed) || empty($section['feed'])) {
+ throw new RuntimeException('模块设置不正确。');
+ }
+ $section['feed'] = $this->encodeFeed($feed['mode'] ?? null, $feed['categories'] ?? null, $feed['limit'] ?? null, $categories);
+ }
+ foreach ($fields as $field => $value) {
+ if (!in_array($field, ['title', 'lead', 'body'], true)) {
+ throw new RuntimeException('画布内容无效。');
+ }
+ if ($field === 'body' && is_array($value)) {
+ $value = Html::applyCanvasEdits($section['body'], $value);
+ }
+ if (!is_string($value)) {
+ throw new RuntimeException('画布内容无效。');
+ }
+ $section[$field] = trim($value);
+ }
+ if ($alignments !== null) {
+ $section['alignments'] = Database::json($this->alignmentMap($alignments, ['title', 'lead']));
+ }
+ $this->checkSection($section, $section['style']);
+ if (isset($fields['body'])) {
+ $section['body'] = Html::sanitize($section['body']);
+ }
+ $section['version'] = $version;
+ $updates[$key] = $section;
+ }
+
+ return $updates;
+ }
+
+ private function alignmentMap(mixed $alignments, array $fields): array
+ {
+ if (!is_array($alignments) || array_diff(array_keys($alignments), $fields)) {
+ throw new RuntimeException('画布对齐设置无效。');
+ }
+ foreach ($alignments as $value) {
+ if (!in_array($value, Html::ALIGNMENTS, true)) {
+ throw new RuntimeException('画布对齐设置无效。');
+ }
+ }
+
+ return $alignments;
+ }
+
+ private function checkSection(array $section, string $savedStyle): void
+ {
+ if ($section['title'] === '' || mb_strlen($section['title']) > 100 || mb_strlen($section['lead']) > 500
+ || strlen($section['body']) > 300000 || !in_array($section['style'], [$savedStyle, 'plain', 'tinted'], true)) {
+ throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
+ }
+ }
+
+ public function preview(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $body = $this->input($request, 'body');
+ if (strlen($body) > 300000) {
+ return $this->error($request, '正文太长。', 413);
+ }
+ $html = $this->input($request, 'format') === 'html' ? Html::sanitize($body) : Html::markdown($body);
+
+ return new Response(200, [
+ 'Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'X-Robots-Tag' => 'noindex, nofollow',
+ 'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'; sandbox",
+ ], $html);
+ }
+
+ protected function guard(Request $request): ?Response
+ {
+ if (!$this->signedIn($request)) {
+ return $request->isAjax()
+ ? $this->json(['message' => '登录已过期。请在新标签页重新登录,再返回继续编辑。'], 401)
+ : View::redirect('/admin/login');
+ }
+ if ($request->method() === 'POST' && !$this->validToken($request)) {
+ return $this->error($request, '表单凭证已更新,请重新提交。', 403);
+ }
+
+ return null;
+ }
+
+ private function signedIn(Request $request): bool
+ {
+ $session = $request->session();
+ $id = $session->get('admin_id');
+ if (!is_int($id) || (int) $session->get('admin_since') < time() - 8 * 60 * 60) {
+ return false;
+ }
+ $user = (new Repository())->administratorById($id);
+ if (!$user || !hash_equals(hash('sha256', $user['password_hash']), (string) $session->get('auth_version'))) {
+ $session->flush();
+ $session->save();
+
+ return false;
+ }
+ $this->user = $user;
+
+ return true;
+ }
+
+ private function openSession(Request $request, array $user): void
+ {
+ $request->sessionRegenerateId(true);
+ $session = $request->session();
+ $session->flush();
+ $session->put([
+ 'admin_id' => $user['id'],
+ 'auth_version' => hash('sha256', $user['password_hash']),
+ 'admin_since' => time(),
+ ]);
+ $this->token($request);
+ }
+
+ private function token(Request $request): string
+ {
+ $session = $request->session();
+ $token = $session->get('csrf');
+ if (!is_string($token)) {
+ $token = bin2hex(random_bytes(32));
+ $session->set('csrf', $token);
+ $session->save();
+ }
+
+ return $token;
+ }
+
+ private function validToken(Request $request): bool
+ {
+ $token = $request->session()->get('csrf');
+
+ return is_string($token) && hash_equals($token, $this->input($request, 'csrf'));
+ }
+
+ protected function input(Request $request, string $key, bool $trimValue = true): string
+ {
+ $value = $request->post($key, '');
+ if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')) {
+ return '';
+ }
+
+ return $trimValue ? trim($value) : $value;
+ }
+
+ protected function version(Request $request): int
+ {
+ $version = $this->input($request, 'version');
+
+ return ctype_digit($version) ? (int) $version : -1;
+ }
+
+ private function articleInput(Request $request): array
+ {
+ $data = [];
+ foreach (['title', 'slug', 'summary', 'body', 'status'] as $key) {
+ $data[$key] = $this->input($request, $key);
+ }
+ $data['body_format'] = $this->input($request, 'body_format');
+ $data['categories'] = $this->selectedCategories($request->post('categories'));
+ foreach (['image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'category_label', 'position'] as $field) {
+ $data['card'][$field] = $this->input($request, 'card_' . $field);
+ }
+ $tags = preg_split('/[,,\r\n]+/u', $this->input($request, 'tags'));
+ $data['tags'] = array_values(array_unique(array_slice(array_filter(
+ array_map('trim', $tags),
+ static fn (string $tag): bool => $tag !== '' && mb_strlen($tag) <= 80 && !str_contains($tag, '/'),
+ ), 0, 12)));
+
+ return $data;
+ }
+
+ private function checkArticleCard(array &$card): void
+ {
+ foreach (['image', 'url', 'extra_url'] as $field) {
+ if (!empty($card[$field]) && (strlen($card[$field]) > 2000 || !Html::url($card[$field], $field === 'image'))) {
+ throw new RuntimeException('请检查目录卡片的媒体地址和链接。');
+ }
+ }
+ foreach (['alt', 'label', 'extra_label', 'category_label'] as $field) {
+ if (mb_strlen($card[$field] ?? '') > 120) {
+ throw new RuntimeException('目录卡片的文字不得超过 120 字。');
+ }
+ }
+ $position = filter_var(($card['position'] ?? '') === '' ? 0 : $card['position'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 9999]]);
+ if ($position === false) {
+ throw new RuntimeException('目录排序应为 0 到 9999 的整数。');
+ }
+ $card['position'] = $position;
+ }
+
+ private function selectedCategories(mixed $input): array
+ {
+ return is_array($input) ? array_values(array_unique(array_filter($input, 'is_string'))) : [];
+ }
+
+ private function feedInput(Request $request, array $available): ?string
+ {
+ $mode = $this->input($request, 'feed_mode');
+ if ($mode === 'off') {
+ return null;
+ }
+ return $this->encodeFeed($mode, $request->post('feed_categories'), $this->input($request, 'feed_limit'), $available);
+ }
+
+ private function encodeFeed(mixed $mode, mixed $selected, mixed $value, array $available): string
+ {
+ $categories = $this->selectedCategories($selected);
+ $limit = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]);
+ if (!in_array($mode, ['merged', 'tabs', 'network', 'catalog'], true) || !$categories || array_diff($categories, array_keys($available)) || $limit === false) {
+ throw new RuntimeException('请选择文章分类,并将展示数量设为 1 至 30。');
+ }
+
+ return Database::json(compact('categories', 'mode', 'limit'));
+ }
+
+ protected function validationMessage(RuntimeException $exception): string
+ {
+ if ($exception instanceof \PDOException) {
+ error_log($exception->getMessage());
+
+ return '保存失败,请稍后重试。';
+ }
+
+ return $exception->getMessage();
+ }
+
+ protected function success(Request $request, string $path): Response
+ {
+ return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
+ }
+
+ protected function json(array $payload, int $status = 200): Response
+ {
+ return new Response($status, [
+ 'Content-Type' => 'application/json; charset=utf-8',
+ 'Cache-Control' => 'no-store',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-Robots-Tag' => 'noindex, nofollow',
+ ], Database::json($payload));
+ }
+
+ protected function render(Request $request, string $view, array $data, int $status = 200): Response
+ {
+ $token = $this->token($request);
+ if ($request->isAjax() && $status >= 400) {
+ return $this->json([
+ 'message' => $data['error'] ?? $data['title'],
+ ...($status === 403 ? ['csrf' => $token] : []),
+ ], $status);
+ }
+
+ return View::render($view, $data + ['token' => $token, 'user' => $this->user, 'adminPath' => $request->path()], $status, true);
+ }
+
+ protected function error(Request $request, string $message, int $status): Response
+ {
+ return $this->render($request, 'admin-error', ['title' => $message], $status);
+ }
+}
diff --git a/app/Controller/BackupController.php b/app/Controller/BackupController.php
new file mode 100644
index 0000000..6bd6444
--- /dev/null
+++ b/app/Controller/BackupController.php
@@ -0,0 +1,78 @@
+guard($request)) {
+ return $failure;
+ }
+ $error = '';
+ if ($request->method() === 'POST') {
+ $path = null;
+ try {
+ $file = $request->file('backup');
+ if ($request->post('replace') !== '1' || !$file instanceof \Webman\Http\UploadFile || !$file->isValid()) {
+ throw new RuntimeException('请选择备份文件并确认覆盖站点内容。');
+ }
+ $path = $this->temporary();
+ if (!copy($file->getPathname(), $path)) {
+ throw new RuntimeException('不能暂存备份文件。');
+ }
+ SiteBackup::import($path);
+ return $this->success($request, '/admin/backup?restored=1');
+ } catch (Throwable $ex) {
+ $error = $ex instanceof RuntimeException && !$ex instanceof \PDOException
+ ? $ex->getMessage() : '备份无法导入。请检查文件格式或服务器日志。';
+ } finally {
+ if ($path && is_file($path)) {
+ unlink($path);
+ }
+ }
+ }
+ return $this->render($request, 'admin-backup', [
+ 'title' => '站点备份', 'error' => $error, 'restored' => $request->get('restored') === '1',
+ ], $error === '' ? 200 : 422);
+ }
+
+ public function export(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ try {
+ $path = $this->temporary();
+ SiteBackup::export($path);
+ Timer::add(600, static function () use ($path): void {
+ if (is_file($path)) {
+ unlink($path);
+ }
+ }, [], false);
+ return (new Response(200, ['Content-Type' => 'application/x-tar', 'Cache-Control' => 'no-store',
+ 'X-Content-Type-Options' => 'nosniff', 'Content-Disposition' => 'attachment; filename="laysite-' . gmdate('Ymd-His') . '.tar"']))->withFile($path);
+ } catch (Throwable $ex) {
+ return $this->error($request, '无法创建站点备份,请检查文件权限和媒体文件。', 500);
+ }
+ }
+
+ private function temporary(): string
+ {
+ $directory = runtime_path('backups');
+ if (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory)) {
+ throw new RuntimeException('不能创建临时备份目录。');
+ }
+
+ return $directory . '/' . bin2hex(random_bytes(20)) . '.tar';
+ }
+}
diff --git a/app/Controller/DesignController.php b/app/Controller/DesignController.php
new file mode 100644
index 0000000..e58ffa3
--- /dev/null
+++ b/app/Controller/DesignController.php
@@ -0,0 +1,149 @@
+guard($request)) {
+ return $failure;
+ }
+
+ return $this->render($request, 'admin-design', [
+ 'title' => '站点设计', 'items' => DesignLibrary::all(), 'site' => (new Repository())->site(),
+ ]);
+ }
+
+ public function edit(Request $request, string $kind, string $key): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $id = $key === 'new' ? null : (int) $key;
+ $item = $id === null ? [
+ 'name' => '', 'preset' => array_key_first(DesignLibrary::PRESETS[$kind]),
+ 'payload' => DesignLibrary::defaults($kind), 'version' => 0,
+ ] : DesignLibrary::find($id, $kind);
+ if (!$item) {
+ return $this->error($request, '找不到这项设计配置。', 404);
+ }
+ $error = '';
+ $default = $id !== null && ((new Repository())->site()[$kind . '_id'] ?? null) === $id;
+ if ($request->method() === 'POST') {
+ try {
+ $item['name'] = $this->input($request, 'name');
+ $item['preset'] = $this->input($request, 'preset');
+ if ($kind === 'palette') {
+ foreach (DesignLibrary::COLORS as $color => $definition) {
+ $item['payload'][$color] = $this->input($request, $color);
+ }
+ } else {
+ $url = $this->input($request, 'action_url');
+ $label = $this->input($request, 'action_label');
+ $item['payload'] = [
+ 'components' => $request->post('components', []),
+ 'brand' => $this->input($request, 'brand'), 'logo' => $this->input($request, 'logo'),
+ 'text' => $this->input($request, 'text'), 'legal' => $this->input($request, 'legal'),
+ 'links' => SiteDesign::parseLinks($this->input($request, 'links')),
+ 'action' => $url === '' && $label === '' ? [] : [[$url, $label, $this->input($request, 'action_style'), $request->post('action_blank') === '1']],
+ 'provider' => [],
+ ];
+ foreach (['mode', 'issuer', 'authorization', 'token', 'userinfo', 'client_id', 'secret_env', 'scope', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
+ $item['payload']['provider'][$field] = $this->input($request, 'provider_' . $field);
+ }
+ }
+ $default = $request->post('make_default') === '1';
+ $id = DesignLibrary::save($kind, $id, $item['name'], $item['preset'], $item['payload'], $this->version($request), $default);
+
+ return $this->success($request, "/admin/design/$kind/$id?saved=1");
+ } catch (RuntimeException $ex) {
+ $error = $this->validationMessage($ex);
+ $item['payload'] = DesignLibrary::defaults($kind);
+ }
+ }
+
+ return $this->render($request, 'admin-design-edit', [
+ 'title' => '设计配置', 'kind' => $kind, 'key' => $key, 'item' => $item, 'default' => $default,
+ 'error' => $error, 'saved' => $request->get('saved') === '1',
+ ], $error === '' ? 200 : 422);
+ }
+
+ public function site(Request $request): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ $site = (new Repository())->site();
+ $error = '';
+ $name = $site['name'];
+ $cdn = $site['cdn']['origin'] ?? '';
+ $version = (int) ($site['revisions']['general'] ?? 0);
+ if ($request->method() === 'POST') {
+ try {
+ $name = $this->input($request, 'name');
+ $cdn = Assets::cdn($this->input($request, 'cdn'));
+ if ($name === '' || mb_strlen($name) > 100) {
+ throw new RuntimeException('站点名称必须为 1 至 100 个字符。');
+ }
+ SiteDesign::saveGeneral($name, $cdn, $this->version($request));
+
+ return $this->success($request, '/admin/settings?saved=1');
+ } catch (RuntimeException $ex) {
+ $error = $this->validationMessage($ex);
+ }
+ }
+
+ return $this->render($request, 'studio-settings', [
+ 'title' => '站点设置', 'name' => $name, 'cdn' => $cdn, 'version' => $version, 'error' => $error,
+ 'saved' => $request->get('saved') === '1',
+ ], $error === '' ? 200 : 422);
+ }
+
+ public function preview(Request $request, string $kind, string $id): Response
+ {
+ if ($failure = $this->guard($request)) {
+ return $failure;
+ }
+ if (!DesignLibrary::find((int) $id, $kind)) {
+ return $this->error($request, '找不到这项设计配置。', 404);
+ }
+ $repo = new Repository();
+ $page = $repo->page('home');
+ $page[$kind . '_id'] = (int) $id;
+ if ($kind !== 'palette') {
+ $page['visibility'][$kind] = true;
+ }
+
+ return (new SiteController())->renderPage($repo, $page, true);
+ }
+
+ public function palette(Request $request, string $id): Response
+ {
+ $palette = DesignLibrary::find((int) $id, 'palette');
+ if (!$palette) {
+ return new Response(404);
+ }
+ $declarations = [];
+ foreach ($palette['payload'] as $variable => $value) {
+ $declarations[] = '--' . $variable . ':' . $value;
+ }
+
+ return new Response(200, [
+ 'Content-Type' => 'text/css; charset=utf-8', 'Cache-Control' => 'public, max-age=60',
+ 'X-Content-Type-Options' => 'nosniff',
+ ], ':root, #main-content.page-theme {' . implode(';', $declarations) . '} .page-theme .hero, .hero-home {background:var(--paper)}'
+ . ' #main-content .button-primary, #main-content .button-primary:hover {color:var(--button-ink);background:var(--accent)}');
+ }
+}
diff --git a/app/Controller/McpController.php b/app/Controller/McpController.php
new file mode 100644
index 0000000..927a02d
--- /dev/null
+++ b/app/Controller/McpController.php
@@ -0,0 +1,216 @@
+header('origin');
+ if ($origin !== null && $origin !== '' && $origin !== rtrim(View::absolute(''), '/')) {
+ return new Response(403, ['Cache-Control' => 'no-store']);
+ }
+ $secret = getenv('LAYSITE_MCP_TOKEN');
+ $header = $request->header('authorization', '');
+ if (!is_string($secret) || strlen($secret) < 32 || !is_string($header) || !hash_equals('Bearer ' . $secret, $header)) {
+ return new Response(401, ['WWW-Authenticate' => 'Bearer realm="LaySite MCP"', 'Cache-Control' => 'no-store']);
+ }
+ if ($request->method() !== 'POST') {
+ return new Response(405, ['Allow' => 'POST', 'Cache-Control' => 'no-store']);
+ }
+ if (!preg_match('~^application/json(?:\s*;|$)~i', $request->header('content-type', ''))) {
+ return new Response(415, ['Cache-Control' => 'no-store']);
+ }
+ $protocol = $request->header('mcp-protocol-version');
+ if ($protocol !== null && $protocol !== '' && !in_array($protocol, self::PROTOCOLS, true)) {
+ return new Response(400, ['Cache-Control' => 'no-store']);
+ }
+ $body = $request->rawBody();
+ if (strlen($body) > 1048576) {
+ return new Response(413, ['Cache-Control' => 'no-store']);
+ }
+ $message = json_decode($body, true, 48);
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ return $this->error(null, -32700, 'Invalid JSON');
+ }
+ $id = $message['id'] ?? null;
+ $method = $message['method'] ?? null;
+ if (!is_array($message) || ($message['jsonrpc'] ?? '') !== '2.0' || !is_string($method)
+ || (array_key_exists('id', $message) && !is_int($id) && !is_string($id))) {
+ return $this->error(null, -32600, 'Invalid request');
+ }
+ if (!array_key_exists('id', $message)) {
+ return new Response(202, ['Cache-Control' => 'no-store']);
+ }
+ $params = $message['params'] ?? [];
+ if (!is_array($params)) {
+ return $this->error($id, -32602, 'Invalid params');
+ }
+
+ return match ($method) {
+ 'initialize' => $this->result($id, [
+ 'protocolVersion' => in_array($params['protocolVersion'] ?? null, self::PROTOCOLS, true) ? $params['protocolVersion'] : self::PROTOCOLS[0],
+ 'capabilities' => ['tools' => (object) []], 'serverInfo' => ['name' => 'laysite', 'version' => trim(file_get_contents(dirname(__DIR__, 2) . '/VERSION'))],
+ 'instructions' => 'Create or revise draft pages. A human can open the editor URL to review, refine and publish.',
+ ]),
+ 'ping' => $this->result($id, (object) []),
+ 'tools/list' => $this->result($id, ['tools' => $this->tools()]),
+ 'tools/call' => $this->invoke($id, $params),
+ default => $this->error($id, -32601, 'Method not found'),
+ };
+ }
+
+ private function tools(): array
+ {
+ $string = ['type' => 'string'];
+ $object = static fn (array $properties, array $required = []): array => [
+ 'type' => 'object', 'properties' => (object) $properties, 'required' => $required, 'additionalProperties' => false,
+ ];
+ $optional = [
+ 'name' => $string, 'title' => $string, 'heading' => $string, 'description' => $string, 'lead' => $string,
+ 'accent' => $string, 'image' => $string, 'alt' => $string,
+ 'header_id' => ['type' => ['integer', 'null']], 'footer_id' => ['type' => ['integer', 'null']], 'palette_id' => ['type' => ['integer', 'null']],
+ 'visibility' => $object(['hero' => ['type' => 'boolean'], 'header' => ['type' => 'boolean'], 'footer' => ['type' => 'boolean']]),
+ 'actions' => ['type' => 'array', 'maxItems' => 8, 'items' => ['type' => 'array', 'description' => '[URL, label, style, boolean opensNewTab]. Style: solid, outline, underline, plain.']],
+ 'sections' => ['type' => 'array', 'maxItems' => 50, 'items' => $object([
+ 'key' => $string, 'title' => $string, 'lead' => $string, 'body' => $string,
+ 'style' => ['enum' => ['plain', 'tinted']], 'preset' => $string,
+ ], ['key'])],
+ ];
+ $definitions = [
+ 'list_pages' => ['List pages and their current revisions.', $object([])],
+ 'get_page' => ['Read a page and its editable sections.', $object(['slug' => $string], ['slug'])],
+ 'list_templates' => ['List whole-page templates and reusable components.', $object([])],
+ 'list_designs' => ['List saved header, footer and palette IDs. Authentication settings are private.', $object([])],
+ 'create_draft' => ['Create a draft from content or a template. Returns the editor URL.', $object(['slug' => $string, 'template' => $string] + $optional, ['slug', 'name'])],
+ 'save_draft' => ['Save a draft at the supplied version. A supplied sections array replaces the section list. Omitted fields are preserved.',
+ $object(['slug' => $string, 'version' => ['type' => 'integer', 'minimum' => 0]] + $optional, ['slug', 'version'])],
+ ];
+
+ $tools = [];
+ foreach ($definitions as $name => [$description, $inputSchema]) {
+ $tools[] = compact('name', 'description', 'inputSchema');
+ }
+ return $tools;
+ }
+
+ private function invoke(int|string $id, array $params): Response
+ {
+ $name = $params['name'] ?? null;
+ $args = $params['arguments'] ?? [];
+ if (!is_string($name) || !is_array($args)) {
+ return $this->error($id, -32602, 'Invalid tool call');
+ }
+ $repo = new Repository();
+ try {
+ $data = match ($name) {
+ 'list_pages' => $repo->pages(),
+ 'get_page' => $this->read($repo, PageDraft::slug($args['slug'] ?? null, [])),
+ 'list_templates' => $this->templates(),
+ 'list_designs' => DesignLibrary::all(),
+ 'create_draft' => $this->create($repo, $args),
+ 'save_draft' => $this->save($repo, $args),
+ default => throw new RuntimeException('Unknown tool'),
+ };
+ return $this->result($id, ['content' => [['type' => 'text', 'text' => Database::json($data)]]]);
+ } catch (RuntimeException $error) {
+ $message = $error instanceof PDOException ? 'Could not save the requested change.' : $error->getMessage();
+ return $this->result($id, ['isError' => true, 'content' => [['type' => 'text', 'text' => $message]]]);
+ }
+ }
+
+ private function read(Repository $repo, string $slug): array
+ {
+ $page = $repo->page($slug);
+ if (!$page) {
+ throw new RuntimeException('页面不存在。');
+ }
+ return $page;
+ }
+
+ private function create(Repository $repo, array $args): array
+ {
+ $slug = PageDraft::slug($args['slug'] ?? null);
+ $key = $args['template'] ?? '';
+ $template = $key === '' ? [] : (is_string($key) ? PageTemplates::find($key) : null);
+ if ($template === null) {
+ throw new RuntimeException('整页模板不存在。');
+ }
+ if (!isset($args['name'])) {
+ throw new RuntimeException('请填写页面名称。');
+ }
+ $page = PageDraft::content($args, $template);
+ $repo->createPage($slug, $page['name'], $page);
+
+ return $this->summary($repo, $slug);
+ }
+
+ private function save(Repository $repo, array $args): array
+ {
+ $slug = PageDraft::slug($args['slug'] ?? null);
+ $page = $this->read($repo, $slug);
+ $version = $args['version'] ?? null;
+ if ($page['status'] !== 'draft' || !is_int($version) || $version !== $page['version']) {
+ throw new RuntimeException('只能编辑匹配当前版本的草稿。请重新读取页面。');
+ }
+ $page = PageDraft::content($args, $page);
+ $replace = array_key_exists('sections', $args);
+ $repo->savePage($slug, $page, $version, $replace ? $page['sections'] : [], replaceDraftSections: $replace);
+
+ return $this->summary($repo, $slug);
+ }
+
+ private function summary(Repository $repo, string $slug): array
+ {
+ return ['slug' => $slug, 'version' => $this->read($repo, $slug)['version'],
+ 'editor' => View::absolute('/admin/pages/' . $slug), 'preview' => View::absolute('/admin/pages/' . $slug . '/preview')];
+ }
+
+ private function templates(): array
+ {
+ $pages = [];
+ foreach (PageTemplates::groups() as $theme => $group) {
+ foreach ($group['pages'] as $key => $page) {
+ $pages[$key] = ['name' => $page['name'], 'theme' => $theme, 'description' => $page['description']];
+ }
+ }
+ $blocks = [];
+ foreach (BlockTemplates::groups() as [, $group]) {
+ foreach ($group as $key => $block) {
+ $blocks[$key] = $block[0];
+ }
+ }
+ return compact('pages', 'blocks');
+ }
+
+ private function error(int|string|null $id, int $code, string $message): Response
+ {
+ return $this->json(['jsonrpc' => '2.0', 'id' => $id, 'error' => compact('code', 'message')]);
+ }
+
+ private function result(int|string $id, array|object $result): Response
+ {
+ return $this->json(['jsonrpc' => '2.0', 'id' => $id, 'result' => $result]);
+ }
+
+ private function json(array $payload): Response
+ {
+ return new Response(200, ['Content-Type' => 'application/json', 'Cache-Control' => 'no-store', 'X-Content-Type-Options' => 'nosniff'], Database::json($payload));
+ }
+}
diff --git a/app/Controller/MediaController.php b/app/Controller/MediaController.php
new file mode 100644
index 0000000..0ebb7c4
--- /dev/null
+++ b/app/Controller/MediaController.php
@@ -0,0 +1,45 @@
+ $media['mime'], 'X-Content-Type-Options' => 'nosniff',
+ 'Content-Security-Policy' => "default-src 'none'; sandbox",
+ 'Cache-Control' => 'public, max-age=31536000, immutable',
+ 'Access-Control-Allow-Origin' => '*', 'Accept-Ranges' => 'bytes',
+ ];
+ $range = $request->header('range');
+ if ($range === null) {
+ return (new Response(200, $headers + ['Content-Length' => (string) $length]))->withFile($path);
+ }
+ if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || $parts[1] === '' && $parts[2] === '') {
+ return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
+ }
+ $start = $parts[1] === '' ? max(0, $length - (int) $parts[2]) : (int) $parts[1];
+ $end = $parts[1] === '' || $parts[2] === '' ? $length - 1 : min($length - 1, (int) $parts[2]);
+ if ($end < $start) {
+ return new Response(416, $headers + ['Content-Range' => "bytes */$length"]);
+ }
+ $count = $end - $start + 1;
+
+ return (new Response(206, $headers + ['Content-Length' => (string) $count, 'Content-Range' => "bytes $start-$end/$length"]))
+ ->withFile($path, $start, $count);
+ }
+}
diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php
new file mode 100644
index 0000000..88f335e
--- /dev/null
+++ b/app/Controller/SiteController.php
@@ -0,0 +1,245 @@
+page($request, 'home');
+ }
+
+ public function page(Request $request, string $slug): Response
+ {
+ $repo = new Repository();
+ $page = $repo->page($slug);
+ if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') {
+ return $this->missing($request);
+ }
+ if ($slug === 'articles' && $request->get('page') !== null) {
+ foreach ($page['sections'] as $section) {
+ $feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
+ if (in_array($feed['mode'] ?? null, ['merged', 'tabs'], true)) {
+ return $this->feedArchive($request, $slug, $section['key']);
+ }
+ }
+
+ return $this->missing($request);
+ }
+ return $this->renderPage($repo, $page);
+ }
+
+ public function renderPage(Repository $repo, array $page, bool $preview = false, bool $canvas = false): Response
+ {
+ $slug = $page['slug'];
+ $isHome = $slug === 'home';
+ $showHero = $page['visibility']['hero'] ?? true;
+ $categories = $repo->categories();
+ foreach ($page['sections'] as &$section) {
+ if (!$section['feed']) {
+ continue;
+ }
+ $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
+ $network = $feed['mode'] === 'network';
+ $catalog = $feed['mode'] === 'catalog';
+ $grouped = $network || ($feed['mode'] === 'tabs' && count($feed['categories']) > 1);
+ $archivePath = '/articles/feed/' . $slug . '/' . $section['key'];
+ $section['archivePath'] = $page['status'] === 'published' ? $archivePath : null;
+ $section['articleFeed'] = [];
+ $section['networkFeed'] = $network;
+ $section['catalogFeed'] = $catalog;
+ $section['feedLimit'] = $feed['limit'];
+ foreach ($grouped ? $feed['categories'] : [''] as $category) {
+ $selected = $category === '' ? $feed['categories'] : [$category];
+ $section['articleFeed'][] = [
+ 'categories' => $selected, 'label' => $categories[$category] ?? '',
+ 'articles' => $repo->articles($selected, limit: $feed['limit'], directoryOrder: $network || $catalog),
+ ];
+ }
+ }
+ unset($section);
+
+ return View::render('page', [
+ 'site' => $repo->site(),
+ 'page' => $page,
+ 'path' => $isHome ? '/' : '/' . $slug,
+ 'title' => $page['title'],
+ 'description' => $page['description'],
+ 'socialImage' => $showHero ? $page['image'] : '',
+ 'socialAlt' => $showHero ? $page['alt'] : '',
+ 'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview,
+ ]);
+ }
+
+ public function archive(Request $request, ?string $category = null, ?string $tag = null): Response
+ {
+ $repo = new Repository();
+ $categories = $repo->categories();
+ if ($category !== null && !isset($categories[$category])) {
+ return $this->missing($request);
+ }
+ $title = $category ? $categories[$category] : ($tag ?: '文章与动态');
+ $path = '/articles' . ($category ? '/category/' . $category : ($tag ? '/tag/' . rawurlencode($tag) : ''));
+
+ $categoryLinks = [];
+ foreach (array_keys($categories) as $key) {
+ $categoryLinks[$key] = '/articles/category/' . $key;
+ }
+
+ return $this->renderArchive($request, $repo, $category, $tag, [
+ 'headline' => $title, 'description' => '浏览文章与动态。',
+ 'archivePath' => $path, 'allPath' => '/articles',
+ 'categoryLinks' => $categoryLinks,
+ 'categories' => $categories, 'category' => $category, 'tag' => $tag,
+ 'backPath' => $category || $tag ? '/articles' : null, 'backLabel' => '全部动态',
+ ]);
+ }
+
+ public function feedArchive(Request $request, string $slug, string $key): Response
+ {
+ $repo = new Repository();
+ $section = $repo->publishedFeed($slug, $key);
+ if (!$section) {
+ return $this->missing($request);
+ }
+ $feed = json_decode($section['feed'], true, flags: JSON_THROW_ON_ERROR);
+ $labels = $repo->categories();
+ $categories = [];
+ foreach ($feed['categories'] as $value) {
+ if (isset($labels[$value])) {
+ $categories[$value] = $labels[$value];
+ }
+ }
+ $category = $request->get('category');
+ if (!$categories || ($category !== null && (!is_string($category) || !isset($categories[$category])))) {
+ return $this->missing($request);
+ }
+
+ $allPath = '/articles/feed/' . $slug . '/' . $key;
+ $returnPath = ($slug === 'home' ? '/' : '/' . $slug) . '#' . $key;
+ $categoryLinks = [];
+ foreach (array_keys($categories) as $value) {
+ $categoryLinks[$value] = $allPath . '?category=' . rawurlencode((string) $value);
+ }
+
+ return $this->renderArchive($request, $repo, $category ?? array_keys($categories), null, [
+ 'headline' => $section['title'] . ($category !== null ? ' · ' . $categories[$category] : ''),
+ 'description' => '查看' . implode('、', $categories) . '分类下的文章。',
+ 'archivePath' => $category === null ? $allPath : $categoryLinks[$category], 'allPath' => $allPath,
+ 'categoryLinks' => $categoryLinks, 'categories' => $categories, 'category' => $category, 'tag' => null,
+ 'categoryScope' => $category === null ? array_keys($categories) : [$category],
+ 'catalog' => $feed['mode'] === 'catalog',
+ 'backPath' => $returnPath, 'backLabel' => '返回原页面', 'noindex' => true,
+ ]);
+ }
+
+ private function renderArchive(Request $request, Repository $repo, string|array|null $category, ?string $tag, array $view): Response
+ {
+ $number = $request->get('page', '1');
+ if (!is_scalar($number) || !preg_match('/^[1-9][0-9]{0,4}$/D', (string) $number)) {
+ return $this->missing($request);
+ }
+ $page = (int) $number;
+ $articles = $repo->articles($category, $tag, limit: 21, offset: ($page - 1) * 20, directoryOrder: $view['catalog'] ?? false);
+ if ($page > 1 && $articles === []) {
+ return $this->missing($request);
+ }
+ $path = $view['archivePath'];
+
+ return View::render('archive', $view + [
+ 'site' => $repo->site(), 'title' => $view['headline'],
+ 'path' => $page > 1 ? View::archivePage($path, $page) : $path,
+ 'pageNumber' => $page, 'hasNext' => count($articles) > 20, 'articles' => array_slice($articles, 0, 20),
+ 'noindex' => $articles === [],
+ ]);
+ }
+
+ public function tagged(Request $request, string $tag): Response
+ {
+ $tag = rawurldecode($tag);
+ if (mb_strlen($tag) > 80 || $tag === '') {
+ return $this->missing($request);
+ }
+
+ return $this->archive($request, tag: $tag);
+ }
+
+ public function article(Request $request, string $slug): Response
+ {
+ $repo = new Repository();
+ $article = $repo->published($slug);
+ if (!$article) {
+ $redirect = $repo->articleRedirect($slug);
+
+ return $redirect ? View::redirect('/articles/' . $redirect['slug'], 301) : $this->missing($request);
+ }
+ $articleHtml = Html::articleBody($article);
+
+ return View::render('article', [
+ 'site' => $repo->site(), 'article' => $article, 'articleHtml' => $articleHtml,
+ 'title' => $article['title'],
+ 'description' => $article['summary'] ?: mb_substr(trim(strip_tags($articleHtml)), 0, 150) ?: $article['title'],
+ 'path' => '/articles/' . $article['slug'],
+ 'socialImage' => $article['card']['image'] ?? '', 'socialAlt' => $article['card']['alt'] ?? '',
+ 'noindex' => trim($articleHtml) === '' && !$article['summary'] && empty($article['card']['url']) && empty($article['card']['image']),
+ ]);
+ }
+
+ public function sitemap(Request $request): Response
+ {
+ $repo = new Repository();
+ $xml = ['', '文章分类
+
+
+
+ = $e($title) ?>
+
+ 查看公开页面
+
+文章与动态
+
+站点备份
导出备份从备份还原
+
+
+LaySite
diff --git a/app/view/admin-category-checkboxes.php b/app/view/admin-category-checkboxes.php
new file mode 100644
index 0000000..208f97d
--- /dev/null
+++ b/app/view/admin-category-checkboxes.php
@@ -0,0 +1,14 @@
+
+
diff --git a/app/view/admin-dashboard.php b/app/view/admin-dashboard.php
new file mode 100644
index 0000000..cbc5f6c
--- /dev/null
+++ b/app/view/admin-dashboard.php
@@ -0,0 +1,61 @@
+ $page['status'] === 'published'));
+?>
+网站后台
+
+网站页面
+
+
+
+
+ 最近编辑的文章
站点编辑
+
+ = $e(['header' => '页头组件', 'footer' => '页脚组件', 'palette' => '配色方案'][$kind]) ?>
+ 预览已保存的配置
+站点设计
= $e($label) ?>
新建= $e($label) ?>
+
+
+ = App\Content\View::escape($title) ?>
+返回内容管理
diff --git a/app/view/admin-feedback.php b/app/view/admin-feedback.php
new file mode 100644
index 0000000..62097b3
--- /dev/null
+++ b/app/view/admin-feedback.php
@@ -0,0 +1,3 @@
+
+登录内容管理
+ = $e($title) ?>
页面画布
+ = $e($title) ?>
= $e($title) ?>
= $e($group['label']) ?>
+ = View::fragment('article-list', ['articles' => $group['articles'], 'categoryScope' => $group['categories']]) ?>
+
+
+
+
+
+ = $e($article['title']) ?>
+
+
+
+
+ $target, 'detail' => $detail] = DirectoryCard::links($item, Html::articleBody($item));
+ ?>
+
diff --git a/app/view/page.php b/app/view/page.php
new file mode 100644
index 0000000..78e00ba
--- /dev/null
+++ b/app/view/page.php
@@ -0,0 +1,74 @@
+ $section['style'] === 'hero-links');
+$alignments = $page['alignments'];
+$alignField = static fn (string $name): string => $canvas ? ' data-studio-align-field="' . $name . '"' : '';
+$field = static fn (string $name): string => $canvas ? ' data-studio-field="' . $name . '"' : '';
+?>
+
+
+ = $e($item['title']) ?>
+
+
+ 查看详情
+
+
= $e($page['name']) ?>
+
+= $alignField('heading') ?>>>= $e($page['heading']) ?>>= $e($page['accent']) ?>
+
= $e($page['accent']) ?> alt="= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"= $canvas ? ' data-studio-hero-image' : '' ?>>
+
= $canvas ? ' data-studio-part="lead"' : '' ?>>= $e($section['lead']) ?>
+暂无可查看的产品和服务。
+= $e($card['category_label']) ?>
+= $e($product['summary']) ?>
+ +没有匹配的= $modules ? '组件' : '元素' ?>。
+ [$category, $items]): ?> +统一查找并引用静态文件、图片、图标和音视频。
= $e(strtolower(pathinfo($file['url'], PATHINFO_EXTENSION))) ?>
+ +', {class: 'ajax-feedback feedback error', role: 'alert', tabindex: -1})
+ .prependTo($form);
+ }
+ $feedback.text(message);
+ if (status === 401) {
+ $feedback.append(' ', $('', {
+ href: '/admin/login', target: '_blank', rel: 'noopener', text: '打开登录页'
+ }));
+ }
+ $feedback.prop('hidden', false).trigger('focus');
+ }
+
+ document.addEventListener('invalid', (event) => {
+ if (event.target.form?.method.toLowerCase() === 'post') clearSavedStatus();
+ }, true);
+
+ $('form[method="post"]').on('submit', function (event) {
+ event.preventDefault();
+ const $form = $(this);
+ if ($form.attr('aria-busy') === 'true') return;
+ const submitter = event.originalEvent?.submitter;
+ if (submitter?.dataset.confirm && !window.confirm(submitter.dataset.confirm)) return;
+ clearSavedStatus();
+ const action = $form.attr('action');
+ const isLogin = action === '/admin/login';
+ const $submit = $form.find(':submit:enabled');
+ const multipart = $form.attr('enctype') === 'multipart/form-data';
+ $form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true);
+ $submit.prop('disabled', true);
+ $form.triggerHandler('studio:busy', [true]);
+
+ function finish() {
+ $form.removeAttr('aria-busy');
+ $submit.prop('disabled', false);
+ $form.triggerHandler('studio:busy', [false]);
+ }
+
+ function submit(canRetryLogin) {
+ $form.triggerHandler('studio:sync');
+ const fields = multipart ? new FormData($form.get(0)) : $form.serializeArray();
+ if (submitter?.name) {
+ if (multipart) fields.append(submitter.name, submitter.value);
+ else fields.push({name: submitter.name, value: submitter.value});
+ }
+ $.ajax({
+ url: action,
+ method: 'POST',
+ data: fields,
+ processData: !multipart,
+ contentType: multipart ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
+ dataType: 'json'
+ }).done(function (response) {
+ if (response.redirect) {
+ $form.triggerHandler('studio:saved');
+ window.location.assign(response.redirect);
+ return;
+ }
+ finish();
+ formError($form, '未收到保存结果,请刷新页面确认。');
+ }).fail(function (request) {
+ const response = request.responseJSON;
+ refreshToken(response);
+ if (canRetryLogin && request.status === 403 && response?.csrf) {
+ submit(false);
+ return;
+ }
+ finish();
+ formError($form, response?.message || '请求未完成,请稍后重试。', request.status);
+ });
+ }
+
+ submit(isLogin);
+ });
+
+ $('[data-editor]').each(function () {
+ const $editor = $(this);
+ if ($editor.find('[data-rich-canvas]').length) return;
+ const area = $editor.find('textarea').get(0);
+ const format = $editor.data('format');
+ const $preview = $editor.find('.editor-preview');
+ const $form = $editor.closest('form');
+ let pendingPreview;
+
+ $editor.on('click', '[data-insert]', function () {
+ const [before, after, example] = formats[format][$(this).data('insert')];
+ const start = area.selectionStart;
+ const end = area.selectionEnd;
+ const selection = area.value.slice(start, end) || example;
+ area.setRangeText(before + selection + after, start, end, 'end');
+ area.focus();
+ area.setSelectionRange(start + before.length, start + before.length + selection.length);
+ });
+
+ $editor.on('click', '[data-preview-button]', function () {
+ const $button = $(this);
+ const show = $preview.prop('hidden');
+ $preview.prop('hidden', !show);
+ $button.text(show ? '收起预览' : '预览正文').attr('aria-expanded', String(show));
+ pendingPreview?.abort();
+ if (!show) return;
+
+ $preview.text('正在加载预览…');
+ pendingPreview = $.ajax({
+ url: '/admin/preview',
+ method: 'POST',
+ data: {body: area.value, format, csrf: $form.find('input[name="csrf"]').val()},
+ dataType: 'text'
+ }).done((markup) => $preview.html(markup)).fail((request, status) => {
+ if (status === 'abort') return;
+ let feedback = request.responseJSON;
+ if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) {
+ try { feedback = JSON.parse(request.responseText); } catch { /* Use the fallback feedback. */ }
+ }
+ refreshToken(feedback);
+ $preview.text(feedback?.message || '预览无法加载,请重试。');
+ });
+ });
+ });
+});
diff --git a/public/assets/article-editor.js b/public/assets/article-editor.js
new file mode 100644
index 0000000..bde229a
--- /dev/null
+++ b/public/assets/article-editor.js
@@ -0,0 +1,56 @@
+'use strict';
+
+jQuery(function ($) {
+ $('[data-article-editor]').each(function () {
+ const Editor = window.toastui?.Editor;
+ if (!Editor) return;
+ const $field = $(this);
+ const $source = $field.find('textarea');
+ const $format = $field.find('input[name="body_format"]');
+ const $host = $field.find('[data-editor-host]');
+ const $status = $field.find('[data-article-editor-status]');
+ const originalFormat = $format.val();
+ const original = $source.val();
+ $host.prop('hidden', false);
+ let editor;
+ try {
+ editor = new Editor({
+ el: $host.get(0),
+ height: '34rem',
+ initialEditType: originalFormat === 'html' ? 'wysiwyg' : 'markdown',
+ initialValue: originalFormat === 'markdown' ? original : '',
+ previewStyle: 'vertical',
+ language: 'zh-CN',
+ usageStatistics: false,
+ autofocus: false,
+ hooks: {
+ addImageBlobHook() {
+ $status.text('请先上传图片到媒体库,再从媒体库插入。');
+ }
+ }
+ });
+ if (originalFormat === 'html') editor.setHTML(original);
+ } catch (error) {
+ $host.prop('hidden', true);
+ return;
+ }
+ const snapshot = originalFormat === 'html' ? editor.getHTML() : editor.getMarkdown();
+ $source.prop('hidden', true);
+ $field.find('[data-article-editor-label]').removeAttr('for');
+ $field.find('[data-insert-article-image]').prop('hidden', false).on('click', () => {
+ $('#media-picker').triggerHandler('studio:pick', ['image/', (file) => {
+ const alt = window.prompt('图片替代文本(装饰图可留空)', file.label);
+ if (alt === null) return;
+ $status.empty();
+ editor.focus();
+ editor.exec('addImage', {imageUrl: file.url, altText: alt});
+ }]);
+ });
+ $field.closest('form').on('studio:sync', function () {
+ const format = editor.isMarkdownMode() ? 'markdown' : 'html';
+ const content = format === 'html' ? editor.getHTML() : editor.getMarkdown();
+ $format.val(format);
+ $source.val(format === originalFormat && content === snapshot ? original : content);
+ });
+ });
+});
diff --git a/public/assets/geist-OFL.txt b/public/assets/geist-OFL.txt
new file mode 100644
index 0000000..5e83a47
--- /dev/null
+++ b/public/assets/geist-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2026 The Geist Project Authors (https://github.com/vercel/geist-font)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/public/assets/geist.woff2 b/public/assets/geist.woff2
new file mode 100644
index 0000000..991445d
Binary files /dev/null and b/public/assets/geist.woff2 differ
diff --git a/public/assets/jquery-4.0.0.min.js b/public/assets/jquery-4.0.0.min.js
new file mode 100644
index 0000000..3b89a1c
--- /dev/null
+++ b/public/assets/jquery-4.0.0.min.js
@@ -0,0 +1,2 @@
+/*! jQuery v4.0.0 | (c) OpenJS Foundation and other contributors | jquery.com/license */
+!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=t(e,!0):t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";if(!e.document)throw Error("jQuery requires a window with a document");var n=[],r=Object.getPrototypeOf,i=n.slice,o=n.flat?function(e){return n.flat.call(e)}:function(e){return n.concat.apply([],e)},a=n.push,s=n.indexOf,u={},l=u.toString,c=u.hasOwnProperty,f=c.toString,p=f.call(Object),d={};function h(e){return null==e?e+"":"object"==typeof e?u[l.call(e)]||"object":typeof e}function g(e){return null!=e&&e===e.window}function v(e){var t=!!e&&e.length,n=h(e);return!("function"==typeof e||g(e))&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var y=e.document,m={type:!0,src:!0,nonce:!0,noModule:!0};function x(e,t,n){var r,i=(n=n||y).createElement("script");for(r in i.text=e,m)t&&t[r]&&(i[r]=t[r]);n.head.appendChild(i).parentNode&&i.parentNode.removeChild(i)}var b="4.0.0",w=/HTML$/i,T=function(e,t){return new T.fn.init(e,t)};function C(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}T.fn=T.prototype={jquery:b,constructor:T,length:0,toArray:function(){return i.call(this)},get:function(e){return null==e?i.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=T.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return T.each(this,e)},map:function(e){return this.pushStack(T.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(i.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(T.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(T.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n =1)){for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(n=0,o=[],a={};n-1:T.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}}return l=this,u