Add visual CMS, media library and product directory

This commit is contained in:
2026-11-21 19:27:46 +08:00
parent 188a63fb2f
commit 474008b06e
42 changed files with 1710 additions and 134 deletions
+21 -13
View File
@@ -8,12 +8,13 @@ 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;
final class AdminController
class AdminController
{
private ?array $user = null;
@@ -189,6 +190,8 @@ final class AdminController
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');
$data['actions'] = [];
$validButtons = true;
foreach ([1, 2] as $index) {
@@ -202,8 +205,10 @@ final class AdminController
}
$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['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['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) {
@@ -232,15 +237,18 @@ final class AdminController
if (!$section) {
return $this->error($request, '找不到此区块。', 404);
}
$savedStyle = $section['style'];
$error = '';
if ($request->method() === 'POST') {
$data = [
'title' => $this->input($request, 'title'), 'lead' => $this->input($request, 'lead'),
'body' => $this->input($request, 'body'),
'style' => $request->post('style') === null ? $section['style'] : $this->input($request, 'style'),
];
$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) {
if ($data['title'] === '' || mb_strlen($data['title']) > 100 || mb_strlen($data['lead']) > 500 || strlen($data['body']) > 300000
|| !in_array($data['style'], [$savedStyle, 'plain', 'tinted'], true)) {
throw new RuntimeException('请填写区块标题,并检查说明及正文长度。');
}
$data['body'] = Html::sanitize($data['body']);
@@ -253,7 +261,7 @@ final class AdminController
}
return $this->render($request, 'admin-section', [
'title' => '编辑区块', 'section' => $section, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => '编辑区块', 'section' => $section, 'savedStyle' => $savedStyle, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error !== '' ? 422 : 200);
}
@@ -274,7 +282,7 @@ final class AdminController
], $html);
}
private function guard(Request $request): ?Response
protected function guard(Request $request): ?Response
{
if (!$this->signedIn($request)) {
return $request->isAjax()
@@ -340,7 +348,7 @@ final class AdminController
return is_string($token) && hash_equals($token, $this->input($request, 'csrf'));
}
private function input(Request $request, string $key, bool $trimValue = true): string
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')) {
@@ -350,7 +358,7 @@ final class AdminController
return $trimValue ? trim($value) : $value;
}
private function version(Request $request): int
protected function version(Request $request): int
{
$version = $this->input($request, 'version');
@@ -372,7 +380,7 @@ final class AdminController
return $data;
}
private function validationMessage(RuntimeException $exception): string
protected function validationMessage(RuntimeException $exception): string
{
if ($exception instanceof \PDOException) {
error_log($exception->getMessage());
@@ -383,12 +391,12 @@ final class AdminController
return $exception->getMessage();
}
private function success(Request $request, string $path): Response
protected function success(Request $request, string $path): Response
{
return $request->isAjax() ? $this->json(['redirect' => $path]) : View::redirect($path);
}
private function json(array $payload, int $status = 200): Response
protected function json(array $payload, int $status = 200): Response
{
return new Response($status, [
'Content-Type' => 'application/json; charset=utf-8',
@@ -398,7 +406,7 @@ final class AdminController
], Database::json($payload));
}
private function render(Request $request, string $view, array $data, int $status = 200): Response
protected function render(Request $request, string $view, array $data, int $status = 200): Response
{
$token = $this->token($request);
if ($request->isAjax() && $status >= 400) {
@@ -411,7 +419,7 @@ final class AdminController
return View::render($view, $data + ['token' => $token, 'user' => $this->user], $status, true);
}
private function error(Request $request, string $message, int $status): Response
protected function error(Request $request, string $message, int $status): Response
{
return $this->render($request, 'admin-error', ['title' => $message], $status);
}
+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);
}
}
+24 -3
View File
@@ -6,6 +6,7 @@ namespace App\Controller;
use App\Content\Html;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Content\View;
use support\Request;
use support\Response;
@@ -21,9 +22,15 @@ final class SiteController
{
$repo = new Repository();
$page = $repo->page($slug);
if (!$page) {
if (!$page || $page['status'] !== 'published' || $slug === 'home' && $request->path() !== '/') {
return $this->missing($request);
}
return $this->renderPage($repo, $page);
}
public function renderPage(Repository $repo, array $page, bool $preview = false): Response
{
$slug = $page['slug'];
$isHome = $slug === 'home';
return View::render('page', [
@@ -35,6 +42,17 @@ final class SiteController
'socialImage' => $page['image'],
'socialAlt' => $page['alt'],
'articles' => $isHome ? $repo->articles(limit: 3) : [],
'previewMode' => $preview, 'noindex' => $preview,
]);
}
public function services(Request $request): Response
{
return View::render('services', [
'site' => (new Repository())->site(), 'path' => '/services',
'title' => '产品与服务 · 来笙 Laysense',
'description' => '浏览来笙的建站工具、智能 DNS 和软件著作权服务。',
'products' => SiteDesign::catalog(),
]);
}
@@ -118,7 +136,8 @@ final class SiteController
{
$repo = new Repository();
$xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
$pages = $repo->pages();
$pages = $repo->pages(publishedOnly: true);
$pages[] = ['slug' => 'services', 'updated_at' => null];
if ($repo->articles(limit: 1)) {
$pages[] = ['slug' => 'articles', 'updated_at' => null];
}
@@ -144,7 +163,9 @@ final class SiteController
$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)) {
$single = preg_match('~^/[a-z0-9-]+$~D', $normal);
$known = $single && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === 'published' && $normal !== '/home';
if ($known || $normal === '/services' || preg_match('~^/articles(?:/[a-z0-9-]+){0,2}$~D', $normal)) {
$query = $request->queryString();
return View::redirect($normal . ($query !== '' ? '?' . $query : ''), 301);
+285
View File
@@ -0,0 +1,285 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Content\Assets;
use App\Content\Html;
use App\Content\Media;
use App\Content\Repository;
use App\Content\SiteDesign;
use App\Http\Request;
use RuntimeException;
use support\Response;
use Webman\Http\UploadFile;
final class StudioController extends AdminController
{
private const BLOCKS = [
'text' => ['正文', '<p>在这里输入区块内容。</p>'],
'image' => ['图文', '<p>介绍图片内容,然后从媒体库插入图片。</p>'],
'cta' => ['行动按钮', '<p>说明下一步。</p><p><a class="button button-primary" href="#contact">联系来笙</a></p>'],
'faq' => ['常见问题', '<div class="faq"><details><summary>请输入问题</summary><div><p>请输入答案。</p></div></details></div>'],
];
public function newPage(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$data = ['title' => '新建页面', 'name' => '', 'slug' => '', 'error' => ''];
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', 'articles', 'home', 'services', 'news', 'main', 'favicon'], true)
|| $data['name'] === '' || mb_strlen($data['name']) > 100) {
throw new RuntimeException('请填写页面名称及可用的网址标识。');
}
(new Repository())->createPage($data['slug'], $data['name']);
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 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) : $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', 'blog', 'partners', 'supported-projects'], true)) {
throw new RuntimeException('区块锚点不可用。');
}
if ($action === 'create') {
$preset = self::BLOCKS[$this->input($request, 'preset')] ?? null;
if ($preset === null) {
throw new RuntimeException('请选择区块类型。');
}
$repo->createSection($slug, $key, $preset[0], 'plain', $preset[1]);
return $this->success($request, "/admin/pages/$slug/$key");
}
if (!in_array($action, ['up', 'down', 'delete'], true)) {
throw new RuntimeException('操作不可用。');
}
$repo->arrangeSection($slug, $key, $action, $this->version($request));
return $this->success($request, "/admin/pages/$slug#blocks");
} catch (RuntimeException $error) {
return $this->error($request, $this->validationMessage($error), 422);
}
}
public function settings(Request $request, string $part): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$site = (new Repository())->site();
$defaults = match ($part) {
'header' => SiteDesign::DEFAULT_HEADER,
'footer' => SiteDesign::DEFAULT_FOOTER + array_intersect_key($site, array_flip(['name', 'address', 'email', 'copyright', 'registration', 'terms'])),
'cdn' => ['origin' => ''],
};
$config = ($site[$part] ?? []) + $defaults;
$version = $site['revisions'][$part] ?? 0;
$error = '';
if ($request->method() === 'POST') {
try {
$config = $this->settingsInput($request, $part, $defaults);
SiteDesign::saveSettings($part, $config, $this->version($request));
return $this->success($request, '/admin/settings/' . $part . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
$version = $this->version($request);
}
}
return $this->render($request, 'studio-settings', [
'part' => $part, 'config' => $config, 'revision' => $version, 'error' => $error, 'saved' => $request->get('saved') === '1',
'title' => ['header' => '页头', 'footer' => '页脚', 'cdn' => '静态资源 CDN'][$part],
], $error === '' ? 200 : 422);
}
public function catalog(Request $request): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
return $this->render($request, 'studio-catalog', ['title' => '产品与服务', 'products' => SiteDesign::catalog()]);
}
public function product(Request $request, ?string $id = null): Response
{
if ($failure = $this->guard($request)) {
return $failure;
}
$fields = ['name', 'category', 'body', 'image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'position'];
$product = $id !== null ? SiteDesign::product((int) $id) : array_fill_keys($fields, '') + ['version' => 0];
if (!$product) {
return $this->error($request, '找不到此产品或服务。', 404);
}
$error = '';
if ($request->method() === 'POST') {
try {
if ($id !== null && $this->input($request, 'operation') === 'delete') {
SiteDesign::deleteProduct((int) $id, $this->version($request));
return $this->success($request, '/admin/catalog');
}
foreach ($fields as $field) {
$product[$field] = $this->input($request, $field);
}
$product['version'] = $this->version($request);
$this->checkProduct($product);
$product['body'] = Html::sanitize($product['body']);
$savedId = SiteDesign::saveProduct($id === null ? null : (int) $id, $product, $product['version']);
return $this->success($request, '/admin/catalog/' . $savedId . '?saved=1');
} catch (RuntimeException $exception) {
$error = $this->validationMessage($exception);
}
}
return $this->render($request, 'studio-product', [
'title' => $id === null ? '添加产品或服务' : '编辑产品或服务', 'product' => $product,
'id' => $id, 'error' => $error, 'saved' => $request->get('saved') === '1',
], $error === '' ? 200 : 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 settingsInput(Request $request, string $part, array $defaults): array
{
if ($part === 'cdn') {
return ['origin' => Assets::cdn($this->input($request, 'origin'))];
}
$result = [];
foreach ($defaults as $key => $default) {
$input = $this->input($request, $key);
if (is_array($default)) {
$result[$key] = SiteDesign::parseLinks($input);
if ($key === 'button') {
if (count($result[$key]) > 1) {
throw new RuntimeException('页头按钮只接受一条链接。');
}
$result[$key] = $result[$key][0] ?? [];
}
} else {
if (mb_strlen($input) > 1000) {
throw new RuntimeException('设置字段过长。');
}
$result[$key] = $input;
}
}
if ($result['logo'] !== '' && !Html::url($result['logo'], true)) {
throw new RuntimeException('请输入有效的标志图片地址。');
}
if ($part === 'footer' && ($result['name'] === '' || ($result['email'] !== '' && !filter_var($result['email'], FILTER_VALIDATE_EMAIL)))) {
throw new RuntimeException('请填写公司名称及有效的联系邮箱。');
}
return $result;
}
private function checkProduct(array $item): void
{
if ($item['name'] === '' || mb_strlen($item['name']) > 100 || $item['category'] === '' || mb_strlen($item['category']) > 70
|| strlen($item['body']) > 300000 || strlen($item['image']) > 1000 || mb_strlen($item['alt']) > 200
|| ($item['image'] !== '' && !Html::url($item['image'], true)) || !preg_match('/^-?\d{1,6}$/D', $item['position'])) {
throw new RuntimeException('请检查名称、分类、简介、封面及排序字段。');
}
foreach ([['url', 'label'], ['extra_url', 'extra_label']] as [$href, $label]) {
if ($href === 'extra_url' && $item[$href] === '' && $item[$label] === '') {
continue;
}
if (strlen($item[$href]) > 1000 || !Html::url($item[$href]) || $item[$label] === '' || mb_strlen($item[$label]) > 70) {
throw new RuntimeException('请填写按钮文案和有效链接。');
}
}
}
private function slug(string $value): bool
{
return strlen($value) <= 70 && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/D', $value) === 1;
}
}