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
+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;
}
}