Launch LaySite visual editor and MCP workspace

This commit is contained in:
2026-11-22 23:26:08 +08:00
commit 1bb0554608
159 changed files with 11103 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
* text=auto
+7
View File
@@ -0,0 +1,7 @@
/vendor/
/runtime/
/storage/*
!/storage/.gitignore
/.env
/.taste-skill/
/shots/
+154
View File
@@ -0,0 +1,154 @@
# LaySite
基于 PHP Webman、SQLite、原生 CSS 和 jQuery 的通用站点编辑器。页面由服务端渲染,公开页复用站点组件和配色。新装提供空白首页、可编辑的文章页,以及六套十二个整页模板。
## 安装
需要 PHP 8.2+ CLI、Composer 2,及 `curl`、`dom`、`fileinfo`、`mbstring`、`openssl`、`pdo_sqlite`、`pcntl`、`posix` 和 `Phar`。确保运行账户能写入 `runtime/`、SQLite 所在目录和上传目录。
```sh
composer install --no-dev
php bin/install.php
php bin/admin.php editor@example.com
php start.php start
```
打开 `http://127.0.0.1:8787/admin`。重设管理员密码可用 `php bin/admin.php reset editor@example.com`。该操作会使该账户的旧会话失效。应用使用进程环境变量,可在 systemd 服务或启动脚本中设置。
| 环境变量 | 用途 |
| --- | --- |
| `LAYSITE_SITE_URL` | 完整站点地址,默认 `http://127.0.0.1:8787`。用于 SEO URL、MCP 编辑链接和登录回调 |
| `LAYSITE_LISTEN` | Webman 监听地址,默认 `http://127.0.0.1:8787` |
| `LAYSITE_WORKERS` | Webman worker 数,默认 2 |
| `LAYSITE_DB` | SQLite 文件,默认 `storage/laysite.sqlite` |
| `LAYSITE_MEDIA_DIR` | 用户上传目录,默认 `storage/media` |
| `LAYSITE_SECURE_COOKIES` | 生产 HTTPS 设为 `1`。本机 HTTP 留空 |
| `LAYSITE_TRUSTED_PROXIES` | 信任的反代 IP,默认 `127.0.0.1,::1` |
| `LAYSITE_MCP_TOKEN` | MCP Bearer 密钥,至少 32 字符。未设置时端点关闭 |
| `LAYSITE_OAUTH_*` | 会员页头选用的客户端密钥,按新建配置时填写的名称设置 |
## 页面与站点设计
- 在「页面」新建空白草稿或从整页模板创建。画布支持编辑、媒体拖拽调整宽度、移动端预览、区块复制与删除。
- 选中按钮后可复制。在「属性」中选择纯色填充、线框、下划线或无样式,并选择是否在新标签页打开。首屏支持最多八个按钮。
- 「站点设计」中可以保存多套页头、页脚和配色。选择布局模板后,可以勾选并排序标识、导航、按钮、文字、版权或用户区组件,填入各组件内容。页头和页脚可以设为站点默认。每页可覆盖这两个默认项、选择配色,或独立隐藏页头和页脚。
- 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。
- 发布后的站点具备独立标题、描述、canonical、Open Graph、站点地图和 robots.txt。可在「站点设置」配置站点名称和静态资源 CDN。
### 会员页头
在「站点设计 → 页头」选择「会员导航」,启用用户区,并选择认证方式。将已配置的页头用作默认、或应用于要开放登录的页面。
| 模式 | 填写内容 |
| --- | --- |
| OpenID Connect | Issuer、客户端 ID 和客户端密钥环境变量。LaySite 通过发现文档获取端点和签名公钥,使用 `openid profile email` 及附加范围 |
| OAuth 2.0 + 用户资料 | 授权、令牌和用户资料三个 HTTPS 地址、客户端 ID、客户端密钥环境变量、权限范围及稳定的用户 ID 字段。名称和头像字段默认使用 `name`、`picture` |
在提供商中注册由站点域名拼接的回调 `https://example.com/account/callback`。密钥写入进程环境,配置页填写类似 `LAYSITE_OAUTH_MEMBER_SECRET` 的变量名。两个模式均使用授权码、state 和 PKCE S256,可按提供商要求选择 HTTP Basic 或表单客户端密钥。通过验证后,访客头像会链接到 `/account`。访客会话与管理员登录分开,退出用户中心时结束本地访客会话。
## MCP
`POST /mcp` 提供无状态 Streamable HTTP JSON-RPC。使用 `openssl rand -hex 32` 生成令牌,然后设置 `LAYSITE_MCP_TOKEN` 并重启 Webman。客户端使用 HTTPS 站点地址及 `Authorization: Bearer <TOKEN>`。
支持 MCP `2025-11-25`、`2025-06-18`、`2025-03-26`。客户端配置示例(字段名称按客户端调整):
```json
{
"mcpServers": {
"laysite": {
"type": "http",
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer YOUR_TOKEN" }
}
}
}
```
| 工具 | 功能 |
| --- | --- |
| `list_pages` / `get_page` | 读取页面、区块及当前修订号 |
| `list_templates` / `list_designs` | 查阅整页模板、组件、页头、页脚和配色 |
| `create_draft` | 按模板或传入内容创建草稿,返回编辑地址 |
| `save_draft` | 用最新修订号更新草稿。传入 `sections` 时替换区块列表 |
Agent 可以编辑草稿,管理员在画布里检查、细改及发布。草稿 HTML 使用与人工画布相同的 HTML 过滤器。按钮参数为 `[href, label, style, opensNewTab]`,样式可选 `solid`、`outline`、`underline`、`plain`。MCP 与站点发布共用 SQLite 和编辑器修订号。
## 站点备份与更新
「站点设计 → 站点备份」支持导出和确认后覆盖导入。备份包是包含版本化 JSON 清单和校验和的 TAR,包含页面、区块、文章、站点设置、布局、配色和媒体数据。管理员密码、运行环境密钥和登录会话由目标安装独立管理。备份存放在站点公开目录外。
当前导出格式为 v2,导入兼容 v1 的基础内容备份并补齐空的设计库。未来格式会保留迁移入口,遇到较新的不兼容格式时提示升级。上传大小受 Webman 与外层代理限制,较大站点可使用 CLI。
```sh
php bin/backup.php export /srv/backups/laysite-2026-11.tar
php bin/backup.php import /srv/backups/laysite-2026-11.tar --replace
```
使用 Git 标签选择更新版本。更新命令先备份,再检出所选版本、安装锁定依赖并运行 SQLite 初始化或迁移。更新时暂停 Webman,更新结束后用原进程环境重新启动。保持源代码工作区干净,并将备份放到部署路径之外。
```sh
bin/update.sh check
bin/update.sh v1.0.0 /srv/backups/pre-update.tar
```
## 生产反代
配置 `LAYSITE_SITE_URL=https://example.com` 和 `LAYSITE_SECURE_COOKIES=1`。下列示例假定代理和 Webman 在同一主机。代理应以实际访客来源覆盖 `X-Real-IP`,并将项目文件、数据库和媒体存储保持在公开根目录之外。
### Nginx
在现有 HTTPS 虚拟主机内加入:
```nginx
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
location / {
proxy_pass http://127.0.0.1:8787;
client_max_body_size 2m;
}
location ~ ^/admin/(media|backup)$ {
proxy_pass http://127.0.0.1:8787;
client_max_body_size 66m;
}
```
### Caddy v2
以下 `request_body` 配置要求 Caddy v2.10+。
```caddyfile
example.com {
@uploads path /admin/media /admin/backup
@pages not path /admin/media /admin/backup
request_body @uploads {
max_size 66MiB
}
request_body @pages {
max_size 2MiB
}
reverse_proxy 127.0.0.1:8787 {
header_up X-Real-IP {remote_host}
}
}
```
### Caddy v1
```caddyfile
example.com {
limits {
body /admin/media 66MB
body /admin/backup 66MB
body / 2MB
}
proxy / 127.0.0.1:8787 {
transparent
}
}
```
Caddy v1 的路径限额按前缀匹配。CDN 应转发 `/assets/`,并保留静态资源 CORS 与音视频 Range 响应。使用会员页头时,站点会对个性化页面发送 `Cache-Control: private, no-store`,外层代理应保留此响应头。
模板视觉参考 Hallmark。代码中的 jQuery、Geist 和 TOAST UI Editor 随各自的许可证分发。
+1
View File
@@ -0,0 +1 @@
1.0.0
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Assets
{
public static function cdn(string $value): string
{
$value = rtrim(trim($value), '/');
if ($value !== '' && (strlen($value) > 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) {
throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.example.com。');
}
if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) {
throw new RuntimeException('CDN 端口无效。');
}
return $value;
}
public static function url(string $path, string $cdn): string
{
return str_starts_with($path, '/assets/') ? $cdn . $path : $path;
}
public static function rewrite(string $html, string $cdn): string
{
if ($cdn === '') {
return $html;
}
// Match opening tags separately from comments and text-only elements' contents.
$tags = <<<'REGEX'
~<!--.*?(?:-->|\z)|(?<opening><(?:(?<textTag>script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?<tail>.*?(?:</\k<textTag>\s*>|\z)))~is
REGEX;
$attributes = <<<'REGEX'
~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~
REGEX;
return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string {
if (!isset($tag['opening'])) {
return $tag[0];
}
$opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string {
if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) {
return $attribute[0];
}
$value = $attribute[4];
$quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : '';
$path = $quote === '' ? $value : substr($value, 1, -1);
return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote;
}, $tag['opening']) ?? $tag['opening'];
return $opening . ($tag['tail'] ?? '');
}, $html) ?? $html;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class BlockTemplates
{
public const ARTICLE_FEED = '{"categories":["announcement","news","product"],"mode":"merged","limit":6}';
public const NETWORK_FEED = '{"categories":["projects","partners"],"mode":"network","limit":30}';
public const CATALOG_FEED = '{"categories":["catalog"],"mode":"catalog","limit":30}';
public const ELEMENT_GROUPS = [
'text-elements' => ['文字与列表', [
'paragraph' => ['段落', '<p>填写正文。</p>'],
'subheading' => ['小标题', '<h3>填写小标题</h3>'],
'lead' => ['导语', '<p class="studio-lead">填写本节的导语。</p>'],
'blockquote' => ['引用', '<blockquote><p>填写需要引用的内容。</p></blockquote>'],
'bullet-list' => ['项目列表', '<ul><li>填写列表项</li><li>填写列表项</li></ul>'],
'ordered-list' => ['编号列表', '<ol><li>填写第一项</li><li>填写第二项</li></ol>'],
'heading-kicker' => ['标题眉标', '<p class="overline">填写分类名称</p>'],
'tag' => ['徽标', '<p><span class="studio-badge">填写标签</span></p>'],
'large-number' => ['重点数字', '<p class="price-value">填写数字</p>'],
'definition-list' => ['术语说明', '<dl class="studio-definitions"><dt>填写术语</dt><dd>填写术语说明。</dd></dl>'],
]],
'link-elements' => ['链接与按钮', [
'button' => ['主按钮', '<p><a class="button button-primary" href="#contact">联系站点</a></p>'],
'outline-button' => ['描边按钮', '<p><a class="button button-outline" href="/">查看服务</a></p>'],
'text-link' => ['文字链接', '<p><a href="/articles">阅读文章</a></p>'],
'button-group' => ['按钮组', '<div class="actions studio-button-group"><a class="button button-primary" href="/">查看服务</a><a class="button button-outline" href="#contact">联系团队</a></div>'],
'breadcrumbs' => ['面包屑', '<p class="breadcrumbs"><a href="/">首页</a><span> / </span><span>当前页面</span></p>'],
'download-link' => ['下载入口', '<p><a class="button button-outline" href="/articles">查看下载</a></p>'],
'email-link' => ['邮件链接', '<p><a href="mailto:hello@example.com">发送邮件</a></p>'],
]],
'media-elements' => ['图片与影音', [
'image' => ['图片', '', 'image/'],
'video' => ['视频', '', 'video/'],
'audio' => ['音频', '', 'audio/'],
'qr-image' => ['二维码', '', 'image/'],
'image-link' => ['图片链接', '<p><a href="/"><img src="/assets/system/sample.webp" alt="版式示意" loading="lazy"></a></p>'],
]],
'structure-elements' => ['版式与数据', [
'separator' => ['分割线', '<hr class="studio-divider">'],
'spacer' => ['留白', '<div class="studio-spacer"></div>'],
'code' => ['代码块', '<pre class="studio-code"><code>填写代码</code></pre>'],
'basic-table' => ['数据表格', '<table><thead><tr><th scope="col">名称</th><th scope="col">数据</th></tr></thead><tbody><tr><td>填写名称</td><td>填写数据</td></tr></tbody></table>'],
'progress' => ['进度条', '<div class="studio-progress"><p>完成进度</p><progress max="100" value="65">65%</progress></div>'],
'alert' => ['提示卡', '<div class="studio-notice"><p><strong>请注意</strong></p><p>填写一条提示信息。</p></div>'],
'simple-card' => ['内容卡片', '<article class="content-card"><h3>填写卡片标题</h3><p>填写卡片内容。</p></article>'],
'link-card' => ['链接卡片', '<article class="content-card"><h3>查看资料</h3><p>填写链接指向的资料说明。</p><a href="/articles">打开资料</a></article>'],
'list-group' => ['列表组', '<ul class="studio-resources"><li><a href="/">产品与服务</a><span>目录</span></li><li><a href="/articles">站点动态</a><span>文章</span></li></ul>'],
'empty-card' => ['空状态', '<div class="studio-empty"><h3>暂无内容</h3><p>填写访客可以执行的下一步。</p><a href="/articles">查看站点动态</a></div>'],
'status-note' => ['状态提示', '<div class="studio-notice studio-success-note"><p><strong>已完成</strong></p><p>填写操作结果或服务状态。</p></div>'],
'disclosure' => ['折叠内容', '<div class="faq"><details><summary>填写折叠标题</summary><div><p>填写展开后的内容。</p></div></details></div>'],
]],
];
public const GROUPS = [
'content' => ['标题与正文', [
'headline' => ['标题与简介', '<div class="studio-intro"><h3>填写区块标题</h3><p>用一句话补充背景或说明。</p></div>'],
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'articles' => ['分类文章', '', '', self::ARTICLE_FEED],
'network' => ['按分类分组', '', '', self::NETWORK_FEED],
'list' => ['步骤列表', '<ol><li>填写第一步</li><li>填写第二步</li><li>填写第三步</li></ol>'],
'notice' => ['重点提示', '<div class="studio-notice"><h3>填写重要提示</h3><p>说明访客需要知悉的事项、条件或时间。</p></div>'],
]],
'cover' => ['封面与横幅', [
'cover' => ['图文封面', '<div class="studio-cover"><img src="/assets/system/sample.webp" alt="" loading="lazy"><div><h3>用一句话介绍你的产品</h3><p>在首段说明访客能获得什么。</p><a class="button button-primary" href="/">查看服务</a></div></div>'],
'banner' => ['横幅', '<div class="studio-banner"><h3>用一句话介绍你的项目</h3><p>简要说明项目能为访客做什么。</p><a class="button button-primary" href="/">了解更多</a></div>'],
'two-actions' => ['双按钮横幅', '<div class="studio-banner studio-banner-two"><div><h3>选择下一步</h3><p>介绍访客可以立即做什么。</p></div><div class="actions"><a class="button button-primary" href="/">查看服务</a><a class="button button-outline" href="/#contact">联系我们</a></div></div>'],
]],
'layout' => ['图文与布局', [
'image' => ['产品图文', '<div class="studio-split"><img src="/assets/system/sample.webp" alt="" loading="lazy"><div><h3>介绍主题</h3><p>在这里说明图片或产品。</p></div></div>'],
'grid' => ['双栏网格', '<div class="studio-two-column"><article class="content-card"><h3>第一栏</h3><p>填写主要内容。</p></article><article class="content-card"><h3>第二栏</h3><p>补充相关信息。</p></article></div>'],
]],
'media' => ['媒体', [
'gallery' => ['三图画廊', '<div class="studio-gallery"><img src="/assets/system/sample.webp" alt="产品界面示意" loading="lazy"><img src="/assets/system/sample.webp" alt="示例作品" loading="lazy"><img src="/assets/system/sample.webp" alt="云端服务插画" loading="lazy"></div>'],
'video-demo' => ['视频演示', '<div class="studio-split"><video controls preload="none" poster="/assets/system/sample.webp"></video><div><h3>演示视频</h3><p>说明视频涵盖的功能与操作。</p></div></div>'],
]],
'features' => ['特性与口碑', [
'features' => ['特性卡片', '<div class="card-grid feature-grid"><article class="content-card feature-card"><h3>特点一</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点二</h3><p>介绍这个特点。</p></article><article class="content-card feature-card"><h3>特点三</h3><p>介绍这个特点。</p></article></div>'],
'quote' => ['引文', '<blockquote><p>在这里填写引用或用户反馈。</p></blockquote>'],
'metrics' => ['关键数据', '<dl class="studio-metrics"><div><dt>累计项目</dt><dd>100</dd></div><div><dt>服务覆盖</dt><dd>12</dd></div><div><dt>合作伙伴</dt><dd>8</dd></div></dl>'],
'testimonials' => ['用户评价', '<div class="studio-two-column studio-testimonials"><blockquote><p>填写用户的评价,并说明他们获得的结果。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote><blockquote><p>填写另一条用户评价。</p><p class="studio-attribution">用户姓名 · 公司或角色</p></blockquote></div>'],
]],
'details' => ['表格与问答', [
'table' => ['对比表格', '<table><thead><tr><th scope="col">项目</th><th scope="col">说明</th></tr></thead><tbody><tr><td>项目一</td><td>填写说明</td></tr><tr><td>项目二</td><td>填写说明</td></tr></tbody></table>'],
'faq' => ['常见问题', '<div class="faq"><details><summary>请输入问题</summary><div><p>请输入答案。</p></div></details></div>'],
'timeline' => ['时间线', '<ol class="studio-timeline"><li><h3>确定目标</h3><p>填写这一阶段需要完成的事项。</p></li><li><h3>实施与验收</h3><p>填写交付时间与验收标准。</p></li></ol>'],
'checklist' => ['清单', '<ul class="studio-checklist"><li>填写必备材料</li><li>填写提交条件</li><li>填写确认事项</li></ul>'],
'changelog' => ['更新记录', '<div class="studio-releases"><article><h3>版本 2.0</h3><p>填写主要功能或改进。</p></article><article><h3>版本 1.0</h3><p>填写上一版本的更新内容。</p></article></div>'],
'pricing' => ['双方案报价', '<div class="card-grid price-grid studio-pricing"><article class="content-card price-card"><h3>基础方案</h3><p class="price-value">填写价格</p><p>填写方案包含的服务。</p><a class="button button-outline" href="/#contact">咨询基础方案</a></article><article class="content-card price-card"><h3>进阶方案</h3><p class="price-value">填写价格</p><p>填写扩展服务或权益。</p><a class="button button-primary" href="/#contact">咨询进阶方案</a></article></div>'],
]],
'actions' => ['导航与引导', [
'service-catalog' => ['目录卡片', '', '', self::CATALOG_FEED],
'navigation' => ['快速导航', '<ul class="studio-quick-nav"><li><a href="/">产品与服务</a></li><li><a href="/articles">动态与文章</a></li><li><a href="/#contact">联系站点</a></li></ul>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系站点</a></p>'],
'resources' => ['资料与链接', '<ul class="studio-resources"><li><a href="/articles">浏览资料</a><span>应用下载</span></li><li><a href="/articles">浏览动态与文档</a><span>网站资源</span></li></ul>'],
'contact-card' => ['联系方式', '<div class="studio-contact"><div><h3>联系团队</h3><p>填写咨询范围与回复时间。</p></div><dl class="studio-definitions"><dt>电子邮件</dt><dd><a href="mailto:hello@example.com">hello@example.com</a></dd><dt>服务时间</dt><dd>填写工作时间</dd></dl></div>'],
]],
];
public static function groups(): array
{
return self::GROUPS;
}
public static function find(string $key): ?array
{
foreach (self::groups() as [, $templates]) {
if (isset($templates[$key])) {
return $templates[$key];
}
}
return null;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class Buttons
{
public const STYLES = ['solid' => '纯色填充', 'outline' => '线框', 'underline' => '下划线', 'plain' => '无样式'];
private const CLASSES = ['solid' => 'button-primary', 'outline' => 'button-outline', 'underline' => 'button-underline', 'plain' => 'button-plain'];
public static function validate(mixed $items, int $limit = 8): array
{
if (!is_array($items) || !array_is_list($items) || count($items) > $limit) {
throw new RuntimeException('按钮或链接数量超过限制。');
}
$buttons = [];
foreach ($items as $index => $item) {
$url = $item[0] ?? null;
$label = $item[1] ?? null;
$style = $item[2] ?? ($index === 0 ? 'solid' : 'outline');
$blank = $item[3] ?? false;
if (!is_string($url) || strlen($url) > 1000 || !Html::url($url) || !is_string($label)
|| trim($label) === '' || mb_strlen($label) > 70 || !is_string($style) || !isset(self::STYLES[$style])
|| !is_bool($blank)) {
throw new RuntimeException('请检查按钮文案、链接和样式。');
}
$buttons[] = [$url, $label, $style, $blank];
}
return $buttons;
}
public static function css(string $style): string
{
return 'button ' . (self::CLASSES[$style] ?? self::CLASSES['solid']);
}
public static function target(bool $blank): string
{
return $blank ? ' target="_blank" rel="noopener noreferrer"' : '';
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
use Throwable;
final class Database
{
private const SCHEMA_VERSION = 1;
// Avoid reusing a deleted ID that may still be open in an editing form.
public const NEXT_ARTICLE_ID = 'MAX(COALESCE((SELECT MAX(id) FROM articles), 0),
COALESCE((SELECT MAX(article_id) FROM article_deletions), 0)) + 1';
private static ?PDO $connection = null;
public static function connect(): PDO
{
if (self::$connection !== null) {
return self::$connection;
}
$path = getenv('LAYSITE_DB') ?: dirname(__DIR__, 2) . '/storage/laysite.sqlite';
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0750, true) && !is_dir(dirname($path))) {
throw new RuntimeException('无法创建 SQLite 存放目录。');
}
$pdo = new PDO('sqlite:' . $path, options: [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA foreign_keys = ON');
self::$connection = $pdo;
return $pdo;
}
public static function initialize(): void
{
$root = dirname(__DIR__, 2);
$pdo = self::connect();
$pdo->exec('PRAGMA journal_mode = WAL');
self::write(function (PDO $pdo) use ($root): void {
$version = (int) $pdo->query('PRAGMA user_version')->fetchColumn();
if ($version > self::SCHEMA_VERSION) {
throw new RuntimeException('当前 SQLite 数据库需要更新版本的 LaySite。');
}
$pdo->exec(file_get_contents($root . '/resources/schema.sql'));
$pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)')->execute([self::json(['name' => '我的网站'])]);
$pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES ('home', '首页', '我的网站', '欢迎访问我的网站。', '我的网站', '', '', '', '', '[]', '[]')")
->execute();
$articles = $pdo->prepare("INSERT OR IGNORE INTO pages
(slug, name, title, description, heading, accent, lead, image, alt, actions, quicklinks)
VALUES ('articles', '文章与动态', '文章与动态', '浏览站点发布的文章。', '文章与动态', '', '', '', '', '[]', '[]')");
$articles->execute();
if ($articles->rowCount() === 1) {
$pdo->prepare("INSERT INTO sections (page_slug, key, title, lead, body, feed, position)
VALUES ('articles', 'posts', '最新文章', '', '', ?, 0)")->execute([BlockTemplates::ARTICLE_FEED]);
}
$category = $pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
foreach (Repository::CATEGORIES as $slug => $name) {
$category->execute([$slug, $name]);
}
if ($version < self::SCHEMA_VERSION) {
$pdo->exec('PRAGMA user_version = ' . self::SCHEMA_VERSION);
}
});
}
public static function write(callable $operation): mixed
{
$pdo = self::connect();
$pdo->exec('BEGIN IMMEDIATE');
try {
$result = $operation($pdo);
$pdo->exec('COMMIT');
return $result;
} catch (Throwable $error) {
$pdo->exec('ROLLBACK');
throw $error;
}
}
public static function json(array $data): string
{
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class DesignLibrary
{
public const PRESETS = [
'header' => ['inline' => '横排导航', 'center' => '居中品牌', 'member' => '会员导航'],
'footer' => ['columns' => '多栏链接', 'compact' => '简约横栏', 'band' => '全宽深色'],
'palette' => ['custom' => '自定义配色'],
];
public const COMPONENTS = [
'header' => ['brand' => '站点标识', 'links' => '导航链接', 'action' => '行动按钮', 'account' => '用户区'],
'footer' => ['brand' => '站点标识', 'text' => '说明文字', 'links' => '页脚链接', 'legal' => '版权文字'],
];
public const COLORS = [
'white' => ['页面背景', '#ffffff'], 'paper' => ['区块背景', '#f5f7fb'],
'ink' => ['正文', '#111a2e'], 'muted' => ['次要文字', '#505d73'],
'accent' => ['强调色', '#214ed7'], 'accent-deep' => ['强调色悬停', '#173bae'],
'accent-light' => ['强调色浅底', '#e8efff'], 'line' => ['边框', '#dbe3f0'],
'button-ink' => ['填充按钮文字', '#ffffff'],
];
public static function all(?string $kind = null): array
{
$query = Database::connect()->prepare('SELECT id, kind, name, preset, version FROM design_presets'
. ($kind === null ? '' : ' WHERE kind = ?') . ' ORDER BY kind, id');
$query->execute($kind === null ? [] : [$kind]);
return $query->fetchAll();
}
public static function find(int $id, string $kind): ?array
{
if ($id < 1) {
return null;
}
$query = Database::connect()->prepare('SELECT * FROM design_presets WHERE id = ? AND kind = ?');
$query->execute([$id, $kind]);
$row = $query->fetch();
if (!$row) {
return null;
}
$row['payload'] = self::normalize($kind, $row['preset'], json_decode($row['payload'], true, flags: JSON_THROW_ON_ERROR));
return $row;
}
public static function defaults(string $kind): array
{
if ($kind === 'palette') {
return array_map(static fn (array $color): string => $color[1], self::COLORS);
}
return [
'components' => array_keys(self::COMPONENTS[$kind]), 'logo' => '', 'brand' => '', 'text' => '',
'legal' => '', 'links' => $kind === 'header' ? [['/', '首页'], ['/articles', '文章']] : [],
'action' => [], 'provider' => [],
];
}
public static function layout(string $kind, array $site, array $page): array
{
$id = (int) ($page[$kind . '_id'] ?? 0) ?: (int) ($site[$kind . '_id'] ?? 0);
return self::find($id, $kind) ?? [
'id' => 0, 'preset' => array_key_first(self::PRESETS[$kind]), 'payload' => self::defaults($kind),
];
}
public static function selection(string $kind, mixed $value): ?int
{
if ($value === '' || $value === null || $value === 0) {
return null;
}
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($id === false || !self::find($id, $kind)) {
throw new RuntimeException('所选页头、页脚或配色方案不存在。');
}
return $id;
}
public static function normalize(string $kind, string $preset, array $data): array
{
if (!isset(self::PRESETS[$kind][$preset])) {
throw new RuntimeException('请选择可用的组件模板。');
}
if ($kind === 'palette') {
$colors = [];
foreach (self::COLORS as $key => [, $default]) {
$color = $data[$key] ?? $default;
if (!is_string($color) || !preg_match('/^#[\da-f]{6}$/iD', $color)) {
throw new RuntimeException('颜色必须使用六位十六进制表示。');
}
$colors[$key] = strtolower($color);
}
return $colors;
}
$clean = self::defaults($kind);
foreach (['brand' => 100, 'text' => 1200, 'legal' => 300, 'logo' => 1000] as $field => $limit) {
$clean[$field] = self::string($data[$field] ?? '', $limit);
}
if ($clean['logo'] !== '' && !Html::url($clean['logo'], true)) {
throw new RuntimeException('请检查站点标识地址。');
}
$components = $data['components'] ?? $clean['components'];
if (!is_array($components) || !array_is_list($components)) {
throw new RuntimeException('组件顺序无效。');
}
foreach ($components as $component) {
if (!is_string($component) || !isset(self::COMPONENTS[$kind][$component])) {
throw new RuntimeException('布局包含未知组件。');
}
}
$clean['components'] = array_values(array_unique($components));
$clean['links'] = Buttons::validate($data['links'] ?? $clean['links'], 20);
$clean['action'] = Buttons::validate($data['action'] ?? []);
$clean['provider'] = $kind === 'header' && $preset === 'member'
? self::provider($data['provider'] ?? []) : [];
return $clean;
}
public static function provider(array $data): array
{
$mode = $data['mode'] ?? '';
if ($mode === '') {
return [];
}
if (!in_array($mode, ['oidc', 'oauth2'], true)) {
throw new RuntimeException('请选择 OIDC 或 OAuth 2.0。');
}
$result = ['mode' => $mode];
foreach (['client_id', 'secret_env', 'scope', 'issuer', 'authorization', 'token', 'userinfo', 'subject_field', 'name_field', 'avatar_field', 'token_auth'] as $field) {
$result[$field] = self::string($data[$field] ?? '', 600);
}
if (!in_array($result['token_auth'], ['', 'client_secret_basic', 'client_secret_post'], true)) {
throw new RuntimeException('令牌端点认证方式无效。');
}
if ($result['client_id'] === '' || !preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $result['secret_env'])) {
throw new RuntimeException('填写客户端 ID 和以 LAYSITE_OAUTH_ 开头的客户端密钥环境变量名。');
}
foreach ($mode === 'oidc' ? ['issuer'] : ['authorization', 'token', 'userinfo'] as $field) {
$url = parse_url($result[$field]);
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || ($field === 'issuer' && isset($url['query'])) || !Html::url($result[$field], true)) {
throw new RuntimeException('认证端点必须使用完整的 HTTPS 地址。');
}
}
if ($mode === 'oauth2' && $result['subject_field'] === '') {
throw new RuntimeException('OAuth 2.0 用户资料需要指定稳定的用户 ID 字段。');
}
return $result;
}
public static function save(string $kind, ?int $id, string $name, string $preset, array $data, int $version, bool $default): int
{
$name = self::string($name, 100);
if ($name === '') {
throw new RuntimeException('请填写配置名称。');
}
$payload = Database::json(self::normalize($kind, $preset, $data));
return Database::write(function (PDO $pdo) use ($kind, $id, $name, $preset, $payload, $version, $default): int {
if ($id === null) {
$pdo->prepare('INSERT INTO design_presets (kind, name, preset, payload) VALUES (?, ?, ?, ?)')->execute([$kind, $name, $preset, $payload]);
$id = (int) $pdo->lastInsertId();
} else {
$query = $pdo->prepare('UPDATE design_presets SET name = ?, preset = ?, payload = ?, version = version + 1 WHERE id = ? AND kind = ? AND version = ?');
$query->execute([$name, $preset, $payload, $id, $kind, $version]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('配置已更新,请重新打开后再保存。');
}
}
if ($kind !== 'palette') {
$site = json_decode($pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if ($default) {
$site[$kind . '_id'] = $id;
} elseif (($site[$kind . '_id'] ?? null) === $id) {
unset($site[$kind . '_id']);
}
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
}
return $id;
});
}
private static function string(mixed $value, int $limit): string
{
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit) {
throw new RuntimeException('配置包含无效或过长的文字。');
}
return trim($value);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMXPath;
final class DirectoryCard
{
public static function links(array $article, string $body): array
{
$detail = self::hasText($article['summary']) || self::hasBody($body) ? '/articles/' . $article['slug'] : '';
$primary = ($article['card']['url'] ?? '') ?: $detail;
return ['primary' => $primary, 'detail' => $primary === $detail ? '' : $detail];
}
private static function hasText(string $text): bool
{
return preg_match('/[^\s\p{Z}\p{Cf}]/u', $text) === 1;
}
private static function hasBody(string $html): bool
{
if (self::hasText(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'))) {
return true;
}
if (!str_contains($html, 'src=')) {
return false;
}
$document = new DOMDocument();
$document->loadHTML('<meta charset="utf-8">' . $html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$xpath = new DOMXPath($document);
return (bool) $xpath->evaluate('boolean(//img[@src] | //audio[@src] | //video[@src] | //audio/source[@src] | //video/source[@src])');
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMNode;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use RuntimeException;
final class Html
{
public const ALIGNMENTS = ['left', 'center', 'right'];
private const TAGS = [
'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
];
public static function url(string $value, bool $media = false): bool
{
if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) {
return false;
}
if (str_starts_with($value, '/')) {
return !str_starts_with($value, '//');
}
if (str_starts_with($value, '#')) {
return !$media && strlen($value) > 1;
}
$scheme = strtolower((string) parse_url($value, PHP_URL_SCHEME));
return in_array($scheme, $media ? ['https'] : ['https', 'http', 'mailto', 'tel'], true);
}
public static function markdown(string $text): string
{
static $converter;
$converter ??= new GithubFlavoredMarkdownConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
$html = $converter->convert($text)->getContent();
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
}
public static function articleBody(array $article): string
{
return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
}
public static function applyCanvasEdits(string $body, array $edits): string
{
if (!array_is_list($edits) || count($edits) > 512) {
throw new RuntimeException('正文增量无效。');
}
$size = strlen($body);
$cursor = 0;
$result = '';
foreach ($edits as $edit) {
if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
throw new RuntimeException('正文增量无效。');
}
[$offset, $remove, $insert] = $edit;
if (!is_int($offset) || !is_int($remove) || !is_string($insert)
|| $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
throw new RuntimeException('正文增量无效。');
}
$result .= substr($body, $cursor, $offset - $cursor) . $insert;
$cursor = $offset + $remove;
if (strlen($result) > 300000) {
throw new RuntimeException('正文太长。');
}
}
$result .= substr($body, $cursor);
if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
throw new RuntimeException('正文太长或编码无效。');
}
return $result;
}
public static function sanitize(string $html, ?string $anchorPrefix = null): string
{
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$body = $document->getElementsByTagName('body')->item(0);
if (!$body) {
return '';
}
self::sanitizeChildren($body);
if ($anchorPrefix !== null) {
$ids = [];
foreach ($body->getElementsByTagName('*') as $element) {
$id = $element->getAttribute('id');
if ($id !== '') {
$ids[$id] = $anchorPrefix . '-' . $id;
$element->setAttribute('id', $ids[$id]);
}
}
foreach ($body->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
$link->setAttribute('href', '#' . $ids[substr($href, 1)]);
}
}
}
$output = '';
foreach ($body->childNodes as $child) {
$output .= $document->saveHTML($child);
}
return trim($output);
}
private static function sanitizeChildren(DOMNode $parent): void
{
foreach (iterator_to_array($parent->childNodes) as $element) {
if ($element->nodeType === XML_COMMENT_NODE) {
$parent->removeChild($element);
continue;
}
if (!$element instanceof DOMElement) {
continue;
}
if (!array_key_exists($element->tagName, self::TAGS)) {
$parent->removeChild($element);
continue;
}
$allowed = [...self::TAGS[$element->tagName], 'class', 'id'];
foreach (iterator_to_array($element->attributes) as $attribute) {
$name = $attribute->name;
$value = $attribute->value;
if (!in_array($name, $allowed, true)
|| ($name === 'href' && !self::url($value))
|| (in_array($name, ['src', 'poster'], true) && !self::url($value, true))
|| ($name === 'target' && $value !== '_blank')
|| ($name === 'tabindex' && $value !== '0')) {
$element->removeAttribute($name);
}
}
if ($element->tagName === 'a') {
if ($element->getAttribute('target') === '_blank') {
$element->setAttribute('rel', 'noopener noreferrer');
} else {
$element->removeAttribute('rel');
}
}
self::sanitizeChildren($element);
}
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace App\Content;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider;
use League\OAuth2\Client\Provider\GenericProvider;
use RuntimeException;
final class IdentityProvider
{
public readonly GenericProvider $client;
private readonly Client $http;
private array $oidc = [];
public function __construct(private readonly array $config)
{
$secret = getenv($config['secret_env']);
if (!is_string($secret) || $secret === '') {
throw new RuntimeException('身份服务的客户端密钥尚未配置。');
}
$this->http = new Client(['timeout' => 8, 'connect_timeout' => 4, 'allow_redirects' => false]);
$scope = preg_split('/\s+/', trim($config['scope']), -1, PREG_SPLIT_NO_EMPTY);
$authorization = $config['authorization'];
$token = $config['token'];
$userinfo = $config['userinfo'];
if ($config['mode'] === 'oidc') {
$this->oidc = $this->document(rtrim($config['issuer'], '/') . '/.well-known/openid-configuration');
if (($this->oidc['issuer'] ?? null) !== $config['issuer']) {
throw new RuntimeException('OIDC Issuer 与发现文档不一致。');
}
$authorization = $this->endpoint($this->oidc['authorization_endpoint'] ?? '');
$token = $this->endpoint($this->oidc['token_endpoint'] ?? '');
$userinfo = isset($this->oidc['userinfo_endpoint']) ? $this->endpoint($this->oidc['userinfo_endpoint']) : '';
$scope = array_values(array_unique(['openid', 'profile', 'email', ...$scope]));
}
$auth = $config['token_auth'];
if ($auth === '') {
$supported = $this->oidc['token_endpoint_auth_methods_supported'] ?? ['client_secret_basic'];
if ($this->oidc === [] || (!in_array('client_secret_basic', $supported, true) && in_array('client_secret_post', $supported, true))) {
$auth = 'client_secret_post';
} elseif (in_array('client_secret_basic', $supported, true)) {
$auth = 'client_secret_basic';
} else {
throw new RuntimeException('身份服务没有公布受支持的令牌端点认证方式。');
}
}
$this->client = new GenericProvider([
'clientId' => $config['client_id'], 'clientSecret' => $secret,
'redirectUri' => View::absolute('/account/callback'), 'urlAuthorize' => $authorization,
'urlAccessToken' => $token, 'urlResourceOwnerDetails' => $userinfo,
'pkceMethod' => GenericProvider::PKCE_METHOD_S256, 'scopes' => $scope, 'scopeSeparator' => ' ',
], [
'httpClient' => $this->http,
'optionProvider' => $auth === 'client_secret_basic' ? new HttpBasicAuthOptionProvider() : new PostAuthOptionProvider(),
]);
}
public function authorization(string $nonce): string
{
return $this->client->getAuthorizationUrl($this->oidc === [] ? [] : ['nonce' => $nonce]);
}
public function profile(string $code, string $proof, string $nonce): array
{
$this->client->setPkceCode($proof);
$token = $this->client->getAccessToken('authorization_code', ['code' => $code]);
if ($this->oidc === []) {
$claims = $this->client->getResourceOwner($token)->toArray();
} else {
$claims = $this->verifiedClaims($token->getValues()['id_token'] ?? '', $nonce);
if (isset($this->oidc['userinfo_endpoint'])) {
$more = $this->client->getResourceOwner($token)->toArray();
if (($more['sub'] ?? null) !== $claims['sub']) {
throw new RuntimeException('OIDC 用户资料的主体与 ID Token 不一致。');
}
$claims = $more + $claims;
}
}
$subject = $claims[$this->oidc !== [] ? 'sub' : $this->config['subject_field']] ?? null;
if ((!is_string($subject) && !is_int($subject)) || (string) $subject === '' || strlen((string) $subject) > 255) {
throw new RuntimeException('身份服务没有返回有效的用户标识。');
}
$name = $claims[$this->config['name_field'] ?: 'name'] ?? $claims['preferred_username'] ?? (string) $subject;
$avatar = $claims[$this->config['avatar_field'] ?: 'picture'] ?? '';
return [
'subject' => (string) $subject,
'name' => is_string($name) ? mb_substr($name, 0, 100) : (string) $subject,
'avatar' => is_string($avatar) && strlen($avatar) <= 2048 && str_starts_with($avatar, 'https://') && Html::url($avatar, true) ? $avatar : '',
];
}
private function verifiedClaims(mixed $encoded, string $nonce): array
{
if (!is_string($encoded) || strlen($encoded) > 16384 || substr_count($encoded, '.') !== 2) {
throw new RuntimeException('身份服务没有返回有效的 ID Token。');
}
$header = JWT::jsonDecode(JWT::urlsafeB64Decode(explode('.', $encoded, 2)[0]));
$algorithm = $header->alg ?? '';
if (!in_array($algorithm, ['RS256', 'RS384', 'RS512', 'ES256', 'ES384'], true)) {
throw new RuntimeException('身份服务使用了不支持的 ID Token 签名算法。');
}
$keys = $this->document($this->endpoint($this->oidc['jwks_uri'] ?? ''));
$claims = (array) JWT::decode($encoded, JWK::parseKeySet($keys, $algorithm));
$audience = (array) ($claims['aud'] ?? []);
$client = $this->config['client_id'];
if (($claims['iss'] ?? null) !== $this->config['issuer'] || !in_array($client, $audience, true)
|| ((count($audience) > 1 || isset($claims['azp'])) && ($claims['azp'] ?? null) !== $client)
|| ($claims['nonce'] ?? null) !== $nonce || !is_string($claims['sub'] ?? null) || $claims['sub'] === ''
|| !is_int($claims['exp'] ?? null) || $claims['exp'] <= time()
|| !is_int($claims['iat'] ?? null) || $claims['iat'] > time() + 60) {
throw new RuntimeException('OIDC ID Token 声明校验失败。');
}
return $claims;
}
private function document(string $endpoint): array
{
$response = $this->http->get($this->endpoint($endpoint), ['headers' => ['Accept' => 'application/json'], 'stream' => true]);
$body = Utils::copyToString($response->getBody(), 1048577);
if (strlen($body) > 1048576 || $response->getStatusCode() !== 200) {
throw new RuntimeException('身份服务文档超过大小限制。');
}
$data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($data)) {
throw new RuntimeException('身份服务文档格式无效。');
}
return $data;
}
private function endpoint(mixed $endpoint): string
{
$url = is_string($endpoint) ? parse_url($endpoint) : false;
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || !Html::url($endpoint, true)) {
throw new RuntimeException('身份服务端点必须使用 HTTPS。');
}
return $endpoint;
}
}
+130
View File
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMXPath;
use RuntimeException;
use Throwable;
use Webman\Http\UploadFile;
final class Media
{
public const MAX_BYTES = 64 * 1024 * 1024;
private const EXTENSIONS = [
'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp',
'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg',
'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov',
'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav',
'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2',
];
public static function all(bool $includeArchived = false): array
{
$query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0');
$files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll();
foreach ($files as &$file) {
$file['url'] = '/assets/uploads/' . $file['name'];
}
unset($file);
return $files;
}
public static function upload(UploadFile $file, string $label): void
{
if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。');
}
$source = $file->getPathname();
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source);
$extension = self::EXTENSIONS[$mime] ?? null;
if ($extension === null) {
throw new RuntimeException('文件类型不受支持。');
}
$content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null;
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$directory = self::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('资源目录无法创建。');
}
$path = $directory . '/' . $name;
try {
$written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content);
if (!$written) {
throw new RuntimeException('文件写入失败。');
}
$query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)');
$query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]);
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function find(string $name): ?array
{
$query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?');
$query->execute([$name]);
return $query->fetch() ?: null;
}
public static function update(string $name, string $label, bool $archived): void
{
Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?')
->execute([$label, (int) $archived, $name]);
}
public static function directory(): string
{
return rtrim(getenv('LAYSITE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/');
}
public static function validateBackup(string $path, string $name, string $mime, int $size): void
{
if ((new \finfo(FILEINFO_MIME_TYPE))->file($path) !== $mime
|| !isset(self::EXTENSIONS[$mime]) || self::EXTENSIONS[$mime] !== pathinfo($name, PATHINFO_EXTENSION)) {
throw new RuntimeException('备份资源类型与清单不一致。');
}
if ($mime === 'image/svg+xml') {
self::safeSvg($path, $size);
}
}
private static function safeSvg(string $source, int $size): string
{
if ($size > 512 * 1024) {
throw new RuntimeException('SVG 图标最大支持 512 KB。');
}
$svg = new DOMDocument();
if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype
|| $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') {
throw new RuntimeException('SVG 图标格式无效。');
}
$tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc'];
$attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap',
'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y',
'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform'];
foreach ((new DOMXPath($svg))->query('//*') as $element) {
if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg'
|| !in_array($element->localName, $tags, true)) {
throw new RuntimeException('SVG 仅支持基础矢量元素。');
}
foreach ($element->attributes as $attribute) {
if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true)
|| !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) {
throw new RuntimeException('SVG 包含不支持的属性或外部引用。');
}
}
}
return $svg->saveXML($svg->documentElement);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace App\Content;
use RuntimeException;
final class PageDraft
{
public const RESERVED = ['admin', 'assets', 'home', 'account', 'mcp', 'palette', 'favicon'];
public static function slug(mixed $value, array $reserved = self::RESERVED): string
{
if (!is_string($value) || strlen($value) > 70 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value)
|| in_array($value, $reserved, true)) {
throw new RuntimeException('网址标识无效或已保留。');
}
return $value;
}
public static function content(array $input, array $page): array
{
$name = self::text($input['name'] ?? $page['name'] ?? '', 100, true);
$page += ['name' => $name, 'title' => $name, 'heading' => $name, 'description' => '', 'lead' => '',
'accent' => '', 'image' => '', 'alt' => '', 'image_scale' => 0, 'alignments' => [], 'visibility' => [],
'actions' => [], 'quicklinks' => [], 'theme' => '', 'sections' => []];
$page['name'] = $name;
foreach (['title' => 160, 'heading' => 110, 'description' => 300, 'lead' => 600, 'accent' => 110, 'image' => 1000, 'alt' => 200] as $field => $limit) {
$page[$field] = self::text($input[$field] ?? $page[$field], $limit, in_array($field, ['title', 'heading'], true));
}
if (mb_strlen($page['heading'] . $page['accent']) > 110 || ($page['image'] !== '' && !Html::url($page['image'], true))) {
throw new RuntimeException('首屏标题过长或图片地址不正确。');
}
foreach (['header', 'footer', 'palette'] as $kind) {
$key = $kind . '_id';
$page[$key] = array_key_exists($key, $input) ? DesignLibrary::selection($kind, $input[$key]) : ($page[$key] ?? null);
}
$page['actions'] = Buttons::validate($input['actions'] ?? $page['actions']);
if (array_key_exists('visibility', $input)) {
if (!is_array($input['visibility'])) {
throw new RuntimeException('页面显示选项无效。');
}
foreach ($input['visibility'] as $area => $visible) {
if (!in_array($area, ['hero', 'header', 'footer'], true) || !is_bool($visible)) {
throw new RuntimeException('页面显示选项无效。');
}
$page['visibility'][$area] = $visible;
}
}
$page['status'] = 'draft';
if (array_key_exists('sections', $input)) {
$oldKeys = array_column($page['sections'], 'key');
$page['sections'] = self::sections($input['sections']);
if (!array_key_exists('actions', $input)) {
$removed = array_map(static fn (string $key): string => '#' . $key, array_diff($oldKeys, array_column($page['sections'], 'key')));
$page['actions'] = array_values(array_filter($page['actions'], static fn (array $button): bool => !in_array($button[0], $removed, true)));
}
$page['quicklinks'] = array_map(static fn (array $section): array => ['#' . $section['key'], $section['title']], array_slice($page['sections'], 0, 20));
}
return $page;
}
private static function sections(mixed $items): array
{
if (!is_array($items) || !array_is_list($items) || count($items) > 50) {
throw new RuntimeException('每页最多可提交 50 个区块。');
}
$sections = [];
foreach ($items as $item) {
if (!is_array($item)) {
throw new RuntimeException('区块必须是对象。');
}
$key = self::slug($item['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (isset($sections[$key])) {
throw new RuntimeException('区块锚点重复。');
}
$preset = null;
if (isset($item['preset'])) {
$preset = is_string($item['preset']) ? BlockTemplates::find($item['preset']) : null;
if (!$preset) {
throw new RuntimeException('区块模板不存在。');
}
}
$style = $item['style'] ?? $preset[4] ?? 'plain';
if (!in_array($style, ['plain', 'tinted'], true)) {
throw new RuntimeException('区块样式无效。');
}
$sections[$key] = [
'key' => $key, 'title' => self::text($item['title'] ?? $preset[0] ?? '', 100, true),
'lead' => self::text($item['lead'] ?? $preset[2] ?? '', 500),
'body' => Html::sanitize(self::text($item['body'] ?? $preset[1] ?? '', 120000)),
'style' => $style, 'feed' => $preset[3] ?? null, 'version' => null,
];
}
return array_values($sections);
}
private static function text(mixed $value, int $limit, bool $required = false): string
{
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8') || mb_strlen($value) > $limit || ($required && trim($value) === '')) {
throw new RuntimeException('请检查页面内容及字段长度。');
}
return trim($value);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class PageTemplates
{
public static function groups(): array
{
static $groups;
return $groups ??= require dirname(__DIR__, 2) . '/resources/page-templates.php';
}
public static function find(string $key): ?array
{
foreach (self::groups() as $theme => $group) {
if (!isset($group['pages'][$key])) {
continue;
}
$template = $group['pages'][$key];
$sections = [];
$quicklinks = [];
foreach ($template['sections'] as [$anchor, $title, $style, $body, $feed]) {
$sections[] = ['key' => $anchor, 'title' => $title, 'style' => $style, 'body' => Html::sanitize($body, $anchor),
'lead' => '', 'feed' => $feed, 'alignments' => '{}', 'version' => 0];
$quicklinks[] = ['#' . $anchor, $title];
}
return array_replace($template, [
'slug' => $key, 'theme' => $theme, 'title' => $template['name'], 'accent' => '',
'lead' => $template['description'], 'quicklinks' => $quicklinks, 'status' => 'draft',
'alignments' => [], 'image_scale' => 0, 'sections' => $sections,
]);
}
return null;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Content;
final class Passwords
{
public const MIN_LENGTH = 8;
public static function isSupported(string $password): bool
{
return strlen($password) <= 72 && !str_contains($password, "\0") && mb_check_encoding($password, 'UTF-8');
}
public static function isValidNew(string $password): bool
{
return self::isSupported($password) && mb_strlen($password, 'UTF-8') >= self::MIN_LENGTH;
}
}
+403
View File
@@ -0,0 +1,403 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class Repository
{
public const DIRECTORIES = [
'catalog' => '目录', 'projects' => '项目', 'partners' => '合作伙伴',
];
public const CATEGORIES = ['announcement' => '公告', 'news' => '新闻', 'product' => '产品'] + self::DIRECTORIES;
private const ARTICLE_FIELDS = 'articles.*, (SELECT json_group_object(c.slug, c.name)
FROM article_category_links l JOIN article_categories c ON c.slug = l.category_slug
WHERE l.article_id = articles.id) AS categories';
private PDO $pdo;
public function __construct()
{
$this->pdo = Database::connect();
}
public function site(): array
{
return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
}
public function pages(bool $publishedOnly = false): array
{
$where = $publishedOnly ? " WHERE status = 'published'" : '';
return $this->pdo->query('SELECT slug, name, title, updated_at, status, version FROM pages' . $where . ' ORDER BY rowid')->fetchAll();
}
public function createPage(string $slug, string $name, array $template = []): void
{
Database::write(function (PDO $pdo) use ($slug, $name, $template): void {
$query = $pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent,
lead, image, alt, actions, quicklinks, theme, visibility, header_id, footer_id, palette_id, status, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?)");
$query->execute([
$slug, $name, $template['title'] ?? $name, $template['description'] ?? '', $template['heading'] ?? $name,
$template['accent'] ?? '', $template['lead'] ?? '', $template['image'] ?? '', $template['alt'] ?? '',
Database::json($template['actions'] ?? []), Database::json($template['quicklinks'] ?? []),
$template['theme'] ?? '', Database::json($template['visibility'] ?? []), $template['header_id'] ?? null, $template['footer_id'] ?? null, $template['palette_id'] ?? null, self::now(),
]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此页面地址已存在。');
}
foreach ($template['sections'] ?? [] as $section) {
self::insertSection($pdo, $slug, $section['key'], $section);
}
});
}
public function page(string $slug): ?array
{
$page = $this->one('SELECT * FROM pages WHERE slug = ?', [$slug]);
if (!$page) {
return null;
}
foreach (['actions', 'quicklinks', 'alignments', 'visibility'] as $key) {
$page[$key] = json_decode($page[$key], true, flags: JSON_THROW_ON_ERROR);
}
$query = $this->pdo->prepare('SELECT * FROM sections WHERE page_slug = ? ORDER BY position, key');
$query->execute([$slug]);
$page['sections'] = $query->fetchAll();
return $page;
}
public function section(string $page, string $key): ?array
{
return $this->one('SELECT * FROM sections WHERE page_slug = ? AND key = ?', [$page, $key]);
}
public function publishedFeed(string $page, string $key): ?array
{
return $this->one("SELECT sections.title, sections.feed FROM sections
JOIN pages ON pages.slug = sections.page_slug
WHERE pages.slug = ? AND pages.status = 'published' AND sections.key = ? AND sections.feed IS NOT NULL", [$page, $key]);
}
public function savePage(string $slug, array $data, int $version, array $sections = [], bool $replaceDraftSections = false): void
{
Database::write(function (PDO $pdo) use ($slug, $data, $version, $sections, $replaceDraftSections): void {
$query = $pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?,
image = ?, alt = ?, image_scale = ?, alignments = ?, actions = ?, quicklinks = ?, visibility = ?, header_id = ?, footer_id = ?, palette_id = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?');
$query->execute([
$data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'],
$data['image'], $data['alt'], $data['image_scale'], Database::json($data['alignments']), Database::json($data['actions']), Database::json($data['quicklinks']),
Database::json($data['visibility']), $data['header_id'], $data['footer_id'], $data['palette_id'], $data['status'], self::now(), $slug, $version,
]);
self::checkVersion($query->rowCount());
if ($replaceDraftSections) {
$pdo->prepare('DELETE FROM sections WHERE page_slug = ?')->execute([$slug]);
}
foreach ($sections as $section) {
if (!empty($section['delete'])) {
self::deleteSection($pdo, $slug, $section['key'], $section['version']);
} elseif ($section['version'] === null) {
self::insertSection($pdo, $slug, $section['key'], $section);
} else {
self::updateSection($pdo, $slug, $section['key'], $section, $section['version']);
}
}
});
}
public function saveSection(string $page, string $key, array $data, int $version): void
{
Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void {
self::updateSection($pdo, $page, $key, $data, $version);
self::touchPage($pdo, $page);
});
}
private static function updateSection(PDO $pdo, string $page, string $key, array $data, int $version): void
{
$query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, feed = ?, alignments = COALESCE(?, alignments), version = version + 1
WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $data['feed'] ?? null, $data['alignments'] ?? null, $page, $key, $version]);
self::checkVersion($query->rowCount());
}
public function createSection(string $page, string $key, string $title, string $style, string $body, ?string $feed = null, string $lead = ''): void
{
Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body, $feed, $lead): void {
self::insertSection($pdo, $page, $key, compact('title', 'style', 'body', 'feed', 'lead'));
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function insertSection(PDO $pdo, string $page, string $key, array $data): void
{
$query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, feed, alignments, position)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?');
$query->execute([$page, $key, $data['title'], $data['lead'], $data['style'], $data['body'], $data['feed'] ?? null, $data['alignments'] ?? '{}', $page]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此区块锚点已被使用。');
}
}
private static function deleteSection(PDO $pdo, string $page, string $key, int $version): void
{
$query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?');
$query->execute([$page, $key, $version]);
self::checkVersion($query->rowCount());
$pdo->prepare("UPDATE pages SET
quicklinks = (SELECT json_group_array(json(value)) FROM json_each(quicklinks) WHERE json_extract(value, '$[0]') <> :anchor),
actions = (SELECT json_group_array(json(value)) FROM json_each(actions) WHERE json_extract(value, '$[0]') <> :anchor)
WHERE slug = :slug")->execute(['anchor' => '#' . $key, 'slug' => $page]);
}
public function arrangeSection(string $page, string $key, string $operation, int $version, int $pageVersion): void
{
Database::write(function (PDO $pdo) use ($page, $key, $operation, $version, $pageVersion): void {
$current = $pdo->prepare('SELECT version FROM pages WHERE slug = ?');
$current->execute([$page]);
$revision = $current->fetchColumn();
self::checkVersion($revision !== false && (int) $revision === $pageVersion ? 1 : 0);
if ($operation === 'delete') {
self::deleteSection($pdo, $page, $key, $version);
self::touchPage($pdo, $page, structureChanged: true);
return;
}
$query = $pdo->prepare("SELECT key, version FROM sections WHERE page_slug = ? AND style <> 'hero-links' ORDER BY position, key");
$query->execute([$page]);
$revisions = $query->fetchAll(PDO::FETCH_KEY_PAIR);
if (!array_key_exists($key, $revisions)) {
throw new RuntimeException('找不到该区块。');
}
self::checkVersion((int) $revisions[$key] === $version ? 1 : 0);
$keys = array_map('strval', array_keys($revisions));
$index = array_search($key, $keys, true);
$other = $index + ($operation === 'up' ? -1 : 1);
if (!isset($keys[$other])) {
return;
}
[$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]];
$query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?');
foreach ($keys as $position => $section) {
$query->execute([$position, $page, $section]);
}
self::touchPage($pdo, $page, structureChanged: true);
});
}
private static function touchPage(PDO $pdo, string $slug, bool $structureChanged = false): void
{
$revision = $structureChanged ? ', version = version + 1' : '';
$pdo->prepare('UPDATE pages SET updated_at = ?' . $revision . ' WHERE slug = ?')->execute([self::now(), $slug]);
}
public function categories(): array
{
return $this->pdo->query('SELECT slug, name FROM article_categories ORDER BY rowid')->fetchAll(PDO::FETCH_KEY_PAIR);
}
public function createCategory(string $slug, string $name): void
{
$query = $this->pdo->prepare('INSERT OR IGNORE INTO article_categories (slug, name) VALUES (?, ?)');
$query->execute([$slug, $name]);
if ($query->rowCount() !== 1) {
throw new RuntimeException('此分类网址标识已被使用。');
}
}
public function articles(string|array|null $category = null, ?string $tag = null, bool $public = true,
int $limit = 30, int $offset = 0, bool $directoryOrder = false): array
{
if ($category === []) {
return [];
}
$sql = 'SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE 1 = 1';
$args = [];
if ($public) {
$sql .= " AND status = 'published'";
}
if ($category !== null) {
$args = (array) $category;
$marks = implode(', ', array_fill(0, count($args), '?'));
$sql .= " AND EXISTS (SELECT 1 FROM article_category_links
WHERE article_id = articles.id AND category_slug IN ($marks))";
}
if ($tag !== null) {
$sql .= ' AND EXISTS (SELECT 1 FROM json_each(articles.tags) WHERE value = ?)';
$args[] = $tag;
}
$order = $public ? 'published_at' : 'updated_at';
$order = $directoryOrder ? "COALESCE(json_extract(card, '$.position'), 0), id" : "$order DESC, id DESC";
$query = $this->pdo->prepare($sql . ' ORDER BY ' . $order . ' LIMIT ? OFFSET ?');
$query->execute([...$args, $limit, $offset]);
return array_map(self::decodeArticle(...), $query->fetchAll());
}
public function articleById(int $id): ?array
{
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . ' FROM articles WHERE id = ?', [$id]));
}
public function published(string $slug): ?array
{
return self::decodeArticle($this->one('SELECT ' . self::ARTICLE_FIELDS . " FROM articles WHERE slug = ? AND status = 'published'", [$slug]));
}
public function articleRedirect(string $slug): ?array
{
return $this->one("SELECT articles.slug FROM article_redirects
JOIN articles ON articles.id = article_redirects.article_id
WHERE article_redirects.slug = ? AND articles.status = 'published'", [$slug]);
}
public function legacyArticle(string $path): ?array
{
return $this->one("SELECT slug FROM articles WHERE legacy_path = ? AND status = 'published'", [$path]);
}
public function saveArticle(?int $id, array $data, int $version): int
{
return Database::write(function (PDO $pdo) use ($id, $data, $version): int {
$old = $id !== null ? $this->articleById($id) : null;
if ($id !== null && (!$old || $old['version'] !== $version)) {
self::checkVersion(0);
}
$existing = $this->one('SELECT id FROM articles WHERE slug = ?', [$data['slug']]);
$redirect = $this->one('SELECT article_id FROM article_redirects WHERE slug = ?', [$data['slug']]);
if (($existing && $existing['id'] !== $id) || ($redirect && $redirect['article_id'] !== $id)) {
throw new RuntimeException('此网址标识已被使用。');
}
$publishedAt = $old['published_at'] ?? ($data['status'] === 'published' && ($old['status'] ?? '') !== 'published' ? self::now() : null);
$values = [
$data['slug'], $data['title'], $data['summary'], $data['body'],
$data['body_format'], Database::json($data['card']),
Database::json($data['tags']), $data['status'], $publishedAt, self::now(),
];
if ($id === null) {
$query = $pdo->prepare('INSERT INTO articles
(id, slug, title, summary, body, body_format, card, tags, status, published_at, updated_at)
VALUES (' . Database::NEXT_ARTICLE_ID . ', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$query->execute($values);
$id = (int) $pdo->lastInsertId();
} else {
if ($old['slug'] !== $data['slug']) {
$pdo->prepare('DELETE FROM article_redirects WHERE slug = ? AND article_id = ?')->execute([$data['slug'], $id]);
$pdo->prepare('INSERT INTO article_redirects (slug, article_id) VALUES (?, ?)')->execute([$old['slug'], $id]);
}
$query = $pdo->prepare('UPDATE articles SET slug = ?, title = ?, summary = ?, body = ?,
body_format = ?, card = ?, tags = ?, status = ?, published_at = ?, updated_at = ?, version = version + 1
WHERE id = ? AND version = ?');
$query->execute([...$values, $id, $version]);
self::checkVersion($query->rowCount());
$pdo->prepare('DELETE FROM article_category_links WHERE article_id = ?')->execute([$id]);
}
$link = $pdo->prepare('INSERT INTO article_category_links (article_id, category_slug) VALUES (?, ?)');
foreach ($data['categories'] as $category) {
$link->execute([$id, $category]);
}
return $id;
});
}
public function deleteArticle(int $id, int $version): void
{
Database::write(function (PDO $pdo) use ($id, $version): void {
// Keep the original seed slug even if the article has been renamed.
$deletions = $pdo->prepare('INSERT INTO article_deletions (slug, article_id)
SELECT slug, id FROM articles WHERE id = :id
UNION ALL SELECT slug, article_id FROM article_redirects WHERE article_id = :id
ON CONFLICT (slug) DO UPDATE SET article_id = excluded.article_id');
$deletions->execute(['id' => $id]);
$delete = $pdo->prepare('DELETE FROM articles WHERE id = ? AND version = ?');
$delete->execute([$id, $version]);
self::checkVersion($delete->rowCount());
});
}
public function sitemapArticles(): iterable
{
$query = $this->pdo->query("SELECT slug, updated_at FROM articles WHERE status = 'published'
AND (trim(body) <> '' OR trim(summary) <> '' OR json_extract(card, '$.image') <> '' OR json_extract(card, '$.url') <> '')
ORDER BY slug");
yield from $query;
}
public function administrator(string $email): ?array
{
return $this->one('SELECT id, email, password_hash FROM users WHERE email = ?', [$email]);
}
public function administratorById(int $id): ?array
{
return $this->one('SELECT id, email, password_hash FROM users WHERE id = ?', [$id]);
}
public function changePassword(array $user, string $newHash): bool
{
$query = $this->pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ? AND password_hash = ?');
$query->execute([$newHash, $user['id'], $user['password_hash']]);
return $query->rowCount() === 1;
}
public function recordFailedLogin(string $address): int
{
$now = time();
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12 && $current['expires_at'] > $now) {
return $current['expires_at'] - $now;
}
return Database::write(function (PDO $pdo) use ($address, $now): int {
$pdo->prepare('DELETE FROM login_attempts WHERE expires_at <= ?')->execute([$now]);
$current = $this->one('SELECT attempts, expires_at FROM login_attempts WHERE address = ?', [$address]);
if ($current && $current['attempts'] >= 12) {
return $current['expires_at'] - $now;
}
$query = $pdo->prepare('INSERT INTO login_attempts (address, attempts, expires_at) VALUES (?, 1, ?)
ON CONFLICT (address) DO UPDATE SET attempts = attempts + 1');
$query->execute([$address, $now + 900]);
return 0;
});
}
private function one(string $sql, array $args): ?array
{
$query = $this->pdo->prepare($sql);
$query->execute($args);
return $query->fetch() ?: null;
}
private static function decodeArticle(?array $article): ?array
{
if ($article !== null) {
foreach (['tags', 'categories', 'card'] as $field) {
$article[$field] = json_decode($article[$field], true, flags: JSON_THROW_ON_ERROR);
}
}
return $article;
}
private static function now(): string
{
return date('Y-m-d H:i:s');
}
private static function checkVersion(int $count): void
{
if ($count !== 1) {
throw new RuntimeException('此内容已在其他窗口更新。请保留你的修改,重新打开后再合并。');
}
}
}
+289
View File
@@ -0,0 +1,289 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use PharData;
use RuntimeException;
use Throwable;
final class SiteBackup
{
private const FORMAT = 'laysite-site';
private const VERSION = 2;
private const TABLES = [
'site_settings', 'design_presets', 'pages', 'sections', 'article_categories', 'articles',
'article_category_links', 'article_redirects', 'article_deletions', 'media',
];
private const MANIFEST_LIMIT = 32 * 1024 * 1024;
public static function export(string $path): void
{
if (!str_ends_with($path, '.tar') || file_exists($path)) {
throw new RuntimeException('请选择尚不存在的 .tar 备份路径。');
}
try {
Database::write(function (PDO $pdo) use ($path): void {
$tables = [];
foreach (self::TABLES as $table) {
$tables[$table] = $pdo->query('SELECT * FROM ' . $table)->fetchAll();
}
$files = [];
$archive = new PharData($path);
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name']);
$file = Media::directory() . '/' . $name;
if (!is_file($file) || is_link($file) || filesize($file) !== (int) $asset['size']) {
throw new RuntimeException('资源文件缺失或大小已变更:' . $name);
}
$files[$name] = hash_file('sha256', $file);
$archive->addFile($file, 'media/' . $name);
}
$manifest = Database::json(['format' => self::FORMAT, 'version' => self::VERSION, 'exported_at' => gmdate('c'), 'tables' => $tables, 'files' => $files]);
if (strlen($manifest) > self::MANIFEST_LIMIT) {
throw new RuntimeException('站点内容超过当前备份格式的大小上限。');
}
$archive->addFromString('site.json', $manifest);
});
} catch (Throwable $error) {
if (is_file($path)) {
unlink($path);
}
throw $error;
}
}
public static function import(string $path): void
{
$archive = new PharData($path);
if (!isset($archive['site.json']) || $archive['site.json']->isLink() || $archive['site.json']->getSize() > self::MANIFEST_LIMIT) {
throw new RuntimeException('备份清单缺失或过大。');
}
$manifest = json_decode($archive['site.json']->getContent(), true, 48, JSON_THROW_ON_ERROR);
$tables = self::prepare($manifest);
$files = $manifest['files'] ?? [];
if (!is_array($files) || count($files) !== count($tables['media'])) {
throw new RuntimeException('备份资源清单不完整。');
}
$directory = Media::directory();
if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) {
throw new RuntimeException('不能写入资源目录。');
}
$stage = $directory . '/.restore-' . bin2hex(random_bytes(12));
if (!mkdir($stage, 0700)) {
throw new RuntimeException('不能创建临时资源目录。');
}
$staged = [];
$installed = [];
try {
foreach ($tables['media'] as $asset) {
$name = self::mediaName($asset['name'] ?? null);
$size = $asset['size'] ?? 0;
if (!is_int($size) || $size < 1 || $size > Media::MAX_BYTES || isset($staged[$name])
|| !is_string($files[$name] ?? null) || !isset($archive['media/' . $name])
|| $archive['media/' . $name]->isLink() || !$archive['media/' . $name]->isFile() || $archive['media/' . $name]->getSize() !== $size) {
throw new RuntimeException('备份资源不完整:' . $name);
}
$staged[$name] = $stage . '/' . $name;
$source = fopen('phar://' . $path . '/media/' . $name, 'rb');
if ($source === false) {
throw new RuntimeException('不能读取备份资源。');
}
try {
$destination = fopen($staged[$name], 'xb');
if ($destination === false) {
throw new RuntimeException('不能暂存备份资源。');
}
try {
$written = stream_copy_to_stream($source, $destination, $size + 1);
} finally {
fclose($destination);
}
} finally {
fclose($source);
}
if ($written !== $size || !hash_equals($files[$name], hash_file('sha256', $staged[$name]))) {
throw new RuntimeException('备份资源校验失败:' . $name);
}
Media::validateBackup($staged[$name], $name, $asset['mime'] ?? '', $size);
}
Database::write(function (PDO $pdo) use ($tables, $staged, $directory, &$installed): void {
self::replaceTables($pdo, $tables);
foreach ($staged as $name => $source) {
$target = $directory . '/' . $name;
if (is_file($target) && !is_link($target) && hash_file('sha256', $target) === hash_file('sha256', $source)) {
continue;
}
if (file_exists($target) || is_link($target) || !link($source, $target)) {
throw new RuntimeException('资源名称冲突:' . $name);
}
$installed[] = $target;
}
});
} catch (Throwable $error) {
foreach ($installed as $file) {
unlink($file);
}
throw $error;
} finally {
foreach ($staged as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($stage);
}
}
private static function prepare(mixed $manifest): array
{
if (!is_array($manifest) || ($manifest['format'] ?? '') !== self::FORMAT
|| !in_array($manifest['version'] ?? null, [1, self::VERSION], true) || !is_array($manifest['tables'] ?? null)) {
throw new RuntimeException('备份格式不受支持,请使用相同或更新版本的 LaySite。');
}
$tables = $manifest['tables'];
if ($manifest['version'] === 1) {
$tables += ['design_presets' => [], 'article_deletions' => []];
}
foreach (self::TABLES as $table) {
if (!is_array($tables[$table] ?? null) || !array_is_list($tables[$table])) {
throw new RuntimeException('备份数据表不完整。');
}
foreach ($tables[$table] as $row) {
if (!is_array($row) || array_is_list($row)) {
throw new RuntimeException('备份数据行格式无效。');
}
}
}
if (count($tables['site_settings']) !== 1 || !in_array('home', array_column($tables['pages'], 'slug'), true)) {
throw new RuntimeException('备份缺少站点身份或首页。');
}
$designs = [];
foreach ($tables['design_presets'] as &$row) {
$payload = self::decode($row['payload'] ?? '');
$row['payload'] = Database::json(DesignLibrary::normalize($row['kind'] ?? '', $row['preset'] ?? '', $payload));
$designs[$row['id']] = $row['kind'];
}
unset($row);
$settings = self::decode($tables['site_settings'][0]['payload'] ?? '');
if (!is_string($settings['name'] ?? null) || trim($settings['name']) === '' || mb_strlen($settings['name']) > 100) {
throw new RuntimeException('备份的站点名称无效。');
}
$site = ['name' => $settings['name'], 'cdn' => ['origin' => Assets::cdn($settings['cdn']['origin'] ?? '')], 'revisions' => ['general' => time()]];
foreach (['header', 'footer'] as $kind) {
if (isset($settings[$kind . '_id'])) {
$site[$kind . '_id'] = self::selection($designs, $kind, $settings[$kind . '_id']);
}
}
$tables['site_settings'] = [['id' => 1, 'payload' => Database::json($site)]];
foreach ($tables['pages'] as &$row) {
PageDraft::slug($row['slug'] ?? null, ['admin', 'assets', 'account', 'mcp', 'palette', 'favicon']);
self::validateAssetUrl($row['image'] ?? '', true);
$row['actions'] = Database::json(Buttons::validate(self::decode($row['actions'] ?? '[]')));
$row['quicklinks'] = Database::json(Buttons::validate(self::decode($row['quicklinks'] ?? '[]'), 20));
$row['visibility'] = Database::json(array_intersect_key(self::decode($row['visibility'] ?? '{}'), array_flip(['header', 'hero', 'footer'])));
$row['alignments'] = Database::json(self::decode($row['alignments'] ?? '{}'));
if (($row['theme'] ?? '') !== '' && !isset(PageTemplates::groups()[$row['theme']])) {
$row['theme'] = '';
}
foreach (['header', 'footer', 'palette'] as $kind) {
$row[$kind . '_id'] = self::selection($designs, $kind, $row[$kind . '_id'] ?? null);
}
}
unset($row);
foreach ($tables['sections'] as &$row) {
PageDraft::slug($row['key'] ?? null, ['home', 'contact', 'main-content', 'primary-navigation', 'preview']);
if (!in_array($row['style'] ?? '', ['plain', 'tinted', 'hero-links'], true)) {
throw new RuntimeException('备份包含未知区块样式。');
}
$row['body'] = Html::sanitize($row['body'] ?? '');
if (isset($row['feed'])) {
$feed = self::decode($row['feed']);
if (!in_array($feed['mode'] ?? '', ['merged', 'tabs', 'network', 'catalog'], true)
|| !is_array($feed['categories'] ?? null) || !array_is_list($feed['categories'])
|| array_diff($feed['categories'], array_column($tables['article_categories'], 'slug'))
|| !is_int($feed['limit'] ?? null) || $feed['limit'] < 1 || $feed['limit'] > 30) {
throw new RuntimeException('备份的动态区块配置无效。');
}
}
}
unset($row);
foreach ($tables['articles'] as &$row) {
if (($row['body_format'] ?? '') === 'html') {
$row['body'] = Html::sanitize($row['body'] ?? '');
}
$card = self::decode($row['card'] ?? '{}');
foreach (['url', 'extra_url', 'image'] as $field) {
self::validateAssetUrl($card[$field] ?? '', $field === 'image');
}
$row['tags'] = Database::json(self::decode($row['tags'] ?? '[]'));
}
unset($row);
return $tables;
}
private static function replaceTables(PDO $pdo, array $tables): void
{
$revisions = [];
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
$revisions[$table] = in_array('version', $columns, true) ? max(1, (int) $pdo->query('SELECT MAX(version) FROM ' . $table)->fetchColumn() + 1) : 0;
}
foreach (array_reverse(self::TABLES) as $table) {
$pdo->exec('DELETE FROM ' . $table);
}
foreach (self::TABLES as $table) {
$columns = array_column($pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(), 'name');
foreach ($tables[$table] as $row) {
$row = array_intersect_key($row, array_flip($columns));
if ($revisions[$table]) {
$row['version'] = $revisions[$table];
}
if (!$row) {
throw new RuntimeException('备份缺少必要的数据列。');
}
$keys = array_keys($row);
$query = $pdo->prepare('INSERT INTO ' . $table . ' ("' . implode('","', $keys) . '") VALUES (' . implode(',', array_fill(0, count($row), '?')) . ')');
$query->execute(array_values($row));
}
}
}
private static function selection(array $designs, string $kind, mixed $id): ?int
{
if ($id === null) {
return null;
}
if (!is_int($id) || ($designs[$id] ?? '') !== $kind) {
throw new RuntimeException('备份引用了缺失的设计方案。');
}
return $id;
}
private static function decode(mixed $value): array
{
$data = is_string($value) ? json_decode($value, true, 32, JSON_THROW_ON_ERROR) : null;
if (!is_array($data)) {
throw new RuntimeException('备份中的配置格式无效。');
}
return $data;
}
private static function validateAssetUrl(mixed $url, bool $media): void
{
if (!is_string($url) || ($url !== '' && !Html::url($url, $media))) {
throw new RuntimeException('备份含有无效的资源地址。');
}
}
private static function mediaName(mixed $name): string
{
if (!is_string($name) || !preg_match('/^[a-f0-9]{32}\.[a-z0-9]+$/D', $name)) {
throw new RuntimeException('备份含有无效的资源名称。');
}
return $name;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Content;
use PDO;
use RuntimeException;
final class SiteDesign
{
public static function parseLinks(string $value): array
{
$links = [];
foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) {
if (trim($line) === '') {
continue;
}
[$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, ''));
if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) {
throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。');
}
$links[] = [$url, $label];
}
return $links;
}
public static function linkText(array $links): string
{
return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links));
}
public static function saveGeneral(string $name, string $origin, int $version): void
{
Database::write(function (PDO $pdo) use ($name, $origin, $version): void {
$site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR);
if (($site['revisions']['general'] ?? 0) !== $version) {
throw new RuntimeException('站点设置已更新,请重新打开后再保存。');
}
$site['name'] = $name;
$site['cdn'] = ['origin' => $origin];
$site['revisions']['general'] = $version + 1;
$pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]);
});
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace App\Content;
use App\Http\VisitorSession;
use support\Response;
final class View
{
public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response
{
$cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? '');
$data['cdn'] = $cdn;
$personalized = false;
if (!$admin) {
$page = $data['page'] ?? [];
$data['header'] = DesignLibrary::layout('header', $data['site'], $page);
$data['footer'] = DesignLibrary::layout('footer', $data['site'], $page);
$data['visitor'] = null;
$provider = $data['header']['payload']['provider'];
$personalized = $provider !== [] && in_array('account', $data['header']['payload']['components'], true)
&& ($page['visibility']['header'] ?? true) && empty($data['previewMode']);
if ($personalized) {
$profile = VisitorSession::profile(request());
if (($profile['layout'] ?? null) === $data['header']['id']
&& ($profile['config'] ?? null) === hash('sha256', json_encode($provider, JSON_THROW_ON_ERROR))) {
$data['visitor'] = $profile;
}
}
}
$html = self::fragment($template, $data);
$page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn);
$assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn;
$articleEditor = $admin && !empty($data['articleEditor']);
$editorImages = $articleEditor ? ' data:' : '';
$editorStyles = $articleEditor ? "style-src-attr 'unsafe-inline'; " : '';
$headers = [
'Content-Type' => 'text/html; charset=utf-8',
'X-Content-Type-Options' => 'nosniff',
'Referrer-Policy' => 'strict-origin-when-cross-origin',
'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY',
'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:$editorImages; media-src 'self' https:; "
. "style-src $assetSources; {$editorStyles}script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors "
. (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'",
];
if ($admin || !empty($data['previewMode'])) {
$headers['Cache-Control'] = 'no-store';
$headers['X-Robots-Tag'] = 'noindex, nofollow';
} elseif (($data['noindex'] ?? false) || $status >= 400) {
$headers['X-Robots-Tag'] = 'noindex';
}
if ($personalized) {
$headers['Cache-Control'] = 'private, no-store';
$headers['Vary'] = 'Cookie';
}
return new Response($status, $headers, $page);
}
public static function fragment(string $template, array $data = []): string
{
extract($data, EXTR_SKIP);
ob_start();
try {
require dirname(__DIR__) . '/view/' . $template . '.php';
return (string) ob_get_contents();
} finally {
ob_end_clean();
}
}
public static function escape(string|int|null $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
public static function absolute(string $path): string
{
return rtrim(getenv('LAYSITE_SITE_URL') ?: 'http://127.0.0.1:8787', '/') . $path;
}
public static function date(?string $value, string $format = 'Y年n月j日'): string
{
return $value ? date($format, strtotime($value)) : '';
}
public static function alignmentClass(?string $alignment): string
{
return in_array($alignment, Html::ALIGNMENTS, true) ? ' studio-align-' . $alignment : '';
}
public static function archivePage(string $path, int $page): string
{
if ($page === 1) {
return $path;
}
return $path . (str_contains($path, '?') ? '&' : '?') . 'page=' . $page;
}
public static function redirect(string $path, int $status = 303): Response
{
return new Response($status, ['Location' => $path, 'Cache-Control' => $status === 301 ? 'public, max-age=300' : 'no-store'], '');
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\DesignLibrary;
use App\Content\IdentityProvider;
use App\Content\Repository;
use App\Content\View;
use App\Http\VisitorSession;
use support\Request;
use support\Response;
use Throwable;
final class AccountController
{
public function login(Request $request, string $id): Response
{
$config = $this->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));
}
}
+662
View File
@@ -0,0 +1,662 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\BlockTemplates;
use App\Content\Buttons;
use App\Content\DesignLibrary;
use App\Content\Database;
use App\Content\Html;
use App\Content\Passwords;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Content\View;
use App\Http\Request;
use RuntimeException;
use support\Response;
class AdminController
{
private ?array $user = null;
public function login(Request $request): Response
{
if ($this->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);
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\SiteBackup;
use App\Http\Request;
use RuntimeException;
use support\Response;
use Throwable;
use Workerman\Timer;
final class BackupController extends AdminController
{
public function index(Request $request): Response
{
if ($failure = $this->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';
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Assets;
use App\Content\Buttons;
use App\Content\DesignLibrary;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Http\Request;
use RuntimeException;
use support\Response;
final class DesignController extends AdminController
{
public function index(Request $request): Response
{
if ($failure = $this->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)}');
}
}
+216
View File
@@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\BlockTemplates;
use App\Content\Database;
use App\Content\DesignLibrary;
use App\Content\PageDraft;
use App\Content\PageTemplates;
use App\Content\Repository;
use App\Content\View;
use PDOException;
use RuntimeException;
use support\Request;
use support\Response;
final class McpController
{
private const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26'];
public function endpoint(Request $request): Response
{
$origin = $request->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));
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Media;
use support\Request;
use support\Response;
final class MediaController
{
public function file(Request $request, string $name): Response
{
$media = Media::find($name);
$path = Media::directory() . '/' . $name;
if (!$media || !is_file($path)) {
return new Response(404);
}
$length = (int) $media['size'];
$headers = [
'Content-Type' => $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);
}
}
+245
View File
@@ -0,0 +1,245 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Html;
use App\Content\Repository;
use App\Content\View;
use support\Request;
use support\Response;
final class SiteController
{
public function home(Request $request): Response
{
return $this->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 = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
$pages = $repo->pages(publishedOnly: true);
foreach ($pages as $page) {
$xml[] = $this->sitemapUrl($page['slug'] === 'home' ? '/' : '/' . $page['slug'], $page['updated_at']);
}
foreach ($repo->sitemapArticles() as $article) {
$xml[] = $this->sitemapUrl('/articles/' . $article['slug'], $article['updated_at']);
}
$xml[] = '</urlset>';
return new Response(200, ['Content-Type' => 'application/xml; charset=utf-8'], implode("\n", $xml) . "\n");
}
public function robots(Request $request): Response
{
return new Response(200, ['Content-Type' => 'text/plain; charset=utf-8'],
"User-agent: *\nAllow: /\nDisallow: /admin\nSitemap: " . View::absolute('/sitemap.xml') . "\n");
}
public function missing(Request $request): Response
{
$path = $request->path();
if ($request->method() === 'GET' && strlen($path) > 1 && str_ends_with($path, '/')) {
$normal = rtrim($path, '/');
$single = preg_match('~^/[a-z0-9-]+$~D', $normal);
$known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home';
if ($known || preg_match('~^/articles(?:/[a-z0-9-]+){1,2}$~D', $normal)) {
$query = $request->queryString();
return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301);
}
}
return View::render('missing', [
'site' => (new Repository())->site(), 'title' => '页面未找到', 'description' => '',
'path' => null, 'noindex' => true,
], 404);
}
private function sitemapUrl(string $path, ?string $updated): string
{
$url = htmlspecialchars(View::absolute($path), ENT_XML1 | ENT_QUOTES, 'UTF-8');
$date = $updated ? '<lastmod>' . View::date($updated, 'Y-m-d') . '</lastmod>' : '';
return ' <url><loc>' . $url . '</loc>' . $date . '</url>';
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\BlockTemplates;
use App\Content\Html;
use App\Content\Media;
use App\Content\PageTemplates;
use App\Content\Repository;
use App\Http\Request;
use RuntimeException;
use support\Response;
use Webman\Http\UploadFile;
final class StudioController extends AdminController
{
public function newPage(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$data = [
'title' => '新建页面', 'name' => '', 'slug' => '', 'error' => '', 'pageTemplateDrawer' => true,
'openTemplates' => $request->get('templates') === '1',
];
if ($request->method() === 'POST') {
$data['name'] = $this->input($request, 'name');
$data['slug'] = $this->input($request, 'slug');
try {
if (!$this->slug($data['slug']) || in_array($data['slug'], ['admin', 'assets', 'home', 'account', 'mcp', 'palette', 'favicon'], true)
|| $data['name'] === '' || mb_strlen($data['name']) > 100) {
throw new RuntimeException('请填写页面名称及可用的网址标识。');
}
$key = $this->input($request, 'template');
$template = $key === '' ? [] : PageTemplates::find($key);
if ($template === null) {
throw new RuntimeException('找不到所选整页模板。');
}
$template['title'] = $data['name'];
(new Repository())->createPage($data['slug'], $data['name'], $template);
return $this->success($request, '/admin/pages/' . $data['slug']);
} catch (RuntimeException $error) {
$data['error'] = $this->validationMessage($error);
}
}
return $this->render($request, 'studio-new-page', $data, $data['error'] === '' ? 200 : 422);
}
public function previewTemplate(Request $request, string $key): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$template = PageTemplates::find($key);
return $template ? (new SiteController())->renderPage(new Repository(), $template, true)
: $this->error($request, '找不到所选整页模板。', 404);
}
public function previewPage(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$page = $repo->page($slug);
return $page ? (new SiteController())->renderPage($repo, $page, true, $request->get('canvas') === '1') : $this->error($request, '找不到此页面。', 404);
}
public function blocks(Request $request, string $slug): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
if (!$repo->page($slug)) {
return $this->error($request, '找不到此页面。', 404);
}
$action = $this->input($request, 'operation');
$key = $this->input($request, 'key');
try {
if (!$this->slug($key) || in_array($key, ['preview', 'home', 'contact', 'main-content', 'partners', 'supported-projects'], true)) {
throw new RuntimeException('区块锚点不可用。');
}
if ($action === 'create') {
$type = $this->input($request, 'preset');
$preset = BlockTemplates::find($type);
if ($preset === null) {
throw new RuntimeException('请选择区块类型。');
}
$repo->createSection($slug, $key, $preset[0], $preset[4] ?? 'plain', Html::sanitize($preset[1], $key), $preset[3] ?? null, $preset[2] ?? '');
return $this->success($request, "/admin/pages/$slug/$key");
}
if (!in_array($action, ['up', 'down', 'delete'], true)) {
throw new RuntimeException('操作不可用。');
}
$pageVersion = $this->input($request, 'page_version');
$repo->arrangeSection($slug, $key, $action, $this->version($request), ctype_digit($pageVersion) ? (int) $pageVersion : -1);
return $this->success($request, "/admin/pages/$slug#blocks");
} catch (RuntimeException $error) {
return $this->error($request, $this->validationMessage($error), 422);
}
}
public function media(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$error = '';
if ($request->method() === 'POST') {
try {
$file = $request->file('file');
if (!$file instanceof UploadFile || !$file->isValid()) {
throw new RuntimeException('请选择要上传的文件。');
}
$label = $this->input($request, 'label') ?: mb_substr((string) $file->getUploadName(), 0, 160);
if (mb_strlen($label) > 160) {
throw new RuntimeException('资源名称最多 160 个字符。');
}
Media::upload($file, $label);
return $this->success($request, '/admin/media?uploaded=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'studio-media', [
'title' => '媒体库', 'files' => Media::all(true), 'error' => $error, 'saved' => $request->get('uploaded') === '1',
], $error === '' ? 200 : 422);
}
public function mediaOptions(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
return $this->json(['files' => Media::all()]);
}
public function mediaMeta(Request $request, string $name): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$label = $this->input($request, 'label');
if (!Media::find($name)) {
return $this->error($request, '找不到此资源。', 404);
}
if ($label === '' || mb_strlen($label) > 160) {
return $this->error($request, '请输入资源名称,最多 160 个字符。', 422);
}
Media::update($name, $label, $this->input($request, 'archived') === '1');
return $this->success($request, '/admin/media');
}
private function slug(string $value): bool
{
return strlen($value) <= 70 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value) === 1;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Http;
final class Request extends \support\Request
{
private const LOOPBACK = ['127.0.0.1', '::1'];
public function clientAddress(): string
{
$peer = $this->getRemoteIp();
$forwarded = $this->header('x-real-ip', '');
if (!$this->fromTrustedProxy() || !filter_var($forwarded, FILTER_VALIDATE_IP)) {
return $peer;
}
return inet_ntop(inet_pton($forwarded));
}
private function fromTrustedProxy(): bool
{
$configured = getenv('LAYSITE_TRUSTED_PROXIES');
$trusted = $configured === false ? self::LOOPBACK : array_map('trim', explode(',', $configured));
return in_array($this->getRemoteIp(), $trusted, true);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Http;
use support\Request;
use support\Response;
use Workerman\Protocols\Http\Session;
final class VisitorSession
{
private const COOKIE = 'LAYSITE_VISITOR';
public static function open(?Request $request): ?Session
{
$id = $request?->cookie(self::COOKIE);
return is_string($id) && preg_match('/^visitor-[a-f0-9]{64}$/D', $id) ? new Session($id) : null;
}
public static function create(): Session
{
return new Session('visitor-' . bin2hex(random_bytes(32)));
}
public static function cookie(Response $response, ?Session $session, int $seconds): Response
{
return $response->cookie(self::COOKIE, $session?->getId() ?? '', $seconds, '/',
secure: getenv('LAYSITE_SECURE_COOKIES') === '1', httpOnly: true, sameSite: 'Lax');
}
public static function profile(?Request $request): ?array
{
$profile = self::open($request)?->get('profile');
return is_array($profile) && ($profile['expires'] ?? 0) > time() ? $profile : null;
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
final class PublicAssets implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$response = $handler($request);
$path = $request->path();
if (str_starts_with($path, '/assets/')) {
$response->withHeader('Access-Control-Allow-Origin', '*');
if ($path === '/assets/jquery-4.0.0.min.js') {
$response->withHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
}
return $response;
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php use App\Content\View; $e = View::escape(...); ?>
<section class="section"><div class="wrap account-panel">
<h1>用户中心</h1>
<?php if ($error !== ''): ?><p role="alert"><?= $e($error) ?></p><?php endif ?>
<?php if ($profile): ?>
<?php if ($profile['avatar'] !== ''): ?><img class="account-avatar" src="<?= $e($profile['avatar']) ?>" width="56" height="56" alt=""><?php endif ?>
<p><?= $e($profile['name']) ?></p>
<form method="post" action="/account/logout">
<input type="hidden" name="token" value="<?= $e($profile['logout']) ?>">
<button class="button button-outline" type="submit">退出登录</button>
</form>
<?php else: ?><p>请从站点页头登录。</p><?php endif ?>
<p><a href="/">返回首页</a></p>
</div></section>
+21
View File
@@ -0,0 +1,21 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin/articles">返回文章列表</a>
<header class="admin-heading"><h1>文章分类</h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/article-categories">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<div class="form-grid">
<label>分类名称<input name="name" value="<?= $e($name) ?>" required maxlength="60"></label>
<label>网址标识<input name="slug" value="<?= $e($slug) ?>" required maxlength="60" pattern="[a-z0-9]+(-[a-z0-9]+)*"></label>
</div>
<div class="form-submit"><button class="button button-primary" type="submit">创建分类</button></div>
</form>
<nav class="filter-nav" aria-label="查看分类">
<?php foreach ($categories as $key => $label): ?>
<a href="/admin/articles?category=<?= $e($key) ?>"><?= $e($label) ?></a>
<?php endforeach ?>
</nav>
+19
View File
@@ -0,0 +1,19 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<?php if ($articles): ?>
<ul class="admin-list">
<?php foreach ($articles as $item): ?>
<li>
<div><strong><?= $e($item['title']) ?></strong>
<small><?= $e(implode('、', $item['categories'])) ?> · <?= $item['status'] === 'published' ? '已发布' : '草稿' ?> · <?= $e(View::date($item['updated_at'])) ?></small>
</div>
<a class="button button-outline" href="/admin/articles/<?= $e($item['id']) ?>">编辑文章</a>
</li>
<?php endforeach ?>
</ul>
<?php else: ?>
<p class="empty-state">暂无文章。</p>
<?php endif ?>
+64
View File
@@ -0,0 +1,64 @@
<?php
use App\Content\Repository;
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin/articles">返回文章列表</a>
<header class="admin-heading">
<h1><?= $e($title) ?></h1>
<?php if ($articleId && $article['status'] === 'published' && $article['slug'] !== ''): ?>
<a class="button button-outline" href="/articles/<?= $e($article['slug']) ?>">查看公开页面</a>
<?php endif ?>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/articles/<?= $e($articleId ?? 'new') ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($article['version']) ?>">
<label>文章标题<input name="title" value="<?= $e($article['title']) ?>" required maxlength="120"></label>
<label>网址标识<input name="slug" value="<?= $e($article['slug']) ?>" required maxlength="100" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="product-update"><small>使用小写英文字母、数字和连字符。</small></label>
<?= View::fragment('admin-category-checkboxes', ['name' => 'categories', 'selected' => array_keys($article['categories']), 'categories' => $categories, 'legend' => '文章分类(可多选)']) ?>
<label>标签<input name="tags" value="<?= $e(implode(',', $article['tags'])) ?>" placeholder="用逗号分隔"></label>
<label>摘要<textarea name="summary" rows="2" maxlength="250"><?= $e($article['summary']) ?></textarea><small>用于动态列表和搜索摘要。</small></label>
<div class="article-editor" data-article-editor>
<div class="article-editor-heading">
<label for="article-source" data-article-editor-label>正文</label>
<button type="button" class="button button-outline" data-insert-article-image hidden>从媒体库插入图片</button>
</div>
<input type="hidden" name="body_format" value="<?= $e($article['body_format']) ?>">
<textarea id="article-source" name="body" rows="16" aria-label="文章正文"><?= $e($article['body']) ?></textarea>
<div data-editor-host hidden></div>
<p class="article-editor-help" data-article-editor-status role="status"></p>
</div>
<details class="admin-options" <?= array_intersect(array_keys($article['categories']), array_keys(Repository::DIRECTORIES)) ? 'open' : '' ?>>
<summary>目录卡片</summary>
<div class="form-grid">
<?= View::fragment('studio-asset-field', ['name' => 'card_image', 'label' => '封面或标志', 'value' => $article['card']['image'] ?? '']) ?>
<label>图片替代文字<input name="card_alt" value="<?= $e($article['card']['alt'] ?? '') ?>" maxlength="120"></label>
<label>主链接<input name="card_url" value="<?= $e($article['card']['url'] ?? '') ?>"></label>
<label>主链接文字<input name="card_label" value="<?= $e($article['card']['label'] ?? '') ?>" maxlength="120"></label>
<label>附加链接<input name="card_extra_url" value="<?= $e($article['card']['extra_url'] ?? '') ?>"></label>
<label>附加链接文字<input name="card_extra_label" value="<?= $e($article['card']['extra_label'] ?? '') ?>" maxlength="120"></label>
<label>类型说明<input name="card_category_label" value="<?= $e($article['card']['category_label'] ?? '') ?>" maxlength="120"></label>
<label>目录排序(从小到大)<input name="card_position" type="number" min="0" max="9999" value="<?= $e($article['card']['position'] ?? 0) ?>"></label>
</div>
</details>
<div class="form-submit">
<label>发布状态<select name="status">
<option value="draft" <?= $article['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $article['status'] === 'published' ? 'selected' : '' ?>>已发布</option>
</select></label>
<button class="button button-primary" type="submit">保存文章</button>
</div>
</form>
<?php if ($articleId !== null): ?>
<details class="admin-panel admin-options">
<summary>删除文章</summary>
<form method="post" action="/admin/articles/<?= $e($articleId) ?>/delete">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($article['version']) ?>">
<p class="field-note">删除后,文章及其目录卡片会从网站移除,且无法恢复。</p>
<button class="button button-danger" type="submit">永久删除</button>
</form>
</details>
<?php endif ?>
+31
View File
@@ -0,0 +1,31 @@
<?php
use App\Content\View;
$e = View::escape(...);
$filters = $category ? 'category=' . rawurlencode($category) . '&' : '';
?>
<header class="admin-heading">
<h1>文章与动态</h1>
<div class="actions">
<a class="button button-outline" href="/admin/article-categories">管理分类</a>
<a class="button button-primary" href="/admin/articles/new<?= $category ? '?category=' . $e($category) : '' ?>">新建文章</a>
</div>
</header>
<?php if ($deleted): ?><p class="feedback success" role="status">文章已删除。</p><?php endif ?>
<nav class="filter-nav" aria-label="筛选文章">
<a href="/admin/articles" <?= $category === null ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $name): ?>
<a href="/admin/articles?category=<?= $e($key) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($name) ?></a>
<?php endforeach ?>
</nav>
<div class="admin-panel">
<?= View::fragment('admin-article-list', ['articles' => $articles]) ?>
</div>
<?php if ($pageNumber > 1 || $hasNext): ?>
<nav class="pagination" aria-label="文章分页">
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="/admin/articles?<?= $e($filters) ?>page=<?= $pageNumber - 1 ?>">上一页</a><?php endif ?>
<span>第 <?= $pageNumber ?> 页</span>
<?php if ($hasNext): ?><a class="button button-outline" href="/admin/articles?<?= $e($filters) ?>page=<?= $pageNumber + 1 ?>">下一页</a><?php endif ?>
</nav>
<?php endif ?>
+15
View File
@@ -0,0 +1,15 @@
<?php use App\Content\View; $e = View::escape(...); ?>
<a class="back-link" href="/admin/design">返回站点设计</a>
<header class="admin-heading"><h1>站点备份</h1><a class="button button-outline" href="/admin/backup/download">导出备份</a></header>
<?php if ($restored): ?><p class="feedback success" role="status">站点已还原。</p><?php endif ?>
<?= View::fragment('admin-feedback', ['error' => $error, 'saved' => false]) ?>
<section class="admin-panel">
<h2>从备份还原</h2>
<p>还原会替换现有页面、文章、设计配置及媒体目录记录。先导出当前站点,再选择需要还原的文件。</p>
<form class="admin-form" method="post" action="/admin/backup" enctype="multipart/form-data">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>LaySite 备份<input type="file" name="backup" accept=".tar,application/x-tar" required></label>
<label><span><input type="checkbox" name="replace" value="1" required> 确认替换站点内容</span></label>
<div class="form-submit"><button class="button button-danger" type="submit" data-confirm="使用这份备份替换当前站点?">还原站点</button></div>
</form>
</section>
+4
View File
@@ -0,0 +1,4 @@
<?php if (is_file(public_path('assets/system/laysite-mark.webp'))): ?>
<img class="laysite-mark" src="/assets/system/laysite-mark.webp" alt="" width="42" height="42">
<?php endif ?>
<span>LaySite</span>
+14
View File
@@ -0,0 +1,14 @@
<?php
use App\Content\View;
$e = View::escape(...);
$checked = array_fill_keys($selected, true);
?>
<fieldset class="category-checks">
<legend><?= $e($legend) ?></legend>
<div>
<?php foreach ($categories as $key => $label): ?>
<label><input type="checkbox" name="<?= $e($name) ?>[]" value="<?= $e($key) ?>" <?= isset($checked[$key]) ? 'checked' : '' ?>> <?= $e($label) ?></label>
<?php endforeach ?>
</div>
</fieldset>
+61
View File
@@ -0,0 +1,61 @@
<?php
use App\Content\View;
$e = View::escape(...);
$live = count(array_filter($pages, static fn (array $page): bool => $page['status'] === 'published'));
?>
<header class="admin-heading dashboard-heading">
<h1>网站后台</h1>
<div class="actions">
<a class="button button-primary" href="/admin/new-page">新建页面</a>
<button type="button" class="button button-outline" data-open-page-templates hidden>整页模板</button>
<a class="button button-outline" href="/admin/articles/new">写文章</a>
</div>
</header>
<div class="dashboard-grid">
<section class="admin-panel dashboard-pages" aria-labelledby="pages-title" data-page-list>
<div class="admin-heading compact">
<h2 id="pages-title">网站页面</h2>
<p class="field-note"><?= $live ?> 个已发布 · <?= count($pages) - $live ?> 个草稿</p>
</div>
<div class="dashboard-filters" data-page-filters hidden>
<label>查找页面<input type="search" data-page-search placeholder="页面名称或地址"></label>
<label>发布状态<select data-page-status>
<option value="">全部状态</option>
<option value="published">已发布</option>
<option value="draft">草稿</option>
</select></label>
</div>
<p class="empty-state" data-page-empty role="status"<?= $pages ? ' hidden' : '' ?>><?= $pages ? '没有匹配的页面。' : '暂无页面。' ?></p>
<ul class="admin-list dashboard-page-list">
<?php foreach ($pages as $page): ?>
<?php $path = $page['slug'] === 'home' ? '/' : '/' . $page['slug']; $published = $page['status'] === 'published'; ?>
<li data-page-item="<?= $e($page['status']) ?>" data-page-label="<?= $e($page['name'] . ' ' . $page['title'] . ' ' . $path) ?>">
<div class="dashboard-page-label"><strong><?= $e($page['name']) ?></strong><small><?= $e($path) ?></small></div>
<span class="dashboard-page-state" data-published="<?= $published ? 'true' : 'false' ?>"><?= $published ? '已发布' : '草稿' ?></span>
<div class="dashboard-page-actions">
<a class="button button-outline" href="/admin/pages/<?= $e($page['slug']) ?>">编辑页面</a>
<a href="<?= $e($published ? $path : '/admin/pages/' . $page['slug'] . '/preview') ?>" target="_blank" rel="noopener"><?= $published ? '查看' : '预览' ?></a>
</div>
</li>
<?php endforeach ?>
</ul>
</section>
<div class="dashboard-secondary">
<section class="admin-panel" aria-labelledby="recent-title">
<div class="admin-heading compact"><h2 id="recent-title">最近编辑的文章</h2></div>
<?= View::fragment('admin-article-list', ['articles' => $articles]) ?>
<a class="back-link" href="/admin/articles">管理全部文章</a>
</section>
<section class="admin-panel dashboard-settings" aria-labelledby="quick-title">
<h2 id="quick-title">站点编辑</h2>
<ul class="dashboard-setting-buttons">
<li><a class="button button-outline" href="/admin/design/header/new">新建页头</a></li>
<li><a class="button button-outline" href="/admin/design/footer/new">新建页脚</a></li>
<li><a class="button button-outline" href="/admin/settings">站点设置</a></li>
<li><a class="button button-outline" href="/admin/media">打开媒体库</a></li>
</ul>
</section>
</div>
</div>
<?= View::fragment('studio-page-templates', compact('token')) ?>
+83
View File
@@ -0,0 +1,83 @@
<?php
use App\Content\Buttons;
use App\Content\DesignLibrary;
use App\Content\SiteDesign;
use App\Content\View;
$e = View::escape(...);
$data = $item['payload'];
$action = $data['action'][0] ?? [];
$provider = $data['provider'] ?? [];
?>
<a class="back-link" href="/admin/design">返回站点设计</a>
<header class="admin-heading">
<h1><?= $e(['header' => '页头组件', 'footer' => '页脚组件', 'palette' => '配色方案'][$kind]) ?></h1>
<?php if ($key !== 'new'): ?><a class="button button-outline" href="/admin/design/<?= $e($kind) ?>/<?= $e($key) ?>/preview" target="_blank" rel="noopener noreferrer">预览已保存的配置</a><?php endif ?>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/design/<?= $e($kind) ?>/<?= $e($key) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($item['version']) ?>">
<label>配置名称<input name="name" maxlength="100" value="<?= $e($item['name']) ?>" required></label>
<label>布局模板<select name="preset" data-layout-preset>
<?php foreach (DesignLibrary::PRESETS[$kind] as $preset => $label): ?>
<option value="<?= $e($preset) ?>" <?= $preset === $item['preset'] ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<?php if ($kind === 'palette'): ?>
<div class="palette-fields">
<?php foreach (DesignLibrary::COLORS as $color => [$label, $fallback]): ?>
<label><?= $e($label) ?><input type="color" name="<?= $e($color) ?>" value="<?= $e($data[$color] ?? $fallback) ?>"></label>
<?php endforeach ?>
</div>
<?php else: ?>
<fieldset class="admin-options"><legend>组件及顺序</legend>
<ul class="admin-list layout-components" data-layout-components>
<?php foreach (array_unique([...$data['components'], ...array_keys(DesignLibrary::COMPONENTS[$kind])]) as $component): ?>
<li><label><input type="checkbox" name="components[]" value="<?= $e($component) ?>" <?= in_array($component, $data['components'], true) ? 'checked' : '' ?>><?= $e(DesignLibrary::COMPONENTS[$kind][$component]) ?></label>
<div class="actions"><button type="button" class="button button-outline" data-component-move="-1">上移</button><button type="button" class="button button-outline" data-component-move="1">下移</button></div></li>
<?php endforeach ?>
</ul>
</fieldset>
<div class="form-grid">
<label>品牌名称<input name="brand" maxlength="100" value="<?= $e($data['brand']) ?>"></label>
<?= View::fragment('studio-asset-field', ['name' => 'logo', 'label' => '品牌图片', 'value' => $data['logo']]) ?>
</div>
<label>链接列表<textarea name="links" rows="4"><?= $e(SiteDesign::linkText($data['links'])) ?></textarea><small>每行填写「名称 | 链接」。</small></label>
<?php if ($kind === 'header'): ?>
<fieldset class="admin-options form-grid"><legend>行动按钮</legend>
<label>文案<input name="action_label" maxlength="70" value="<?= $e($action[1] ?? '') ?>"></label>
<label>链接<input name="action_url" maxlength="1000" value="<?= $e($action[0] ?? '') ?>"></label>
<label>样式<select name="action_style"><?php foreach (Buttons::STYLES as $style => $label): ?>
<option value="<?= $e($style) ?>" <?= ($action[2] ?? 'outline') === $style ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?></select></label>
<label><span><input type="checkbox" name="action_blank" value="1" <?= !empty($action[3]) ? 'checked' : '' ?>> 在新标签页打开</span></label>
</fieldset>
<fieldset class="admin-options form-grid" data-provider-settings><legend>用户区认证</legend>
<label>认证方式<select name="provider_mode"><option value="">关闭</option>
<?php foreach (['oidc' => 'OpenID Connect', 'oauth2' => 'OAuth 2.0 + 用户资料'] as $mode => $label): ?>
<option value="<?= $e($mode) ?>" <?= ($provider['mode'] ?? '') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<label>客户端 ID<input name="provider_client_id" value="<?= $e($provider['client_id'] ?? '') ?>"></label>
<label>客户端密钥环境变量<input name="provider_secret_env" value="<?= $e($provider['secret_env'] ?? '') ?>" placeholder="LAYSITE_OAUTH_MEMBER_SECRET"></label>
<label>令牌端点认证<select name="provider_token_auth">
<?php foreach (['' => '自动', 'client_secret_basic' => 'HTTP Basic', 'client_secret_post' => '表单客户端密钥'] as $method => $label): ?>
<option value="<?= $e($method) ?>" <?= ($provider['token_auth'] ?? '') === $method ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<label>权限范围<input name="provider_scope" value="<?= $e($provider['scope'] ?? '') ?>" placeholder="openid profile email"></label>
<label data-provider-mode="oidc">OIDC Issuer<input name="provider_issuer" value="<?= $e($provider['issuer'] ?? '') ?>" placeholder="https://id.example.com"></label>
<?php foreach (['authorization' => '授权端点', 'token' => '令牌端点', 'userinfo' => '用户资料端点', 'subject_field' => '用户 ID 字段', 'name_field' => '名称字段', 'avatar_field' => '头像字段'] as $field => $label): ?>
<label data-provider-mode="oauth2"><?= $e($label) ?><input name="provider_<?= $e($field) ?>" value="<?= $e($provider[$field] ?? '') ?>"></label>
<?php endforeach ?>
<p class="field-note">回调地址 <code><?= $e(View::absolute('/account/callback')) ?></code></p>
</fieldset>
<?php else: ?>
<label>说明文字<textarea name="text" rows="3"><?= $e($data['text']) ?></textarea></label>
<label>版权文字<input name="legal" value="<?= $e($data['legal']) ?>"></label>
<?php endif ?>
<label><span><input type="checkbox" name="make_default" value="1" <?= $default ? 'checked' : '' ?>> 用作站点默认<?= $kind === 'header' ? '页头' : '页脚' ?></span></label>
<?php endif ?>
<button type="submit" class="button button-primary">保存配置</button>
</form>
+23
View File
@@ -0,0 +1,23 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1>站点设计</h1><div class="actions"><a class="button button-outline" href="/admin/settings">站点设置</a><a class="button button-outline" href="/admin/backup">站点备份</a></div></header>
<div class="design-overview">
<?php foreach (['header' => '页头', 'footer' => '页脚', 'palette' => '配色方案'] as $kind => $label): ?>
<section class="admin-panel">
<div class="admin-heading compact"><h2><?= $e($label) ?></h2><a class="button button-outline" href="/admin/design/<?= $e($kind) ?>/new">新建<?= $e($label) ?></a></div>
<?php $group = array_filter($items, static fn (array $item): bool => $item['kind'] === $kind); ?>
<?php if (!$group): ?><p class="field-note">暂无自定义配置。</p><?php endif ?>
<ul class="admin-list">
<?php foreach ($group as $item): ?>
<li><strong><?= $e($item['name']) ?></strong>
<?php if (($site[$kind . '_id'] ?? null) === $item['id']): ?><small>站点默认</small><?php endif ?>
<a class="button button-outline" href="/admin/design/<?= $e($kind) ?>/<?= $e($item['id']) ?>">编辑</a>
</li>
<?php endforeach ?>
</ul>
</section>
<?php endforeach ?>
</div>
+32
View File
@@ -0,0 +1,32 @@
<?php
use App\Content\View;
use App\Content\Html;
$e = View::escape(...);
?>
<div class="editor" data-editor data-format="<?= $format ?>">
<label for="editor-text">正文(<?= $format === 'markdown' ? 'Markdown' : 'HTML' ?>)</label>
<div class="editor-toolbar">
<div role="group" aria-label="插入格式">
<button type="button" data-insert="heading">小标题</button>
<button type="button" data-insert="bold">粗体</button>
<button type="button" data-insert="list">列表</button>
<button type="button" data-insert="link">链接</button>
</div>
<?php if ($format === 'html'): ?>
<button type="button" data-rich-media>插入媒体</button>
<button type="button" data-source-toggle aria-pressed="false">HTML 源码</button>
<?php else: ?>
<button data-preview-button type="button" aria-controls="editor-preview" aria-expanded="false">预览正文</button>
<?php endif ?>
</div>
<?php if ($format === 'html'): ?>
<div class="rich studio-rich" contenteditable="true" role="textbox" aria-multiline="true" aria-label="可视化正文" data-rich-canvas hidden><?= Html::sanitize($body) ?></div>
<p class="field-note" data-rich-status role="status" hidden></p>
<?php endif ?>
<textarea id="editor-text" name="body" rows="15" spellcheck="false"><?= $e($body) ?></textarea>
<?php if ($format === 'html'): ?>
<p class="field-note">可以直接编辑文字,插入链接、图片、音视频。复杂区块可切换到 HTML 源码调整。</p>
<?php endif ?>
<div class="editor-preview rich prose" id="editor-preview" aria-live="polite" hidden></div>
</div>
+2
View File
@@ -0,0 +1,2 @@
<h1><?= App\Content\View::escape($title) ?></h1>
<a class="button button-primary" href="/admin">返回内容管理</a>
+3
View File
@@ -0,0 +1,3 @@
<?php use App\Content\View; ?>
<?php if ($error): ?><p class="feedback error" role="alert"><?= View::escape($error) ?></p><?php endif ?>
<?php if ($saved && !$error): ?><p class="feedback success" data-save-confirmation role="status">已保存。</p><?php endif ?>
+78
View File
@@ -0,0 +1,78 @@
<?php
use App\Content\View;
$e = View::escape(...);
$active = match (true) {
str_starts_with($adminPath, '/admin/article') => 'articles',
str_starts_with($adminPath, '/admin/media') => 'media',
str_starts_with($adminPath, '/admin/settings') || str_starts_with($adminPath, '/admin/design') || str_starts_with($adminPath, '/admin/backup') => 'settings',
$adminPath === '/admin/password' => '',
default => 'pages',
};
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="/assets/system/laysite-mark.webp" type="image/webp">
<title><?= $e($title) ?> CMS</title>
<link rel="stylesheet" href="/assets/site.css">
<link rel="stylesheet" href="/assets/admin.css">
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/admin.js" defer></script>
<script src="/assets/studio.js" defer></script>
<?php if (!empty($pageTemplateDrawer)): ?>
<link rel="stylesheet" href="/assets/page-template-drawer.css">
<script src="/assets/page-template-drawer.js" defer></script>
<?php endif ?>
<?php if (!empty($articleEditor)): ?>
<link rel="stylesheet" href="/assets/vendor/toastui/toastui-editor.min.css">
<script src="/assets/vendor/toastui/toastui-editor.min.js" defer></script>
<script src="/assets/vendor/toastui/zh-cn.js" defer></script>
<script src="/assets/article-editor.js" defer></script>
<?php endif ?>
</head>
<body class="admin-body">
<a class="skip-link" href="#admin-content">跳到内容</a>
<header class="admin-bar">
<div class="admin-wrap admin-bar-inner">
<a class="wordmark" href="/admin" aria-label="LaySite 后台"><?= View::fragment('admin-brand') ?></a>
<?php if ($user): ?>
<nav class="admin-primary" aria-label="后台导航">
<a href="/admin"<?= $active === 'pages' ? ' aria-current="page"' : '' ?>>页面</a>
<a href="/admin/articles"<?= $active === 'articles' ? ' aria-current="page"' : '' ?>>文章</a>
<a href="/admin/media"<?= $active === 'media' ? ' aria-current="page"' : '' ?>>媒体库</a>
<a href="/admin/design"<?= $active === 'settings' ? ' aria-current="page"' : '' ?>>站点设计</a>
</nav>
<div class="admin-utility">
<a href="/">访问网站</a>
<details class="admin-account">
<summary>账户</summary>
<div class="admin-account-menu">
<a href="/admin/password">修改密码</a>
<form method="post" action="/admin/logout">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<button type="submit">退出登录</button>
</form>
</div>
</details>
</div>
<?php else: ?>
<a class="back-link" href="/">返回网站</a>
<?php endif ?>
</div>
</header>
<main class="admin-wrap admin-main<?= !empty($wideAdmin) ? ' admin-wide' : '' ?>" id="admin-content"><?= $content ?></main>
<?php if ($user): ?>
<dialog class="media-picker" id="media-picker" aria-labelledby="picker-heading">
<header class="admin-heading compact"><h2 id="picker-heading">从媒体库选择</h2><button class="button button-outline" type="button" data-close-picker>关闭</button></header>
<label>查找资源<input type="search" data-media-query placeholder="搜索文件名或资源路径"></label>
<p data-picker-status role="status"></p>
<div class="picker-grid" data-picker-items></div>
<a class="back-link" href="/admin/media" target="_blank" rel="noopener">打开媒体库上传</a>
</dialog>
<?php endif ?>
</body>
</html>
+17
View File
@@ -0,0 +1,17 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="login-box">
<h1>登录内容管理</h1>
<p>管理网站页面、媒体和文章。</p>
<?php if ($error): ?><p class="feedback error" role="alert"><?= $e($error) ?></p><?php endif ?>
<form class="admin-form" method="post" action="/admin/login">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>管理员邮箱<input name="email" type="email" value="<?= $e($email) ?>" autocomplete="username" required maxlength="254"></label>
<label>密码<input name="password" type="password" autocomplete="current-password" required></label>
<button class="button button-primary" type="submit">登录</button>
</form>
<p class="field-note">忘记密码时,可请服务器管理员通过命令行重设。</p>
</div>
+173
View File
@@ -0,0 +1,173 @@
<?php
use App\Content\Buttons;
use App\Content\Database;
use App\Content\SiteDesign;
use App\Content\View;
$e = View::escape(...);
$slug = $page['slug'];
$path = $slug === 'home' ? '/' : '/' . $slug;
$previewUrl = '/admin/pages/' . $slug . '/preview';
?>
<a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p class="studio-page-meta"><code><?= $e($path) ?></code>
<span class="dashboard-page-state" data-published="<?= $page['status'] === 'published' ? 'true' : 'false' ?>"><?= $page['status'] === 'draft' ? '草稿' : '已发布' ?></span></p></div>
<div class="actions">
<a class="button button-outline" href="#studio-page-settings">页面设置</a>
<button type="button" class="button button-outline" data-open-page-templates hidden>整页模板</button>
<?php if ($page['status'] === 'published'): ?><a class="button button-outline" href="<?= $e($path) ?>">公开页面</a><?php endif ?>
<a class="button button-outline" href="<?= $e($previewUrl) ?>" target="_blank" rel="noopener">打开预览</a>
</div>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<div class="studio-layout">
<aside class="admin-panel studio-library" aria-labelledby="studio-library-title">
<h2 id="studio-library-title">页面编辑</h2>
<?= View::fragment('studio-templates', [
'layers' => View::fragment('studio-layers', compact('page', 'slug', 'token')),
'anchorForm' => View::fragment('studio-anchor-form', compact('slug', 'token')),
]) ?>
</aside>
<div class="studio-workspace">
<section class="admin-panel studio-preview" data-preview-studio aria-labelledby="studio-preview-title">
<div class="admin-heading compact">
<h2 id="studio-preview-title">页面画布</h2>
<div class="preview-selector" aria-label="预览尺寸">
<button type="button" class="button button-outline" data-preview-size="desktop" aria-pressed="true">桌面</button>
<button type="button" class="button button-outline" data-preview-size="phone" aria-pressed="false">手机</button>
</div>
</div>
<div class="editor-toolbar studio-canvas-toolbar" data-canvas-toolbar hidden aria-label="正文工具">
<div>
<button type="button" data-canvas-command="heading">小标题</button>
<button type="button" data-canvas-command="bold">粗体</button>
<button type="button" data-canvas-command="list">列表</button>
<button type="button" data-canvas-command="link">插入链接</button>
<button type="button" data-canvas-command="media">插入媒体</button>
</div>
<button class="button button-primary" form="studio-page-settings" type="submit">保存页面</button>
</div>
<div class="studio-frame-window">
<iframe title="可编辑页面画布" src="<?= $e($previewUrl) ?>?canvas=1" sandbox="allow-same-origin"></iframe>
<div class="studio-element-tools" data-element-tools role="group" aria-label="所选元素" hidden>
<div class="studio-element-align" data-element-align role="group" aria-label="对齐">
<?php foreach (['left' => '居左', 'center' => '居中', 'right' => '居右'] as $value => $label): ?>
<button type="button" data-align="<?= $value ?>" aria-pressed="false" aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', ['icon' => $value]) ?></button>
<?php endforeach ?>
</div>
<?php foreach (['module-settings' => ['settings', '模块设置'], 'properties' => ['edit', '属性'], 'copy' => ['copy', '复制'], 'delete' => ['delete', '删除']] as $action => [$icon, $label]): ?>
<button type="button" data-element-<?= $action ?> aria-label="<?= $label ?>" title="<?= $label ?>"><?= View::fragment('studio-icon', compact('icon')) ?></button>
<?php endforeach ?>
</div>
<button class="studio-media-handle" type="button" role="slider" aria-label="媒体宽度" aria-valuemin="10" aria-valuemax="100" aria-valuenow="100" data-media-handle hidden></button>
<div class="studio-media-sizing" data-media-sizing hidden>
<output data-media-size aria-hidden="true"></output>
<button class="button button-outline" type="button" data-reset-media>原始尺寸</button>
<button class="button button-outline" type="button" data-replace-media>替换媒体</button>
</div>
</div>
<p class="field-note studio-canvas-status" data-canvas-status role="status"></p>
<dialog class="media-picker canvas-properties" data-canvas-properties aria-labelledby="canvas-properties-heading">
<div class="admin-heading compact"><h2 id="canvas-properties-heading" data-property-heading>编辑属性</h2></div>
<form class="admin-form" method="dialog">
<label data-property-row="label">文案<input name="label"></label>
<label data-property-row="note">副标题<input name="note" maxlength="200"></label>
<label data-property-row="url">地址<input name="url" maxlength="1000"></label>
<label data-property-row="buttonStyle">按钮样式<select name="buttonStyle">
<?php foreach (Buttons::STYLES as $style => $label): ?><option value="<?= $e($style) ?>"><?= $e($label) ?></option><?php endforeach ?>
</select></label>
<label data-property-row="newTab">打开方式<select name="newTab"><option value="0">当前标签页</option><option value="1">新标签页</option></select></label>
<label data-property-row="alt">图片替代文本<input name="alt" maxlength="200"></label>
<label data-property-row="quicklinks">目录链接<textarea name="quicklinks" rows="5" placeholder="概览 | #overview"></textarea><small>每行填写「文案 | 链接」。</small></label>
<label data-property-row="value">当前值<input name="value" inputmode="numeric"></label>
<label data-property-row="max">最大值<input name="max" inputmode="numeric"></label>
<label data-property-row="poster">视频封面<input name="poster" maxlength="1000"></label>
<p class="feedback error" role="alert" data-property-error hidden></p>
<div class="actions">
<button type="button" class="button button-outline" data-property-pick="url">从媒体库选择</button>
<button type="button" class="button button-outline" data-property-pick="poster">选择视频封面</button>
</div>
<div class="actions">
<button type="submit" class="button button-primary">应用</button>
<button type="button" class="button button-outline" data-property-close>取消</button>
</div>
</form>
</dialog>
<dialog class="media-picker canvas-module-settings" data-module-dialog aria-labelledby="module-settings-title">
<div class="admin-heading compact"><h2 id="module-settings-title">模块设置</h2></div>
<form class="admin-form" method="dialog">
<label>模块标题<input name="module_title" maxlength="100" required></label>
<label>模块简介<textarea name="module_lead" rows="2" maxlength="500"></textarea></label>
<?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => [], 'allowOff' => false]) ?>
<p class="feedback error" role="alert" data-module-error hidden></p>
<div class="actions">
<button class="button button-primary" type="submit">应用</button>
<button class="button button-outline" data-module-close type="button">取消</button>
</div>
</form>
</dialog>
</section>
</div>
<form id="studio-page-settings" class="admin-form admin-panel studio-inspector" method="post" action="/admin/pages/<?= $e($slug) ?>">
<h2>页面设置</h2>
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="canvas_sections" value="">
<input type="hidden" name="alignments" value="<?= $e(Database::json($page['alignments'])) ?>">
<details class="studio-hero-settings">
<summary>首屏与目录</summary>
<div class="studio-hero-controls">
<button class="button button-outline" type="button" disabled data-hero-control="image">首屏图片</button>
<button class="button button-outline" type="button" disabled data-hero-control="add-action">添加首屏按钮</button>
<button class="button button-outline" type="button" disabled data-hero-control="navigation">本页目录</button>
</div>
</details>
<label>页面名称<input name="name" value="<?= $e($page['name']) ?>" required maxlength="100"></label>
<label>SEO 标题<input name="title" value="<?= $e($page['title']) ?>" required maxlength="160"></label>
<label>SEO 描述<textarea name="description" rows="2" maxlength="300"><?= $e($page['description']) ?></textarea></label>
<fieldset class="admin-options form-grid">
<legend>页面显示</legend>
<?php foreach (['header' => '页头', 'hero' => '首屏', 'footer' => '页脚'] as $area => $label): ?>
<?php $visible = $page['visibility'][$area] ?? true; ?>
<label><?= $e($label) ?><select name="show_<?= $e($area) ?>">
<option value="1" <?= $visible ? 'selected' : '' ?>>显示</option>
<option value="0" <?= !$visible ? 'selected' : '' ?>>隐藏</option>
</select></label>
<?php endforeach ?>
</fieldset>
<fieldset class="admin-options form-grid"><legend>页头、页脚与配色</legend>
<?php foreach (['header' => '页头方案', 'footer' => '页脚方案', 'palette' => '配色方案'] as $kind => $label): ?>
<label><?= $e($label) ?><select name="<?= $e($kind) ?>_id">
<option value=""><?= $kind === 'palette' ? '页面原有配色' : '站点默认' ?></option>
<?php foreach ($designs as $item): ?>
<?php if ($item['kind'] !== $kind) continue; ?>
<option value="<?= $e($item['id']) ?>" <?= ($page[$kind . '_id'] ?? null) === $item['id'] ? 'selected' : '' ?>><?= $e($item['name']) ?></option>
<?php endforeach ?>
</select></label>
<?php endforeach ?>
<a href="/admin/design" target="_blank" rel="noopener noreferrer">管理设计配置</a>
</fieldset>
<textarea name="hero_actions" hidden><?= $e(Database::json(Buttons::validate($page['actions']))) ?></textarea>
<?php
$contentFields = [
'heading' => $page['heading'], 'accent' => $page['accent'], 'lead' => $page['lead'],
'image' => $page['image'], 'alt' => $page['alt'], 'image_scale' => $page['image_scale'],
'quicklinks' => SiteDesign::linkText($page['quicklinks']),
];
?>
<?php foreach ($contentFields as $field => $value): ?>
<?php if ($field === 'quicklinks'): ?>
<textarea name="quicklinks" hidden><?= $e($value) ?></textarea>
<?php else: ?>
<input type="hidden" name="<?= $e($field) ?>" value="<?= $e($value) ?>">
<?php endif ?>
<?php endforeach ?>
<?php if ($slug !== 'home'): ?>
<label>发布状态<select name="status"><option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>草稿</option>
<option value="published" <?= $page['status'] === 'published' ? 'selected' : '' ?>>已发布</option></select></label>
<?php endif ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存页面</button></div>
</form>
</div>
<?= View::fragment('studio-page-templates', compact('token')) ?>
+14
View File
@@ -0,0 +1,14 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><h1><?= $e($title) ?></h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel password-form" method="post" action="/admin/password">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>当前密码<input name="current_password" type="password" autocomplete="current-password" required></label>
<label>新密码<input name="new_password" type="password" autocomplete="new-password" minlength="8" required><small>至少 8 个字符,最多 72 字节。</small></label>
<label>再次输入新密码<input name="confirm_password" type="password" autocomplete="new-password" minlength="8" required></label>
<div class="form-submit"><button class="button button-primary" type="submit">修改密码</button></div>
</form>
+33
View File
@@ -0,0 +1,33 @@
<?php
use App\Content\View;
$e = View::escape(...);
$slug = $section['page_slug'];
$key = $section['key'];
$feed = json_decode($section['feed'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
?>
<a class="back-link" href="/admin/pages/<?= $e($slug) ?>">返回页面编辑</a>
<header class="admin-heading">
<div><h1><?= $e($title) ?></h1><p><?= $e($slug) ?> · #<?= $e($key) ?></p></div>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/preview#<?= $e($key) ?>" target="_blank" rel="noopener">预览区块</a>
</header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/pages/<?= $e($slug) ?>/<?= $e($key) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($section['version']) ?>">
<label>区块标题<input name="title" value="<?= $e($section['title']) ?>" required maxlength="100"></label>
<label>区块简介<textarea name="lead" rows="2" maxlength="500"><?= $e($section['lead']) ?></textarea></label>
<?php if ($savedStyle !== 'hero-links'): ?>
<label>区块背景<select name="style">
<?php foreach (array_unique([$savedStyle, 'plain', 'tinted']) as $style): ?>
<option value="<?= $e($style) ?>" <?= $style === $section['style'] ? 'selected' : '' ?>><?= $e(['plain' => '默认', 'tinted' => '浅色背景'][$style] ?? '保留原布局') ?></option>
<?php endforeach ?>
</select></label>
<details class="admin-options" <?= $feed ? 'open' : '' ?>>
<summary>动态模块</summary>
<?= View::fragment('studio-feed-fields', ['categories' => $categories, 'feed' => $feed, 'allowOff' => true]) ?>
</details>
<?php endif ?>
<?= View::fragment('admin-editor', ['format' => 'html', 'body' => $section['body']]) ?>
<div class="form-submit"><button class="button button-primary" type="submit">保存区块</button></div>
</form>
+32
View File
@@ -0,0 +1,32 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<section class="section article-page" aria-labelledby="archive-title" data-enter>
<div class="wrap">
<div class="section-heading">
<?php if ($backPath): ?><a class="back-link" href="<?= $e($backPath) ?>"><?= $e($backLabel) ?></a><?php endif ?>
<h1 id="archive-title"><?= $e($headline) ?></h1>
<p><?= $e($description) ?></p>
</div>
<nav class="filter-nav" aria-label="动态分类">
<a href="<?= $e($allPath) ?>" <?= !$category && !$tag ? 'aria-current="page"' : '' ?>>全部</a>
<?php foreach ($categories as $key => $label): ?>
<a href="<?= $e($categoryLinks[$key]) ?>" <?= $category === (string) $key ? 'aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
</nav>
<?php if (!empty($catalog)): ?>
<?= View::fragment('service-cards', ['products' => $articles]) ?>
<?php else: ?>
<?= View::fragment('article-list', ['articles' => $articles, 'categoryScope' => $categoryScope ?? null]) ?>
<?php endif ?>
<?php if ($pageNumber > 1 || $hasNext): ?>
<nav class="pagination" aria-label="动态分页">
<?php if ($pageNumber > 1): ?><a class="button button-outline" href="<?= $e(View::archivePage($archivePath, $pageNumber - 1)) ?>" rel="prev">上一页</a><?php endif ?>
<span>第 <?= $e($pageNumber) ?> 页</span>
<?php if ($hasNext): ?><a class="button button-outline" href="<?= $e(View::archivePage($archivePath, $pageNumber + 1)) ?>" rel="next">下一页</a><?php endif ?>
</nav>
<?php endif ?>
</div>
</section>
+23
View File
@@ -0,0 +1,23 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="article-feed" <?= count($groups) > 1 ? 'data-article-tabs' : '' ?>>
<?php if (count($groups) > 1): ?>
<div class="filter-nav article-tabs" data-tab-list role="tablist" aria-labelledby="heading-<?= $e($sectionKey) ?>" hidden>
<?php foreach ($groups as $index => $group): ?>
<button type="button" role="tab" id="<?= $e($sectionKey) ?>-tab-<?= $index ?>" aria-controls="<?= $e($sectionKey) ?>-articles-<?= $index ?>"><?= $e($group['label']) ?></button>
<?php endforeach ?>
</div>
<?php endif ?>
<?php foreach ($groups as $index => $group): ?>
<div id="<?= $e($sectionKey) ?>-articles-<?= $index ?>" data-tab-panel>
<?php if ($group['label'] !== ''): ?><h3 data-tab-heading><?= $e($group['label']) ?></h3><?php endif ?>
<?= View::fragment('article-list', ['articles' => $group['articles'], 'categoryScope' => $group['categories']]) ?>
</div>
<?php endforeach ?>
<?php if ($archivePath !== null): ?>
<p class="article-feed-archive"><a class="back-link" href="<?= $e($archivePath) ?>">查看全部动态</a></p>
<?php endif ?>
</div>
+24
View File
@@ -0,0 +1,24 @@
<?php
use App\Content\View;
$e = View::escape(...);
$scope = isset($categoryScope) ? array_flip($categoryScope) : null;
?>
<?php if ($articles): ?>
<ul class="article-list">
<?php foreach ($articles as $item): ?>
<?php $labels = $scope === null ? $item['categories'] : array_intersect_key($item['categories'], $scope); ?>
<li>
<a class="article-row" href="/articles/<?= $e($item['slug']) ?>">
<span class="article-category"><?= $e(implode('、', $labels)) ?></span>
<span class="article-row-title"><?= $e($item['title']) ?>
<?php if ($item['summary']): ?><small><?= $e($item['summary']) ?></small><?php endif ?>
</span>
<?php if ($item['published_at']): ?><time datetime="<?= $e(View::date($item['published_at'], 'Y-m-d')) ?>"><?= $e(View::date($item['published_at'], 'Y.m.d')) ?></time><?php endif ?>
</a>
</li>
<?php endforeach ?>
</ul>
<?php else: ?>
<p class="empty-state">暂无已发布的动态。</p>
<?php endif ?>
+46
View File
@@ -0,0 +1,46 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<article class="section article-page" itemscope itemtype="https://schema.org/Article" data-enter>
<?php $card = $article['card']; ?>
<div class="wrap reading-wrap">
<a class="back-link" href="/articles">全部动态</a>
<header class="section-heading">
<div class="article-meta">
<?php foreach ($article['categories'] as $key => $name): ?>
<a href="/articles/category/<?= $e($key) ?>" itemprop="articleSection"><?= $e($name) ?></a>
<?php endforeach ?>
<?php if ($article['published_at']): ?><time itemprop="datePublished" datetime="<?= $e(View::date($article['published_at'], DATE_ATOM)) ?>"><?= $e(View::date($article['published_at'])) ?></time><?php endif ?>
<meta itemprop="dateModified" content="<?= $e(View::date($article['updated_at'], DATE_ATOM)) ?>">
</div>
<h1 itemprop="headline"><?= $e($article['title']) ?></h1>
<?php if ($article['summary']): ?><p itemprop="description"><?= $e($article['summary']) ?></p><?php endif ?>
<span itemprop="author" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="<?= $e($site['name']) ?>"></span>
</header>
<?php if (!empty($card['image'])): ?>
<img class="article-cover" src="<?= $e($card['image']) ?>" alt="<?= $e($card['alt'] ?? '') ?>">
<?php endif ?>
<div class="rich prose" itemprop="articleBody">
<?php if (trim($articleHtml) !== ''): ?>
<?= $articleHtml ?>
<?php elseif (!$article['summary'] && empty($card['image']) && empty($card['url'])): ?>
<p class="empty-state">此文章的原文暂不可用。</p>
<?php endif ?>
</div>
<?php if (!empty($card['url']) || !empty($card['extra_url'])): ?>
<div class="actions">
<?php if (!empty($card['url'])): ?><a class="button button-primary" href="<?= $e($card['url']) ?>"><?= $e(($card['label'] ?? '') ?: '访问网站') ?></a><?php endif ?>
<?php if (!empty($card['extra_url'])): ?><a href="<?= $e($card['extra_url']) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
<?php endif ?>
<?php if ($article['tags']): ?>
<nav class="filter-nav" aria-label="文章标签">
<?php foreach ($article['tags'] as $tag): ?>
<a href="/articles/tag/<?= $e(rawurlencode($tag)) ?>"><?= $e($tag) ?></a>
<?php endforeach ?>
</nav>
<?php endif ?>
</div>
</article>
+26
View File
@@ -0,0 +1,26 @@
<?php
use App\Content\View;
$e = View::escape(...);
$data = $footer['payload'];
$brand = $data['brand'] ?: $site['name'];
?>
<footer class="site-footer site-footer-<?= $e($footer['preset']) ?>" id="contact"<?= $showFooter ? '' : ' hidden' ?>>
<div class="wrap site-footer-components">
<?php foreach ($data['components'] as $component): ?>
<?php if ($component === 'brand'): ?>
<a class="wordmark site-brand" href="/" aria-label="<?= $e($brand) ?>,首页">
<?php if ($data['logo'] !== ''): ?><img src="<?= $e($data['logo']) ?>" alt="<?= $e($brand) ?>" loading="lazy"><?php else: ?><?= $e($brand) ?><?php endif ?>
</a>
<?php elseif ($component === 'text' && $data['text'] !== ''): ?>
<p class="site-footer-text"><?= $e($data['text']) ?></p>
<?php elseif ($component === 'links' && $data['links']): ?>
<nav class="site-footer-nav" aria-label="页脚导航">
<?php foreach ($data['links'] as [$url, $label]): ?><a href="<?= $e($url) ?>"><?= $e($label) ?></a><?php endforeach ?>
</nav>
<?php elseif ($component === 'legal' && $data['legal'] !== ''): ?>
<small><?= $e($data['legal']) ?></small>
<?php endif ?>
<?php endforeach ?>
</div>
</footer>
+42
View File
@@ -0,0 +1,42 @@
<?php
use App\Content\Buttons;
use App\Content\View;
$e = View::escape(...);
$data = $header['payload'];
$brand = $data['brand'] ?: $site['name'];
$member = $header['preset'] === 'member' && $data['provider'] !== [];
?>
<header class="masthead masthead-<?= $e($header['preset']) ?>"<?= $showHeader ? '' : ' hidden' ?>>
<div class="wrap masthead-inner">
<?php foreach ($data['components'] as $component): ?>
<?php if ($component === 'brand'): ?>
<a class="wordmark site-brand" href="/" aria-label="<?= $e($brand) ?>,首页">
<?php if ($data['logo'] !== ''): ?><img src="<?= $e($data['logo']) ?>" alt="<?= $e($brand) ?>"><?php else: ?><?= $e($brand) ?><?php endif ?>
</a>
<?php elseif ($component === 'links' && $data['links']): ?>
<button class="menu-toggle" type="button" aria-expanded="false" aria-controls="primary-navigation" hidden>
<span></span><span></span><span class="sr-only">菜单</span>
</button>
<nav id="primary-navigation" class="primary-nav" aria-label="主导航">
<?php foreach ($data['links'] as [$url, $label]): ?>
<a href="<?= $e($url) ?>"<?= $url === $path ? ' aria-current="page"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
</nav>
<?php elseif ($component === 'action' && $data['action']): ?>
<?php [$url, $label, $style, $blank] = $data['action'][0]; ?>
<a class="<?= $e(Buttons::css($style)) ?> masthead-action" href="<?= $e($url) ?>"<?= Buttons::target($blank) ?>><?= $e($label) ?></a>
<?php elseif ($component === 'account' && $member): ?>
<?php if ($visitor): ?>
<a class="site-account" href="/account" aria-label="打开用户中心">
<?php if ($visitor['avatar'] !== ''): ?><img class="account-avatar" src="<?= $e($visitor['avatar']) ?>" alt="" width="36" height="36"><?php else: ?>
<span class="account-avatar account-initial" aria-hidden="true"><?= $e(mb_substr($visitor['name'], 0, 1)) ?></span>
<?php endif ?>
</a>
<?php else: ?>
<a class="button button-outline site-account" href="/account/login/<?= $e($header['id']) ?>">登录</a>
<?php endif ?>
<?php endif ?>
<?php endforeach ?>
</div>
</header>
+60
View File
@@ -0,0 +1,60 @@
<?php
use App\Content\View;
use App\Content\Assets;
use App\Content\DesignLibrary;
$e = View::escape(...);
$canonical = $path !== null && empty($previewMode) ? View::absolute($path) : null;
$imageUrl = !empty($socialImage) ? Assets::url($socialImage, $cdn) : '';
if (str_starts_with($imageUrl, '/')) {
$imageUrl = View::absolute($imageUrl);
}
$theme = $page['theme'] ?? '';
$palette = DesignLibrary::find((int) ($page['palette_id'] ?? 0), 'palette');
$showHeader = $page['visibility']['header'] ?? true;
$showFooter = $page['visibility']['footer'] ?? true;
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $e($title) ?></title>
<meta name="description" content="<?= $e($description) ?>">
<meta name="theme-color" content="#f5f7fb">
<?php if ($canonical): ?>
<link rel="canonical" href="<?= $e($canonical) ?>">
<meta property="og:url" content="<?= $e($canonical) ?>">
<?php endif ?>
<?php if (!empty($noindex)): ?><meta name="robots" content="noindex"><?php endif ?>
<meta property="og:type" content="<?= isset($article) ? 'article' : 'website' ?>">
<meta property="og:locale" content="zh_CN">
<meta property="og:site_name" content="<?= $e($site['name']) ?>">
<meta property="og:title" content="<?= $e($title) ?>">
<meta property="og:description" content="<?= $e($description) ?>">
<?php if ($imageUrl !== ''): ?>
<meta property="og:image" content="<?= $e($imageUrl) ?>">
<meta property="og:image:alt" content="<?= $e($socialAlt ?? '') ?>">
<?php endif ?>
<?php if (isset($article)): ?>
<meta property="article:published_time" content="<?= $e(View::date($article['published_at'], DATE_ATOM)) ?>">
<meta property="article:modified_time" content="<?= $e(View::date($article['updated_at'], DATE_ATOM)) ?>">
<?php endif ?>
<meta name="twitter:card" content="summary_large_image">
<link rel="stylesheet" href="/assets/site.css">
<?php if ($theme !== ''): ?><link rel="stylesheet" href="/assets/page-themes.css"><?php endif ?>
<?php if ($palette): ?><link rel="stylesheet" data-page-palette href="/palette/<?= $e($palette['id']) ?>.css?v=<?= $e($palette['version']) ?>"><?php endif ?>
<script src="/assets/jquery-4.0.0.min.js" defer></script>
<script src="/assets/site.js" defer></script>
</head>
<body>
<a class="skip-link" href="#main-content">跳到内容</a>
<?php if ($showHeader || !empty($canvas)): ?>
<?= View::fragment('header', compact('header', 'site', 'showHeader', 'visitor', 'path')) ?>
<?php endif ?>
<main id="main-content"<?= $theme !== '' ? ' class="page-theme theme-' . $e($theme) . '"' : '' ?> tabindex="-1"><?= $content ?></main>
<?php if ($showFooter || !empty($canvas)): ?>
<?= View::fragment('footer', compact('footer', 'site', 'showFooter')) ?>
<?php endif ?>
</body>
</html>
+8
View File
@@ -0,0 +1,8 @@
<section class="section article-page">
<div class="wrap">
<p class="overline">404</p>
<h1>页面未找到</h1>
<p>请检查网址,或回到首页浏览产品与服务。</p>
<a class="button button-primary" href="/">返回首页</a>
</div>
</section>
+27
View File
@@ -0,0 +1,27 @@
<?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<ul class="network-list">
<?php foreach ($articles as $item): ?>
<?php
$card = $item['card'];
['primary' => $target, 'detail' => $detail] = DirectoryCard::links($item, Html::articleBody($item));
?>
<li>
<?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?php else: ?><span class="network-static"><?php endif ?>
<?php if (!empty($card['image'])): ?>
<img src="<?= $e($card['image']) ?>" alt="" loading="lazy" width="76" height="28">
<?php endif ?>
<span><?= $e($item['title']) ?></span>
<?php if ($target !== ''): ?></a><?php else: ?></span><?php endif ?>
<?php if ($standalone && $detail !== ''): ?>
<a class="network-detail" href="<?= $e($detail) ?>">查看详情</a>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
+74
View File
@@ -0,0 +1,74 @@
<?php
use App\Content\Buttons;
use App\Content\View;
$e = View::escape(...);
$home = $page['slug'] === 'home';
$showHero = $page['visibility']['hero'] ?? true;
$heroLinks = array_filter($page['sections'], static fn (array $section): bool => $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 . '"' : '';
?>
<?php if (!$showHero && !$canvas): ?><h1 class="sr-only"><?= $e($page['name']) ?></h1><?php endif ?>
<?php if ($showHero || $canvas || $heroLinks): ?>
<section class="hero hero-<?= $e($page['slug']) ?>" id="home" data-enter>
<?php if ($showHero || $canvas): ?>
<div class="wrap hero-inner<?= $page['image'] === '' ? ' hero-text-only' : '' ?>"<?= $canvas ? ' data-studio-hero-content' : '' ?><?= $showHero ? '' : ' hidden' ?>>
<div class="hero-copy">
<?php if (!$home): ?>
<nav class="breadcrumbs" aria-label="面包屑" itemscope itemtype="https://schema.org/BreadcrumbList">
<span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="/"><span itemprop="name">首页</span></a>
<meta itemprop="position" content="1">
</span>
<span class="crumb-divider" aria-hidden="true">/</span>
<span itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
<a itemprop="item" href="/<?= $e($page['slug']) ?>" aria-current="page"><span itemprop="name"<?= $field('name') ?>><?= $e($page['name']) ?></span></a>
<meta itemprop="position" content="2">
</span>
</nav>
<?php else: ?>
<p class="overline hero-label"><?= $e($site['name']) ?></p>
<?php endif ?>
<h1<?= isset($alignments['heading']) ? ' class="' . trim(View::alignmentClass($alignments['heading'])) . '"' : '' ?><?= $alignField('heading') ?>><span class="hero-heading-primary"<?= $field('heading') ?>><?= $e($page['heading']) ?></span><?php if ($canvas): ?><span class="studio-accent"<?= $field('accent') ?>><?= $e($page['accent']) ?></span><?php elseif ($page['accent'] !== ''): ?><br><span><?= $e($page['accent']) ?></span><?php endif ?></h1>
<p class="hero-lead<?= View::alignmentClass($alignments['lead'] ?? null) ?>"<?= $field('lead') ?><?= $alignField('lead') ?>><?= $e($page['lead']) ?></p>
<div class="actions hero-actions<?= View::alignmentClass($alignments['actions'] ?? null) ?>"<?= $alignField('actions') ?>>
<?php foreach (Buttons::validate($page['actions']) as $index => [$url, $label, $style, $blank]): ?>
<a class="<?= $e(Buttons::css($style)) ?>" href="<?= $e($url) ?>"<?= Buttons::target($blank) ?><?= $canvas ? ' data-studio-action="' . $index . '"' : '' ?>><?= $e($label) ?></a>
<?php endforeach ?>
</div>
</div>
<?php if ($canvas || $page['image'] !== ''): ?>
<div class="hero-visual app-frame<?= $page['image_scale'] ? ' studio-media-' . $e($page['image_scale']) : '' ?><?= View::alignmentClass($alignments['image'] ?? null) ?>" data-visual<?= $alignField('image') ?><?= $page['image'] === '' ? ' hidden' : '' ?>>
<img<?= $page['image'] === '' ? '' : ' src="' . $e($page['image']) . '"' ?> alt="<?= $e($page['alt']) ?>" width="1448" height="1086" fetchpriority="high"<?= $canvas ? ' data-studio-hero-image' : '' ?>>
</div>
<?php endif ?>
</div>
<?php endif ?>
<?php foreach ($heroLinks as $section): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => false, 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<?php endforeach ?>
</section>
<?php endif ?>
<?php if ($canvas || $page['quicklinks']): ?>
<nav class="section-nav" aria-label="本页目录"<?= $canvas ? ' data-studio-navigation' : '' ?><?= !$page['quicklinks'] ? ' hidden' : '' ?>>
<div class="wrap section-nav-inner">
<?php foreach ($page['quicklinks'] as [$url, $label]): ?>
<a href="<?= $e($url) ?>"><?= $e($label) ?></a>
<?php endforeach ?>
</div>
</nav>
<?php endif ?>
<?php foreach ($page['sections'] as $section): ?>
<?php if ($section['style'] !== 'hero-links'): ?>
<?= View::fragment('section', ['section' => $section, 'moment' => false, 'canvas' => $canvas, 'pageSlug' => $page['slug']]) ?>
<?php endif ?>
<?php endforeach ?>
<?php if ($canvas): ?>
<template data-studio-section-end><?= View::fragment('section', [
'section' => ['style' => 'plain', 'key' => 'new', 'version' => null, 'title' => '', 'lead' => '', 'body' => ''],
'moment' => false, 'canvas' => true,
]) ?></template>
<?php endif ?>
+54
View File
@@ -0,0 +1,54 @@
<?php
use App\Content\View;
$e = View::escape(...);
$canvas ??= false;
$body = $section['body'];
$dynamic = isset($section['feed']);
$studio = $canvas ? ' data-studio-section="' . $e($section['version']) . '" data-studio-source="' . $e(base64_encode($section['body'])) . '"' : '';
if ($canvas && $dynamic) {
$studio .= ' data-studio-dynamic data-studio-feed="' . $e($section['feed']) . '" tabindex="0"';
}
if ($section['style'] === 'hero-links'):
?>
<div class="wrap hero-directory-slot" id="<?= $e($section['key']) ?>"<?= $studio ?>>
<?php if ($canvas): ?><span data-studio-part="title" hidden><?= $e($section['title']) ?></span><span data-studio-part="lead" hidden><?= $e($section['lead']) ?></span><?php endif ?>
<div<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div>
</div>
<?php
return;
endif;
$alignments = json_decode($section['alignments'] ?? '{}', true, flags: JSON_THROW_ON_ERROR);
if ($dynamic && $body === '<p><a class="back-link" href="/articles">查看全部动态</a></p>') {
$body = '';
}
$network = $section['networkFeed'] ?? false;
$catalog = $section['catalogFeed'] ?? false;
?>
<section class="section section-<?= $e($section['style']) ?><?= $network ? ' network' : '' ?>" id="<?= $e($section['key']) ?>" aria-labelledby="heading-<?= $e($section['key']) ?>" <?= $moment ? 'data-moment="iris-opens"' : '' ?><?= $studio ?>>
<div class="wrap">
<div class="section-heading">
<h2 id="heading-<?= $e($section['key']) ?>"<?= isset($alignments['title']) ? ' class="' . trim(View::alignmentClass($alignments['title'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="title"' : '' ?>><?= $e($section['title']) ?></h2>
<?php if ($canvas || $section['lead']): ?><p<?= isset($alignments['lead']) ? ' class="' . trim(View::alignmentClass($alignments['lead'])) . '"' : '' ?><?= $canvas ? ' data-studio-part="lead"' : '' ?>><?= $e($section['lead']) ?></p><?php endif ?>
</div>
<?php if ($network): ?>
<?php foreach ($section['articleFeed'] as $group): ?>
<?php $slug = $group['categories'][0]; $anchor = ($pageSlug ?? '') === 'home' && $section['key'] === 'network' ? $slug : $section['key'] . '-group-' . $slug; ?>
<div class="network-group" id="<?= $e($anchor) ?>">
<h3><?= $e($group['label']) ?></h3>
<?= View::fragment('network-items', ['articles' => $group['articles'], 'standalone' => false]) ?>
</div>
<?php endforeach ?>
<?php if ($section['archivePath'] !== null): ?><p class="article-feed-archive"><a class="back-link" href="<?= $e($section['archivePath']) ?>">查看全部</a></p><?php endif ?>
<?php elseif ($catalog): ?>
<?= View::fragment('service-cards', ['products' => $section['articleFeed'][0]['articles']]) ?>
<?php if ($section['archivePath'] !== null && count($section['articleFeed'][0]['articles']) >= $section['feedLimit']): ?>
<p class="article-feed-archive"><a class="back-link" href="<?= $e($section['archivePath']) ?>">查看全部</a></p>
<?php endif ?>
<?php elseif (!empty($section['articleFeed'])): ?>
<?= View::fragment('article-feed', ['groups' => $section['articleFeed'], 'sectionKey' => $section['key'], 'archivePath' => $section['archivePath']]) ?>
<?php endif ?>
<?php if ($canvas || $body !== ''): ?><div class="rich<?= $dynamic ? ' article-feed-note' : '' ?>"<?= $canvas ? ' data-studio-part="body"' : '' ?>><?= $body ?></div><?php endif ?>
</div>
</section>
+38
View File
@@ -0,0 +1,38 @@
<?php
use App\Content\DirectoryCard;
use App\Content\Html;
use App\Content\View;
$e = View::escape(...);
?>
<?php if (!$products): ?><p class="empty-state">暂无可查看的产品和服务。</p><?php endif ?>
<div class="catalog-grid">
<?php foreach ($products as $product): ?>
<?php
$card = $product['card'];
$body = Html::articleBody($product);
$target = DirectoryCard::links($product, $body)['primary'];
$extra = $card['extra_url'] ?? '';
?>
<article class="catalog-card">
<?php if (!empty($card['image'])): ?>
<div class="catalog-image"><img src="<?= $e($card['image']) ?>" alt="<?= $e($card['alt'] ?? '') ?>" loading="lazy"></div>
<?php endif ?>
<div class="catalog-content">
<?php if (!empty($card['category_label'])): ?><p class="overline"><?= $e($card['category_label']) ?></p><?php endif ?>
<h3><?php if ($target !== ''): ?><a href="<?= $e($target) ?>"><?= $e($product['title']) ?></a><?php else: ?><?= $e($product['title']) ?><?php endif ?></h3>
<?php if ($product['summary']): ?>
<p><?= $e($product['summary']) ?></p>
<?php else: ?>
<div class="rich"><?= $body ?></div>
<?php endif ?>
<?php if ($target !== '' || $extra !== ''): ?>
<div class="actions">
<?php if ($target !== ''): ?><a class="button button-primary" href="<?= $e($target) ?>"><?= $e(($card['label'] ?? '') ?: '了解详情') ?></a><?php endif ?>
<?php if ($extra !== '' && $extra !== $target): ?><a href="<?= $e($extra) ?>"><?= $e(($card['extra_label'] ?? '') ?: '相关链接') ?></a><?php endif ?>
</div>
<?php endif ?>
</div>
</article>
<?php endforeach ?>
</div>
+24
View File
@@ -0,0 +1,24 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
?>
<details class="studio-anchor-create">
<summary>按锚点新建区块</summary>
<form class="admin-form" method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="operation" value="create">
<label>锚点<input name="key" pattern="[a-z0-9]+(-[a-z0-9]+)*" maxlength="70" placeholder="overview" required></label>
<label>模板<select name="preset">
<?php foreach (BlockTemplates::groups() as [$category, $templates]): ?>
<optgroup label="<?= $e($category) ?>">
<?php foreach ($templates as $preset => [$label]): ?>
<option value="<?= $e($preset) ?>"><?= $e($label) ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select></label>
<button type="submit" class="button button-outline">新建</button>
</form>
</details>
+9
View File
@@ -0,0 +1,9 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<div class="asset-field">
<label><?= $e($label) ?><input name="<?= $e($name) ?>" value="<?= $e($value) ?>" maxlength="1000"></label>
<button type="button" class="button button-outline" data-asset-pick="<?= $e($name) ?>" data-asset-type="image/">媒体库</button>
</div>
+15
View File
@@ -0,0 +1,15 @@
<?php
use App\Content\View;
$e = View::escape(...);
$modes = ($allowOff ? ['off' => '不展示'] : []) + ['merged' => '合并列表', 'tabs' => '分类标签页', 'network' => '项目与伙伴卡片', 'catalog' => '产品与服务卡片'];
?>
<div class="form-grid">
<label>展示方式<select name="feed_mode">
<?php foreach ($modes as $mode => $label): ?>
<option value="<?= $mode ?>" <?= ($feed['mode'] ?? 'off') === $mode ? 'selected' : '' ?>><?= $e($label) ?></option>
<?php endforeach ?>
</select></label>
<label>展示数量<input name="feed_limit" type="number" required min="1" max="30" value="<?= $e($feed['limit'] ?? 6) ?>"><small>分组时每个分类独立计数。</small></label>
</div>
<?= View::fragment('admin-category-checkboxes', ['name' => 'feed_categories', 'selected' => $feed['categories'] ?? [], 'categories' => $categories, 'legend' => '展示分类']) ?>
+12
View File
@@ -0,0 +1,12 @@
<?php
$paths = [
'left' => '<path d="M3 6h18M3 10h12M3 14h18M3 18h12"/>',
'center' => '<path d="M3 6h18M6 10h12M3 14h18M6 18h12"/>',
'right' => '<path d="M3 6h18M9 10h12M3 14h18M9 18h12"/>',
'settings' => '<path d="M4 6h12m4 0h0M4 12h3m4 0h9M4 18h10m4 0h2"/><circle cx="17" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="16" cy="18" r="2"/>',
'edit' => '<path d="m14 5 5 5M5 19l4-.8L20 7.3 16.7 4 5.8 15z"/>',
'copy' => '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 4H6a2 2 0 0 0-2 2v10"/>',
'delete' => '<path d="M4 7h16M9 7V4h6v3m3 0-.8 13H6.8L6 7m4 4v5m4-5v5"/>',
];
?>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><?= $paths[$icon] ?></svg>
+30
View File
@@ -0,0 +1,30 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<details class="studio-layers" id="blocks">
<summary>区块顺序</summary>
<ul class="admin-list studio-blocks">
<?php foreach ($page['sections'] as $index => $item): ?>
<?php $fixedSlot = $item['style'] === 'hero-links'; ?>
<li>
<div><strong><?= $e($item['title']) ?></strong><small>#<?= $e($item['key']) ?></small></div>
<div class="actions studio-block-actions">
<button class="button button-outline" type="button" data-canvas-jump="<?= $e($item['key']) ?>" hidden>在画布编辑</button>
<a class="button button-outline" href="/admin/pages/<?= $e($slug) ?>/<?= $e($item['key']) ?>">区块设置</a>
<form method="post" action="/admin/page-blocks/<?= $e($slug) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="key" value="<?= $e($item['key']) ?>">
<input type="hidden" name="page_version" value="<?= $e($page['version']) ?>">
<input type="hidden" name="version" value="<?= $e($item['version']) ?>">
<button class="button button-outline" name="operation" value="up" type="submit" <?= $fixedSlot || $index === 0 || $page['sections'][$index - 1]['style'] === 'hero-links' ? 'disabled' : '' ?>>上移</button>
<button class="button button-outline" name="operation" value="down" type="submit" <?= $fixedSlot || $index === count($page['sections']) - 1 ? 'disabled' : '' ?>>下移</button>
<button class="button button-outline" name="operation" value="delete" type="submit" data-confirm="删除这个区块?">删除</button>
</form>
</div>
</li>
<?php endforeach ?>
</ul>
</details>
+63
View File
@@ -0,0 +1,63 @@
<?php
use App\Content\View;
$e = View::escape(...);
$modules = $kind === 'modules';
?>
<section role="tabpanel" id="studio-panel-<?= $kind ?>" aria-labelledby="studio-tab-<?= $kind ?>" data-library-panel="<?= $kind ?>" hidden>
<ul class="studio-library-categories" data-library-index>
<?php foreach ($groups as $group => [$category, $items]): ?>
<li><button type="button" data-library-category="<?= $e($group) ?>" data-library-label="<?= $e($category) ?>">
<span><?= $e($category) ?></span><small><?= count($items) ?></small>
</button></li>
<?php endforeach ?>
</ul>
<?php if ($modules): ?><?= $anchorForm ?><?php endif ?>
<div class="studio-library-content" data-library-content hidden>
<div class="studio-library-category-title">
<button type="button" data-library-back>返回分类</button>
<h3 data-library-title></h3>
</div>
<label class="studio-template-search">查找本分类<input type="search" data-template-search autocomplete="off"></label>
<?php if ($modules): ?>
<label class="studio-insert-mode"><input type="checkbox" data-template-inline> 插入当前正文</label>
<?php endif ?>
<p class="field-note" data-template-empty hidden role="status">没有匹配的<?= $modules ? '组件' : '元素' ?>。</p>
<?php foreach ($groups as $group => [$category, $items]): ?>
<div class="<?= $modules ? 'studio-template-cards' : 'studio-element-items' ?>" data-template-group="<?= $e($group) ?>" hidden>
<?php foreach ($items as $key => $item): ?>
<?php [$label, $markup, $option, $feed] = array_pad($item, 4, null); ?>
<?php if ($modules): ?>
<article class="studio-template-card" data-template-card data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" class="studio-template-image" data-template-preview="<?= $e($key) ?>" data-template-title="<?= $e($label) ?>"
aria-label="预览<?= $e($label) ?>组件">
<img src="/assets/template-previews/<?= $e($key) ?>.webp" alt="" width="768" height="480" loading="lazy">
</button>
<div class="studio-template-meta">
<span><?= $e($label) ?></span>
<button type="button" class="button button-outline" disabled data-canvas-template="<?= $e($key) ?>"
data-template-title="<?= $e($label) ?>" data-template-lead="<?= $e($option) ?>" data-template-style="<?= $e($item[4] ?? 'plain') ?>"
<?= $feed !== null ? 'data-template-feed="' . $e($feed) . '"' : '' ?> aria-label="添加<?= $e($label) ?>组件">添加</button>
</div>
<template data-preset="<?= $e($key) ?>"><?= $markup ?></template>
</article>
<?php else: ?>
<div data-library-item data-template-search-text="<?= $e($label . ' ' . $key) ?>">
<button type="button" disabled data-canvas-element="<?= $e($key) ?>"
<?php if ($option): ?>data-element-mime="<?= $e($option) ?>"<?php endif ?>
aria-label="插入<?= $e($label) ?>"><?= $e($label) ?></button>
<template data-element="<?= $e($key) ?>"><?= $markup ?></template>
</div>
<?php endif ?>
<?php endforeach ?>
</div>
<?php endforeach ?>
</div>
<?php if ($modules): ?>
<p class="field-note" data-template-status role="status"></p>
<ul class="studio-pending" data-template-pending aria-label="待保存区块" hidden></ul>
<?php else: ?>
<p class="field-note" data-element-status role="status"></p>
<?php endif ?>
</section>
+50
View File
@@ -0,0 +1,50 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<header class="admin-heading"><div><h1>媒体库</h1><p>统一查找并引用静态文件、图片、图标和音视频。</p></div></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/media" enctype="multipart/form-data">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<div class="form-grid">
<label>文件<input type="file" name="file" accept="image/*,video/*,audio/*,.pdf,.woff,.woff2" required>
<small>支持常见图片、SVG 图标、音视频、PDF、WOFF/WOFF2,单文件最大 64 MB。</small>
</label>
<label>资源名称<input name="label" maxlength="160" placeholder="默认使用文件名"></label>
</div>
<div class="form-submit"><button type="submit" class="button button-primary">上传文件</button></div>
</form>
<section class="admin-panel media-library" data-media-library aria-labelledby="library-heading">
<h2 id="library-heading">资源列表</h2>
<div class="form-grid">
<label>搜索<input type="search" data-library-query placeholder="搜索名称或路径"></label>
<label>类型<select data-library-type><option value="">全部资源</option><option value="image/">图片与图标</option><option value="video/">视频</option><option value="audio/">音频</option><option value="other">其他文件</option></select></label>
</div>
<p data-library-count role="status"></p>
<div class="media-grid">
<?php foreach ($files as $file): ?>
<article class="media-card" data-library-card data-mime="<?= $e($file['mime']) ?>" data-search="<?= $e($file['label'] . ' ' . $file['url']) ?>">
<?php if (str_starts_with($file['mime'], 'image/')): ?>
<img src="<?= $e($file['url']) ?>" alt="" loading="lazy">
<?php else: ?>
<p class="media-file-type"><?= $e(strtolower(pathinfo($file['url'], PATHINFO_EXTENSION))) ?></p>
<?php endif ?>
<h3><?= $e($file['label']) ?></h3>
<small><?= $e((string) max(1, ceil($file['size'] / 1024))) ?> KB · <?= $file['name'] === '' ? '项目文件' : ($file['archived'] ? '已归档' : '上传文件') ?></small>
<div class="actions"><a href="<?= $e($file['url']) ?>" target="_blank" rel="noopener">打开</a><button type="button" class="button button-outline" data-copy-asset="<?= $e($file['url']) ?>">复制路径</button></div>
<?php if ($file['name'] !== ''): ?>
<details><summary>管理文件</summary>
<form class="admin-form" method="post" action="/admin/media/<?= $e($file['name']) ?>">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>名称<input name="label" value="<?= $e($file['label']) ?>" maxlength="160" required></label>
<label class="media-archive"><input type="checkbox" name="archived" value="1" <?= $file['archived'] ? 'checked' : '' ?>>归档</label>
<small>归档从选取器隐藏文件,已有链接仍可访问。</small>
<button type="submit" class="button button-outline">保存</button>
</form>
</details>
<?php endif ?>
</article>
<?php endforeach ?>
</div>
</section>
+20
View File
@@ -0,0 +1,20 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin">返回页面</a>
<header class="admin-heading">
<h1>新建页面</h1>
<button type="button" class="button button-outline" data-open-page-templates hidden>整页模板</button>
</header>
<?= View::fragment('admin-feedback', ['error' => $error, 'saved' => false]) ?>
<form class="admin-form admin-panel" method="post" action="/admin/new-page">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<label>页面名称<input name="name" maxlength="100" value="<?= $e($name) ?>" required></label>
<label>网址标识<input name="slug" maxlength="70" value="<?= $e($slug) ?>" pattern="[a-z0-9]+(-[a-z0-9]+)*" placeholder="my-page" required>
<small>创建后为草稿。可在编辑画布中预览,并自行发布。</small>
</label>
<div class="form-submit"><button type="submit" class="button button-primary">创建草稿</button></div>
</form>
<?= View::fragment('studio-page-templates', compact('token', 'openTemplates')) ?>
+60
View File
@@ -0,0 +1,60 @@
<?php
use App\Content\PageTemplates;
use App\Content\View;
$e = View::escape(...);
$groups = PageTemplates::groups();
$previewRoot = '/assets/page-templates/';
?>
<dialog class="page-template-drawer" data-page-template-drawer<?= !empty($openTemplates) ? ' data-open-on-load' : '' ?> aria-labelledby="page-template-title">
<header class="page-template-header">
<h2 id="page-template-title">整页模板</h2>
<button type="button" class="button button-outline" data-close-page-templates>关闭</button>
</header>
<div class="page-template-content">
<section data-template-panel="groups" aria-labelledby="page-template-groups">
<h3 id="page-template-groups" tabindex="-1">选择套系</h3>
<div class="page-template-groups">
<?php foreach ($groups as $key => $group): ?>
<button type="button" class="page-template-card" data-template-group="<?= $e($key) ?>">
<span class="page-template-image"><img src="<?= $e($previewRoot . $key . '.webp') ?>" width="768" height="480" alt="" loading="lazy"></span>
<span class="page-template-card-copy"><strong><?= $e($group['name']) ?></strong><small><?= $e($group['description']) ?></small></span>
</button>
<?php endforeach ?>
</div>
</section>
<?php foreach ($groups as $key => $group): ?>
<section data-template-panel="<?= $e($key) ?>" aria-labelledby="page-template-<?= $e($key) ?>" hidden>
<button type="button" class="button button-outline page-template-back" data-template-back="groups">返回套系</button>
<h3 id="page-template-<?= $e($key) ?>" tabindex="-1"><?= $e($group['name']) ?></h3>
<div class="page-template-pages">
<?php foreach ($group['pages'] as $pageKey => $pageTemplate): ?>
<button type="button" class="page-template-card" data-page-template="<?= $e($pageKey) ?>">
<span class="page-template-image"><img src="<?= $e($previewRoot . $pageKey . '.webp') ?>" width="768" height="480" alt="" loading="lazy"></span>
<span class="page-template-card-copy"><strong><?= $e($pageTemplate['name']) ?></strong></span>
</button>
<?php endforeach ?>
</div>
</section>
<?php endforeach ?>
<section data-template-panel="detail" aria-labelledby="page-template-detail-heading" hidden>
<button type="button" class="button button-outline page-template-back" data-template-back="pages">返回套内页面</button>
<h3 id="page-template-detail-heading" data-template-name tabindex="-1"></h3>
<div class="page-template-detail">
<div>
<div class="page-template-image"><img data-template-preview width="768" height="480" alt=""></div>
<a class="button button-outline page-template-preview-link" data-template-live target="_blank" rel="noopener">打开完整页面预览</a>
</div>
<form class="admin-form" method="post" action="/admin/new-page">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="template">
<div class="form-grid">
<label>页面名称<input name="name" maxlength="100" required></label>
<label>网址标识<input name="slug" maxlength="70" pattern="[a-z0-9]+(-[a-z0-9]+)*" required></label>
</div>
<div class="form-submit"><button type="submit" class="button button-primary">用此模板创建草稿</button></div>
</form>
</div>
</section>
</div>
</dialog>
+15
View File
@@ -0,0 +1,15 @@
<?php
use App\Content\View;
$e = View::escape(...);
?>
<a class="back-link" href="/admin/design">返回站点设计</a>
<header class="admin-heading"><h1>站点设置</h1></header>
<?= View::fragment('admin-feedback', compact('error', 'saved')) ?>
<form class="admin-form admin-panel" method="post" action="/admin/settings">
<input type="hidden" name="csrf" value="<?= $e($token) ?>">
<input type="hidden" name="version" value="<?= $e($version) ?>">
<label>站点名称<input name="name" value="<?= $e($name) ?>" maxlength="100" required></label>
<label>静态资源 CDN<input name="cdn" value="<?= $e($cdn) ?>" placeholder="https://cdn.example.com"><small>填写后,公开页面的 /assets/ 文件从该地址加载。</small></label>
<button type="submit" class="button button-primary">保存设置</button>
</form>
+35
View File
@@ -0,0 +1,35 @@
<?php
use App\Content\BlockTemplates;
use App\Content\View;
$e = View::escape(...);
$labels = ['modules' => '组件', 'elements' => '元素', 'layers' => '图层'];
?>
<div class="studio-presets" data-canvas-presets>
<div class="studio-library-tabs" role="tablist" aria-label="页面编辑工具" data-library-tabs hidden>
<?php foreach ($labels as $kind => $label): ?>
<button type="button" role="tab" id="studio-tab-<?= $kind ?>" aria-controls="studio-panel-<?= $kind ?>"
aria-selected="false" tabindex="-1" data-library-tab="<?= $kind ?>"><?= $e($label) ?></button>
<?php endforeach ?>
</div>
<?php foreach (['modules' => BlockTemplates::groups(), 'elements' => BlockTemplates::ELEMENT_GROUPS] as $kind => $groups): ?>
<?= View::fragment('studio-library-panel', compact('kind', 'groups', 'anchorForm')) ?>
<?php endforeach ?>
<section role="tabpanel" id="studio-panel-layers" aria-labelledby="studio-tab-layers" data-library-panel="layers">
<?= $layers ?>
</section>
<div class="studio-template-peek" data-template-peek aria-hidden="true" hidden>
<img alt="">
<p></p>
</div>
<dialog class="media-picker studio-template-dialog" data-template-dialog aria-labelledby="studio-template-preview-title">
<header class="admin-heading compact">
<h2 id="studio-template-preview-title"></h2>
<button type="button" class="button button-outline" data-template-close>关闭</button>
</header>
<img alt="" width="768" height="480">
<div class="actions"><button type="button" class="button button-primary" data-template-use>添加到画布</button></div>
</dialog>
</div>
+52
View File
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Content\Database;
use App\Content\Passwords;
use App\Content\Repository;
$reset = ($argv[1] ?? '') === 'reset';
$email = strtolower(trim($argv[$reset ? 2 : 1] ?? ''));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
fwrite(STDERR, "用法:php bin/admin.php [reset] admin@example.com\n");
exit(1);
}
fwrite(STDERR, "请输入至少 8 字符的管理员密码:");
$tty = function_exists('stream_isatty') && stream_isatty(STDIN);
if ($tty) {
exec('stty -echo');
}
try {
$password = rtrim((string) fgets(STDIN), "\r\n");
} finally {
if ($tty) {
exec('stty echo');
}
fwrite(STDERR, "\n");
}
if (!Passwords::isValidNew($password)) {
fwrite(STDERR, "密码至少 8 个字符,最多 72 字节。\n");
exit(1);
}
Database::initialize();
$hash = password_hash($password, PASSWORD_DEFAULT);
if ($reset) {
$repo = new Repository();
$user = $repo->administrator($email);
if (!$user || !$repo->changePassword($user, $hash)) {
fwrite(STDERR, "未能重设密码。请确认邮箱对应的账户存在,且未被同时修改。\n");
exit(1);
}
fwrite(STDOUT, "密码已重设,旧会话将失效。\n");
exit(0);
}
$query = Database::connect()->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)
ON CONFLICT (email) DO UPDATE SET password_hash = excluded.password_hash');
$query->execute([$email, $hash]);
fwrite(STDOUT, "管理员账户已就绪。\n");
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env php
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Content\SiteBackup;
[$command, $path, $confirm] = array_pad(array_slice($argv, 1), 3, null);
if (!is_string($path) || ($command !== 'export' && ($command !== 'import' || $confirm !== '--replace'))) {
fwrite(STDERR, "Usage: php bin/backup.php export snapshot.tar | import snapshot.tar --replace\n");
exit(2);
}
$path = str_starts_with($path, '/') ? $path : getcwd() . '/' . $path;
try {
if ($command === 'export') {
SiteBackup::export($path);
} else {
SiteBackup::import($path);
}
echo ($command === 'export' ? '备份已导出。' : '站点已还原。') . PHP_EOL;
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Content\Database;
umask(0027);
Database::initialize();
fwrite(STDOUT, "SQLite 已初始化。现有内容会保留。\n");
Executable
+41
View File
@@ -0,0 +1,41 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
php_bin=${LAYSITE_PHP:-php}
composer_bin=${LAYSITE_COMPOSER:-composer}
target=${1:-check}
if [ "$target" = check ]; then
git fetch origin --tags
git describe --tags --always
git tag --list 'v[0-9]*' --sort=-version:refname
exit 0
fi
if ! printf '%s\n' "$target" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || [ "$#" -ne 2 ]; then
printf '%s\n' 'Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar' >&2
exit 2
fi
if [ -n "$(git status --porcelain)" ]; then
printf '%s\n' 'Commit or set aside local source changes before updating.' >&2
exit 1
fi
git fetch origin --tags
current=$(git rev-parse HEAD)
next=$(git rev-parse --verify "refs/tags/$target^{commit}")
git merge-base --is-ancestor "$current" "$next"
"$php_bin" bin/backup.php export "$2"
if git switch --detach "$next" &&
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts &&
"$php_bin" bin/install.php
then
printf 'Updated to %s. Start Webman with the original site environment.\n' "$target"
else
git switch --detach "$current"
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts
printf 'Update failed. The prior source version is checked out and the backup is at %s.\n' "$2" >&2
exit 1
fi
+28
View File
@@ -0,0 +1,28 @@
{
"name": "laysense/laysite",
"description": "LaySite visual editor and content management system",
"type": "project",
"require": {
"ext-curl": "*",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-mbstring": "*",
"ext-openssl": "*",
"ext-pdo_sqlite": "*",
"ext-phar": "*",
"firebase/php-jwt": "^7.0",
"league/commonmark": "^2.8",
"league/oauth2-client": "^2.8",
"monolog/monolog": "^3.0",
"php": "^8.2",
"workerman/webman-framework": "^2.2"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
},
"config": {
"sort-packages": true
}
}
Generated
+1836
View File
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
<?php
return [
'debug' => false,
'error_reporting' => E_ALL,
'default_timezone' => 'Asia/Shanghai',
'request_class' => App\Http\Request::class,
'public_path' => base_path() . '/public',
'runtime_path' => base_path() . '/runtime',
'controller_suffix' => 'Controller',
'controller_reuse' => false,
];
+3
View File
@@ -0,0 +1,3 @@
<?php
return [support\bootstrap\Session::class];
+3
View File
@@ -0,0 +1,3 @@
<?php
return new Webman\Container();
+3
View File
@@ -0,0 +1,3 @@
<?php
return ['' => support\exception\Handler::class];
+12
View File
@@ -0,0 +1,12 @@
<?php
return [
'default' => [
'handlers' => [
[
'class' => Monolog\Handler\RotatingFileHandler::class,
'constructor' => [runtime_path() . '/logs/webman.log', 14, Monolog\Level::Info],
],
],
],
];
+15
View File
@@ -0,0 +1,15 @@
<?php
return [
'webman' => [
'handler' => Webman\App::class,
'listen' => getenv('LAYSITE_LISTEN') ?: 'http://127.0.0.1:8787',
'count' => max(1, (int) (getenv('LAYSITE_WORKERS') ?: 2)),
'constructor' => [
'requestClass' => App\Http\Request::class,
'logger' => support\Log::channel('default'),
'appPath' => app_path(),
'publicPath' => public_path(),
],
],
];
+58
View File
@@ -0,0 +1,58 @@
<?php
use App\Controller\AccountController;
use App\Controller\AdminController;
use App\Controller\DesignController;
use App\Controller\BackupController;
use App\Controller\SiteController;
use App\Controller\StudioController;
use App\Controller\MediaController;
use App\Controller\McpController;
use support\Request;
use Webman\Route;
Route::disableDefaultRoute();
Route::get('/', [SiteController::class, 'home']);
Route::add(['GET', 'POST', 'DELETE'], '/mcp', [McpController::class, 'endpoint']);
Route::get('/account', [AccountController::class, 'index']);
Route::get('/account/login/{id:[0-9]+}', [AccountController::class, 'login']);
Route::get('/account/callback', [AccountController::class, 'callback']);
Route::post('/account/logout', [AccountController::class, 'logout']);
Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::class, 'file']);
Route::get('/articles/category/{category:[a-z0-9-]+}', [SiteController::class, 'archive']);
Route::get('/articles/tag/{tag:[^/]+}', [SiteController::class, 'tagged']);
Route::get('/articles/feed/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [SiteController::class, 'feedArchive']);
Route::get('/articles/{slug:[a-z0-9-]+}', [SiteController::class, 'article']);
Route::get('/robots.txt', [SiteController::class, 'robots']);
Route::get('/sitemap.xml', [SiteController::class, 'sitemap']);
Route::add(['GET', 'POST'], '/admin/login', [AdminController::class, 'login']);
Route::post('/admin/logout', [AdminController::class, 'logout']);
Route::add(['GET', 'POST'], '/admin/password', [AdminController::class, 'password']);
Route::get('/admin', [AdminController::class, 'dashboard']);
Route::add(['GET', 'POST'], '/admin/article-categories', [AdminController::class, 'articleCategories']);
Route::get('/admin/articles', [AdminController::class, 'articles']);
Route::add(['GET', 'POST'], '/admin/articles/new', [AdminController::class, 'article']);
Route::add(['GET', 'POST'], '/admin/articles/{id:[0-9]+}', [AdminController::class, 'article']);
Route::post('/admin/articles/{id:[0-9]+}/delete', [AdminController::class, 'deleteArticle']);
Route::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']);
Route::get('/admin/page-templates/{key:[a-z0-9-]+}/preview', [StudioController::class, 'previewTemplate']);
Route::get('/admin/pages/{slug:[a-z0-9-]+}/preview', [StudioController::class, 'previewPage']);
Route::post('/admin/page-blocks/{slug:[a-z0-9-]+}', [StudioController::class, 'blocks']);
Route::add(['GET', 'POST'], '/admin/settings', [DesignController::class, 'site']);
Route::add(['GET', 'POST'], '/admin/backup', [BackupController::class, 'index']);
Route::get('/admin/backup/download', [BackupController::class, 'export']);
Route::get('/admin/design', [DesignController::class, 'index']);
Route::get('/admin/design/{kind:header|footer|palette}/{id:[0-9]+}/preview', [DesignController::class, 'preview']);
Route::add(['GET', 'POST'], '/admin/design/{kind:header|footer|palette}/{key:new|[0-9]+}', [DesignController::class, 'edit']);
Route::get('/palette/{id:[0-9]+}.css', [DesignController::class, 'palette']);
Route::add(['GET', 'POST'], '/admin/media', [StudioController::class, 'media']);
Route::get('/admin/media/options', [StudioController::class, 'mediaOptions']);
Route::post('/admin/media/{name:[a-f0-9]{32}\.[a-z0-9]+}', [StudioController::class, 'mediaMeta']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}', [AdminController::class, 'page']);
Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [AdminController::class, 'section']);
Route::post('/admin/preview', [AdminController::class, 'preview']);
Route::get('/{slug:[a-z0-9-]+}', [SiteController::class, 'page']);
Route::fallback(static fn (Request $request) => (new SiteController())->missing($request));
+10
View File
@@ -0,0 +1,10 @@
<?php
return [
'pid_file' => runtime_path() . '/webman.pid',
'status_file' => runtime_path() . '/webman.status',
'stdout_file' => runtime_path() . '/logs/stdout.log',
'log_file' => runtime_path() . '/logs/workerman.log',
'stop_timeout' => 4,
'max_package_size' => 66 * 1024 * 1024,
];
+14
View File
@@ -0,0 +1,14 @@
<?php
return [
'type' => 'file',
'handler' => Webman\Session\FileSessionHandler::class,
'config' => ['file' => ['save_path' => runtime_path() . '/sessions']],
'session_name' => 'LAYSITE_CMS',
'lifetime' => 8 * 60 * 60,
'cookie_lifetime' => 0,
'cookie_path' => '/admin',
'http_only' => true,
'secure' => getenv('LAYSITE_SECURE_COOKIES') === '1',
'same_site' => 'Lax',
];
+3
View File
@@ -0,0 +1,3 @@
<?php
return ['enable' => true, 'middleware' => [App\Middleware\PublicAssets::class]];
+324
View File
@@ -0,0 +1,324 @@
.admin-body { background: var(--paper); min-height: 100vh; }
.admin-wrap { width: min(calc(100% - 2rem), 67rem); margin-inline: auto; }
.admin-bar { background: var(--white); border-bottom: 1px solid var(--line); }
.admin-bar-inner, .admin-bar nav { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem 1.15rem; }
.admin-bar-inner { justify-content: space-between; min-height: 4.5rem; padding-block: .45rem; }
.admin-bar nav > a { display: inline-flex; min-height: 44px; align-items: center; text-decoration: none; font-weight: 550; }
.admin-main { padding-block: clamp(1.65rem, 4vw, 3.25rem); }
.admin-main h1 { font-size: clamp(2rem, 4vw, 3.1rem); margin: 0; }
.admin-main h2 { font-size: 1.38rem; margin-bottom: 1rem; }
.admin-heading { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1.25rem; margin: 0 0 1.2rem; }
.admin-heading.compact h2, .admin-heading p { margin: 0; }
.admin-heading p { margin-top: .4rem; }
.admin-panel, .login-box { border: 1px solid var(--line); padding: clamp(1rem, 3vw, 2rem); background: var(--white); border-radius: var(--radius); margin-bottom: 1.15rem; }
.login-box { max-width: 27rem; margin: clamp(1.5rem, 6vw, 5rem) auto; }
.login-box p { margin-block: .6rem 1.25rem; }
.admin-form { display: grid; gap: 1rem; }
.admin-form label { display: grid; gap: .4rem; font-weight: 570; color: var(--ink); }
.admin-form :where(input:not([type=hidden]), select, textarea) {
background: white;
color: var(--ink);
width: 100%;
border: 1px solid #b9c7dd;
border-radius: .5rem;
padding: .6rem .75rem;
font-size: 1rem;
font-weight: 400;
min-height: 44px;
}
.admin-form textarea { resize: vertical; }
.admin-form small, .field-note { color: var(--muted); font-size: .875rem; font-weight: 400; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .85rem; }
.form-submit { display: flex; flex-wrap: wrap; gap: .75rem; align-items: end; }
.form-submit label { min-width: 10rem; }
.admin-list { margin: 0; padding: 0; list-style: none; }
.admin-list li { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: .65rem; padding-block: .7rem; border-top: 1px solid var(--line); }
.admin-list small { display: block; color: var(--muted); font-size: .875rem; }
.feedback { padding: .8rem 1rem; border-radius: .5rem; }
.feedback.error { background: #feebeb; color: #9c252a; }
.feedback.success { background: #e5f6ed; color: #126044; }
.button-danger { color: #9c252a; background: transparent; border-color: #e6b6b9; }
.button-danger:hover { color: #9c252a; background: #feebeb; }
.editor { display: grid; gap: .45rem; }
.editor-toolbar { display: flex; flex-wrap: wrap; gap: .45rem; justify-content: space-between; padding: .45rem; border: 1px solid var(--line); background: var(--paper); border-radius: .5rem; }
.editor-toolbar > div { display: flex; flex-wrap: wrap; gap: .25rem; }
.editor-toolbar button { border: 1px solid var(--line); background: var(--white); border-radius: .35rem; min-height: 44px; padding: .45rem .7rem; color: var(--ink); }
.editor-toolbar button:hover { border-color: var(--accent); color: var(--accent); }
.editor textarea { font-family: var(--mono); font-size: .95rem; line-height: 1.55; }
.editor-preview { padding: 1rem; border: 1px solid var(--line); border-radius: .5rem; }
.field-note { margin: 0; }
@media (max-width: 38rem) {
.form-grid { grid-template-columns: 1fr; }
.admin-bar nav { gap: .3rem .85rem; }
}
.password-form { max-width: 37rem; }
.admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; }
.admin-form .ajax-feedback { margin: 0; }
.studio-frame-window { position: relative; height: min(67vh, 39rem); overflow: hidden; margin-bottom: .8rem; border: 1px solid var(--line); border-radius: .55rem; background: var(--paper); }
.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; }
.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; }
.studio-canvas-toolbar { margin-bottom: .55rem; }
.studio-canvas-toolbar button:disabled { opacity: .5; cursor: default; }
.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; }
.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.studio-inspector details label { margin-top: .7rem; }
.studio-blocks form, .studio-block-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .32rem; }
.studio-blocks .button { padding-inline: .65rem; }
.studio-block-add { margin-top: 1.25rem; }
.studio-rich { min-height: 15rem; max-width: 100%; overflow-x: auto; padding: 1rem; background: #fff; border: 1px solid var(--line); border-radius: .55rem; }
.studio-rich:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
.studio-rich details { margin-bottom: .5rem; }
.studio-rich img, .studio-rich video { max-width: 100%; height: auto; }
.asset-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: .55rem; }
.settings-form { max-width: 54rem; }
.media-grid, .picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); gap: .8rem; }
.media-card, .picker-item { min-width: 0; border: 1px solid var(--line); border-radius: .65rem; background: white; padding: .75rem; overflow-wrap: anywhere; }
.media-card > img, .picker-item img, .media-file-type { height: 6rem; width: 100%; object-fit: contain; background: var(--paper); border-radius: .45rem; margin-bottom: .7rem; }
.media-card .media-file-type { display: grid; place-items: center; font-size: 1.1rem; text-transform: uppercase; }
.media-card h3 { font-size: 1rem; margin-bottom: 0; }
.media-card small { color: var(--muted); }
.media-card .actions { margin: .45rem 0; }
.media-card .button { padding-inline: .55rem; }
.media-card .media-archive { display: flex; align-items: center; }
.media-card .media-archive input { width: auto; min-height: 0; }
.media-picker { max-width: min(92vw, 52rem); max-height: 86vh; width: 100%; padding: 1.25rem; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); }
.media-picker.canvas-properties { max-width: min(92vw, 32rem); }
.media-picker::backdrop { background: #101c3488; }
.media-picker label { display: grid; gap: .35rem; }
.media-picker input { padding: .55rem .75rem; border: 1px solid var(--line); border-radius: .4rem; }
.picker-grid { max-height: 50vh; overflow: auto; padding: .25rem; }
.picker-item { text-align: left; min-height: 44px; }
.picker-item:hover { border-color: var(--accent); }
@media (max-width: 65rem) {
}
.admin-wrap.admin-wide { width: calc(100% - clamp(1rem, 3vw, 3rem)); }
.studio-layout {
display: grid;
align-items: start;
grid-template-columns: minmax(12rem, 15rem) minmax(0, 1fr);
grid-template-areas: "library workspace" "library settings";
gap: .9rem;
}
.studio-library { grid-area: library; position: sticky; z-index: 3; top: .75rem; max-height: calc(100vh - 1.5rem); overflow: auto; }
.studio-library h2 { font-size: 1.05rem; margin-bottom: .7rem; }
.studio-workspace { grid-area: workspace; min-width: 0; }
.studio-inspector { grid-area: settings; }
.studio-workspace .studio-preview { padding: clamp(.55rem, 1.25vw, 1rem); }
.studio-workspace .studio-frame-window { height: max(34rem, calc(100dvh - 16rem)); }
.studio-workspace .studio-preview h2 { font-size: 1.2rem; }
.studio-presets { display: grid; gap: .4rem; }
.studio-library .studio-layers button:not(.button), .studio-pending button {
width: 100%;
min-height: 2.75rem;
padding: .55rem .75rem;
margin: 0;
border: 1px solid var(--line);
border-radius: .45rem;
background: var(--white);
color: var(--ink);
text-align: left;
}
.studio-library button:not(.button):hover { border-color: var(--accent); color: var(--accent); }
.studio-insert-mode { margin-block: .45rem .15rem; font-size: .875rem; }
.studio-pending { padding: 0; margin: 0; list-style: none; }
.studio-pending li + li { margin-top: .3rem; }
.studio-presets [role="status"]:empty { margin: 0; }
.studio-layers { border-top: 1px solid var(--line); margin-top: .85rem; padding-top: .55rem; }
.studio-layers summary { cursor: pointer; font-weight: 620; }
.studio-layers[open] > summary { margin-bottom: .55rem; }
.studio-library .studio-layers > button + button { margin-top: .3rem; }
.studio-layers .studio-blocks li { display: grid; gap: .4rem; }
.studio-layers .studio-block-actions .button { min-height: 2.25rem; padding: .25rem .5rem; font-size: .8rem; }
.studio-media-sizing { position: absolute; z-index: 1; inset: auto .6rem .6rem auto; display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; padding: .45rem .6rem; max-width: calc(100% - 1.2rem); background: var(--accent-light); border: 1px solid var(--line); border-radius: .45rem; }
.studio-element-tools {
position: absolute; z-index: 3; display: flex; align-items: center; gap: .12rem; padding: .18rem;
border: 1px solid #c7d6f3; border-radius: .52rem; background: var(--white);
box-shadow: 0 .22rem .85rem #16305230;
}
.studio-element-tools button {
display: grid; place-items: center; width: 2rem; height: 2rem; padding: 0;
border: 0; border-radius: .32rem; background: transparent; color: #35496d; cursor: pointer;
}
.studio-element-tools button svg { width: 1rem; height: 1rem; pointer-events: none; }
.studio-element-tools button:hover, .studio-element-tools button:focus-visible { background: var(--accent-light); color: var(--accent-deep); }
.studio-element-tools button:focus-visible { outline: 1px solid var(--accent); outline-offset: -2px; }
.studio-element-tools button[data-element-delete]:hover { color: #a12727; background: #fceeee; }
.studio-element-tools.is-module [data-element-module-settings] { background: var(--accent-light); color: var(--accent-deep); }
.studio-media-handle {
position: absolute; z-index: 2; width: 1.4rem; height: 2.8rem; translate: -50% -50%;
display: grid; place-content: center; border: 2px solid white; border-radius: .42rem;
background: var(--accent); box-shadow: 0 0 0 1px var(--accent); color: white; cursor: ew-resize;
touch-action: none; user-select: none;
}
.studio-media-handle::after { content: ''; width: .38rem; height: .9rem; border-inline: 1px solid currentColor; }
.studio-media-sizing output { font-size: .85rem; font-variant-numeric: tabular-nums; }
.studio-media-sizing .button { min-height: 2.2rem; padding: .25rem .7rem; }
@media (max-width: 54rem) {
.studio-layout { grid-template-columns: minmax(0, 1fr); grid-template-areas: "library" "workspace" "settings"; }
.studio-library { position: static; max-height: none; }
.studio-workspace .studio-frame-window { height: max(25rem, 64dvh); }
}
.studio-template-search { display: grid; gap: .3rem; font-size: .9rem; font-weight: 600; }
.studio-template-search input {
width: 100%;
min-height: 42px;
padding: .45rem .6rem;
color: var(--ink);
background: var(--white);
border: 1px solid var(--line);
border-radius: .5rem;
}
.studio-library-tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .2rem; padding: .22rem; margin-bottom: .45rem; border-radius: .6rem; background: var(--paper); }
.studio-library-tabs button, .studio-library-categories button, .studio-library-category-title button, .studio-element-items button {
color: var(--ink); font-family: inherit; cursor: pointer;
}
.studio-library-tabs button { min-height: 2.4rem; padding: .3rem .18rem; border: 1px solid transparent; border-radius: .42rem; background: transparent; font-size: .84rem; }
.studio-library-tabs button[aria-selected="true"] { border-color: var(--line); background: var(--white); color: var(--accent-deep); font-weight: 650; box-shadow: 0 1px 2px #182e5110; }
.studio-library-categories { list-style: none; padding: 0; margin: 0; }
.studio-library-categories li + li { border-top: 1px solid var(--line); }
.studio-library-categories button, .studio-element-items button {
display: flex; gap: .35rem; align-items: center; width: 100%; min-height: 2.65rem; padding: .4rem .32rem;
text-align: left; border: 1px solid transparent; border-radius: .35rem; background: transparent; font-size: .9rem;
}
.studio-library-categories button::after { content: ''; width: .38rem; height: .38rem; border: solid currentColor; border-width: 1px 1px 0 0; rotate: 45deg; margin-inline-end: .25rem; }
.studio-library-categories small { margin-inline-start: auto; color: var(--muted); font-variant-numeric: tabular-nums; }
.studio-library-content { display: grid; gap: .55rem; min-width: 0; }
.studio-library-category-title { display: grid; gap: .28rem; }
.studio-library-category-title h3 { font-size: 1rem; margin: 0; }
.studio-library-category-title button { justify-self: start; min-height: 2.25rem; padding: .25rem .45rem; background: var(--white); border: 1px solid var(--line); border-radius: .38rem; font-size: .8rem; }
.studio-library-category-title button::before { content: '‹'; margin-inline-end: .3em; }
.studio-element-items { display: grid; gap: .35rem; }
.studio-element-items button { justify-content: space-between; padding-inline: .55rem; border-color: var(--line); background: var(--white); }
.studio-element-items button::after { content: '+'; color: var(--accent-deep); }
.studio-element-items button:disabled { opacity: .55; cursor: wait; }
.studio-template-cards { display: grid; gap: .48rem; }
.studio-template-card { min-width: 0; border: 1px solid var(--line); border-radius: .55rem; background: var(--white); }
.studio-template-card:focus-within { border-color: var(--accent); }
.studio-template-image {
display: block;
width: 100%;
padding: 0;
overflow: hidden;
border: 0;
border-radius: .5rem .5rem 0 0;
background: var(--paper);
}
.studio-template-image img { display: block; width: 100%; height: auto; aspect-ratio: 8 / 5; transition: transform .16s ease; }
.studio-template-image:hover img, .studio-template-image:focus-visible img { transform: scale(1.07); }
.studio-template-meta { display: flex; align-items: center; justify-content: space-between; gap: .3rem; padding: .3rem .38rem .3rem .55rem; font-size: .875rem; }
.studio-template-meta .button { min-height: 33px; font-size: .8rem; flex: 0 0 auto; padding: .2rem .45rem; }
.studio-template-peek {
position: fixed;
z-index: 2;
overflow: hidden;
pointer-events: none;
background: var(--white);
border: 1px solid #adbfdf;
border-radius: .65rem;
box-shadow: 0 14px 35px #142e5626;
}
.studio-template-peek img, .studio-template-dialog img { width: 100%; height: auto; aspect-ratio: 8 / 5; display: block; }
.studio-template-peek p { padding: .5rem .8rem; margin: 0; font-size: .9rem; color: var(--ink); }
.studio-template-dialog { width: min(90vw, 49rem); }
.studio-template-dialog > img { border: 1px solid var(--line); border-radius: .55rem; }
.studio-template-dialog > .actions { justify-content: flex-end; margin-top: .75rem; }
@media (max-width: 54rem) {
.studio-library-content { max-height: 55dvh; overflow-y: auto; padding: .2rem; }
.studio-template-cards { grid-template-columns: repeat(auto-fill, minmax(8.5rem, 1fr)); }
.studio-template-meta { flex-wrap: wrap; }
.studio-template-peek { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.studio-template-image img { transition: none; }
}
.category-checks { min-width: 0; padding: .75rem 1rem; border: 1px solid var(--line); border-radius: .5rem; }
.category-checks > div { display: flex; flex-wrap: wrap; gap: .45rem 1.25rem; }
.admin-form .category-checks label { display: inline-flex; align-items: center; gap: .35rem; }
.admin-form .category-checks input { min-height: 0; width: auto; }
.admin-options { padding: .7rem 1rem; border: 1px solid var(--line); border-radius: .5rem; }
.admin-options > summary { font-weight: 650; cursor: pointer; }
.admin-options[open] > summary { margin-bottom: .85rem; }
.admin-options .form-grid + .category-checks { margin-top: .8rem; }
.article-editor { min-width: 0; }
.article-editor-heading { display: flex; align-items: center; justify-content: space-between; gap: .6rem; margin-bottom: .45rem; }
.article-editor-heading > .button { min-height: 2.1rem; padding: .25rem .6rem; }
.article-editor-help:empty { display: none; }
.studio-element-align { display: flex; gap: .05rem; padding-inline-end: .15rem; border-inline-end: 1px solid var(--line); }
.studio-element-align button[aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); }
.admin-primary a { padding: .28rem .65rem; border-radius: .48rem; color: var(--muted); }
.admin-primary a[aria-current="page"] { background: var(--accent-light); color: var(--accent-deep); }
.admin-utility { display: flex; gap: .8rem; align-items: center; font-size: .88rem; }
.admin-utility > a { padding-block: .55rem; white-space: nowrap; }
.admin-account { position: relative; z-index: 5; }
.admin-account summary {
min-height: 2.45rem; padding: .43rem .6rem; border: 1px solid var(--line);
border-radius: .45rem; color: var(--ink); cursor: pointer;
}
.admin-account-menu {
position: absolute; inset: calc(100% + .4rem) 0 auto auto; min-width: 8rem; padding: .3rem;
border: 1px solid var(--line); border-radius: .5rem; background: white; box-shadow: 0 .55rem 1.5rem #1d315026;
}
.admin-account-menu a, .admin-account-menu button {
display: block; width: 100%; padding: .52rem .65rem; border: 0; border-radius: .3rem; background: white;
color: var(--ink); text-align: left; text-decoration: none; font: inherit; cursor: pointer;
}
.admin-account-menu :is(a, button):hover { background: var(--paper); color: var(--accent-deep); }
.dashboard-heading { margin-bottom: 1.55rem; }
.dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(0, 1fr); align-items: start; gap: 1.05rem; }
.dashboard-grid .admin-panel { padding: clamp(.95rem, 2.3vw, 1.55rem); }
.dashboard-filters { display: grid; grid-template-columns: 1fr minmax(6.8rem, 9rem); gap: .7rem; margin-bottom: .8rem; }
.dashboard-filters label { display: grid; min-width: 0; gap: .25rem; font-size: .83rem; color: var(--muted); }
.dashboard-filters :is(input, select) { width: 100%; min-height: 2.65rem; padding: .38rem .52rem; border: 1px solid var(--line); border-radius: .45rem; color: var(--ink); background: var(--white); font: inherit; }
.dashboard-page-list li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: .55rem .85rem; }
.dashboard-page-label { min-width: 0; overflow-wrap: anywhere; }
.dashboard-page-state { padding: .15rem .48rem; border-radius: .35rem; background: var(--paper); color: var(--muted); font-size: .78rem; white-space: nowrap; }
.dashboard-page-state[data-published="true"] { background: #e9f6ef; color: #1b6744; }
.dashboard-page-actions { display: flex; align-items: center; gap: .55rem; white-space: nowrap; }
.dashboard-page-actions > a { font-size: .84rem; }
.dashboard-page-actions > .button { min-height: 2.25rem; padding: .28rem .55rem; }
.dashboard-secondary .admin-list li { gap: .35rem .65rem; }
.dashboard-secondary .admin-list .button { min-height: 2.15rem; padding: .25rem .5rem; font-size: .82rem; }
.dashboard-settings h2 { margin-bottom: .55rem; }
.dashboard-setting-buttons { display: flex; flex-wrap: wrap; gap: .45rem; list-style: none; padding: 0; margin: 0; }
.dashboard-setting-buttons .button { min-height: 2.45rem; padding: .3rem .6rem; font-size: .85rem; }
@media (max-width: 51rem) {
.dashboard-grid { grid-template-columns: 1fr; gap: 0; }
.admin-bar .admin-primary { order: 3; width: 100%; gap: .15rem .35rem; }
}
@media (max-width: 28rem) {
.dashboard-page-list li { grid-template-columns: minmax(0, 1fr) auto; }
.dashboard-page-actions { grid-column: 1 / -1; }
}
.studio-page-meta { display: flex; flex-wrap: wrap; align-items: center; gap: .65rem; }
.studio-page-meta code { color: var(--muted); font-size: .86rem; }
.studio-anchor-create, .studio-hero-settings { padding: .55rem .65rem; border: 1px solid var(--line); border-radius: .45rem; }
.studio-anchor-create { margin-top: .55rem; font-size: .84rem; }
.studio-anchor-create summary, .studio-hero-settings summary { cursor: pointer; font-weight: 630; }
.studio-anchor-create[open] form, .studio-hero-controls { margin-top: .6rem; }
.studio-hero-controls { display: flex; flex-wrap: wrap; gap: .42rem; }
.studio-hero-controls .button { min-height: 2.35rem; padding: .3rem .62rem; font-size: .85rem; }
.studio-canvas-status:empty { display: none; }
.canvas-module-settings { max-width: min(92vw, 40rem); }
@media (pointer: coarse) {
.studio-element-tools button { width: 2.5rem; height: 2.5rem; }
}
.canvas-module-settings .category-checks { max-height: min(15rem, 27dvh); overflow-y: auto; }
.canvas-module-settings .actions { position: sticky; bottom: 0; padding-block: .35rem; margin: 0; background: var(--white); }
.design-overview, .palette-fields { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); }
.palette-fields input[type=color] { padding: .25rem; }
.layout-components input[type=checkbox] { width: auto; min-height: auto; }
.layout-components label { display: flex; align-items: center; }
.admin-bar .wordmark { display: inline-flex; gap: .5rem; align-items: center; font-size: 1.26rem; font-weight: 700; color: var(--ink); text-decoration: none; }
.admin-bar .laysite-mark { width: 2.6rem; height: 2.6rem; max-width: 2.6rem; max-height: 2.6rem; object-fit: contain; }
+197
View File
@@ -0,0 +1,197 @@
'use strict';
jQuery(function ($) {
$('[data-layout-components]').on('click', '[data-component-move]', function () {
const $item = $(this).closest('li');
if (this.dataset.componentMove === '-1') $item.prev().before($item);
else $item.next().after($item);
$(this).trigger('focus');
});
$('[data-provider-settings]').each(function () {
const $settings = $(this);
const $preset = $settings.closest('form').find('[data-layout-preset]');
const $mode = $settings.find('[name=provider_mode]');
const sync = () => {
$settings.prop('hidden', $preset.val() !== 'member');
$settings.find('[data-provider-mode]').each(function () {
$(this).prop('hidden', this.dataset.providerMode !== $mode.val());
});
};
$preset.add($mode).on('change', sync);
sync();
});
$('[data-page-list]').each(function () {
const $panel = $(this);
const $search = $panel.find('[data-page-search]');
const $status = $panel.find('[data-page-status]');
const $pages = $panel.find('[data-page-item]');
$panel.find('[data-page-filters]').prop('hidden', false);
$search.add($status).on('input change', function () {
const query = $search.val().trim().toLowerCase();
const status = $status.val();
let count = 0;
$pages.each(function () {
const visible = (!status || this.dataset.pageItem === status) && this.dataset.pageLabel.toLowerCase().includes(query);
$(this).prop('hidden', !visible);
if (visible) count++;
});
$panel.find('[data-page-empty]').prop('hidden', count !== 0);
});
});
const formats = {
markdown: {
heading: ['## ', '', '小标题'],
bold: ['**', '**', '粗体文字'],
list: ['- ', '', '列表项'],
link: ['[', '](https://)', '链接文字']
},
html: {
heading: ['<h3>', '</h3>', '小标题'],
bold: ['<strong>', '</strong>', '粗体文字'],
list: ['<ul>\n <li>', '</li>\n</ul>', '列表项'],
link: ['<a href="https://">', '</a>', '链接文字']
}
};
function clearSavedStatus() {
$('[data-save-confirmation]').prop('hidden', true);
}
if (document.querySelector('[data-save-confirmation]')) {
const url = new URL(window.location.href);
if (url.searchParams.get('saved') === '1') {
url.searchParams.delete('saved');
window.history.replaceState(window.history.state, '', url.href);
}
}
function refreshToken(response) {
if (response?.csrf) {
$('input[name="csrf"]').val(response.csrf);
}
}
function formError($form, message, status) {
let $feedback = $form.children('.ajax-feedback');
if (!$feedback.length) {
$feedback = $('<p>', {class: 'ajax-feedback feedback error', role: 'alert', tabindex: -1})
.prependTo($form);
}
$feedback.text(message);
if (status === 401) {
$feedback.append(' ', $('<a>', {
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 || '预览无法加载,请重试。');
});
});
});
});
+56
View File
@@ -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);
});
});
});
+93
View File
@@ -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.
Binary file not shown.
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+64
View File
@@ -0,0 +1,64 @@
.page-template-drawer {
position: fixed;
inset: 0 0 0 auto;
margin: 0;
width: min(100%, clamp(45rem, 80vw, 78rem));
max-width: none;
height: 100dvh;
max-height: none;
overflow: auto;
overscroll-behavior: contain;
border: 0;
padding: 0;
background: var(--white);
color: var(--ink);
box-shadow: -16px 0 48px #111a2e29;
}
.page-template-drawer::backdrop { background: #111a2e60; }
.page-template-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
position: sticky;
top: 0;
z-index: 1;
padding: .9rem clamp(1rem, 4vw, 1.6rem);
background: var(--white);
border-bottom: 1px solid var(--line);
}
.page-template-header h2 { margin: 0; }
.page-template-content { padding: 1.3rem clamp(1rem, 4vw, 1.6rem) 2rem; }
.page-template-content h3 { margin-bottom: 1rem; }
.page-template-content h3:focus { outline: none; }
.page-template-back { margin-bottom: 1.15rem; }
.page-template-groups, .page-template-pages { display: grid; gap: .75rem; }
.page-template-groups { grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr)); }
.page-template-pages { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.page-template-detail { display: grid; gap: clamp(1rem, 3vw, 2rem); align-items: start; }
.page-template-card {
display: grid;
grid-template-columns: 1fr;
width: 100%;
padding: 0;
overflow: hidden;
color: var(--ink);
background: var(--white);
border: 1px solid var(--line);
border-radius: .7rem;
text-align: start;
}
.page-template-card:hover, .page-template-card:focus-visible { border-color: var(--accent); }
.page-template-card-copy { display: grid; align-content: center; gap: .24rem; padding: clamp(.65rem, 2vw, 1rem); }
.page-template-card-copy small { line-height: 1.5; color: var(--muted); }
.page-template-image { display: block; overflow: hidden; background: var(--paper); }
.page-template-image img { width: 100%; height: auto; transition: transform 180ms ease; }
.page-template-card:hover img, .page-template-card:focus-visible img { transform: scale(1.035); }
.page-template-preview-link { margin-block: .8rem 1.2rem; }
@media (min-width: 49rem) {
.page-template-detail { grid-template-columns: minmax(0, 1.8fr) minmax(17rem, 1fr); }
.page-template-detail .form-grid { grid-template-columns: 1fr; }
}
@media (max-width: 30rem) {
.page-template-pages { grid-template-columns: 1fr; }
}
+51
View File
@@ -0,0 +1,51 @@
'use strict';
jQuery(function ($) {
$('[data-page-template-drawer]').each(function () {
const drawer = this;
const $drawer = $(drawer);
const $opener = $('[data-open-page-templates]').prop('hidden', false);
const $panels = $drawer.find('[data-template-panel]');
const $detail = $panels.filter('[data-template-panel=detail]');
const $form = $detail.find('form');
let $groupButton;
let $pageButton;
function showPanel(key, $focus) {
const $panel = $panels.filter((_, panel) => panel.dataset.templatePanel === key);
$panels.prop('hidden', true);
$panel.prop('hidden', false);
$drawer.scrollTop(0);
($focus ?? $panel.find('h3')).trigger('focus');
}
function open() {
drawer.showModal();
showPanel('groups');
}
$opener.on('click', open);
$drawer.on('close', () => $opener.trigger('focus'))
.on('click', '[data-close-page-templates]', () => drawer.close())
.on('click', '[data-template-group]', function () {
$groupButton = $(this);
showPanel(this.dataset.templateGroup);
})
.on('click', '[data-page-template]', function () {
$pageButton = $(this);
const key = this.dataset.pageTemplate;
const name = $pageButton.find('strong').text();
$detail.find('[data-template-name]').text(name);
$detail.find('[data-template-preview]').attr('src', $pageButton.find('img').attr('src'));
$detail.find('[data-template-live]').attr('href', '/admin/page-templates/' + key + '/preview');
$form.find('[name=template], [name=slug]').val(key);
$form.find('[name=name]').val(name);
$form.children('.ajax-feedback').prop('hidden', true);
showPanel('detail');
})
.on('click', '[data-template-back=groups]', () => showPanel('groups', $groupButton))
.on('click', '[data-template-back=pages]', () => showPanel($groupButton.attr('data-template-group'), $pageButton));
if ($drawer.is('[data-open-on-load]')) open();
});
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Some files were not shown because too many files have changed in this diff Show More