diff --git a/README.md b/README.md index c7c8f75..dbe29f8 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ PHP Webman、原生 CSS 和 SQLite 实现的来笙官网。公开页面由服务 ## 本地启动 -需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom` 和 `mbstring` 的 PHP 环境。 +需要 Linux、PHP 8.2+ CLI、Composer 2,以及启用 `pcntl`、`posix`、`pdo_sqlite`、`dom`、`fileinfo` 和 `mbstring` 的 PHP 环境。 ```sh composer install @@ -27,7 +27,10 @@ php bin/admin.php reset admin@example.com ## 后台编辑 -- **页面**可修改首屏标题、简介、图片、按钮,以及每页的 SEO 标题和描述。页面正文按区块编辑,支持受限 HTML 和预览。 +- **页面设计**支持新建草稿、发布和撤回。首屏标题与简介可在桌面或手机画布中直接编辑。区块支持新增、排序、删除、可视化编辑、媒体插入和 HTML 源码。 +- **媒体库**集中列出项目静态文件及上传文件,支持查找、选取、复制路径、改名和归档。归档资源的已有 URL 保持可访问。上传文件放在 `LAYSENSE_MEDIA_DIR`,由 `/assets/uploads/` 提供。 +- **产品与服务**在 `/services` 显示独立的服务端 HTML 目录。后台支持添加、排序、修改和移除条目,并设置分类、封面、简介和按钮链接。 +- **网站设置**分别编辑页头标志、导航及按钮,和页脚的公司信息、链接与备注。CDN 设置接受 HTTPS 源站地址。浏览器看到的公开 `/assets/…` 路径使用该源站。 - **文章与动态**使用 Markdown,支持正文预览、摘要、标签和公告、新闻、产品分类。状态选「草稿」可撤回公开文章。已发布文章改网址标识后,旧标识会自动跳转。 - 首页动态、分类列表和站点地图随发布状态更新。源代码和 SQLite 数据分开管理。安装命令可重复执行,已编辑的内容会保留。 @@ -40,13 +43,19 @@ php bin/admin.php reset admin@example.com 下面的 Nginx 片段可放入现有 HTTPS 虚拟主机。Nginx 会覆盖请求携带的 `X-Real-IP`,应用默认信任本机回环地址传来的该请求头。密码验证失败的请求按来源计数,超过阈值后返回 429。正确密码仍可登录。 ```nginx +proxy_http_version 1.1; +proxy_set_header Host $host; +proxy_set_header X-Real-IP $remote_addr; + location / { proxy_pass http://127.0.0.1:8787; - proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; client_max_body_size 2m; } + +location = /admin/media { + proxy_pass http://127.0.0.1:8787; + client_max_body_size 66m; +} ``` | 环境变量 | 默认值与用途 | @@ -55,10 +64,15 @@ location / { | `LAYSENSE_LISTEN` | `http://127.0.0.1:8787` · Webman 监听地址 | | `LAYSENSE_WORKERS` | `2` · Webman worker 数量 | | `LAYSENSE_DB` | `storage/laysense.sqlite` · SQLite 文件路径。生产可指向独立的持久化目录 | +| `LAYSENSE_MEDIA_DIR` | `storage/media` · 上传资源的持久化目录 | | `LAYSENSE_SECURE_COOKIES` | 默认关闭 · 本地 HTTP 使用默认值。生产 HTTPS 设置为 `1`。 | | `LAYSENSE_TRUSTED_PROXIES` | 默认 `127.0.0.1,::1` · 逗号分隔的受信反代 IP,设为空字符串可关闭信任 | -SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录和 `runtime/` 有写权限。 +SQLite 已启用 WAL。迁移服务器或做线上备份时,可用 `sqlite3 storage/laysense.sqlite ".backup 'laysense-backup.sqlite'"` 取得一致备份。更新代码时保留数据库文件及其存放目录,以同一 `LAYSENSE_DB` 执行 `php bin/install.php` 应用迁移,然后重启服务。已有数据库会补回 PAGEPAN 原始功能图标,保留已编辑的文案和已有图像。服务用户需要对 SQLite 目录、媒体目录和 `runtime/` 有写权限。备份站点时一并保存 SQLite 和媒体目录。 + +### CDN + +先让 CDN 的 `/assets/` 转发到 Webman 站点,再在「网站设置 → CDN」填写地址。CDN 需要保留静态资源的 CORS 响应头和视频 Range 请求。配置留空时,公开资源由站点直接提供。后台登录和编辑资源始终由站点提供。 ## 迁移范围 diff --git a/app/Content/Assets.php b/app/Content/Assets.php new file mode 100644 index 0000000..fb017c5 --- /dev/null +++ b/app/Content/Assets.php @@ -0,0 +1,45 @@ + 263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) { + throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.laysense.cn。'); + } + if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) { + throw new RuntimeException('CDN 端口无效。'); + } + + return $value; + } + + public static function url(string $path, string $cdn): string + { + return str_starts_with($path, '/assets/') ? $cdn . $path : $path; + } + + public static function rewrite(string $html, string $cdn): string + { + if ($cdn === '') { + return $html; + } + $document = new DOMDocument('1.0', 'UTF-8'); + $document->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); + $xpath = new DOMXPath($document); + foreach ($xpath->query('//@src | //@href | //@poster') as $attribute) { + $attribute->value = self::url($attribute->value, $cdn); + } + + return $document->saveHTML(); + } +} diff --git a/app/Content/Database.php b/app/Content/Database.php index ad9ddb3..06897d0 100644 --- a/app/Content/Database.php +++ b/app/Content/Database.php @@ -40,6 +40,9 @@ final class Database self::write(function (PDO $pdo) use ($root, $seed): void { $pdo->exec(file_get_contents($root . '/resources/schema.sql')); + if (!in_array('status', array_column($pdo->query('PRAGMA table_info(pages)')->fetchAll(), 'name'), true)) { + $pdo->exec("ALTER TABLE pages ADD COLUMN status TEXT NOT NULL DEFAULT 'published' CHECK (status IN ('draft', 'published'))"); + } $site = $pdo->prepare('INSERT OR IGNORE INTO site_settings (id, payload) VALUES (1, ?)'); $site->execute([self::json($seed['site'])]); @@ -85,6 +88,10 @@ final class Database if ($migration->rowCount() === 1) { PagepanFeatureIcons::migrate($pdo); } + $migration->execute(['product_directory_and_service_icons']); + if ($migration->rowCount() === 1) { + DesignMigration::apply($pdo); + } }); } diff --git a/app/Content/DesignMigration.php b/app/Content/DesignMigration.php new file mode 100644 index 0000000..c683f98 --- /dev/null +++ b/app/Content/DesignMigration.php @@ -0,0 +1,67 @@ +loadHTML('' . $stockBody, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET); + $xpath = new DOMXPath($doc); + $insert = $pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, extra_url, extra_label, position) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); + foreach ($xpath->query('//article[contains(concat(" ", @class, " "), " project ")]') as $position => $card) { + $image = $xpath->query('.//img', $card)->item(0); + $links = $xpath->query('.//a', $card); + $body = ''; + foreach ($xpath->query('.//p', $card) as $paragraph) { + $body .= $doc->saveHTML($paragraph); + } + $insert->execute([ + trim($xpath->evaluate('string(.//h3)', $card)), trim($xpath->evaluate('string(.//span)', $card)), + Html::sanitize($body), $image->getAttribute('src'), $image->getAttribute('alt'), + $links->item(0)->getAttribute('href'), trim($links->item(0)->textContent), + $links->item(1)?->getAttribute('href') ?? '', trim($links->item(1)?->textContent ?? ''), $position * 10, + ]); + } + $pdo->prepare('INSERT INTO catalog (name, category, body, image, alt, url, label, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)') + ->execute(['SHNU 学生软著服务', '校园服务', '

