v10: 修影院编辑回填布尔化 bug;评分改 10 星制;观影人改弹窗+拼音首字母联想;豆瓣自动补充迁移(movie_details.douban_meta,schema v10)

This commit is contained in:
2026-10-01 10:21:45 +08:00
parent 746f02581e
commit 2c36335c3e
8 changed files with 1050 additions and 39 deletions
+417
View File
@@ -0,0 +1,417 @@
<?php
/**
* 豆瓣自动补充(v10,MovieLog fetch_movie.php 同源迁移)。
*
* 数据来源(公开网页接口,非官方 API):
* 1) 搜索 https://movie.douban.com/j/subject_suggest?q=片名
* 2) 详情 https://m.douban.com/rexxar/api/v2/movie/<id>
* 3) 海报 https://imgN.doubanio.com/...(需带 Referer,防盗链)
*
* 与 MovieLog 版的差异:
* · 环境变量前缀改为 FAMILYBOOK_DOUBAN_*(便于本地 mock 端到端测试);
* · 海报落盘不走本类 —— 交给 Upload::image() 的 poster 槽位管线
* (裁剪/缩放/转 JPEG/Storage 统一出口),本类只负责「取回字节」;
* · 元数据不落库,组装成数组返回,由调用方决定存哪。
*/
declare(strict_types=1);
namespace App;
final class Douban
{
/** 移动端 UA:豆瓣移动端接口(rexxar)对移动 UA 正常返回,桌面 UA 会被反爬 302 */
private const UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) '
. 'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1';
/** 海报字节上限:正常海报几十 KB,超了说明响应不对 */
private const MAX_POSTER_BYTES = 12 * 1024 * 1024;
// ---------------- 对外入口 ----------------
/**
* 片名候选列表(下拉联想用;只读,不取详情、不写任何文件)。
* @return array{ok:bool, items?:array, error?:string}
*/
public static function suggest(string $kw): array
{
$kw = trim($kw);
if ($kw === '') {
return ['ok' => true, 'items' => []];
}
$res = self::getJson(self::searchEndpoint($kw));
if (!$res['ok']) {
return ['ok' => false, 'error' => '搜索失败:' . $res['err']];
}
return ['ok' => true, 'items' => self::buildSuggestItems(is_array($res['data']) ? $res['data'] : [])];
}
/**
* 按豆瓣条目 id 取详情,返回整理好的字段。
* @return array{ok:bool, meta?:array, title?:string, poster_url?:string, error?:string}
*/
public static function fetchById(string $id): array
{
if (!preg_match('/^\d{1,12}$/', $id)) {
return ['ok' => false, 'error' => '无效的豆瓣条目 ID'];
}
return self::fetchDetail($id, []);
}
/**
* 按片名搜索 → 挑最佳候选 → 取详情。
* @return array{ok:bool, meta?:array, title?:string, poster_url?:string, error?:string}
*/
public static function fetchByTitle(string $q): array
{
$q = trim($q);
if ($q === '') {
return ['ok' => false, 'error' => '请输入电影名称'];
}
$search = self::getJson(self::searchEndpoint($q));
if (!$search['ok']) {
return ['ok' => false, 'error' => '搜索失败:' . $search['err']];
}
$list = is_array($search['data']) ? $search['data'] : [];
if ($list === []) {
return ['ok' => false, 'error' => '豆瓣没有找到「' . $q . '」,换个更准确的片名试试'];
}
$picked = self::pickCandidate($list, $q);
if ($picked === null) {
return ['ok' => false, 'error' => '豆瓣没有找到「' . $q . '」的影视条目,换个更准确的片名试试'];
}
return self::fetchDetail((string)$picked['id'], $picked, $q);
}
/**
* 代理豆瓣缩略图(防盗链,浏览器不能直连)。只读、不落盘。
* @return array{mime:string, body:string}|null
*/
public static function thumb(string $url): ?array
{
if (!self::imageUrlAllowed($url)) {
return null;
}
$res = self::httpGet($url, 'https://movie.douban.com/');
$binary = $res['ok'] ? $res['body'] : '';
if ($binary === '') {
return null;
}
$mime = self::imageMimeFromMagic($binary);
return $mime === '' ? null : ['mime' => $mime, 'body' => $binary];
}
/** 下载海报字节(给 Upload 管线用)。失败返回空串。 */
public static function downloadPoster(string $url): string
{
if (!self::imageUrlAllowed($url)) {
return '';
}
// 豆瓣图片服务器要求带 Referer,否则 403
$res = self::httpGet($url, 'https://movie.douban.com/');
$binary = $res['ok'] ? $res['body'] : '';
if ($binary === '' || strlen($binary) > self::MAX_POSTER_BYTES) {
return '';
}
// 不是已知图片格式(比如被反爬拦成 HTML)就退回 —— 交给调用方提示
return self::imageMimeFromMagic($binary) === '' ? '' : $binary;
}
// ---------------- 详情与字段整理 ----------------
/** @param array $cand 搜索候选(id 直连时为空数组),供标题/年份/海报兜底 */
private static function fetchDetail(string $id, array $cand, string $q = ''): array
{
$detail = self::getJson(self::detailEndpoint($id), self::detailReferer($id));
if (!$detail['ok']) {
return ['ok' => false, 'error' => '获取详情失败:' . $detail['err']];
}
$d = is_array($detail['data']) ? $detail['data'] : [];
$title = (string)($d['title'] ?? '') !== ''
? (string)$d['title']
: (string)($cand['title'] ?? $q);
$rating = '';
if (isset($d['rating']) && is_array($d['rating']) && isset($d['rating']['value'])) {
$rv = (float)$d['rating']['value'];
if ($rv > 0) {
$rating = number_format($rv, 1, '.', '');
}
}
// 海报地址优先级:详情 pic.normal(大图)> cover_url > 搜索结果缩略图
$posterUrl = '';
foreach ([(string)($d['pic']['normal'] ?? ''), (string)($d['cover_url'] ?? ''),
(string)($cand['img'] ?? '')] as $u) {
if ($u !== '') {
$posterUrl = $u;
break;
}
}
$meta = [
'douban_id' => $id,
'douban_url' => 'https://movie.douban.com/subject/' . $id . '/',
'year' => self::str($d, 'year') !== '' ? self::str($d, 'year') : (string)($cand['year'] ?? ''),
'genre' => self::joinList($d['genres'] ?? []),
'runtime' => self::joinList($d['durations'] ?? []),
'director' => self::joinNames($d['directors'] ?? []),
'actors' => self::joinNames($d['actors'] ?? [], 6),
'plot' => (string)($d['intro'] ?? ''),
'rating' => $rating,
'country' => self::joinList($d['countries'] ?? []),
'alias' => self::joinList($d['aka'] ?? [], 3),
];
return ['ok' => true, 'meta' => $meta, 'title' => $title, 'poster_url' => $posterUrl];
}
private static function str(array $d, string $k): string
{
return isset($d[$k]) && is_scalar($d[$k]) ? (string)$d[$k] : '';
}
// ---------------- 搜索候选整理 ----------------
/** 规范化片名用于匹配:去空白、去常见标点、转小写 */
private static function normalizeTitle(string $s): string
{
$s = preg_replace('/[\s\x{3000}]+/u', '', $s) ?? '';
$s = str_replace([',', ',', '。', '·', '・', ':', ':', '!', '!', '?', '?', '、', '《', '》'], '', $s);
return function_exists('mb_strtolower') ? mb_strtolower($s, 'UTF-8') : strtolower($s);
}
/** 从搜索候选里挑出最可能的那一条:同名优先、有海报优先、有年份优先 */
private static function pickCandidate(array $list, string $q): ?array
{
$qNorm = self::normalizeTitle($q);
$best = null;
$bestScore = -1;
foreach ($list as $item) {
if (!is_array($item) || empty($item['id'])) {
continue;
}
$type = isset($item['type']) ? (string)$item['type'] : 'movie';
if (in_array($type, ['celebrity', 'person', 'actor', 'director'], true)) {
continue;
}
$title = self::str($item, 'title');
$sub = self::str($item, 'sub_title');
$score = 0;
if ($title !== '' && self::normalizeTitle($title) === $qNorm) $score += 5;
if ($sub !== '' && self::normalizeTitle($sub) === $qNorm) $score += 5;
if (!empty($item['img'])) $score += 2;
if (!empty($item['year'])) $score += 1;
if ($best === null || $score > $bestScore) {
$best = $item;
$bestScore = $score;
}
}
return $best;
}
/** 判断候选是电影还是剧集:suggest 里两者 type 都是 movie,只能靠 episode 区分 */
private static function kindLabel(string $type, string $episode): string
{
if ((int)$episode > 1) return '剧集';
if ($type === '' || $type === 'movie') return '电影';
return $type;
}
/** 把 suggest 的原始结果整理成前端下拉要用的字段(过滤影人、去重、限量) */
private static function buildSuggestItems(array $list, int $limit = 8): array
{
$items = [];
$seen = [];
foreach ($list as $it) {
if (!is_array($it) || empty($it['id'])) {
continue;
}
$type = isset($it['type']) ? (string)$it['type'] : 'movie';
if (in_array($type, ['celebrity', 'person', 'actor', 'director'], true)) {
continue;
}
$id = (string)$it['id'];
if (isset($seen[$id])) {
continue;
}
$seen[$id] = true;
$img = self::str($it, 'img');
$episode = self::str($it, 'episode');
$items[] = [
'id' => $id,
'title' => self::str($it, 'title'),
'sub_title' => self::str($it, 'sub_title'),
'year' => self::str($it, 'year'),
'episode' => $episode,
'kind' => self::kindLabel($type, $episode),
'thumb' => $img !== '' ? self::thumbProxyUrl($img) : '',
];
if (count($items) >= $limit) {
break;
}
}
return $items;
}
// ---------------- 图片地址白名单(防 SSRF) ----------------
/**
* action=thumb / 海报下载都是「服务端代取」,放任任意 URL 就是 SSRF 跳板。
* 只允许豆瓣图片 CDN(img*.doubanio.com)下的图片路径。
* FAMILYBOOK_DOUBAN_IMG_ALLOW(逗号分隔的完整来源)是本地端到端测试留给 mock 的口子。
*/
public static function imageUrlAllowed(string $url): bool
{
if ($url === '') {
return false;
}
$p = parse_url($url);
if (!$p || empty($p['host']) || empty($p['path'])) {
return false;
}
$scheme = strtolower((string)($p['scheme'] ?? ''));
$host = strtolower((string)$p['host']);
$port = isset($p['port']) ? ':' . $p['port'] : '';
$origin = ($scheme === '' || $host === '') ? '' : $scheme . '://' . $host . $port;
$raw = getenv('FAMILYBOOK_DOUBAN_IMG_ALLOW');
if ($raw !== false && $raw !== '') {
foreach (explode(',', $raw) as $allowed) {
$allowed = rtrim(trim($allowed), '/');
if ($allowed !== '' && $origin !== '' && strcasecmp($origin, strtolower($allowed)) === 0) {
return true;
}
}
}
if ($scheme !== 'https') return false;
if (!preg_match('/^img\d*\.doubanio\.com$/i', $host)) return false;
if (!preg_match('#^/view/photo/[A-Za-z0-9_/]+\.(?:jpg|jpeg|png|webp)$#i', (string)$p['path'])) return false;
return true;
}
/** 豆瓣图片地址 → 本站代理地址(豆瓣有防盗链,<img> 直连一律 403) */
public static function thumbProxyUrl(string $img): string
{
if (!self::imageUrlAllowed($img)) {
return '';
}
// 路由的 url() 会在输出处再转义;这里手动拼查询串
return 'index.php?r=movies/douban&action=thumb&u=' . rawurlencode($img);
}
// ---------------- HTTP 与格式识别 ----------------
private static function searchEndpoint(string $q): string
{
$base = getenv('FAMILYBOOK_DOUBAN_SEARCH');
$base = $base ? rtrim($base, '/') : 'https://movie.douban.com/j/subject_suggest';
return $base . '?q=' . rawurlencode($q);
}
private static function detailEndpoint(string $id): string
{
$base = getenv('FAMILYBOOK_DOUBAN_DETAIL');
$base = $base ? rtrim($base, '/') : 'https://m.douban.com/rexxar/api/v2/movie';
return $base . '/' . rawurlencode($id);
}
private static function detailReferer(string $id): string
{
$ref = getenv('FAMILYBOOK_DOUBAN_DETAIL_REF');
return $ref ? $ref : ('https://m.douban.com/movie/subject/' . rawurlencode($id) . '/');
}
/** @return array{ok:bool, http:int, body:string, err:string} */
private static function httpGet(string $url, string $referer = '', string $accept = ''): array
{
$headers = [];
if ($referer !== '') $headers[] = 'Referer: ' . $referer;
if ($accept !== '') $headers[] = 'Accept: ' . $accept;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => 15,
CURLOPT_USERAGENT => self::UA,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_ENCODING => '',
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$body = curl_exec($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($body === false) {
return ['ok' => false, 'http' => $http, 'body' => '', 'err' => $err !== '' ? $err : '请求失败'];
}
if ($http < 200 || $http >= 300) {
return ['ok' => false, 'http' => $http, 'body' => (string)$body, 'err' => 'HTTP ' . $http];
}
return ['ok' => true, 'http' => $http, 'body' => (string)$body, 'err' => ''];
}
/** @return array{ok:bool, data:mixed, err:string} */
private static function getJson(string $url, string $referer = ''): array
{
$res = self::httpGet($url, $referer, 'application/json');
if (!$res['ok']) {
return ['ok' => false, 'data' => null, 'err' => $res['err']];
}
$data = json_decode($res['body'], true);
if (!is_array($data)) {
return ['ok' => false, 'data' => null, 'err' => '返回内容不是合法 JSON(可能被反爬拦截)'];
}
return ['ok' => true, 'data' => $data, 'err' => ''];
}
/** 按魔数判断图片类型;不是已知图片返回空串(兜底 fileinfo、挡反爬 HTML) */
private static function imageMimeFromMagic(string $binary): string
{
if (strncmp($binary, "\xFF\xD8\xFF", 3) === 0) return 'image/jpeg';
if (strncmp($binary, "\x89PNG\r\n\x1A\n", 8) === 0) return 'image/png';
if (strncmp($binary, 'GIF87a', 6) === 0 || strncmp($binary, 'GIF89a', 6) === 0) return 'image/gif';
if (strlen($binary) >= 12 && substr($binary, 0, 4) === 'RIFF' && substr($binary, 8, 4) === 'WEBP') {
return 'image/webp';
}
return '';
}
// ---------------- 名单拼接 ----------------
/** [{'name':'饺子'}] -> '饺子 / 另一位' */
private static function joinNames(mixed $list, int $limit = 0): string
{
if (!is_array($list)) return '';
$names = [];
foreach ($list as $it) {
if (is_array($it) && !empty($it['name'])) {
$names[] = (string)$it['name'];
} elseif (is_string($it) && $it !== '') {
$names[] = $it;
}
}
if ($limit > 0) $names = array_slice($names, 0, $limit);
return implode(' / ', $names);
}
private static function joinList(mixed $list, int $limit = 0): string
{
if (!is_array($list)) return '';
$vals = [];
foreach ($list as $v) {
if (is_string($v) && $v !== '') $vals[] = $v;
elseif (is_scalar($v) && (string)$v !== '') $vals[] = (string)$v;
}
if ($limit > 0) $vals = array_slice($vals, 0, $limit);
return implode(' / ', $vals);
}
}
+9 -3
View File
@@ -59,7 +59,7 @@ final class Movie
public static function find(int $familyId, int $id): ?array public static function find(int $familyId, int $id): ?array
{ {
$st = Database::get()->prepare( $st = Database::get()->prepare(
'SELECT e.*, d.info, d.poster_key, d.ticket_key, d.cinema_id, 'SELECT e.*, d.info, d.poster_key, d.ticket_key, d.cinema_id, d.douban_meta,
c.place AS cinema_place, c.name AS cinema_name, c.place AS cinema_place, c.name AS cinema_name,
c.address AS cinema_address, c.color AS cinema_color c.address AS cinema_address, c.color AS cinema_color
FROM events e FROM events e
@@ -145,19 +145,25 @@ final class Movie
{ {
$db = Database::get(); $db = Database::get();
$cid = (int)($d['cinema_id'] ?? 0); $cid = (int)($d['cinema_id'] ?? 0);
// 豆瓣元数据:进来是数组(表单提交的 JSON 已由路由解码校验),存成 JSON 文本;
// 空数组/缺省 = 不写(保持 NULL,详情页就不渲染豆瓣块)
$meta = isset($d['douban_meta']) && is_array($d['douban_meta']) && $d['douban_meta'] !== []
? json_encode($d['douban_meta'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
: null;
$row = [ $row = [
self::textOrNull($d['info'] ?? ''), self::textOrNull($d['info'] ?? ''),
self::keyOrNull($d['poster_key'] ?? ''), self::keyOrNull($d['poster_key'] ?? ''),
self::keyOrNull($d['ticket_key'] ?? ''), self::keyOrNull($d['ticket_key'] ?? ''),
$cid > 0 ? $cid : null, $cid > 0 ? $cid : null,
$meta,
]; ];
$has = $db->prepare('SELECT COUNT(*) FROM movie_details WHERE event_id = ?'); $has = $db->prepare('SELECT COUNT(*) FROM movie_details WHERE event_id = ?');
$has->execute([$eventId]); $has->execute([$eventId]);
if ((int)$has->fetchColumn() > 0) { if ((int)$has->fetchColumn() > 0) {
$db->prepare('UPDATE movie_details SET info=?, poster_key=?, ticket_key=?, cinema_id=? WHERE event_id=?') $db->prepare('UPDATE movie_details SET info=?, poster_key=?, ticket_key=?, cinema_id=?, douban_meta=? WHERE event_id=?')
->execute([...$row, $eventId]); ->execute([...$row, $eventId]);
} else { } else {
$db->prepare('INSERT INTO movie_details (info, poster_key, ticket_key, cinema_id, event_id) VALUES (?,?,?,?,?)') $db->prepare('INSERT INTO movie_details (info, poster_key, ticket_key, cinema_id, douban_meta, event_id) VALUES (?,?,?,?,?,?)')
->execute([...$row, $eventId]); ->execute([...$row, $eventId]);
} }
} }
+9 -1
View File
@@ -50,7 +50,7 @@ final class Schema
* + movie_review_comments(两级平铺讨论),movie_details 旧的单条 * + movie_review_comments(两级平铺讨论),movie_details 旧的单条
* rating/review/feelings 迁进 movie_reviews 后删列。 * rating/review/feelings 迁进 movie_reviews 后删列。
*/ */
public const VERSION = '9'; public const VERSION = '10';
/** @return string[] */ /** @return string[] */
public static function statements(): array public static function statements(): array
@@ -254,6 +254,7 @@ CREATE TABLE IF NOT EXISTS `movie_details` (
`poster_key` VARCHAR(255) DEFAULT NULL COMMENT '海报(存储相对键,如 posters/xxx.jpg)', `poster_key` VARCHAR(255) DEFAULT NULL COMMENT '海报(存储相对键,如 posters/xxx.jpg)',
`ticket_key` VARCHAR(255) DEFAULT NULL COMMENT '票根照片(存储相对键)', `ticket_key` VARCHAR(255) DEFAULT NULL COMMENT '票根照片(存储相对键)',
`cinema_id` INT UNSIGNED DEFAULT NULL COMMENT '看的哪家影院(cinemas.id)', `cinema_id` INT UNSIGNED DEFAULT NULL COMMENT '看的哪家影院(cinemas.id)',
`douban_meta` TEXT DEFAULT NULL COMMENT '豆瓣自动补充的元数据(JSON:年份/类型/导演/主演/评分/链接等)',
PRIMARY KEY (`event_id`), PRIMARY KEY (`event_id`),
KEY `idx_mdet_cinema` (`cinema_id`), KEY `idx_mdet_cinema` (`cinema_id`),
CONSTRAINT `fk_mdet_event` FOREIGN KEY (`event_id`) REFERENCES `events` (`id`) ON DELETE CASCADE, CONSTRAINT `fk_mdet_event` FOREIGN KEY (`event_id`) REFERENCES `events` (`id`) ON DELETE CASCADE,
@@ -513,6 +514,13 @@ SQL,
} }
} }
// ---- 豆瓣自动补充(版本 10,MovieLog fetch_movie 同源迁移)----
// 豆瓣抓到的元数据(年份/类型/导演/主演/时长/国家/别名/评分/豆瓣链接)
// 整体存一个 JSON 列,随用随解 —— 不为每个字段单开列(家庭应用不需要按
// 这些维度做查询),以后豆瓣再补字段也不用动表。
self::addColumn($db, 'movie_details', 'douban_meta',
"ADD COLUMN `douban_meta` TEXT DEFAULT NULL COMMENT '豆瓣自动补充的元数据(JSON)' AFTER `cinema_id`");
// 被容错跳过的数据步骤记进设置,系统设置页会把它显出来 —— // 被容错跳过的数据步骤记进设置,系统设置页会把它显出来 ——
// 不然「升级没跑完」这件事只活在日志里,跟没发生一样。 // 不然「升级没跑完」这件事只活在日志里,跟没发生一样。
if (self::$stepErrors) { if (self::$stepErrors) {
+102 -14
View File
@@ -954,19 +954,106 @@ textarea.input { min-height: 76px; resize: vertical; }
.rv-form-inline { padding: 12px 14px; } .rv-form-inline { padding: 12px 14px; }
.rv-rating-row { display: flex; align-items: center; gap: 8px 14px; flex-wrap: wrap; margin-bottom: 12px; } .rv-rating-row { display: flex; align-items: center; gap: 8px 14px; flex-wrap: wrap; margin-bottom: 12px; }
.rv-rating-label { font-size: 14px; font-weight: 600; color: var(--ink); } .rv-rating-label { font-size: 14px; font-weight: 600; color: var(--ink); }
.rv-scale { display: flex; gap: 6px; flex-wrap: wrap; } /* ---- 10 星评分(v10):空心 ☆ 灰、点亮 ★ 金黄。
.rv-num { position: relative; } DOM 按 10..1 倒序渲染 + row-reverse,视觉即 1..10 从左到右;
.rv-num input { position: absolute; width: 1px; height: 1px; opacity: 0; } 「点亮的星星」由 JS 加 .lit(含悬停预览),.no-js 兜底用 :has() 只亮已选中那一档。 ---- */
.rv-num span { .rv-scale { display: flex; gap: 2px; }
display: inline-flex; align-items: center; justify-content: center; .rv-stars { flex-direction: row-reverse; justify-content: flex-end; }
min-width: 34px; height: 34px; padding: 0 6px; .rv-star { position: relative; cursor: pointer; line-height: 1; }
border: 1px solid var(--line); border-radius: 8px; background: var(--surface); .rv-star input { position: absolute; width: 1px; height: 1px; opacity: 0; }
color: var(--muted); font-size: 14px; font-weight: 600; .rv-star .st-glyph { font-size: 28px; line-height: 1; }
cursor: pointer; user-select: none; .rv-star .st-off { color: #c9cdd4; }
.rv-star .st-on { display: none; color: #f5b301; }
.rv-star.lit .st-on { display: inline; }
.rv-star.lit .st-off { display: none; }
.rv-star:hover .st-off { color: #aeb4be; }
.rv-star:focus-within { outline: 2px solid var(--brand); outline-offset: 1px; border-radius: 4px; }
/* 无 JS 兜底:至少选中的那一档及其左边(视觉)会亮 */
.rv-stars.no-js .rv-star:has(input:checked) .st-on,
.rv-stars.no-js .rv-star:has(input:checked) ~ .rv-star .st-on { display: inline; }
.rv-stars.no-js .rv-star:has(input:checked) .st-off,
.rv-stars.no-js .rv-star:has(input:checked) ~ .rv-star .st-off { display: none; }
/* 评价列表里的静态星级展示 */
.stars-disp { display: inline-flex; gap: 1px; font-size: 17px; line-height: 1; vertical-align: -2px; }
.stars-disp .d-on { color: #f5b301; }
.stars-disp .d-off { color: #d3d7de; }
/* ---- 同行观影人选择(v10):chips + 弹窗 + 拼音首字母联想 ---- */
.att-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
.att-chips:empty { display: none; }
.att-chip {
display: inline-flex; align-items: center; gap: 6px; padding: 3px 6px 3px 10px;
border: 1px solid var(--line); border-radius: 999px; background: var(--surface);
font-size: 13px;
} }
.rv-num:hover span { border-color: var(--brand); color: var(--brand); } .att-chip .att-x {
.rv-num input:checked + span { background: var(--brand); border-color: transparent; color: #fff; } border: 0; background: none; color: var(--muted); font-size: 15px;
.rv-num:focus-within span { outline: 2px solid var(--brand); outline-offset: 1px; } line-height: 1; padding: 0 2px; cursor: pointer;
}
.att-chip .att-x:hover { color: #c0392b; }
.att-modal {
position: fixed; inset: 0; z-index: 60; display: flex; align-items: center;
justify-content: center; background: rgba(0, 0, 0, .35); padding: 16px;
}
.att-modal[hidden] { display: none; }
.att-modal-box {
background: var(--surface); border-radius: 12px; box-shadow: 0 12px 40px rgba(0, 0, 0, .2);
width: min(420px, 100%); max-height: 70vh; display: flex; flex-direction: column;
padding: 14px 16px; box-sizing: border-box;
}
.att-modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
.att-close {
border: 0; background: none; font-size: 20px; line-height: 1;
color: var(--muted); cursor: pointer; padding: 2px 6px;
}
.att-modal-box .input { margin-bottom: 8px; }
.att-list { overflow-y: auto; border: 1px solid var(--line); border-radius: 8px; }
.att-item {
display: flex; align-items: center; gap: 8px; padding: 8px 12px; cursor: pointer;
border-bottom: 1px solid var(--line-2); font-size: 14px;
}
.att-item:last-child { border-bottom: 0; }
.att-item:hover { background: var(--line-2); }
.att-item input { accent-color: var(--brand); }
.att-item .att-initials { margin-left: auto; color: var(--muted); font-size: 12px; }
.att-empty { padding: 10px 12px; color: var(--muted); font-size: 13px; }
/* ---- 豆瓣自动补充(v10):片名行 + 下拉候选 + 海报预览 ---- */
.db-title-row { display: flex; gap: 8px; align-items: center; }
.db-title-row .input { flex: 1 1 auto; }
.db-title-row .btn { flex: 0 0 auto; white-space: nowrap; }
.db-suggest {
margin-top: 6px; border: 1px solid var(--line); border-radius: 10px;
background: var(--surface); overflow: hidden; max-height: 300px; overflow-y: auto;
}
.db-suggest[hidden] { display: none; }
.db-item {
display: flex; align-items: center; gap: 10px; width: 100%; padding: 8px 12px;
border: 0; border-bottom: 1px solid var(--line-2); background: none;
text-align: left; cursor: pointer; font: inherit; color: var(--ink);
}
.db-item:last-child { border-bottom: 0; }
.db-item:hover { background: var(--line-2); }
.db-item img { width: 32px; height: 45px; object-fit: cover; border-radius: 4px; background: var(--line-2); flex: 0 0 auto; }
.db-item-tx { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.db-item-tx b { font-size: 14px; }
.db-item-tx small { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.db-poster-preview { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
.db-poster-preview[hidden] { display: none; }
.db-poster-preview img {
width: 60px; height: 90px; object-fit: cover; border-radius: 6px;
border: 1px solid var(--line); background: var(--line-2);
}
/* 详情页英雄区里的豆瓣信息块 */
.db-meta {
display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline;
margin: 8px 0 2px; padding: 8px 12px; border-radius: 10px;
background: var(--line-2); font-size: 13px; color: var(--ink);
}
.db-meta .db-rating { color: #f5b301; font-weight: 600; }
.db-meta .db-rating b { font-size: 16px; }
.db-meta .db-line { display: inline-flex; gap: 6px; align-items: baseline; min-width: 0; }
.db-meta .db-label { color: var(--muted); flex: 0 0 auto; }
.db-meta .db-link { margin-left: auto; color: var(--brand); text-decoration: none; white-space: nowrap; }
.db-meta .db-link:hover { text-decoration: underline; }
.rv-word { font-size: 13px; color: var(--muted); } .rv-word { font-size: 13px; color: var(--muted); }
.rv-word.is-set { color: var(--brand); font-weight: 600; } .rv-word.is-set { color: var(--brand); font-weight: 600; }
.rv-textarea { .rv-textarea {
@@ -1000,8 +1087,9 @@ textarea.input { min-height: 76px; resize: vertical; }
color: #fff; border-radius: 6px; padding: 0 6px; color: #fff; border-radius: 6px; padding: 0 6px;
} }
.rv-time { display: block; font-size: 12px; color: var(--muted); } .rv-time { display: block; font-size: 12px; color: var(--muted); }
.rv-score { flex: 0 0 auto; font-size: 20px; font-weight: 700; color: var(--brand); font-variant-numeric: tabular-nums; } .rv-score { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 5px; }
.rv-score-max { font-size: 12px; font-weight: 500; color: var(--muted); } .rv-score .stars-disp { font-size: 16px; }
.rv-score-max { font-size: 12px; font-weight: 500; color: var(--muted); font-variant-numeric: tabular-nums; }
.rv-del { margin-left: auto; } .rv-del { margin-left: auto; }
.rv-del-btn { .rv-del-btn {
background: none; border: none; cursor: pointer; color: var(--muted); background: none; border: none; cursor: pointer; color: var(--muted);
+133
View File
@@ -16,6 +16,7 @@ use App\Birthday;
use App\Cinema; use App\Cinema;
use App\Crypto; use App\Crypto;
use App\Database; use App\Database;
use App\Douban;
use App\Family; use App\Family;
use App\Kinship; use App\Kinship;
use App\Movie; use App\Movie;
@@ -1437,6 +1438,26 @@ switch ($r) {
// 不能凭它把别人家的成员挂进自己家的观影记录里(会顺着详情页漏人名)。 // 不能凭它把别人家的成员挂进自己家的观影记录里(会顺着详情页漏人名)。
'attendees' => array_map('intval', (array)($_POST['attendees'] ?? [])), 'attendees' => array_map('intval', (array)($_POST['attendees'] ?? [])),
]; ];
// 豆瓣元数据(v10):表单隐藏字段带 JSON,解码后只认白名单键、逐字段限长,
// 防手搓请求往库里塞垃圾。整体一个数组交给模型存 douban_meta。
$doubanMeta = [];
$metaRaw = trim((string)($_POST['douban_meta'] ?? ''));
if ($metaRaw !== '') {
$metaDecoded = json_decode($metaRaw, true);
if (is_array($metaDecoded)) {
foreach (['douban_id', 'douban_url', 'year', 'genre', 'runtime', 'director',
'actors', 'plot', 'rating', 'country', 'alias'] as $mk) {
if (isset($metaDecoded[$mk]) && is_scalar($metaDecoded[$mk])) {
$mv = trim((string)$metaDecoded[$mk]);
if ($mv !== '') {
$doubanMeta[$mk] = mb_substr($mv, 0, 2000, 'UTF-8');
}
}
}
}
}
$d['douban_meta'] = $doubanMeta;
$_familyPeople = Person::map($familyId); $_familyPeople = Person::map($familyId);
$d['attendees'] = array_values(array_filter($d['attendees'], $d['attendees'] = array_values(array_filter($d['attendees'],
static fn($pid) => isset($_familyPeople[$pid]))); static fn($pid) => isset($_familyPeople[$pid])));
@@ -1467,6 +1488,22 @@ switch ($r) {
$d[$slot === 'poster' ? 'poster_key' : 'ticket_key'] = (string)($m[$slot === 'poster' ? 'poster_key' : 'ticket_key'] ?? ''); $d[$slot === 'poster' ? 'poster_key' : 'ticket_key'] = (string)($m[$slot === 'poster' ? 'poster_key' : 'ticket_key'] ?? '');
} }
} }
// 豆瓣抓取的海报(v10):前端抓取成功时把存储键放进了隐藏 poster_key。
// 用户**自己选的文件优先**($_FILES['poster'] 真有文件就不覆盖);
// 键必须是 posters/ 下的本站存储键,编辑时换用新键就顺带删掉旧对象。
$dbPosterKey = trim((string)($_POST['poster_key'] ?? ''));
$posterFileGiven = isset($_FILES['poster']['error']) && !is_array($_FILES['poster']['error'])
&& (int)$_FILES['poster']['error'] === UPLOAD_ERR_OK;
if (!$posterFileGiven && $dbPosterKey !== ''
&& preg_match('#^posters/[A-Za-z0-9._-]+$#', $dbPosterKey)) {
if (($d['poster_key'] ?? '') !== $dbPosterKey) {
$oldPosterKey = $isEdit ? (string)($m['poster_key'] ?? '') : '';
$d['poster_key'] = $dbPosterKey;
if ($oldPosterKey !== '' && $oldPosterKey !== $dbPosterKey) {
\App\Storage\Storage::delete($familyId, $oldPosterKey);
}
}
}
// 现场照片(多选,仅新增表单提供;编辑页在详情页里逐张补/删) // 现场照片(多选,仅新增表单提供;编辑页在详情页里逐张补/删)
if (!$isEdit) { if (!$isEdit) {
$photoFiles = []; $photoFiles = [];
@@ -1570,6 +1607,102 @@ switch ($r) {
redirect('movies'); redirect('movies');
break; break;
// ---------------- 豆瓣自动补充(v10,MovieLog fetch_movie 同源迁移) ----------------
/** 片名联想 / 缩略图代理 / 抓取详情+海报入库。全部回 JSON(thumb 回图片字节)。 */
case 'movies/douban':
$familyId = (int)Auth::familyId();
$act = (string)($_GET['action'] ?? '');
if (!Auth::check()) {
http_response_code(401);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => '未登录或登录已过期,请重新登录后再试'], JSON_UNESCAPED_UNICODE);
break;
}
if ($act === 'suggest') {
header('Content-Type: application/json; charset=utf-8');
$res = Douban::suggest((string)($_GET['q'] ?? ''));
echo json_encode($res, JSON_UNESCAPED_UNICODE);
break;
}
if ($act === 'thumb') {
// 浏览器不能直连豆瓣图片(防盗链),由服务端代取;只读、不落盘
$img = Douban::thumb((string)($_GET['u'] ?? ''));
if ($img === null) {
http_response_code(404);
break;
}
header('Content-Type: ' . $img['mime']);
header('Content-Length: ' . strlen($img['body']));
header('Cache-Control: public, max-age=86400');
echo $img['body'];
break;
}
if ($act !== '') {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['error' => '不支持的 action'], JSON_UNESCAPED_UNICODE);
break;
}
// 默认:抓取详情 + 海报入库(写存储,访客不行)。JSON 错误而非 302,
// 前端才能在会话过期/无权限时给出明确提示。
header('Content-Type: application/json; charset=utf-8');
if (!Auth::canWrite()) {
http_response_code(403);
echo json_encode(['error' => '访客账号没有写权限'], JSON_UNESCAPED_UNICODE);
break;
}
$idDb = trim((string)($_GET['id'] ?? ''));
$qDb = trim((string)($_GET['q'] ?? ''));
if ($idDb !== '') {
$resDb = Douban::fetchById($idDb);
} elseif ($qDb !== '') {
$resDb = Douban::fetchByTitle($qDb);
} else {
$resDb = ['ok' => false, 'error' => '请输入电影名称'];
}
if (!$resDb['ok']) {
echo json_encode(['error' => $resDb['error']], JSON_UNESCAPED_UNICODE);
break;
}
// 海报:下载字节 → poster 槽位管线(裁 2:3、缩放、转 JPEG、Storage 统一出口)
$posterKey = '';
$posterShow = '';
if (($resDb['poster_url'] ?? '') !== '') {
$bytes = Douban::downloadPoster((string)$resDb['poster_url']);
if ($bytes !== '') {
$tmp = tempnam(sys_get_temp_dir(), 'fbdb');
if ($tmp !== false) {
file_put_contents($tmp, $bytes);
$up = Upload::image($familyId, ['error' => UPLOAD_ERR_OK, 'tmp_name' => $tmp], 'poster');
@unlink($tmp);
if ($up['ok']) {
$posterKey = (string)$up['file'];
$posterShow = \App\Storage\Storage::url($familyId, $posterKey);
}
}
}
}
// 清掉上一次抓取但没被采用的海报(每次「自动获取」都下一张,不清就堆孤儿)
$oldPoster = trim((string)($_GET['old_poster'] ?? ''));
if ($oldPoster !== '' && $oldPoster !== $posterKey
&& preg_match('#^posters/[A-Za-z0-9._-]+$#', $oldPoster)) {
$stRef = Database::get()->prepare('SELECT COUNT(*) FROM movie_details WHERE poster_key = ?');
$stRef->execute([$oldPoster]);
if ((int)$stRef->fetchColumn() === 0) {
\App\Storage\Storage::delete($familyId, $oldPoster);
}
}
echo json_encode([
'ok' => true,
'source' => 'douban',
'title' => (string)($resDb['title'] ?? ''),
'meta' => $resDb['meta'],
'poster_key' => $posterKey,
'poster' => $posterShow,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
break;
// ---------------- 影院管理(v9,MovieLog 同款) ---------------- // ---------------- 影院管理(v9,MovieLog 同款) ----------------
/** 影院管理单页:上面加/编表单,下面列表。GET 带参数时进入编辑态。 */ /** 影院管理单页:上面加/编表单,下面列表。GET 带参数时进入编辑态。 */
+10 -5
View File
@@ -5,8 +5,13 @@
* 颜色用「取色器 + 50 色预设板」两路输入(内联小段 JS 只是取色联动, * 颜色用「取色器 + 50 色预设板」两路输入(内联小段 JS 只是取色联动,
* 不依赖 JS 也能手填 hex 或直接用取色器)。删除是 POST 小表单 + confirm; * 不依赖 JS 也能手填 hex 或直接用取色器)。删除是 POST 小表单 + confirm;
* 删掉的影院只把关联观影记录的 cinema_id 置空,记录本身不动。 * 删掉的影院只把关联观影记录的 cinema_id 置空,记录本身不动。
*
* ⚠️ $editing 是路由传进来的「被编辑影院的记录数组」(或 null)。
* 曾经这里写成 `$editing = !empty($editing);` —— 数组被原地变成布尔值,
* 表面看标题还会显示「编辑影院」,但 hidden id 变 0、四个字段全部回填为空,
* 点「编辑」就像没带入一样(v9 线上实测)。布尔化结果必须存进**另一个**变量。
*/ */
$editing = !empty($editing); $isEditing = !empty($editing);
$canWrite = \App\Auth::canWrite(); $canWrite = \App\Auth::canWrite();
?> ?>
<div class="page-head"> <div class="page-head">
@@ -21,10 +26,10 @@ $canWrite = \App\Auth::canWrite();
<div class="card card-pad empty"><b>只读账号</b>访客只能查看影院列表。</div> <div class="card card-pad empty"><b>只读账号</b>访客只能查看影院列表。</div>
<?php else: ?> <?php else: ?>
<div class="card card-pad cinema-form-card"> <div class="card card-pad cinema-form-card">
<h2 class="cinema-h2"><?= $editing ? '编辑影院' : '添加影院' ?></h2> <h2 class="cinema-h2"><?= $isEditing ? '编辑影院' : '添加影院' ?></h2>
<form method="post" action="<?= e(url('movies/cinemas_save')) ?>"> <form method="post" action="<?= e(url('movies/cinemas_save')) ?>">
<?= csrf_field() ?> <?= csrf_field() ?>
<?php if ($editing): ?> <?php if ($isEditing): ?>
<input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"> <input type="hidden" name="id" value="<?= (int)$editing['id'] ?>">
<?php endif; ?> <?php endif; ?>
<div class="form-grid"> <div class="form-grid">
@@ -58,8 +63,8 @@ $canWrite = \App\Auth::canWrite();
</div> </div>
</div> </div>
<div class="btn-row"> <div class="btn-row">
<button type="submit" class="btn"><?= $editing ? '保存' : '添加影院' ?></button> <button type="submit" class="btn"><?= $isEditing ? '保存' : '添加影院' ?></button>
<?php if ($editing): ?> <?php if ($isEditing): ?>
<a class="btn btn-ghost" href="<?= e(url('movies/cinemas')) ?>">取消编辑</a> <a class="btn btn-ghost" href="<?= e(url('movies/cinemas')) ?>">取消编辑</a>
<?php endif; ?> <?php endif; ?>
</div> </div>
+298 -7
View File
@@ -44,7 +44,22 @@ $selAttendees = array_map('intval', (array)old('attendees', $curAttendees));
<div class="form-grid"> <div class="form-grid">
<div class="field full"> <div class="field full">
<label for="title">片名 *</label> <label for="title">片名 *</label>
<input class="input" id="title" name="title" value="<?= e(old('title', $m['title'] ?? '')) ?>" required> <div class="db-title-row">
<input class="input" id="title" name="title" value="<?= e(old('title', $m['title'] ?? '')) ?>"
required autocomplete="off">
<button type="button" class="btn btn-ghost btn-sm" id="dbFetch"
title="按片名从豆瓣抓取片名、简介、海报等">📡 自动获取</button>
</div>
<?php /* v10 豆瓣自动补充:输入片名出下拉候选,点「自动获取」直接抓。
抓到的元数据整体进隐藏 douban_meta(JSON),海报走服务端落盘的 poster_key。 */ ?>
<div class="db-suggest" id="dbSuggest" hidden></div>
<input type="hidden" name="douban_meta" id="dbMeta" value="">
<input type="hidden" name="poster_key" id="dbPosterKey" value="">
<div class="db-poster-preview" id="dbPosterWrap" hidden>
<img id="dbPosterImg" alt="海报预览">
<span class="tip">海报已从豆瓣取回,保存后生效。</span>
</div>
<span class="tip">片名可从豆瓣自动补充:输入后从下拉里选,或点「自动获取」。</span>
<?php if (!empty($errors['title'])): ?><span class="err"><?= e($errors['title']) ?></span><?php endif; ?> <?php if (!empty($errors['title'])): ?><span class="err"><?= e($errors['title']) ?></span><?php endif; ?>
</div> </div>
@@ -80,16 +95,42 @@ $selAttendees = array_map('intval', (array)old('attendees', $curAttendees));
<div class="field full"> <div class="field full">
<label>同行的人</label> <label>同行的人</label>
<?php /* v10:名册人多时 checkbox 网格会拉得很长 —— 改为「chips + 弹窗选择」。
attendees[] 的 checkbox 仍保留(在弹窗列表里,选中即提交),无 JS 时
借 noscript 样式把弹窗平铺成普通勾选列表,提交语义完全不变。 */ ?>
<?php if ($people): ?> <?php if ($people): ?>
<div class="feel-grid"> <div class="att-chips" id="attChips">
<?php foreach ($people as $p): ?> <?php foreach ($people as $p): ?>
<label class="feel-item"> <?php if (in_array((int)$p['id'], $selAttendees, true)): ?>
<input type="checkbox" name="attendees[]" value="<?= (int)$p['id'] ?>" <span class="att-chip" data-id="<?= (int)$p['id'] ?>"><?= e($p['shown'] ?? $p['name']) ?><button type="button" class="att-x" data-id="<?= (int)$p['id'] ?>" title="移除">×</button></span>
<?= in_array((int)$p['id'], $selAttendees, true) ? 'checked' : '' ?>> <?php endif; ?>
<span><?= e($p['shown'] ?? $p['name']) ?></span>
</label>
<?php endforeach; ?> <?php endforeach; ?>
</div> </div>
<button type="button" class="btn btn-ghost btn-sm att-open-btn" id="attOpen">+ 添加观影人</button>
<div class="att-modal" id="attModal" hidden>
<div class="att-modal-box">
<div class="att-modal-head">
<b>选择观影人</b>
<button type="button" class="att-close" id="attClose" title="关闭">×</button>
</div>
<input class="input" id="attSearch" type="text"
placeholder="输入名字或拼音首字母,如 zy 找「张三」" autocomplete="off">
<div class="att-list" id="attList">
<?php foreach ($people as $p): ?>
<label class="att-item"
data-name="<?= e((string)$p['name']) ?>"
data-shown="<?= e((string)($p['shown'] ?? '')) ?>">
<input type="checkbox" name="attendees[]" value="<?= (int)$p['id'] ?>"
<?= in_array((int)$p['id'], $selAttendees, true) ? 'checked' : '' ?>>
<span><?= e($p['shown'] ?? $p['name']) ?></span>
<span class="att-initials" hidden></span>
</label>
<?php endforeach; ?>
<div class="att-empty" hidden>没有匹配的人。</div>
</div>
</div>
</div>
<noscript><style>.att-open-btn { display: none; } .att-modal { position: static; display: block; background: none; padding: 0; } .att-modal-box { box-shadow: none; border: 1px solid var(--line); max-height: none; }</style></noscript>
<?php else: ?> <?php else: ?>
<span class="tip">名册里还没有人,先把家人加进名册再来记。</span> <span class="tip">名册里还没有人,先把家人加进名册再来记。</span>
<?php endif; ?> <?php endif; ?>
@@ -138,3 +179,253 @@ $selAttendees = array_map('intval', (array)old('attendees', $curAttendees));
</div> </div>
</div> </div>
</form> </form>
<?php if ($people): ?>
<!-- 观影人选择弹窗:chips 同步 + 拼音首字母联想(Intl pinyin 排序 + 23 锚字二分,零依赖) -->
<script>
(function () {
var modal = document.getElementById('attModal');
if (!modal) return;
var openBtn = document.getElementById('attOpen');
var closeBtn = document.getElementById('attClose');
var search = document.getElementById('attSearch');
var list = document.getElementById('attList');
var chips = document.getElementById('attChips');
var emptyTip = list.querySelector('.att-empty');
/* ---- 汉字 → 拼音首字母:锚字表 a..z(23 个,无 i/u/v 开头字),
用拼音 collation 做二分定位;不支持的浏览器返回 null(只按名字搜) ---- */
var initialsOf = (function () {
var anchors = '阿八擦搭娥发嘎哈击喀垃妈拿哦啪期然撒塌挖昔压匝';
var letters = 'abcdefghjklmnopqrstwxyz';
var coll;
try { coll = new Intl.Collator('zh-Hans-CN-u-co-pinyin'); } catch (e) { return null; }
if (!coll || coll.compare('阿', '匝') >= 0) return null; // collation 没生效
return function (s) {
var out = '';
for (var i = 0; i < s.length; i++) {
var ch = s[i];
if (/[a-zA-Z]/.test(ch)) { out += ch.toUpperCase(); continue; }
if (ch.charCodeAt(0) < 0x2E80) continue; // 非 CJK:不产字母
var lo = 0, hi = anchors.length - 1, best = -1;
while (lo <= hi) {
var mid = (lo + hi) >> 1;
if (coll.compare(ch, anchors[mid]) >= 0) { best = mid; lo = mid + 1; }
else { hi = mid - 1; }
}
if (best >= 0) out += letters[best];
}
return out;
};
})();
/* 预计算每个人的首字母串,挂在 data-initials 上 */
Array.prototype.forEach.call(list.querySelectorAll('.att-item'), function (el) {
var s = (el.getAttribute('data-name') || '') + (el.getAttribute('data-shown') || '');
var ini = initialsOf ? initialsOf(s) : '';
el.setAttribute('data-initials', ini.toLowerCase());
var badge = el.querySelector('.att-initials');
if (badge && ini) { badge.textContent = ini; badge.hidden = false; }
});
function syncChips() {
if (!chips) return;
chips.innerHTML = '';
Array.prototype.forEach.call(list.querySelectorAll('.att-item input:checked'), function (box) {
var item = box.closest('.att-item');
var label = item.querySelector('span').textContent;
var id = box.value;
var chip = document.createElement('span');
chip.className = 'att-chip';
chip.setAttribute('data-id', id);
chip.textContent = label;
var x = document.createElement('button');
x.type = 'button'; x.className = 'att-x'; x.textContent = '×';
x.title = '移除'; x.setAttribute('data-id', id);
chip.appendChild(x);
chips.appendChild(chip);
});
}
chips.addEventListener('click', function (e) {
var x = e.target.closest ? e.target.closest('.att-x') : null;
if (!x) return;
var id = x.getAttribute('data-id');
Array.prototype.forEach.call(list.querySelectorAll('.att-item input'), function (box) {
if (box.value === id) box.checked = false;
});
syncChips();
});
function applyFilter() {
var q = (search.value || '').trim().toLowerCase();
var shown = 0;
Array.prototype.forEach.call(list.querySelectorAll('.att-item'), function (el) {
var hit = !q ||
(el.getAttribute('data-name') || '').toLowerCase().indexOf(q) >= 0 ||
(el.getAttribute('data-shown') || '').toLowerCase().indexOf(q) >= 0 ||
(el.getAttribute('data-initials') || '').indexOf(q) >= 0;
el.hidden = !hit;
if (hit) shown++;
});
emptyTip.hidden = shown > 0;
}
function openModal() { modal.hidden = false; search.value = ''; applyFilter(); syncChips(); search.focus(); }
function closeModal() { modal.hidden = true; }
openBtn.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !modal.hidden) closeModal();
});
search.addEventListener('input', applyFilter);
/* 选一个 = 勾上 + 出 chips + 关弹窗(再添加就再点一次「+ 添加观影人」);
在弹窗里取消勾选只同步 chips,不关弹窗 */
list.addEventListener('change', function (e) {
if (!e.target || e.target.tagName !== 'INPUT') return;
syncChips();
if (e.target.checked) closeModal();
});
})();
</script>
<!-- 豆瓣自动补充:下拉联想(320ms 防抖 + 中文输入法组字期不请求)+ 一键抓取 -->
<script>
(function () {
var DB_URL = <?= json_encode(url('movies/douban')) ?>;
var titleEl = document.getElementById('title');
var box = document.getElementById('dbSuggest');
var fetchBtn = document.getElementById('dbFetch');
var metaEl = document.getElementById('dbMeta');
var posterKeyEl = document.getElementById('dbPosterKey');
var posterWrap = document.getElementById('dbPosterWrap');
var posterImg = document.getElementById('dbPosterImg');
var infoEl = document.getElementById('info');
if (!titleEl || !box || !fetchBtn || !metaEl) return;
var lastPosterKey = ''; // 本次会话里最近一次抓到的海报键(下次抓取时回传清理)
var timer = null;
var composing = false;
var seq = 0; // 丢弃过期响应
titleEl.addEventListener('compositionstart', function () { composing = true; });
titleEl.addEventListener('compositionend', function () { composing = false; schedule(); });
titleEl.addEventListener('input', function () {
if (composing) return; // 组字期间的拼音串没有意义,也不劫持回车
schedule();
});
document.addEventListener('click', function (e) {
if (!box.hidden && !box.contains(e.target) && e.target !== titleEl) hideBox();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') hideBox();
});
function schedule() {
clearTimeout(timer);
timer = setTimeout(suggest, 320);
}
function hideBox() { box.hidden = true; box.innerHTML = ''; }
function suggest() {
var q = titleEl.value.trim();
if (q === '') { hideBox(); return; }
var my = ++seq;
getJson(DB_URL + '&action=suggest&q=' + encodeURIComponent(q), function (data, err) {
if (my !== seq) return; // 过期响应丢弃
if (err) return; // 联想失败静默(正片抓取会给出明确报错)
renderItems(data && data.items ? data.items : []);
});
}
function renderItems(items) {
box.innerHTML = '';
if (!items.length) { hideBox(); return; }
items.forEach(function (it) {
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'db-item';
if (it.thumb) {
var im = document.createElement('img');
im.src = it.thumb; im.alt = ''; im.loading = 'lazy';
btn.appendChild(im);
}
var tx = document.createElement('span');
tx.className = 'db-item-tx';
var b = document.createElement('b');
// 候选文本来自豆瓣 —— 一律 textContent 插入,绝不拼 innerHTML(豆瓣侧内容可注入脚本)
b.textContent = it.title || '(无片名)';
tx.appendChild(b);
var bits = [];
if (it.sub_title && it.sub_title !== it.title) bits.push(it.sub_title);
if (it.year) bits.push(it.year);
if (it.kind) bits.push(it.kind);
if (bits.length) {
var sm = document.createElement('small');
sm.textContent = bits.join(' · ');
tx.appendChild(sm);
}
btn.appendChild(tx);
btn.addEventListener('click', function () { hideBox(); fetchById(it.id); });
box.appendChild(btn);
});
box.hidden = false;
}
function fetchById(id) {
doFetch(DB_URL + '&id=' + encodeURIComponent(id));
}
fetchBtn.addEventListener('click', function () {
var q = titleEl.value.trim();
if (q === '') { titleEl.focus(); return; }
doFetch(DB_URL + '&q=' + encodeURIComponent(q));
});
function doFetch(urlWithQ) {
if (lastPosterKey) urlWithQ += '&old_poster=' + encodeURIComponent(lastPosterKey);
fetchBtn.disabled = true;
var my = ++seq;
getJson(urlWithQ, function (data, err) {
fetchBtn.disabled = false;
if (my !== seq) return;
if (err || !data) { alert(err || '抓取失败,请稍后再试'); return; }
if (data.error) { alert(data.error); return; }
apply(data);
});
}
function apply(data) {
if (data.title) titleEl.value = data.title;
if (data.meta) {
metaEl.value = JSON.stringify(data.meta);
// 剧情简介填进「简介」,但只填空白的 —— 用户已经写了就不覆盖
if (infoEl && data.meta.plot && infoEl.value.trim() === '') infoEl.value = data.meta.plot;
}
if (data.poster_key) {
lastPosterKey = data.poster_key;
posterKeyEl.value = data.poster_key;
if (data.poster) {
posterImg.src = data.poster;
posterWrap.hidden = false;
}
}
}
function getJson(u, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', u, true);
xhr.onload = function () {
var data = null, err = '';
try { data = JSON.parse(xhr.responseText); }
catch (e) { err = '返回内容异常'; }
if (xhr.status >= 400) err = (data && data.error) ? data.error : ('请求失败(' + xhr.status + ')');
cb(data, err);
};
xhr.onerror = function () { cb(null, '网络异常'); };
xhr.send();
}
})();
</script>
<?php endif; ?>
+72 -9
View File
@@ -10,6 +10,14 @@
$canWrite = \App\Auth::canWrite(); $canWrite = \App\Auth::canWrite();
$hasPoster = !empty($m['poster_key']); $hasPoster = !empty($m['poster_key']);
$hasTicket = !empty($m['ticket_key']); $hasTicket = !empty($m['ticket_key']);
// 豆瓣元数据(v10):整体 JSON 存 douban_meta,随用随解;解不开就当没有
$doubanMeta = [];
if (!empty($m['douban_meta'])) {
$decoded = json_decode((string)$m['douban_meta'], true);
if (is_array($decoded)) {
$doubanMeta = $decoded;
}
}
$watchTxt = \App\Movie::formatWatch($m['starts_at'], $m['ends_at'] ?? null); $watchTxt = \App\Movie::formatWatch($m['starts_at'], $m['ends_at'] ?? null);
$fmtNum = static function ($v): string { $fmtNum = static function ($v): string {
if ($v === null) { if ($v === null) {
@@ -57,6 +65,16 @@ $feelTags = static function (array $keys) use ($feelCat) {
<?php return ob_get_clean(); <?php return ob_get_clean();
}; };
/** 静态 10 星展示(v10):左 n 颗实心金黄,其余空心灰;n 越界按 0/10 兜底 */
$starsHtml = static function (int $n): string {
$n = max(0, min(10, $n));
$out = '<span class="stars-disp" aria-hidden="true">';
for ($i = 1; $i <= 10; $i++) {
$out .= '<span class="' . ($i <= $n ? 'd-on' : 'd-off') . '">' . ($i <= $n ? '★' : '☆') . '</span>';
}
return $out . '</span>';
};
/** 我的评价表单(打分 + 正文 + 感受),details 按需展开;写评价与修改共用这一份 */ /** 我的评价表单(打分 + 正文 + 感受),details 按需展开;写评价与修改共用这一份 */
$rvForm = static function (string $summary, bool $open) use ($m, $myReview, $feelPick, $rvError) { $rvForm = static function (string $summary, bool $open) use ($m, $myReview, $feelPick, $rvError) {
ob_start(); ?> ob_start(); ?>
@@ -67,12 +85,14 @@ $rvForm = static function (string $summary, bool $open) use ($m, $myReview, $fee
<input type="hidden" name="id" value="<?= (int)$m['id'] ?>"> <input type="hidden" name="id" value="<?= (int)$m['id'] ?>">
<div class="rv-rating-row"> <div class="rv-rating-row">
<span class="rv-rating-label">我的评分</span> <span class="rv-rating-label">我的评分</span>
<span class="rv-scale" role="radiogroup" aria-label="评分,1 分到 10 分"> <?php /* v10:10 星制。DOM 倒序(10..1)+ CSS row-reverse,视觉 1..10 从左到右;
点亮由 JS 加 .lit(含悬停预览), radios 保持 name="rating" 原语义。 */ ?>
<span class="rv-scale rv-stars no-js" role="radiogroup" aria-label="评分,1 分到 10 分">
<?php $myRating = (int)($myReview['rating'] ?? 0); ?> <?php $myRating = (int)($myReview['rating'] ?? 0); ?>
<?php for ($i = 1; $i <= 10; $i++): ?> <?php for ($i = 10; $i >= 1; $i--): ?>
<label class="rv-num" title="<?= $i ?> 分"> <label class="rv-star" data-v="<?= $i ?>" title="<?= $i ?> 分 · <?= e(\App\MovieReview::ratingWord($i)) ?>">
<input type="radio" name="rating" value="<?= $i ?>"<?= $myRating === $i ? ' checked' : '' ?>> <input type="radio" name="rating" value="<?= $i ?>"<?= $myRating === $i ? ' checked' : '' ?>>
<span><?= $i ?></span> <span class="st-glyph st-off" aria-hidden="true">☆</span><span class="st-glyph st-on" aria-hidden="true">★</span>
</label> </label>
<?php endfor; ?> <?php endfor; ?>
</span> </span>
@@ -157,6 +177,30 @@ $commentBox = static function (int $reviewId, int $parentId, string $summary) us
<?php endif; ?> <?php endif; ?>
<span>👥 观影人 <?= count($m['attendees']) ?> 人</span> <span>👥 观影人 <?= count($m['attendees']) ?> 人</span>
</div> </div>
<?php if ($doubanMeta): ?>
<div class="db-meta">
<?php if (!empty($doubanMeta['rating'])): ?>
<span class="db-rating" title="豆瓣评分">豆瓣 <b><?= e((string)$doubanMeta['rating']) ?></b></span>
<?php endif; ?>
<?php foreach ([
'年份' => (string)($doubanMeta['year'] ?? ''),
'类型' => (string)($doubanMeta['genre'] ?? ''),
'片长' => (string)($doubanMeta['runtime'] ?? ''),
'导演' => (string)($doubanMeta['director'] ?? ''),
'主演' => (string)($doubanMeta['actors'] ?? ''),
'制片国家/地区' => (string)($doubanMeta['country'] ?? ''),
'又名' => (string)($doubanMeta['alias'] ?? ''),
] as $dbLbl => $dbVal): ?>
<?php if ($dbVal !== ''): ?>
<span class="db-line"><span class="db-label"><?= $dbLbl ?></span><?= e($dbVal) ?></span>
<?php endif; ?>
<?php endforeach; ?>
<?php if (!empty($doubanMeta['douban_url'])): ?>
<a class="db-link" href="<?= e((string)$doubanMeta['douban_url']) ?>"
target="_blank" rel="noopener noreferrer">在豆瓣查看 ↗</a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if (!empty($m['info'])): ?> <?php if (!empty($m['info'])): ?>
<div class="info-text"><?= nl2br(e($m['info'])) ?></div> <div class="info-text"><?= nl2br(e($m['info'])) ?></div>
<?php endif; ?> <?php endif; ?>
@@ -277,7 +321,7 @@ $commentBox = static function (int $reviewId, int $parentId, string $summary) us
<?php if ($rvMine): ?><span class="rv-mine">我</span><?php endif; ?> <?php if ($rvMine): ?><span class="rv-mine">我</span><?php endif; ?>
<span class="rv-time"><?= e(substr((string)$rv['created_at'], 0, 16)) ?></span> <span class="rv-time"><?= e(substr((string)$rv['created_at'], 0, 16)) ?></span>
</span> </span>
<span class="rv-score" title="<?= e(\App\MovieReview::ratingWord($rvRate)) ?>"><?= $rvRate ?><span class="rv-score-max">/10</span></span> <span class="rv-score" title="<?= e(\App\MovieReview::ratingWord($rvRate)) ?>"><?= $starsHtml($rvRate) ?><span class="rv-score-max"><?= $rvRate ?>/10</span></span>
<?php if ($rvMine && $canWrite): ?> <?php if ($rvMine && $canWrite): ?>
<form method="post" action="<?= e(url('movies/review_del')) ?>" class="rv-del" <form method="post" action="<?= e(url('movies/review_del')) ?>" class="rv-del"
onsubmit="return confirm('删除我的这条评价?下面的评论也会一起删除,不可恢复。')"> onsubmit="return confirm('删除我的这条评价?下面的评论也会一起删除,不可恢复。')">
@@ -466,23 +510,42 @@ $commentBox = static function (int $reviewId, int $parentId, string $summary) us
<?php endif; ?> <?php endif; ?>
<?php if ($canWrite): ?> <?php if ($canWrite): ?>
<!-- 打分实时提示「几分 · 怎么样」;纯增强,radio 没 JS 也能选 --> <!-- 打分:星星点亮 + 悬停预览 + 实时提示「几分 · 怎么样」;radio 没 JS 也能选(:has 兜底点亮) -->
<script> <script>
(function () { (function () {
var form = document.getElementById('reviewForm'); var form = document.getElementById('reviewForm');
var word = document.getElementById('rvWord'); var word = document.getElementById('rvWord');
if (!form || !word) return; if (!form || !word) return;
var scale = form.querySelector('.rv-stars');
if (scale) scale.classList.remove('no-js');
var WORDS = <?= json_encode(\App\MovieReview::ratingWords(), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>; var WORDS = <?= json_encode(\App\MovieReview::ratingWords(), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
function sync() { function pickedV() {
var picked = form.querySelector('input[name="rating"]:checked'); var picked = form.querySelector('input[name="rating"]:checked');
if (!picked) { word.textContent = '未评分'; word.classList.remove('is-set'); return; } return picked ? parseInt(picked.value, 10) : 0;
var v = parseInt(picked.value, 10); }
function paint(v) {
if (!scale) return;
Array.prototype.forEach.call(scale.querySelectorAll('.rv-star'), function (el) {
el.classList.toggle('lit', parseInt(el.getAttribute('data-v'), 10) <= v);
});
}
function sync() {
var v = pickedV();
if (!v) { word.textContent = '未评分'; word.classList.remove('is-set'); paint(0); return; }
word.textContent = v + ' 分 · ' + (WORDS[v - 1] || ''); word.textContent = v + ' 分 · ' + (WORDS[v - 1] || '');
word.classList.add('is-set'); word.classList.add('is-set');
paint(v);
} }
Array.prototype.forEach.call(form.querySelectorAll('input[name="rating"]'), function (el) { Array.prototype.forEach.call(form.querySelectorAll('input[name="rating"]'), function (el) {
el.addEventListener('change', sync); el.addEventListener('change', sync);
}); });
if (scale) {
scale.addEventListener('mouseover', function (e) {
var lab = e.target.closest ? e.target.closest('.rv-star') : null;
if (lab) paint(parseInt(lab.getAttribute('data-v'), 10));
});
scale.addEventListener('mouseleave', function () { paint(pickedV()); });
}
sync(); sync();
})(); })();
</script> </script>