forked from laysense/laysense.cn
581 lines
25 KiB
PHP
581 lines
25 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Controller;
|
||
|
||
use App\Content\BlockTemplates;
|
||
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),
|
||
]);
|
||
}
|
||
|
||
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,
|
||
]);
|
||
}
|
||
|
||
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 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);
|
||
$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 {
|
||
$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 ||
|
||
($data['image_scale'] !== 0 && ($data['image_scale'] < 10 || $data['image_scale'] > 100)) ||
|
||
strlen($data['image']) > 1000 || ($data['image'] !== '' && !Html::url($data['image'], true)) || !$validButtons) {
|
||
throw new RuntimeException('请检查页面标题、说明、图片地址和按钮链接。');
|
||
}
|
||
$sections = $this->canvasSections($request->post('canvas_sections', ''), $page['sections']);
|
||
$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, 'wideAdmin' => true, '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);
|
||
}
|
||
$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' => $request->post('style') === null ? $section['style'] : $this->input($request, 'style'),
|
||
'feed' => $section['feed'],
|
||
];
|
||
$section = array_replace($section, $data, ['version' => $this->version($request)]);
|
||
try {
|
||
if ($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
|
||
{
|
||
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'] ?? null;
|
||
$isNew = is_array($change) && array_key_exists('version', $change) && $version === null;
|
||
if (!is_string($key) || isset($updates[$key]) || !is_array($fields) || $fields === []
|
||
|| ($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('区块已变更或画布内容无效,请重新打开编辑页。');
|
||
}
|
||
$section = $available[$key] ?? ['key' => $key, 'title' => '', 'lead' => '', 'body' => '', 'style' => 'plain'];
|
||
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);
|
||
}
|
||
$this->checkSection($section, $section['style']);
|
||
if (isset($fields['body'])) {
|
||
$section['body'] = Html::sanitize($section['body']);
|
||
}
|
||
if ($isNew && ($change['template'] ?? null) === 'articles') {
|
||
$section['feed'] = BlockTemplates::ARTICLE_FEED;
|
||
}
|
||
$section['version'] = $version;
|
||
$updates[$key] = $section;
|
||
}
|
||
|
||
return $updates;
|
||
}
|
||
|
||
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;
|
||
}
|
||
$categories = $this->selectedCategories($request->post('feed_categories'));
|
||
$limit = filter_var($this->input($request, 'feed_limit'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 30]]);
|
||
if (!in_array($mode, ['merged', 'tabs'], 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], $status, true);
|
||
}
|
||
|
||
protected function error(Request $request, string $message, int $status): Response
|
||
{
|
||
return $this->render($request, 'admin-error', ['title' => $message], $status);
|
||
}
|
||
}
|