Files
laysense.cn/plugin/laysense/Site.php

156 lines
8.2 KiB
PHP

<?php
declare(strict_types=1);
namespace LaysenseSite;
use App\Config\Environment;
use App\Content\Assets;
use App\Content\Repository;
use App\Content\View;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
final class Site implements MiddlewareInterface
{
private const FAVICON = '/assets/favicon.png';
private const SOCIAL_IMAGE = '/assets/original/home-hero.webp';
private const MIME = [
'css' => 'text/css; charset=utf-8', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
'png' => 'image/png', 'webp' => 'image/webp', 'svg' => 'image/svg+xml', 'mp4' => 'video/mp4',
];
private const PAGE_REDIRECTS = [
'/main' => '/articles',
'/articles/category/services' => '/articles/category/catalog',
'/articles/category/supported-projects' => '/articles/category/projects',
];
private const SECTION_STYLES = ['home' => ['product' => 'projects', 'about' => 'about'], 'pagepan' => ['demo' => 'demos']];
private const PHOTO_CREDITS = [
'/assets/page-templates/studio-letterpress.webp' => ['Adam Lusch', 'CC BY-SA 2.0', 'https://commons.wikimedia.org/wiki/File:Wood_Type_close-up.jpg', 'https://creativecommons.org/licenses/by-sa/2.0/'],
'/assets/page-templates/dusk-dunes.webp' => ['Bob Wick / BLM Utah', '公有领域', 'https://commons.wikimedia.org/wiki/File:Utah_Dunes_Landscape_-_West_Desert_District.jpg', ''],
];
public static function assets(): array
{
static $assets;
return $assets ??= ['assets/laysense-site-compat.css', ...json_decode(file_get_contents(__DIR__ . '/assets.json'), true, flags: JSON_THROW_ON_ERROR)];
}
public function process(Request $request, callable $handler): Response
{
$path = $request->path();
$asset = ltrim($path, '/');
$read = in_array($request->method(), ['GET', 'HEAD'], true);
if ($read && in_array($asset, self::assets(), true)) {
return $this->legacyAsset($request, $asset);
}
$response = $handler($request);
if ($read && isset(self::PAGE_REDIRECTS[$path]) && $response->getStatusCode() === 404) {
return View::redirect(self::PAGE_REDIRECTS[$path], 301);
}
if ($read && $path === '/favicon.ico' && $response->getStatusCode() === 301) {
return $response->withHeader('Location', self::FAVICON);
}
$preview = preg_match('~^/admin/pages/([a-z0-9-]+)/preview$~D', $path, $match) === 1;
if (!$read || (str_starts_with($path, '/admin') && !$preview)
|| !str_starts_with((string) $response->getHeader('Content-Type'), 'text/html')
|| !str_contains($body = $response->rawBody(), '</head>')) {
return $response;
}
$slug = $preview ? $match[1] : ($path === '/' ? 'home' : trim($path, '/'));
$body = $this->brand($body, $preview);
$body = $this->theme($body, $slug, $preview && $request->get('canvas') === '1');
return $response->withBody($body);
}
private function legacyAsset(Request $request, string $asset): Response
{
if ($asset === 'assets/laysense-site-compat.css') {
return (new Response(200, ['Content-Type' => self::MIME['css'], 'X-Content-Type-Options' => 'nosniff']))
->withFile(__DIR__ . '/compat.css');
}
$directory = realpath(Environment::path('LAYSENSE_SITE_DIR', 'storage/laysense-site') . '/assets');
$path = $directory === false ? false : realpath($directory . '/' . substr($asset, strlen('assets/')));
if ($path === false || !str_starts_with($path, $directory . '/') || !is_file($path)) {
return new Response(404);
}
$size = filesize($path);
$headers = [
'Content-Type' => self::MIME[pathinfo($asset, PATHINFO_EXTENSION)] ?? 'application/octet-stream',
'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "default-src 'none'; sandbox",
'Cache-Control' => 'public, max-age=3600',
'Access-Control-Allow-Origin' => '*',
'Accept-Ranges' => 'bytes',
];
$range = $request->header('range');
if ($range === null) {
return (new Response(200, $headers))->withFile($path);
}
$invalid = new Response(416, $headers + ['Content-Range' => "bytes */$size"]);
if (!preg_match('/^bytes=(\d*)-(\d*)$/D', $range, $parts) || ($parts[1] === '' && $parts[2] === '')) {
return $invalid;
}
$start = $parts[1] === '' ? max(0, $size - (int) $parts[2]) : (int) $parts[1];
$stop = $parts[1] === '' || $parts[2] === '' ? $size - 1 : min($size - 1, (int) $parts[2]);
if ($start > $stop) {
return $invalid;
}
return (new Response(206, $headers + ['Content-Range' => "bytes $start-$stop/$size"]))
->withFile($path, $start, $stop - $start + 1);
}
private function brand(string $html, bool $preview): string
{
$cdn = $preview ? '' : ((new Repository())->site()['cdn']['origin'] ?? '');
$favicon = View::escape(Assets::url(self::FAVICON, $cdn));
$html = preg_replace('~<link rel="icon"[^>]+>~', '<link rel="icon" href="' . $favicon . '" type="image/png">', $html, 1) ?? $html;
$style = '<link rel="stylesheet" href="/assets/laysense.css"><link rel="stylesheet" href="/assets/laysense-site-compat.css">';
if (!str_contains(substr($html, 0, strpos($html, '</head>')), 'property="og:image"')) {
$url = $cdn === '' ? View::absolute(self::SOCIAL_IMAGE) : Assets::url(self::SOCIAL_IMAGE, $cdn);
$style .= '<meta property="og:image" content="' . View::escape($url) . '">'
. '<meta property="og:image:alt" content="来笙 Laysense">';
}
return preg_replace('~</head>~', $style . '</head>', $html, 1) ?? $html;
}
private function theme(string $html, string $slug, bool $canvas): string
{
if (in_array($slug, ['sc', 'shnu-sc'], true)) {
$html = str_replace(['<body>', 'class="hero-visual app-frame'], ['<body class="copyright-service">', 'class="hero-visual app-frame hero-service-art'], $html);
}
if ($slug === 'home') {
$html = preg_replace('~class="hero-visual app-frame~', 'class="hero-visual hero-illustration', $html, 1) ?? $html;
if (!$canvas) {
$html = preg_replace('~(<div class="hero-copy">.*)</h1>~sU', '$1<span class="home-cursor" aria-hidden="true">_</span></h1>', $html, 1) ?? $html;
$html = preg_replace_callback('~<div class="hero-visual hero-illustration[^>]*>\s*<img\b[^>]+src="[^"]*/assets/original/home-hero\.webp"[^>]*>~',
static fn (array $match): string => $match[0] . file_get_contents(__DIR__ . '/home-motion.svg'), $html, 1) ?? $html;
}
}
foreach (self::SECTION_STYLES[$slug] ?? [] as $id => $style) {
$html = preg_replace('~<section class="(section [^"]*)" id="' . $id . '"~',
'<section class="$1 section-' . $style . '" id="' . $id . '"' . ($style === 'about' ? ' data-moment="iris-opens"' : ''),
$html, 1) ?? $html;
}
if ($slug === 'home' || $slug === 'network') {
$html = str_replace(['class="network-group" id="projects"', 'class="network-group" id="network-group-projects"', 'class="network-group" id="network-group-partners"'],
['class="network-group" id="supported-projects"', 'class="network-group" id="supported-projects"', 'class="network-group" id="partners"'], $html);
}
foreach (self::PHOTO_CREDITS as $image => [$author, $license, $source, $terms]) {
if (preg_match('~class="hero-visual [^"]*"[^>]*>\s*<img[^>]*src="[^"]*' . preg_quote($image, '~') . '"~', $html)) {
$credit = '<p class="wrap page-photo-credit">摄影 <a href="' . View::escape($source) . '">' . View::escape($author) . '</a> · '
. ($terms === '' ? View::escape($license) : '<a href="' . View::escape($terms) . '">' . View::escape($license) . '</a>') . '</p>';
$html = str_replace('</main>', $credit . '</main>', $html);
break;
}
}
return $html;
}
}