Files
NiceQuote/Renderer.php

633 lines
17 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* NiceQuote 前端引用插件 - 渲染组件
*
* @package NiceQuote
* @author 石头厝
*/
namespace TypechoPlugin\NiceQuote;
use Typecho\Common;
use Typecho\Date;
use Utils\Helper;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
require_once __DIR__ . '/Remote.php';
/**
* 引用卡片的数据组装与渲染
*
* 内嵌模式与 iframe 模式共用同一套 HTML,保证两种方式外观一致。
*
* 站内引用(文章 / 页面 / 评论 / 用户 / 分类 / 标签)与外部链接引用({url-…})
* 均为「标题 + 摘要 + 日期」三行卡片,不显示左侧缩略图。
*
* @package NiceQuote
*/
class Renderer
{
/** 同一请求内复用,一页多次引用同一对象时不重复查库 */
private static array $pool = [];
/** 当前请求的摘要字数 */
private static int $len = 120;
/** 正在取数:此时不要触发正文过滤器 */
private static int $busy = 0;
/**
* 是否正在读取被引用内容
*
* @return bool
*/
public static function busy(): bool
{
return self::$busy > 0;
}
/**
* 渲染一张卡片
*
* @param string $type post|page|comment|user|meta|category|tag|url
* @param int $id
* @param array $options Plugin::options()
* @param string $url 外部链接引用时的网址
* @return string
*/
public static function render(string $type, int $id, array $options, string $url = ''): string
{
self::prepare($options);
if ('url' === strtolower($type)) {
return self::build(self::loadUrl($url), $options);
}
$data = self::load($type, $id);
if (null === $data) {
return '<span class="nq-missing">' . self::e($options['fail'] ?? '引用内容不存在') . '</span>';
}
return self::build($data, $options);
}
/**
* 渲染一张外部链接卡片
*
* @param string $url
* @param array $options
* @return string
*/
public static function renderUrl(string $url, array $options): string
{
self::prepare($options);
return self::build(self::loadUrl($url), $options);
}
/**
* 记录本次渲染使用的选项
*
* @param array $options
* @return void
*/
private static function prepare(array $options): void
{
self::$len = max(20, min(400, (int) ($options['len'] ?? 120)));
}
/**
* Feed 用的纯链接
*
* @param string $type
* @param int $id
* @param string $url 外部链接引用时的网址
* @return string|null
*/
public static function plain(string $type, int $id, string $url = ''): ?string
{
$data = 'url' === strtolower($type) ? self::loadUrl($url) : self::load($type, $id);
if (null === $data) {
return null;
}
if ('' === $data['url']) {
return self::e($data['title']);
}
return '<a href="' . self::e($data['url']) . '" rel="noopener">' . self::e($data['title']) . '</a>';
}
/**
* 取数并归一化
*
* @param string $type
* @param int $id
* @return array|null
*/
private static function load(string $type, int $id): ?array
{
// page / category / tag 只是 post / meta 的细分,渲染逻辑完全一致
$type = Plugin::base($type);
$key = $type . ':' . $id;
if (array_key_exists($key, self::$pool)) {
return self::$pool[$key];
}
self::$pool[$key] = null;
self::$busy++;
try {
$data = self::fetch($type, $id);
} catch (\Throwable $e) {
$data = null;
} finally {
self::$busy--;
}
return self::$pool[$key] = $data;
}
/**
* 外部链接:抓一次标题摘要,抓不到就用网址兜底
*
* @param string $url
* @return array
*/
private static function loadUrl(string $url): array
{
$url = trim($url);
$key = 'url:' . $url;
if (isset(self::$pool[$key])) {
return self::$pool[$key];
}
$meta = null;
if ('' !== $url) {
self::$busy++;
try {
$meta = Remote::meta($url);
} catch (\Throwable $e) {
$meta = null;
} finally {
self::$busy--;
}
}
$title = trim((string) ($meta['title'] ?? ''));
$date = trim((string) ($meta['date'] ?? ''));
$data = [
'type' => 'url',
'id' => 0,
'url' => '' === $url ? '' : (string) ($meta['url'] ?? $url),
'title' => '' === $title ? $url : $title,
'desc' => self::plainText((string) ($meta['desc'] ?? ''), self::$len),
'meta' => '' === $date ? date('Y-m-d') : $date,
];
return self::$pool[$key] = $data;
}
/**
* 按类型取数据
*
* @param string $type
* @param int $id
* @return array|null
*/
private static function fetch(string $type, int $id): ?array
{
if (!isset(Plugin::TYPES[$type])) {
return null;
}
$widget = Helper::widgetById(Plugin::TYPES[$type], $id);
if (null === $widget) {
return null;
}
switch ($type) {
case 'post':
return self::fromPost($widget, $id);
case 'comment':
return self::fromComment($widget, $id);
case 'user':
return self::fromUser($widget, $id);
case 'meta':
return self::fromMeta($widget, $id);
}
return null;
}
/**
* 文章 / 独立页面
*
* @param mixed $w
* @param int $id
* @return array|null
*/
private static function fromPost($w, int $id): ?array
{
if (empty($w->cid) || !in_array($w->type, ['post', 'page'], true)) {
return null;
}
// 草稿、待审、私密一律不对外展示
if ('publish' !== $w->status) {
return null;
}
$locked = !empty($w->password);
$meta = [];
if ('page' === $w->type) {
$meta[] = _t('页面');
} else {
$meta[] = self::dateStr($w);
}
$categories = $w->categories;
if (!empty($categories) && isset($categories[0]['name'])) {
$meta[] = (string) $categories[0]['name'];
}
$comments = (int) $w->commentsNum;
if ($comments > 0) {
$meta[] = _t('%d 条评论', $comments);
}
return [
'type' => 'page' === $w->type ? 'page' : 'post',
'id' => $id,
'url' => (string) $w->permalink,
'title' => (string) $w->title,
'desc' => $locked ? _t('该内容已加密,暂时无法显示摘要') : self::summary($w, self::$len),
'meta' => implode(' · ', array_filter($meta)),
'thumb' => self::thumb($w),
'icon' => false,
];
}
/**
* 评论
*
* @param mixed $w
* @param int $id
* @return array|null
*/
private static function fromComment($w, int $id): ?array
{
if (empty($w->coid) || 'approved' !== $w->status) {
return null;
}
$author = trim((string) $w->author);
$author = '' === $author ? _t('匿名用户') : $author;
return [
'type' => 'comment',
'id' => $id,
'url' => (string) $w->permalink,
'title' => _t('%s 的评论', $author),
'desc' => self::plainText((string) $w->content, self::$len),
'meta' => self::dateStr($w) . ' · ' . _t('评论'),
'thumb' => self::avatar((string) $w->mail),
'icon' => false,
];
}
/**
* 用户
*
* @param mixed $w
* @param int $id
* @return array|null
*/
private static function fromUser($w, int $id): ?array
{
if (empty($w->uid)) {
return null;
}
$name = trim((string) ($w->screenName ?: $w->name));
$meta = [];
$created = (int) $w->created;
if ($created > 0) {
$meta[] = _t('加入于 %s', (new Date($created))->format('Y-m-d'));
}
if ((int) $w->logged > 0) {
$meta[] = _t('最后登录 %s', (new Date((int) $w->logged))->format('Y-m-d'));
}
$url = trim((string) $w->url);
$desc = self::groupLabel((string) $w->group);
if ('' !== $url) {
$desc .= ($desc === '' ? '' : ' · ') . $url;
}
return [
'type' => 'user',
'id' => $id,
// 用户卡片不做跳转,是全站唯一一个不可点的引用类型
'url' => '',
'title' => '' === $name ? _t('未命名用户') : $name,
'desc' => $desc,
'meta' => implode(' · ', $meta),
'thumb' => self::avatar((string) $w->mail),
'icon' => false,
];
}
/**
* 分类 / 标签
*
* @param mixed $w
* @param int $id
* @return array|null
*/
private static function fromMeta($w, int $id): ?array
{
if (empty($w->mid)) {
return null;
}
$isTag = 'tag' === $w->type;
$icon = Helper::options()->pluginUrl . '/NiceQuote/img/' . ($isTag ? 'tag.svg' : 'cate.svg');
$description = trim((string) $w->description);
return [
'type' => 'meta',
'id' => $id,
'url' => (string) $w->permalink,
'title' => (string) $w->name,
'desc' => '' === $description ? '' : self::plainText($description, self::$len),
'meta' => ($isTag ? _t('标签') : _t('分类')) . ' · ' . _t('%d 篇内容', (int) $w->count),
'thumb' => $icon,
'icon' => true,
];
}
/**
* 拼装卡片 HTML
*
* 卡片为「标题 + 摘要 + 日期」三行结构,不显示左侧缩略图。
*
* @param array $d
* @param array $options
* @return string
*/
private static function build(array $d, array $options): string
{
$skin = in_array($options['skin'] ?? 'auto', ['dark', 'light'], true)
? ' nq-skin-' . $options['skin']
: '';
$hasUrl = '' !== $d['url'];
$tag = $hasUrl ? 'a' : 'div';
$attr = '';
if ($hasUrl) {
// 引用卡片一律新窗口打开;用户卡片没有跳转地址,所以还是 div
$attr = ' href="' . self::e($d['url']) . '"'
. ' target="_blank" rel="noopener noreferrer"';
}
$html = '<' . $tag . ' class="nq-card nq-' . $d['type'] . $skin . '"'
. ' data-nq="' . $d['type'] . '-' . $d['id'] . '"' . $attr . '>';
$html .= '<span class="nq-body">'
. '<span class="nq-title">' . self::e($d['title']) . '</span>';
if ('' !== $d['desc']) {
$html .= '<span class="nq-desc">' . self::e($d['desc']) . '</span>';
}
if ('' !== $d['meta']) {
$html .= '<span class="nq-meta">' . self::e($d['meta']) . '</span>';
}
return $html . '</span></' . $tag . '>';
}
/**
* 文章缩略图:自定义字段 → Thumb 插件缓存 → 正文首图 → 默认图
*
* @param mixed $w
* @return string
*/
private static function thumb($w): string
{
$options = Helper::options();
$default = $options->pluginUrl . '/NiceQuote/img/none.webp';
$custom = trim((string) $w->fields->thumb);
if ('' === $custom) {
$custom = trim((string) $w->fields->img);
}
if ('' !== $custom) {
return self::suffix(self::url($custom), $default);
}
// 兼容 Thumb 插件生成的本地缩略图
$name = md5((string) $w->cid);
$dir = __TYPECHO_ROOT_DIR__ . __TYPECHO_PLUGIN_DIR__ . '/Thumb/uploads/';
foreach ([$name . '.webp', $name . '.jpg'] as $file) {
if (is_file($dir . $file)) {
return Common::url(
__TYPECHO_PLUGIN_DIR__ . '/Thumb/uploads/' . $file . '?' . filemtime($dir . $file),
$options->rootUrl
);
}
}
// 正文首图(Markdown 已被渲染成 <img>)
$content = (string) $w->content;
if ('' !== $content && preg_match_all('#<img\b[^>]*\ssrc=["\']([^"\']+)["\']#i', $content, $matches)) {
foreach ($matches[1] as $src) {
if (preg_match('#(icon|avatar|logo|alipay|wechat|qrcode|emoji|smiley)#i', $src)) {
continue;
}
return self::suffix(self::url(html_entity_decode($src, ENT_QUOTES, 'UTF-8')), $default);
}
}
return $default;
}
/**
* 追加主题配置的图片后缀(如又拍云缩略参数)
*
* @param string $img
* @param string $default
* @return string
*/
private static function suffix(string $img, string $default): string
{
if ('' === $img || $img === $default) {
return $default;
}
$suffix = (string) Helper::options()->thumbnail;
return $img . $suffix;
}
/**
* 相对地址补全
*
* @param string $path
* @return string
*/
private static function url(string $path): string
{
$path = trim($path);
if ('' === $path) {
return '';
}
if (preg_match('#^(https?:)?//#i', $path) || 0 === strpos($path, 'data:')) {
return $path;
}
return Common::url($path, Helper::options()->siteUrl);
}
/**
* 头像
*
* @param string $mail
* @return string
*/
private static function avatar(string $mail): string
{
$prefix = defined('__TYPECHO_GRAVATAR_PREFIX__')
? __TYPECHO_GRAVATAR_PREFIX__
: 'https://cravatar.cn/avatar/';
$mail = strtolower(trim($mail));
if ('' === $mail) {
return Helper::options()->pluginUrl . '/NiceQuote/img/none.webp';
}
return $prefix . md5($mail) . '?s=128&d=mm&r=g';
}
/**
* 文章摘要:优先副标题,其次正文纯文本
*
* @param mixed $w
* @param int $len
* @return string
*/
private static function summary($w, int $len): string
{
$subtitle = trim((string) $w->fields->subtitle);
if ('' !== $subtitle) {
return self::plainText($subtitle, $len);
}
return self::plainText((string) $w->content, $len);
}
/**
* HTML → 截断的纯文本
*
* @param string $html
* @param int $len
* @return string
*/
private static function plainText(string $html, int $len): string
{
$text = preg_replace('#<(script|style)\b[^>]*>.*?</\1>#is', ' ', $html) ?? $html;
// 去掉未解析的短码/自定义块,避免卡片里出现 {video} 之类
$text = preg_replace('#\{[^{}]{0,80}\}#', ' ', $text) ?? $text;
$text = strip_tags($text);
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
$text = trim(preg_replace('/\s+/u', ' ', $text) ?? $text);
if ('' === $text) {
return '';
}
return Common::subStr($text, 0, max(20, $len), '…');
}
/**
* 用户组名称
*
* @param string $group
* @return string
*/
private static function groupLabel(string $group): string
{
$map = [
'administrator' => _t('管理员'),
'editor' => _t('编辑'),
'contributor' => _t('贡献者'),
'subscriber' => _t('关注者'),
'visitor' => _t('访问者'),
];
return $map[$group] ?? $group;
}
/**
* 日期
*
* @param mixed $w
* @param string $format
* @return string
*/
private static function dateStr($w, string $format = 'Y-m-d'): string
{
try {
$date = $w->date;
if ($date instanceof Date) {
return $date->format($format);
}
} catch (\Throwable $e) {
}
$created = (int) $w->created;
return $created > 0 ? (new Date($created))->format($format) : '';
}
/**
* HTML 转义
*
* @param string $value
* @return string
*/
private static function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
}