forked from laysense/laysite
264 lines
11 KiB
PHP
264 lines
11 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Content\CanvasStyle;
|
|
use App\Content\Html;
|
|
use App\Content\Licenses;
|
|
use App\Content\Repository;
|
|
use App\Content\SiteIcon;
|
|
use App\Content\View;
|
|
use FastRoute\Dispatcher;
|
|
use support\Request;
|
|
use support\Response;
|
|
use Webman\Route;
|
|
|
|
final class SiteController
|
|
{
|
|
public function home(Request $request): Response
|
|
{
|
|
$repo = new Repository();
|
|
$page = $repo->homepage();
|
|
$response = $page ? $this->renderPage($repo, $page, root: true) : $this->missing($request);
|
|
|
|
return $response->withHeader('Cache-Control', 'no-store');
|
|
}
|
|
|
|
public function license(Request $request): Response
|
|
{
|
|
$text = Licenses::projectText();
|
|
|
|
return new Response($text === null ? 404 : 200, [
|
|
'Content-Type' => 'text/plain; charset=utf-8', 'X-Content-Type-Options' => 'nosniff',
|
|
], $text ?? 'License not found.');
|
|
}
|
|
|
|
public function page(Request $request, string $slug): Response
|
|
{
|
|
$repo = new Repository();
|
|
$page = $repo->page($slug);
|
|
if (!$page || $page['layout_kind'] !== null || !in_array($page['page_type'], ['page', 'home'], true)
|
|
|| $page['status'] !== 'published') {
|
|
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, int $status = 200, bool $root = false): Response
|
|
{
|
|
$slug = $page['slug'];
|
|
$showHero = $page['visibility']['hero'] ?? true;
|
|
$page = $repo->withSectionFeeds($page);
|
|
|
|
return View::render('page', [
|
|
'site' => $repo->site(),
|
|
'page' => $page,
|
|
'path' => empty($page['layout_kind']) && in_array($page['page_type'] ?? 'page', ['page', 'home'], true)
|
|
? ($root ? '/' : '/' . $slug) : null,
|
|
'title' => $page['title'],
|
|
'description' => $page['description'],
|
|
'socialImage' => $showHero ? $page['image'] : '',
|
|
'socialAlt' => $showHero ? $page['alt'] : '',
|
|
'previewMode' => $preview, 'canvas' => $preview && $canvas, 'noindex' => $preview || $status >= 400,
|
|
], $status);
|
|
}
|
|
|
|
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 . '#' . $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);
|
|
if (in_array('home', array_column($pages, 'page_type'), true)) {
|
|
$xml[] = $this->sitemapUrl('/', null);
|
|
}
|
|
foreach ($pages as $page) {
|
|
$xml[] = $this->sitemapUrl('/' . $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 favicon(Request $request): Response
|
|
{
|
|
$site = (new Repository())->site();
|
|
|
|
return SiteIcon::response($site['favicon'] ?? '', $request->path() === '/favicon.ico');
|
|
}
|
|
|
|
public function canvasStyle(Request $request): Response
|
|
{
|
|
static $css;
|
|
$css ??= CanvasStyle::stylesheet();
|
|
|
|
return new Response(200, ['Content-Type' => 'text/css; charset=utf-8',
|
|
'Cache-Control' => 'public, max-age=3600', 'X-Content-Type-Options' => 'nosniff'], $css);
|
|
}
|
|
|
|
public function missing(Request $request): Response
|
|
{
|
|
$path = $request->path();
|
|
if (in_array($request->method(), ['GET', 'HEAD'], true) && strlen($path) > 1 && str_ends_with($path, '/')) {
|
|
$normal = rtrim($path, '/');
|
|
$entry = preg_match('~^/(?:admin|account)(?:/|$)~D', $normal)
|
|
&& Route::dispatch($request->method(), $normal)[0] === Dispatcher::FOUND;
|
|
$single = preg_match('~^/[a-z0-9]+(?:-[a-z0-9]+)*$~D', $normal);
|
|
$page = $single ? (new Repository())->page(substr($normal, 1)) : null;
|
|
if ($entry || ($page && $page['layout_kind'] === null && in_array($page['page_type'], ['page', 'home'], true) && $page['status'] === 'published')
|
|
|| 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, 'atHomepage' => $path === '/',
|
|
], 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>';
|
|
}
|
|
}
|