page($request, 'home');
}
public function page(Request $request, string $slug): Response
{
$repo = new Repository();
$page = $repo->page($slug);
if (!$page || $page['layout_kind'] !== null || $page['page_type'] !== '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, int $status = 200): Response
{
$slug = $page['slug'];
$isHome = $slug === 'home';
$showHero = $page['visibility']['hero'] ?? true;
$page = $repo->withSectionFeeds($page);
return View::render('page', [
'site' => $repo->site(),
'page' => $page,
'path' => ($page['page_type'] ?? 'page') !== 'page' ? null : ($isHome ? '/' : '/' . $slug),
'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 === '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 = ['', ''];
$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[] = '';
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
{
return View::redirect(Assets::DEFAULT_ICON, 301);
}
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);
if ($entry || ($single && $normal !== '/home' && ((new Repository())->page(substr($normal, 1))['status'] ?? null) === '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,
], 404);
}
private function sitemapUrl(string $path, ?string $updated): string
{
$url = htmlspecialchars(View::absolute($path), ENT_XML1 | ENT_QUOTES, 'UTF-8');
$date = $updated ? '' . View::date($updated, 'Y-m-d') . '' : '';
return ' ' . $url . '' . $date . '';
}
}