Rebuild Laysense site with Webman and SQLite CMS

This commit is contained in:
2026-11-21 17:29:24 +08:00
commit d9bda755d1
99 changed files with 4280 additions and 0 deletions
+345
View File
@@ -0,0 +1,345 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Html;
use App\Content\Repository;
use App\Content\View;
use RuntimeException;
use support\Request;
use support\Response;
final class AdminController
{
private ?array $user = null;
public function login(Request $request): Response
{
if ($this->signedIn($request)) {
return View::redirect('/admin');
}
$error = '';
$email = '';
$status = 200;
if ($request->method() === 'POST') {
if (!$this->validToken($request)) {
return $this->error($request, '表单已过期,请刷新后重试。', 403);
}
$email = strtolower($this->input($request, 'email'));
$password = $this->input($request, 'password', trimValue: false);
$repo = new Repository();
$address = $this->address($request);
if (!$repo->recordLoginAttempt($address)) {
$error = '尝试次数过多,请在 15 分钟后重试。';
$status = 429;
} else {
$user = strlen($email) <= 254 ? $repo->administrator($email) : null;
$hash = $user['password_hash'] ?? '$2y$12$XGNKW.dBbfpUrZT8MYvWquCW1dBN3fIlVb29tlaoFIge3YDWG0AzG';
if (strlen($password) <= 72 && password_verify($password, $hash) && $user) {
$request->sessionRegenerateId(true);
$request->session()->flush();
$request->session()->set('admin_id', $user['id']);
$request->session()->set('auth_version', hash('sha256', $user['password_hash']));
$request->session()->set('admin_since', time());
$repo->clearLoginAttempts($address);
return View::redirect('/admin');
}
$error = '邮箱或密码有误。';
$status = 422;
}
}
return $this->render($request, 'admin-login', ['title' => '登录内容管理', 'error' => $error, 'email' => $email], $status);
}
public function logout(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$request->session()->flush();
$request->sessionRegenerateId(true);
return View::redirect('/admin/login');
}
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),
]);
}
public function articles(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$page = max(1, min(10000, (int) $request->get('page', 1)));
$articles = (new Repository())->articles(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,
]);
}
public function article(Request $request, ?string $id = null): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$repo = new Repository();
$article = $id !== null ? $repo->articleById((int) $id) : [
'title' => '', 'slug' => '', 'summary' => '', 'category' => 'news', 'body' => '',
'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, ['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
|| !isset(Repository::CATEGORIES[$data['category']])
|| !in_array($data['status'], ['draft', 'published'], true)) {
throw new RuntimeException('请检查标题、网址标识、分类、摘要和正文长度。');
}
if ($data['status'] === 'published' && trim(Html::markdown($data['body'])) === '') {
throw new RuntimeException('发布前请填写文章正文。');
}
$saved = $repo->saveArticle($id === null ? null : (int) $id, $data, $this->version($request));
return View::redirect('/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, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
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['actions'] = [];
$validButtons = true;
foreach ([1, 2] as $index) {
$label = $this->input($request, 'label' . $index);
$url = $this->input($request, 'url' . $index);
if ($label === '' && $url === '') {
continue;
}
$data['actions'][] = [$url, $label];
$validButtons = $validButtons && mb_strlen($label) <= 50 && $label !== '' && strlen($url) <= 1000 && Html::url($url);
}
$page = array_replace($page, $data, ['version' => $this->version($request)]);
try {
if ($data['title'] === '' || mb_strlen($data['title']) > 160 ||
$data['description'] === '' || mb_strlen($data['description']) > 300 ||
$data['heading'] === '' || mb_strlen($data['heading'] . $data['accent']) > 110 ||
mb_strlen($data['lead']) > 600 || mb_strlen($data['alt']) > 200 ||
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
}
$repo->savePage($slug, $data, $this->version($request));
return View::redirect('/admin/pages/' . $slug . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'admin-page', [
'title' => '编辑 ' . $page['name'], 'page' => $page, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $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);
}
$error = '';
if ($request->method() === 'POST') {
$data = [
'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
'body' => $this->input($request, 'body'),
];
$section = array_replace($section, $data, ['version' => $this->version($request)]);
try {
if ($data['title'] === '' || mb_strlen($data['title']) > 100 || mb_strlen($data['lead']) > 500 || strlen($data['body']) > 300000) {
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
}
$data['body'] = Html::sanitize($data['body']);
$repo->saveSection($slug, $key, $data, $this->version($request));
return View::redirect('/admin/pages/' . $slug . '/' . $key . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'admin-section', [
'title' => '编辑区块', 'section' => $section, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
public function preview(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$body = $this->input($request, 'body');
if (strlen($body) > 300000) {
return new Response(413, ['Cache-Control' => 'no-store'], '正文太长。');
}
$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);
}
private function guard(Request $request): ?Response
{
if (!$this->signedIn($request)) {
return 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();
return false;
}
$this->user = $user;
return true;
}
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);
}
return $token;
}
private function validToken(Request $request): bool
{
return hash_equals($this->token($request), $this->input($request, 'csrf'));
}
private 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;
}
private 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', 'category', 'summary', 'body', 'status'] as $key) {
$data[$key] = $this->input($request, $key);
}
$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 address(Request $request): string
{
$peer = $request->getRemoteIp();
$trusted = explode(',', getenv('LAYSENSE_TRUSTED_PROXIES') ?: '');
$candidate = $request->header('x-real-ip', '');
return in_array($peer, $trusted, true) && filter_var($candidate, FILTER_VALIDATE_IP) ? $candidate : $peer;
}
private function validationMessage(RuntimeException $exception): string
{
if ($exception instanceof \PDOException) {
error_log($exception->getMessage());
return '保存失败,请稍后重试。';
}
return $exception->getMessage();
}
private function render(Request $request, string $view, array $data, int $status = 200): Response
{
return View::render($view, $data + ['token' => $this->token($request), 'user' => $this->user], $status, true);
}
private function error(Request $request, string $message, int $status): Response
{
return $this->render($request, 'admin-error', ['title' => $message], $status);
}
}
+167
View File
@@ -0,0 +1,167 @@
<?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) {
return $this->missing($request);
}
$isHome = $slug === 'home';
return View::render('page', [
'site' => $repo->site(),
'page' => $page,
'path' => $isHome ? '/' : '/' . $slug,
'title' => $page['title'],
'description' => $page['description'],
'socialImage' => $page['image'],
'socialAlt' => $page['alt'],
'articles' => $isHome ? $repo->articles(limit: 3) : [],
]);
}
public function archive(Request $request, ?string $category = null, ?string $tag = null): Response
{
$repo = new Repository();
$title = $category ? Repository::CATEGORIES[$category] : ($tag ?: '来笙动态');
$path = '/articles' . ($category ? '/category/' . $category : ($tag ? '/tag/' . rawurlencode($tag) : ''));
$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);
if ($page > 1 && $articles === []) {
return $this->missing($request);
}
return View::render('archive', [
'site' => $repo->site(), 'title' => $title . ' · 来笙', 'headline' => $title,
'description' => '查看来笙的公告、新闻和产品动态。',
'path' => $path . ($page > 1 ? '?page=' . $page : ''), 'archivePath' => $path,
'category' => $category, 'tag' => $tag, '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::markdown($article['body']);
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'], 'noindex' => trim($articleHtml) === '',
]);
}
public function legacyArticle(Request $request, string $id): Response
{
$article = (new Repository())->legacyArticle('/news/id/' . $id . '.html');
return $article ? View::redirect('/articles/' . $article['slug'], 301) : $this->missing($request);
}
public function legacyCategory(Request $request, string $id): Response
{
$target = [
'1' => '/articles/category/product', '2' => '/articles/category/news', '3' => '/articles/category/announcement',
'5' => '/#supported-projects', '6' => '/#partners',
][$id] ?? null;
return $target ? View::redirect($target, 301) : $this->missing($request);
}
public function legacyTag(Request $request, string $tag): Response
{
return View::redirect('/articles/tag/' . rawurlencode(rawurldecode($tag)), 301);
}
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();
if ($repo->articles(limit: 1)) {
$pages[] = ['slug' => 'articles', 'updated_at' => null];
}
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, '/');
if (preg_match('~^/(?:pagepan|highspeaker|sc|shnu-sc|articles(?:/[a-z0-9-]+){0,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>';
}
}