面向 SHNU 学生的软件著作权申请服务。

', + '/assets/original/shnu-hero.webp', '', '/shnu-sc', '查看学生方案', 30]); + $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 + WHERE page_slug = 'home' AND key = 'product' AND version = 0 AND body = ?") + ->execute(['

浏览来笙的建站工具、智能 DNS 和软件著作权服务。

查看产品与服务', $stockBody]); + + $choices = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'why' AND page_slug IN ('sc', 'shnu-sc')"); + $updateChoice = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'why'"); + foreach ($choices->fetchAll() as $section) { + $body = preg_replace('~(]*class="[^"]*\bfeature-card)("(?:[^>]*>)\s*选择来笙)~u', + '$1 choice-card$2', $section['body']); + if ($body !== null && $body !== $section['body']) { + $updateChoice->execute([$body, $section['page_slug']]); + } + } + + $icons = ['/assets/original/10-1.png' => '/assets/service/project.svg', + '/assets/original/10-2.png' => '/assets/service/code.svg', '/assets/original/10-3.png' => '/assets/service/support.svg']; + $sections = $pdo->query("SELECT page_slug, body FROM sections WHERE key = 'options' AND page_slug IN ('sc', 'shnu-sc')"); + $update = $pdo->prepare("UPDATE sections SET body = ?, version = version + 1 WHERE page_slug = ? AND key = 'options'"); + foreach ($sections->fetchAll() as $section) { + $body = strtr($section['body'], $icons); + $body = preg_replace('/(]*>)\s*]*>(.*?)<\/li>\s*(<\/article>)/s', '$1$2$3', $body); + if ($body !== $section['body']) { + $update->execute([$body, $section['page_slug']]); + } + } + } +} diff --git a/app/Content/Html.php b/app/Content/Html.php index b336afd..f3d776e 100644 --- a/app/Content/Html.php +++ b/app/Content/Html.php @@ -12,7 +12,7 @@ use League\CommonMark\CommonMarkConverter; final class Html { private const TAGS = [ - 'a' => ['href'], 'article' => [], 'b' => [], 'blockquote' => [], 'br' => [], + 'a' => ['href'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'], 'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [], 'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'], @@ -20,7 +20,7 @@ final class Html 'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [], 'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [], 'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [], - 'video' => ['controls', 'muted', 'playsinline', 'poster', 'preload'], + 'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'], ]; public static function url(string $value, bool $media = false): bool diff --git a/app/Content/Media.php b/app/Content/Media.php new file mode 100644 index 0000000..dfd98b7 --- /dev/null +++ b/app/Content/Media.php @@ -0,0 +1,135 @@ + 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp', + 'image/avif' => 'avif', 'image/x-icon' => 'ico', 'image/vnd.microsoft.icon' => 'ico', 'image/svg+xml' => 'svg', + 'video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov', + 'audio/mpeg' => 'mp3', 'audio/ogg' => 'ogg', 'audio/wav' => 'wav', + 'application/pdf' => 'pdf', 'font/woff' => 'woff', 'font/woff2' => 'woff2', + ]; + + public static function all(bool $includeArchived = false): array + { + $query = 'SELECT name, label, mime, size, created_at, archived FROM media' . ($includeArchived ? '' : ' WHERE archived = 0'); + $files = Database::connect()->query($query . ' ORDER BY created_at DESC, name')->fetchAll(); + foreach ($files as &$file) { + $file['url'] = '/assets/uploads/' . $file['name']; + } + unset($file); + + $root = dirname(__DIR__, 2) . '/public/assets'; + $builtIn = []; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root)) as $file) { + if (!$file->isFile() || $file->isLink() || str_starts_with($file->getFilename(), '.')) { + continue; + } + $path = str_replace(DIRECTORY_SEPARATOR, '/', substr($file->getPathname(), strlen($root) + 1)); + $label = $file->getFilename(); + $type = array_search(strtolower($file->getExtension()), self::EXTENSIONS, true) ?: 'application/octet-stream'; + $builtIn[] = ['label' => $label, 'name' => '', 'mime' => $type, 'size' => $file->getSize(), + 'url' => '/assets/' . $path, 'archived' => 0]; + } + usort($builtIn, static fn (array $left, array $right): int => strnatcasecmp($left['url'], $right['url'])); + + return [...$files, ...$builtIn]; + } + + public static function upload(UploadFile $file, string $label): void + { + if (!$file->isValid() || ($size = $file->getSize()) < 1 || $size > self::MAX_BYTES) { + throw new RuntimeException('请选择大小不超过 64 MB 的有效文件。'); + } + $source = $file->getPathname(); + $mime = (new \finfo(FILEINFO_MIME_TYPE))->file($source); + $extension = self::EXTENSIONS[$mime] ?? null; + if ($extension === null) { + throw new RuntimeException('文件类型不受支持。'); + } + $content = $mime === 'image/svg+xml' ? self::safeSvg($source, $size) : null; + $name = bin2hex(random_bytes(16)) . '.' . $extension; + $directory = self::directory(); + if (!is_dir($directory) && !mkdir($directory, 0750, true) && !is_dir($directory)) { + throw new RuntimeException('资源目录无法创建。'); + } + $path = $directory . '/' . $name; + try { + $written = $content === null ? copy($source, $path) : file_put_contents($path, $content) === strlen($content); + if (!$written) { + throw new RuntimeException('文件写入失败。'); + } + $query = Database::connect()->prepare('INSERT INTO media (name, label, mime, size, created_at) VALUES (?, ?, ?, ?, ?)'); + $query->execute([$name, $label, $mime, $content === null ? $size : strlen($content), gmdate('c')]); + } catch (Throwable $error) { + if (is_file($path)) { + unlink($path); + } + throw $error; + } + } + + public static function find(string $name): ?array + { + $query = Database::connect()->prepare('SELECT * FROM media WHERE name = ?'); + $query->execute([$name]); + + return $query->fetch() ?: null; + } + + public static function update(string $name, string $label, bool $archived): void + { + Database::connect()->prepare('UPDATE media SET label = ?, archived = ? WHERE name = ?') + ->execute([$label, (int) $archived, $name]); + } + + public static function directory(): string + { + return rtrim(getenv('LAYSENSE_MEDIA_DIR') ?: dirname(__DIR__, 2) . '/storage/media', '/'); + } + + private static function safeSvg(string $source, int $size): string + { + if ($size > 512 * 1024) { + throw new RuntimeException('SVG 图标最大支持 512 KB。'); + } + $svg = new DOMDocument(); + if (!$svg->loadXML(file_get_contents($source), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING) || $svg->doctype + || $svg->documentElement?->namespaceURI !== 'http://www.w3.org/2000/svg' || $svg->documentElement->localName !== 'svg') { + throw new RuntimeException('SVG 图标格式无效。'); + } + $tags = ['svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'title', 'desc']; + $attributes = ['viewBox', 'width', 'height', 'fill', 'fill-rule', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-linecap', + 'stroke-linejoin', 'stroke-dasharray', 'stroke-opacity', 'curve', 'clip-rule', 'opacity', 'd', 'x', 'y', + 'rx', 'ry', 'cx', 'cy', 'r', 'x1', 'x2', 'y1', 'y2', 'points', 'transform']; + foreach ((new DOMXPath($svg))->query('//*') as $element) { + if (!$element instanceof DOMElement || $element->namespaceURI !== 'http://www.w3.org/2000/svg' + || !in_array($element->localName, $tags, true)) { + throw new RuntimeException('SVG 仅支持基础矢量元素。'); + } + foreach ($element->attributes as $attribute) { + if ($attribute->namespaceURI !== null || !in_array($attribute->localName, $attributes, true) + || !preg_match('/^[a-z0-9#.,%\s()+-]*$/iD', $attribute->value) || preg_match('/url\s*\(/i', $attribute->value)) { + throw new RuntimeException('SVG 包含不支持的属性或外部引用。'); + } + } + } + + return $svg->saveXML($svg->documentElement); + } +} diff --git a/app/Content/Repository.php b/app/Content/Repository.php index b659317..21661e4 100644 --- a/app/Content/Repository.php +++ b/app/Content/Repository.php @@ -22,9 +22,22 @@ final class Repository return json_decode((string) $this->pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR); } - public function pages(): array + public function pages(bool $publishedOnly = false): array { - return $this->pdo->query('SELECT slug, name, title, updated_at FROM pages ORDER BY rowid')->fetchAll(); + $where = $publishedOnly ? " WHERE status = 'published'" : ''; + + return $this->pdo->query('SELECT slug, name, title, updated_at, status FROM pages' . $where . ' ORDER BY rowid')->fetchAll(); + } + + public function createPage(string $slug, string $name): void + { + $query = $this->pdo->prepare("INSERT OR IGNORE INTO pages (slug, name, title, description, heading, accent, + lead, image, alt, actions, quicklinks, partners, status, updated_at) + VALUES (?, ?, ?, '', ?, '', '', '', '', '[]', '[]', '[]', 'draft', ?)"); + $query->execute([$slug, $name, $name . ' · 来笙', $name, self::now()]); + if ($query->rowCount() !== 1) { + throw new RuntimeException('此页面地址已存在。'); + } } public function page(string $slug): ?array @@ -50,11 +63,12 @@ final class Repository public function savePage(string $slug, array $data, int $version): void { - $query = $this->pdo->prepare('UPDATE pages SET title = ?, description = ?, heading = ?, accent = ?, lead = ?, - image = ?, alt = ?, actions = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); + $query = $this->pdo->prepare('UPDATE pages SET name = ?, title = ?, description = ?, heading = ?, accent = ?, lead = ?, + image = ?, alt = ?, actions = ?, quicklinks = ?, status = ?, updated_at = ?, version = version + 1 WHERE slug = ? AND version = ?'); $query->execute([ - $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], - $data['image'], $data['alt'], Database::json($data['actions']), self::now(), $slug, $version, + $data['name'], $data['title'], $data['description'], $data['heading'], $data['accent'], $data['lead'], + $data['image'], $data['alt'], Database::json($data['actions']), Database::json($data['quicklinks']), + $data['status'], self::now(), $slug, $version, ]); self::checkVersion($query->rowCount()); } @@ -62,15 +76,64 @@ final class Repository public function saveSection(string $page, string $key, array $data, int $version): void { Database::write(function (PDO $pdo) use ($page, $key, $data, $version): void { - $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, version = version + 1 + $query = $pdo->prepare('UPDATE sections SET title = ?, lead = ?, body = ?, style = ?, version = version + 1 WHERE page_slug = ? AND key = ? AND version = ?'); - $query->execute([$data['title'], $data['lead'], $data['body'], $page, $key, $version]); + $query->execute([$data['title'], $data['lead'], $data['body'], $data['style'], $page, $key, $version]); self::checkVersion($query->rowCount()); $query = $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?'); $query->execute([self::now(), $page]); }); } + public function createSection(string $page, string $key, string $title, string $style, string $body): void + { + Database::write(function (PDO $pdo) use ($page, $key, $title, $style, $body): void { + $query = $pdo->prepare('INSERT OR IGNORE INTO sections (page_slug, key, title, lead, style, body, position) + SELECT ?, ?, ?, ?, ?, ?, COALESCE(MAX(position), -1) + 1 FROM sections WHERE page_slug = ?'); + $query->execute([$page, $key, $title, '', $style, $body, $page]); + if ($query->rowCount() !== 1) { + throw new RuntimeException('此区块锚点已被使用。'); + } + self::touchPage($pdo, $page); + }); + } + + public function arrangeSection(string $page, string $key, string $operation, int $version): void + { + Database::write(function (PDO $pdo) use ($page, $key, $operation, $version): void { + if ($operation === 'delete') { + $query = $pdo->prepare('DELETE FROM sections WHERE page_slug = ? AND key = ? AND version = ?'); + $query->execute([$page, $key, $version]); + self::checkVersion($query->rowCount()); + self::touchPage($pdo, $page); + + return; + } + $query = $pdo->prepare('SELECT key FROM sections WHERE page_slug = ? ORDER BY position, key'); + $query->execute([$page]); + $keys = $query->fetchAll(PDO::FETCH_COLUMN); + $index = array_search($key, $keys, true); + if ($index === false) { + throw new RuntimeException('找不到该区块。'); + } + $other = $index + ($operation === 'up' ? -1 : 1); + if (!isset($keys[$other])) { + return; + } + [$keys[$index], $keys[$other]] = [$keys[$other], $keys[$index]]; + $query = $pdo->prepare('UPDATE sections SET position = ? WHERE page_slug = ? AND key = ?'); + foreach ($keys as $position => $section) { + $query->execute([$position, $page, $section]); + } + self::touchPage($pdo, $page); + }); + } + + private static function touchPage(PDO $pdo, string $slug): void + { + $pdo->prepare('UPDATE pages SET updated_at = ? WHERE slug = ?')->execute([self::now(), $slug]); + } + public function articles(?string $category = null, ?string $tag = null, bool $public = true, int $limit = 30, int $offset = 0): array { $sql = 'SELECT * FROM articles WHERE 1 = 1'; diff --git a/app/Content/SiteDesign.php b/app/Content/SiteDesign.php new file mode 100644 index 0000000..e360587 --- /dev/null +++ b/app/Content/SiteDesign.php @@ -0,0 +1,107 @@ + '/assets/wordmark.webp', 'alt' => 'Laysense 来笙', + 'links' => [['/', '首页'], ['/services', '产品与服务'], ['/articles', '动态'], ['/#about', '关于来笙']], + 'button' => ['#contact', '联系来笙'], + ]; + + public const DEFAULT_FOOTER = [ + 'logo' => '/assets/wordmark.webp', 'alt' => '来笙 Laysense', + 'products_title' => '产品与服务', + 'products' => [['/pagepan', 'PAGEPAN 小飞页'], ['/highspeaker', 'HighSpeaker DNS'], ['/sc', '软著代理服务'], ['/shnu-sc', 'SHNU 学生软著服务']], + 'company_title' => '公司', + 'company' => [['/#about', '关于来笙'], ['/articles', '来笙动态'], ['https://git.laysense.com', 'Laysense Git'], ['https://www.layso.de', 'LaySo']], + 'phones' => [['tel:+16699004532', '+1 (669) 900 4532'], ['tel:+85257012856', '+852 5701 2856']], + ]; + + public static function parseLinks(string $value): array + { + $links = []; + foreach (preg_split('/\R/u', $value, -1, PREG_SPLIT_NO_EMPTY) as $line) { + if (trim($line) === '') { + continue; + } + [$label, $url] = array_map('trim', array_pad(explode('|', $line, 2), 2, '')); + if ($label === '' || mb_strlen($label) > 70 || strlen($url) > 1000 || !Html::url($url) || count($links) >= 20) { + throw new RuntimeException('每行填写「文案 | 链接」,最多 20 条。'); + } + $links[] = [$url, $label]; + } + + return $links; + } + + public static function linkText(array $links): string + { + return implode("\n", array_map(static fn (array $link): string => $link[1] . ' | ' . $link[0], $links)); + } + + public static function saveSettings(string $part, array $data, int $version): void + { + Database::write(function (PDO $pdo) use ($part, $data, $version): void { + $site = json_decode((string) $pdo->query('SELECT payload FROM site_settings WHERE id = 1')->fetchColumn(), true, flags: JSON_THROW_ON_ERROR); + if (($site['revisions'][$part] ?? 0) !== $version) { + throw new RuntimeException('设置已在另一页面更新。请复制本次修改后重新打开。'); + } + $site[$part] = $data; + $site['revisions'][$part] = $version + 1; + $pdo->prepare('UPDATE site_settings SET payload = ? WHERE id = 1')->execute([Database::json($site)]); + }); + } + + public static function catalog(): array + { + return Database::connect()->query('SELECT * FROM catalog ORDER BY position, id')->fetchAll(); + } + + public static function product(int $id): ?array + { + $query = Database::connect()->prepare('SELECT * FROM catalog WHERE id = ?'); + $query->execute([$id]); + + return $query->fetch() ?: null; + } + + public static function saveProduct(?int $id, array $product, int $version): int + { + $pdo = Database::connect(); + $fields = ['name', 'category', 'body', 'image', 'alt', 'url', 'label', 'extra_url', 'extra_label', 'position']; + $values = array_map(static fn (string $field) => $product[$field], $fields); + if ($id === null) { + $pdo->prepare('INSERT INTO catalog (' . implode(', ', $fields) . ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)') + ->execute($values); + + return (int) $pdo->lastInsertId(); + } + + $query = $pdo->prepare('UPDATE catalog SET ' . implode(' = ?, ', $fields) . ' = ?, version = version + 1 WHERE id = ? AND version = ?'); + $query->execute([...$values, $id, $version]); + self::checkProduct($query->rowCount()); + + return $id; + } + + public static function deleteProduct(int $id, int $version): void + { + $query = Database::connect()->prepare('DELETE FROM catalog WHERE id = ? AND version = ?'); + $query->execute([$id, $version]); + self::checkProduct($query->rowCount()); + } + + private static function checkProduct(int $count): void + { + if ($count !== 1) { + throw new RuntimeException('此项目已在另一页面更新,请重新打开。'); + } + } +} diff --git a/app/Content/View.php b/app/Content/View.php index 22b5f4d..02a5dba 100644 --- a/app/Content/View.php +++ b/app/Content/View.php @@ -10,17 +10,21 @@ final class View { public static function render(string $template, array $data, int $status = 200, bool $admin = false): Response { + $cdn = $admin || !empty($data['previewMode']) ? '' : ($data['site']['cdn']['origin'] ?? ''); + $data['cdn'] = $cdn; $html = self::fragment($template, $data); - $page = self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]); + $page = Assets::rewrite(self::fragment($admin ? 'admin-layout' : 'layout', $data + ['content' => $html]), $cdn); + $assetSources = $cdn === '' ? "'self'" : "'self' " . $cdn; $headers = [ 'Content-Type' => 'text/html; charset=utf-8', 'X-Content-Type-Options' => 'nosniff', 'Referrer-Policy' => 'strict-origin-when-cross-origin', - 'X-Frame-Options' => 'DENY', + 'X-Frame-Options' => !empty($data['previewMode']) ? 'SAMEORIGIN' : 'DENY', 'Content-Security-Policy' => "default-src 'self'; img-src 'self' https:; media-src 'self' https:; " - . "style-src 'self'; script-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'; object-src 'none'", + . "style-src $assetSources; script-src $assetSources; font-src $assetSources; frame-src 'self'; frame-ancestors " + . (!empty($data['previewMode']) ? "'self'" : "'none'") . "; form-action 'self'; base-uri 'none'; object-src 'none'", ]; - if ($admin) { + if ($admin || !empty($data['previewMode'])) { $headers['Cache-Control'] = 'no-store'; $headers['X-Robots-Tag'] = 'noindex, nofollow'; } elseif (($data['noindex'] ?? false) || $status >= 400) { diff --git a/app/Controller/AdminController.php b/app/Controller/AdminController.php index eb4fe1f..6490bc8 100644 --- a/app/Controller/AdminController.php +++ b/app/Controller/AdminController.php @@ -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); } diff --git a/app/Controller/MediaController.php b/app/Controller/MediaController.php new file mode 100644 index 0000000..0ebb7c4 --- /dev/null +++ b/app/Controller/MediaController.php @@ -0,0 +1,45 @@ + $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); + } +} diff --git a/app/Controller/SiteController.php b/app/Controller/SiteController.php index 842dd46..6a4835d 100644 --- a/app/Controller/SiteController.php +++ b/app/Controller/SiteController.php @@ -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 = ['', '']; - $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); diff --git a/app/Controller/StudioController.php b/app/Controller/StudioController.php new file mode 100644 index 0000000..4e827f1 --- /dev/null +++ b/app/Controller/StudioController.php @@ -0,0 +1,285 @@ + ['正文', '

在这里输入区块内容。

'], + 'image' => ['图文', '

介绍图片内容,然后从媒体库插入图片。

'], + 'cta' => ['行动按钮', '

说明下一步。

联系来笙

'], + 'faq' => ['常见问题', '
请输入问题

请输入答案。

'], + ]; + + 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; + } +} diff --git a/app/Middleware/PublicAssets.php b/app/Middleware/PublicAssets.php new file mode 100644 index 0000000..5ea2d2d --- /dev/null +++ b/app/Middleware/PublicAssets.php @@ -0,0 +1,26 @@ +path(); + if (str_starts_with($path, '/assets/')) { + $response->withHeader('Access-Control-Allow-Origin', '*'); + if ($path === '/assets/jquery-4.0.0.min.js') { + $response->withHeader('Cache-Control', 'public, max-age=31536000, immutable'); + } + } + + return $response; + } +} diff --git a/app/view/admin-dashboard.php b/app/view/admin-dashboard.php index 6d16c2e..c05e9cb 100644 --- a/app/view/admin-dashboard.php +++ b/app/view/admin-dashboard.php @@ -5,14 +5,15 @@ $e = View::escape(...); ?>

内容管理

管理网站页面、文章、公告和产品动态。

- 新建文章 +

网站页面

  • -
    +
    ·
    编辑页面
  • diff --git a/app/view/admin-editor.php b/app/view/admin-editor.php index 5226839..5e39b67 100644 --- a/app/view/admin-editor.php +++ b/app/view/admin-editor.php @@ -1,5 +1,6 @@ @@ -12,11 +13,20 @@ $e = View::escape(...); - + + + + + + + + + + -

    支持段落、标题、链接、图片、列表、表格和折叠问答。保存时会清理脚本、内联样式等标签或属性。

    +

    可以直接编辑文字,插入链接、图片、音视频。复杂区块可切换到 HTML 源码调整。

    diff --git a/app/view/admin-layout.php b/app/view/admin-layout.php index d853837..f6bf11b 100644 --- a/app/view/admin-layout.php +++ b/app/view/admin-layout.php @@ -15,6 +15,7 @@ $e = View::escape(...); + @@ -25,6 +26,9 @@ $e = View::escape(...); - 联系来笙 + + +
    - + $footer]) ?> diff --git a/app/view/page.php b/app/view/page.php index 98d5f05..0bdd270 100644 --- a/app/view/page.php +++ b/app/view/page.php @@ -7,7 +7,7 @@ $home = $page['slug'] === 'home'; $service = in_array($page['slug'], ['sc', 'shnu-sc'], true); ?>
    -
    +
    -

    上海来笙信息科技有限公司

    +

    -


    -

    +


    +

    [$url, $label]): ?> - +
    @@ -40,7 +40,7 @@ $service = in_array($page['slug'], ['sc', 'shnu-sc'], true);
    - 产品与服务 + 产品与服务 PAGEPAN可视化建站 HighSpeaker DNS开源智能解析 软著代理登记申请与材料服务 diff --git a/app/view/services.php b/app/view/services.php new file mode 100644 index 0000000..f48a6c5 --- /dev/null +++ b/app/view/services.php @@ -0,0 +1,35 @@ + +
    +
    + +

    产品与服务

    +

    自托管建站、开源智能 DNS 与软件著作权代理服务。

    +
    +
    +
    +
    +

    暂无可查看的产品和服务。

    +
    + +
    + +
    <?= $e($product['alt']) ?>
    + +
    +

    +

    +
    +
    + + +
    +
    +
    + +
    +
    +
    diff --git a/app/view/studio-asset-field.php b/app/view/studio-asset-field.php new file mode 100644 index 0000000..bd6f12e --- /dev/null +++ b/app/view/studio-asset-field.php @@ -0,0 +1,9 @@ + +
    + + +
    diff --git a/app/view/studio-catalog.php b/app/view/studio-catalog.php new file mode 100644 index 0000000..e26ea7e --- /dev/null +++ b/app/view/studio-catalog.php @@ -0,0 +1,19 @@ + +
    +

    产品与服务

    管理公开目录中的条目、分类和按钮链接。

    + +
    +
    +

    暂无产品或服务。

    + +
    diff --git a/app/view/studio-media.php b/app/view/studio-media.php new file mode 100644 index 0000000..3d0a78c --- /dev/null +++ b/app/view/studio-media.php @@ -0,0 +1,50 @@ + +

    媒体库

    统一查找并引用静态文件、图片、图标和音视频。

    + +
    + +
    + + +
    +
    +
    +
    +

    资源列表

    +
    + + +
    +

    +
    + +
    + + + +

    + +

    + KB · +
    打开
    + +
    管理文件 +
    + + + + 归档从选取器隐藏文件,已有链接仍可访问。 + +
    +
    + +
    + +
    +
    diff --git a/app/view/studio-new-page.php b/app/view/studio-new-page.php new file mode 100644 index 0000000..697b715 --- /dev/null +++ b/app/view/studio-new-page.php @@ -0,0 +1,16 @@ + +返回页面 +

    新建页面

    + $error, 'saved' => false]) ?> +
    + + + +
    +
    diff --git a/app/view/studio-product.php b/app/view/studio-product.php new file mode 100644 index 0000000..9b3b791 --- /dev/null +++ b/app/view/studio-product.php @@ -0,0 +1,36 @@ + +返回目录管理 +

    + +
    + + +
    + + +
    +
    + '封面', 'name' => 'image', 'value' => $product['image']]) ?> + +
    +
    + + + + +
    + + 'html', 'body' => $product['body']]) ?> +
    +
    + +
    + + +
    +
    + diff --git a/app/view/studio-settings.php b/app/view/studio-settings.php new file mode 100644 index 0000000..693074a --- /dev/null +++ b/app/view/studio-settings.php @@ -0,0 +1,52 @@ + +

    查看公开网站
    + + +
    + + + + + + '站点标志', 'name' => 'logo', 'value' => $config['logo']]) ?> + + + + + +
    + '公司名称', 'address' => '联系地址', 'email' => '邮箱', 'registration' => '备案号', 'copyright' => '版权信息'] as $key => $text): ?> + + +
    + +
    + '第一列', 'company' => '第二列'] as $key => $text): ?> +
    + + +
    + +
    + + + +
    +
    diff --git a/composer.json b/composer.json index f678cbc..6a437d5 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,7 @@ "require": { "php": "^8.2", "ext-dom": "*", + "ext-fileinfo": "*", "ext-mbstring": "*", "ext-pdo_sqlite": "*", "league/commonmark": "^2.8", diff --git a/composer.lock b/composer.lock index b043931..44754a5 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c9d25a83ed6ca15405ef7765391c2f0d", + "content-hash": "b550e1c39f23f72dcd3480e7d01e9b56", "packages": [ { "name": "dflydev/dot-access-data", @@ -1098,6 +1098,7 @@ "platform": { "php": "^8.2", "ext-dom": "*", + "ext-fileinfo": "*", "ext-mbstring": "*", "ext-pdo_sqlite": "*" }, diff --git a/config/route.php b/config/route.php index f74aa42..d2cbc0c 100644 --- a/config/route.php +++ b/config/route.php @@ -2,13 +2,16 @@ use App\Controller\AdminController; use App\Controller\SiteController; +use App\Controller\StudioController; +use App\Controller\MediaController; use App\Content\View; use support\Request; use Webman\Route; Route::disableDefaultRoute(); Route::get('/', [SiteController::class, 'home']); -Route::get('/{slug:pagepan|highspeaker|sc|shnu-sc}', [SiteController::class, 'page']); +Route::get('/services', [SiteController::class, 'services']); +Route::get('/assets/uploads/{name:[a-f0-9]{32}\.[a-z0-9]+}', [MediaController::class, 'file']); Route::get('/articles', [SiteController::class, 'archive']); Route::get('/articles/category/{category:announcement|news|product}', [SiteController::class, 'archive']); Route::get('/articles/tag/{tag:[^/]+}', [SiteController::class, 'tagged']); @@ -27,8 +30,20 @@ Route::get('/admin', [AdminController::class, 'dashboard']); Route::get('/admin/articles', [AdminController::class, 'articles']); Route::add(['GET', 'POST'], '/admin/articles/new', [AdminController::class, 'article']); Route::add(['GET', 'POST'], '/admin/articles/{id:[0-9]+}', [AdminController::class, 'article']); +Route::add(['GET', 'POST'], '/admin/new-page', [StudioController::class, 'newPage']); +Route::get('/admin/pages/{slug:[a-z0-9-]+}/preview', [StudioController::class, 'previewPage']); +Route::post('/admin/page-blocks/{slug:[a-z0-9-]+}', [StudioController::class, 'blocks']); +Route::add(['GET', 'POST'], '/admin/settings/{part:header|footer|cdn}', [StudioController::class, 'settings']); +Route::get('/admin/catalog', [StudioController::class, 'catalog']); +Route::add(['GET', 'POST'], '/admin/catalog/new', [StudioController::class, 'product']); +Route::add(['GET', 'POST'], '/admin/catalog/{id:[0-9]+}', [StudioController::class, 'product']); +Route::add(['GET', 'POST'], '/admin/media', [StudioController::class, 'media']); +Route::get('/admin/media/options', [StudioController::class, 'mediaOptions']); +Route::post('/admin/media/{name:[a-f0-9]{32}\.[a-z0-9]+}', [StudioController::class, 'mediaMeta']); Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}', [AdminController::class, 'page']); Route::add(['GET', 'POST'], '/admin/pages/{slug:[a-z0-9-]+}/{key:[a-z0-9-]+}', [AdminController::class, 'section']); Route::post('/admin/preview', [AdminController::class, 'preview']); +Route::get('/{slug:[a-z0-9-]+}', [SiteController::class, 'page']); + Route::fallback(static fn (Request $request) => (new SiteController())->missing($request)); diff --git a/config/server.php b/config/server.php index 083d25c..4d2d9f6 100644 --- a/config/server.php +++ b/config/server.php @@ -6,5 +6,5 @@ return [ 'stdout_file' => runtime_path() . '/logs/stdout.log', 'log_file' => runtime_path() . '/logs/workerman.log', 'stop_timeout' => 4, - 'max_package_size' => 2 * 1024 * 1024, + 'max_package_size' => 66 * 1024 * 1024, ]; diff --git a/config/static.php b/config/static.php index 7132f83..8b1fb0d 100644 --- a/config/static.php +++ b/config/static.php @@ -1,3 +1,3 @@ true, 'middleware' => []]; +return ['enable' => true, 'middleware' => [App\Middleware\PublicAssets::class]]; diff --git a/public/assets/admin.css b/public/assets/admin.css index a624c27..7273170 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -53,3 +53,40 @@ .password-form { max-width: 37rem; } .admin-form button:disabled, .admin-bar button:disabled { cursor: progress; opacity: .65; } .admin-form .ajax-feedback { margin: 0; } + +.studio-layout { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(16rem, 1fr); gap: 1rem; align-items: start; } +.studio-frame-window { position: relative; height: min(67vh, 39rem); overflow: hidden; margin-bottom: .8rem; border: 1px solid var(--line); border-radius: .55rem; background: var(--paper); } +.studio-frame-window iframe { display: block; width: 100%; height: 100%; border: 0; background: white; } +.studio-frame-window.has-scaled-preview iframe { position: absolute; top: 0; transform-origin: 0 0; } +.preview-selector { display: flex; gap: .35rem; flex-wrap: wrap; } +.preview-selector [aria-pressed="true"] { background: var(--accent-light); color: var(--accent-deep); } +.studio-inspector details label { margin-top: .7rem; } +.studio-blocks form, .studio-block-actions { display: flex; align-items: center; flex-wrap: wrap; gap: .32rem; } +.studio-blocks .button { padding-inline: .65rem; } +.studio-block-add { margin-top: 1.25rem; } +.studio-rich { min-height: 15rem; max-width: 100%; overflow-x: auto; padding: 1rem; background: #fff; border: 1px solid var(--line); border-radius: .55rem; } +.studio-rich:focus { outline: 2px solid var(--accent); outline-offset: 2px; } +.studio-rich details { margin-bottom: .5rem; } +.studio-rich img, .studio-rich video { max-width: 100%; height: auto; } +.asset-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: .55rem; } +.settings-form { max-width: 54rem; } +.media-grid, .picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); gap: .8rem; } +.media-card, .picker-item { min-width: 0; border: 1px solid var(--line); border-radius: .65rem; background: white; padding: .75rem; overflow-wrap: anywhere; } +.media-card > img, .picker-item img, .media-file-type { height: 6rem; width: 100%; object-fit: contain; background: var(--paper); border-radius: .45rem; margin-bottom: .7rem; } +.media-card .media-file-type { display: grid; place-items: center; font-size: 1.1rem; text-transform: uppercase; } +.media-card h3 { font-size: 1rem; margin-bottom: 0; } +.media-card small { color: var(--muted); } +.media-card .actions { margin: .45rem 0; } +.media-card .button { padding-inline: .55rem; } +.media-card .media-archive { display: flex; align-items: center; } +.media-card .media-archive input { width: auto; min-height: 0; } +.media-picker { max-width: min(92vw, 52rem); max-height: 86vh; width: 100%; padding: 1.25rem; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); } +.media-picker::backdrop { background: #101c3488; } +.media-picker label { display: grid; gap: .35rem; } +.media-picker input { padding: .55rem .75rem; border: 1px solid var(--line); border-radius: .4rem; } +.picker-grid { max-height: 50vh; overflow: auto; padding: .25rem; } +.picker-item { text-align: left; min-height: 44px; } +.picker-item:hover { border-color: var(--accent); } +@media (max-width: 65rem) { + .studio-layout { grid-template-columns: minmax(0, 1fr); } +} diff --git a/public/assets/admin.js b/public/assets/admin.js index 9dd6bbe..4c37187 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -41,9 +41,12 @@ jQuery(function ($) { event.preventDefault(); const $form = $(this); if ($form.attr('aria-busy') === 'true') return; + const submitter = event.originalEvent?.submitter; + if (submitter?.dataset.confirm && !window.confirm(submitter.dataset.confirm)) return; const action = $form.attr('action'); const isLogin = action === '/admin/login'; - const $submit = $form.find(':submit'); + const $submit = $form.find(':submit:enabled'); + const multipart = $form.attr('enctype') === 'multipart/form-data'; $form.attr('aria-busy', 'true').children('.ajax-feedback').prop('hidden', true); $submit.prop('disabled', true); @@ -53,10 +56,18 @@ jQuery(function ($) { } function submit(canRetryLogin) { + $form.triggerHandler('studio:sync'); + const fields = multipart ? new FormData($form.get(0)) : $form.serializeArray(); + if (submitter?.name) { + if (multipart) fields.append(submitter.name, submitter.value); + else fields.push({name: submitter.name, value: submitter.value}); + } $.ajax({ url: action, method: 'POST', - data: $form.serialize(), + data: fields, + processData: !multipart, + contentType: multipart ? false : 'application/x-www-form-urlencoded; charset=UTF-8', dataType: 'json' }).done(function (response) { if (response.redirect) { @@ -82,6 +93,7 @@ jQuery(function ($) { $('[data-editor]').each(function () { const $editor = $(this); + if ($editor.find('[data-rich-canvas]').length) return; const area = $editor.find('textarea').get(0); const format = $editor.data('format'); const $preview = $editor.find('.editor-preview'); @@ -116,7 +128,7 @@ jQuery(function ($) { if (status === 'abort') return; let feedback = request.responseJSON; if (!feedback && request.getResponseHeader('Content-Type')?.startsWith('application/json')) { - feedback = JSON.parse(request.responseText); + try { feedback = JSON.parse(request.responseText); } catch { /* Use the fallback feedback. */ } } refreshToken(feedback); $preview.text(feedback?.message || '预览无法加载,请重试。'); diff --git a/public/assets/service/code.svg b/public/assets/service/code.svg new file mode 100644 index 0000000..ee8113f --- /dev/null +++ b/public/assets/service/code.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/service/project.svg b/public/assets/service/project.svg new file mode 100644 index 0000000..47786a8 --- /dev/null +++ b/public/assets/service/project.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/service/support.svg b/public/assets/service/support.svg new file mode 100644 index 0000000..88b1a66 --- /dev/null +++ b/public/assets/service/support.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/site.css b/public/assets/site.css index 3c5e288..5c69601 100644 --- a/public/assets/site.css +++ b/public/assets/site.css @@ -371,3 +371,74 @@ progress { width: 100%; height: .8rem; accent-color: var(--accent); } .payment-methods { display: flex; gap: .65rem; align-items: center; margin-block: .5rem; } .payment-methods img { width: 1.625rem; height: 1.625rem; object-fit: contain; } + +.hero-inner.hero-text-only { grid-template-columns: minmax(0, 1fr); min-height: 28rem; } +.hero-directory > .directory-label { border-inline-start: 0; } +.catalog-hero { background: var(--paper); padding-block: clamp(3rem, 6vw, 6rem); } +.catalog-hero h1 { margin-bottom: .85rem; } +.catalog-hero p { margin: 0; font-size: 1.15rem; } +.catalog-listing { padding-block: clamp(3rem, 6vw, 6rem); } +.catalog-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: clamp(1rem, 3vw, 2rem); } +.catalog-card { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; } +.catalog-image { aspect-ratio: 16 / 8; padding: clamp(.8rem, 3vw, 1.8rem); background: var(--paper); display: grid; place-items: center; } +.catalog-image img { max-height: 100%; width: 100%; height: 100%; object-fit: contain; } +.catalog-content { padding: clamp(1.25rem, 3vw, 2rem); flex: 1; display: flex; flex-direction: column; } +.catalog-content h2 { font-size: clamp(1.45rem, 3vw, 2.6rem); margin-bottom: .7rem; } +.catalog-content .overline { margin-bottom: .4rem; } +.catalog-content .actions { margin-top: auto; padding-top: 1rem; } + +.copyright-service #materials .feature-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } +.copyright-service #why .choice-card { background: #e9f0ff; border-color: #7599ec; box-shadow: inset 0 3px var(--accent); } +.copyright-service #why .choice-card h3 { color: var(--accent-deep); } +.copyright-service #options .feature-card { display: flex; flex-direction: column; align-items: flex-start; } +.copyright-service #options .feature-card > img { width: 3.6rem; height: 3.6rem; margin-bottom: .95rem; } +.copyright-service #options .feature-card > a { margin-top: auto; } +.copyright-service #faq .faq { max-width: none; } +.copyright-service #faq summary { font-size: clamp(1.05rem, 1.35vw, 1.2rem); min-height: 3.75rem; } +.copyright-service #faq details > div { max-width: 75ch; } +.copyright-service #go { padding-block: clamp(2rem, 5vw, 4rem); background: var(--white); } +.copyright-service #go > .wrap { + position: relative; + padding: clamp(1.5rem, 5vw, 4.5rem); + padding-right: clamp(11rem, 29vw, 23rem); + border-radius: var(--radius); + background: radial-gradient(ellipse at 88% 110%, #264b9a 0, transparent 59%), #132443; + color: var(--white); + min-height: 16rem; + display: flex; + flex-direction: column; + justify-content: center; +} +.copyright-service #go .section-heading { margin-bottom: .8rem; } +.copyright-service #go h2 { font-size: clamp(1.8rem, 4vw, 3.5rem); } +.copyright-service #go .contact-panel { display: block; } +.copyright-service #go .contact-panel p { color: #d9e8ff; max-width: 40ch; } +.copyright-service #go .contact-panel img { + position: absolute; + top: 50%; + right: clamp(1.5rem, 6vw, 6rem); + transform: translateY(-50%); + width: clamp(8rem, 13vw, 12rem); + padding: .5rem; + border: 0; + border-radius: .85rem; + background: white; +} +.copyright-service #go .button { color: #142956; background: #eef4ff; border-color: #eef4ff; } +.copyright-service #terms { padding-block: 1.4rem 2.5rem; border-top: 0; } +.copyright-service #terms .section-heading { margin-bottom: .35rem; } +.copyright-service #terms h2 { font-size: .95rem; letter-spacing: 0; } +.copyright-service #terms .rich { font-size: .875rem; color: var(--muted); } + +@media (max-width: 62rem) { + .copyright-service #materials .feature-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +@media (max-width: 44rem) { + .catalog-grid, .copyright-service #materials .feature-grid { grid-template-columns: 1fr; } + .hero-directory > .directory-label { grid-column: 1 / -1; border-top: 0; } + .copyright-service #go > .wrap { padding: 1.55rem; min-height: 0; } + .copyright-service #go .contact-panel { display: flex; gap: 1rem; } + .copyright-service #go .contact-panel img { position: static; transform: none; width: 7rem; } +} +.hero h1 .hero-heading-primary { color: inherit; } +[data-studio-field][contenteditable] { min-height: 1em; outline: 1px dashed #7896d5; outline-offset: 3px; } diff --git a/public/assets/studio.js b/public/assets/studio.js new file mode 100644 index 0000000..643d4c1 --- /dev/null +++ b/public/assets/studio.js @@ -0,0 +1,259 @@ +'use strict'; + +jQuery(function ($) { + const $picker = $('#media-picker'); + const $pickerItems = $picker.find('[data-picker-items]'); + const $pickerStatus = $picker.find('[data-picker-status]'); + let pick = null; + let files = []; + let mediaType = ''; + let pickerRequest; + + function renderPicker() { + const query = String($picker.find('[data-media-query]').val() || '').trim().toLowerCase(); + const results = files.filter((file) => file.mime.startsWith(mediaType) + && (file.label + ' ' + file.url).toLowerCase().includes(query)); + $pickerStatus.text(results.length ? results.length + ' 个资源' : '没有匹配资源。'); + $pickerItems.empty(); + for (const file of results) { + const $item = $('