Files
NiceQuote/Scanner.php

506 lines
16 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\Db;
use Utils\Helper;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
/**
* 引用记录扫描器
*
* 后台「引用管理」不额外建表:正文里的短码就是唯一事实来源。
* 建一张索引表看着快,但用户在正文里手动改一个字符就会和真实内容对不上,
* 而引用数量对一个博客来说还远没到需要索引的规模,扫一遍最省心也最不会骗人。
*
* 扫描、批量补标题、统计、改写正文,都在这里完成。
*
* @package NiceQuote
*/
class Scanner
{
/** 细分类型 → 数据表(与 Plugin::TYPES 对应) */
private const TABLE = [
'post' => 'contents',
'page' => 'contents',
'comment' => 'comments',
'user' => 'users',
'meta' => 'metas',
'category' => 'metas',
'tag' => 'metas',
];
/** 类型中文名 */
public const LABEL = [
'post' => '文章',
'page' => '页面',
'comment' => '评论',
'user' => '用户',
'meta' => '分类/标签',
'category' => '分类',
'tag' => '标签',
'url' => '外部',
];
/**
* 筛选下拉里给出的类型
*
* meta 是 1.x 的合并写法,只用于兜底解析老短码,不再单独摆一个筛选项,
* 否则「分类/标签」和「分类」「标签」会同时出现,看着就重复。
*/
public const FILTER = ['post', 'page', 'comment', 'user', 'category', 'tag', 'url'];
/** 前台链接缓存:同一对象只取一次 */
private static array $links = [];
/**
* 扫描所有文章与独立页面里的引用
*
* @return array<int, array<string, mixed>>
*/
public static function rows(): array
{
try {
$db = Db::get();
$contents = $db->fetchAll(
$db->select('cid', 'authorId', 'title', 'type', 'status', 'created', 'modified', 'text')
->from('table.contents')
->where('type IN ?', ['post', 'page'])
->order('created', Db::SORT_DESC)
);
} catch (\Throwable $e) {
return [];
}
$authors = self::authors();
$rows = [];
foreach ($contents as $content) {
$matches = Plugin::matches((string) $content['text']);
if (empty($matches)) {
continue;
}
$uid = (int) $content['authorId'];
$seq = 0;
foreach ($matches as $match) {
$rows[] = [
'cid' => (int) $content['cid'],
'host' => (string) $content['title'],
'host_type' => (string) $content['type'],
'host_status' => (string) $content['status'],
'uid' => $uid,
'author' => $authors[$uid] ?? ('#' . $uid),
'created' => (int) $content['created'],
'modified' => (int) $content['modified'],
'seq' => ++$seq,
'offset' => (int) $match['offset'],
'raw' => (string) $match['raw'],
'type' => (string) $match['type'],
'ref_id' => (int) $match['id'],
'ref_url' => (string) ($match['url'] ?? ''),
'ref_title' => '',
'ref_kind' => (string) $match['type'],
'ref_exists' => false,
];
}
}
return $rows;
}
/**
* 批量补全被引用对象的标题与有效性
*
* 每种表只查一次,不逐条调 widgetById,几百条引用也不会变成几百次查询。
*
* @param array $rows
* @return array 与入参同序,已填充 ref_title / ref_kind / ref_exists
*/
public static function resolve(array $rows): array
{
if (empty($rows)) {
return $rows;
}
$want = ['contents' => [], 'comments' => [], 'users' => [], 'metas' => []];
foreach ($rows as $row) {
$table = self::TABLE[$row['type']] ?? '';
if (isset($want[$table])) {
$want[$table][$row['ref_id']] = true;
}
}
$index = [
'contents' => self::fetchMap('contents', 'cid', ['cid', 'title', 'type', 'status'], $want['contents']),
'comments' => self::fetchMap('comments', 'coid', ['coid', 'author', 'text', 'status'], $want['comments']),
'users' => self::fetchMap('users', 'uid', ['uid', 'name', 'screenName'], $want['users']),
'metas' => self::fetchMap('metas', 'mid', ['mid', 'name', 'type'], $want['metas']),
];
foreach ($rows as $i => $row) {
// 外部链接没有本地记录可查,网址本身就是事实
if ('url' === ($row['type'] ?? '')) {
$rows[$i]['ref_title'] = (string) $row['ref_url'];
$rows[$i]['ref_kind'] = 'url';
$rows[$i]['ref_exists'] = true;
continue;
}
$table = self::TABLE[$row['type']] ?? '';
$item = $index[$table][$row['ref_id']] ?? null;
if (null === $item) {
$rows[$i]['ref_title'] = '#' . $row['ref_id'];
$rows[$i]['ref_exists'] = false;
continue;
}
switch ($table) {
case 'contents':
$rows[$i]['ref_title'] = (string) $item['title'];
$rows[$i]['ref_kind'] = 'page' === $item['type'] ? 'page' : 'post';
$rows[$i]['ref_exists'] = 'publish' === $item['status'];
break;
case 'comments':
$author = trim((string) $item['author']);
$rows[$i]['ref_title'] = \Typecho\Common::subStr(
trim(strip_tags((string) $item['text'])),
0,
32,
'…'
);
$rows[$i]['ref_kind'] = 'comment';
$rows[$i]['ref_exists'] = 'approved' === $item['status'];
$rows[$i]['author_ref'] = '' === $author ? '匿名' : $author;
break;
case 'users':
$name = trim((string) ($item['screenName'] ?: $item['name']));
$rows[$i]['ref_title'] = '' === $name ? '#' . $row['ref_id'] : $name;
$rows[$i]['ref_kind'] = 'user';
$rows[$i]['ref_exists'] = true;
break;
case 'metas':
$rows[$i]['ref_title'] = (string) $item['name'];
$rows[$i]['ref_kind'] = 'tag' === $item['type'] ? 'tag' : 'category';
$rows[$i]['ref_exists'] = true;
break;
}
}
return $rows;
}
/**
* 给每行补上前台地址
*
* 引用管理里两个位置都要能点开看:
* 引用位置 → 写了引用的那篇文章 / 页面
* 被引用内容 → 被引用的文章、独立页面、评论、分类、标签各自的前台页面
*
* 只对当前这一页的几十行做,别拿全站引用去逐个取 widget。
*
* @param array $rows
* @return array
*/
public static function links(array $rows): array
{
foreach ($rows as $i => $row) {
$rows[$i]['host_url'] = self::permalink('contents', (int) $row['cid']);
$rows[$i]['ref_link'] = '';
if ('url' === ($row['type'] ?? '')) {
// 外部链接本身就是地址,直接开新窗口过去
$rows[$i]['ref_link'] = (string) $row['ref_url'];
continue;
}
if (empty($row['ref_exists'])) {
continue;
}
$table = self::TABLE[$row['type']] ?? '';
// 用户没有前台页面,只能显示名字
if ('users' === $table) {
continue;
}
$rows[$i]['ref_link'] = self::permalink($table, (int) $row['ref_id']);
}
return $rows;
}
/**
* 取某个对象的前台永久链接
*
* @param string $table contents|comments|metas
* @param int $id
* @return string
*/
private static function permalink(string $table, int $id): string
{
if ($id <= 0) {
return '';
}
$key = $table . ':' . $id;
if (array_key_exists($key, self::$links)) {
return self::$links[$key];
}
self::$links[$key] = '';
$widget = ['contents' => 'Contents', 'comments' => 'Comments', 'metas' => 'Metas'][$table] ?? '';
if ('' === $widget) {
return '';
}
try {
$item = Helper::widgetById($widget, $id);
if (null !== $item) {
self::$links[$key] = trim((string) $item->permalink);
}
} catch (\Throwable $e) {
self::$links[$key] = '';
}
return self::$links[$key];
}
/**
* 统计
*
* @param array $rows
* @return array
*/
public static function stats(array $rows): array
{
$total = count($rows);
$hosts = [];
$targets = [];
$missing = 0;
$byKind = [];
$byMonth = [];
foreach ($rows as $row) {
$hosts[$row['cid']] = true;
// 外部链接的 id 都是 0,只能拿网址当唯一键
$key = 'url' === $row['type']
? 'url:' . $row['ref_url']
: $row['type'] . ':' . $row['ref_id'];
$kind = $row['ref_kind'] ?: $row['type'];
$byKind[$kind] = ($byKind[$kind] ?? 0) + 1;
if (!$row['ref_exists']) {
$missing++;
continue;
}
if (!isset($targets[$key])) {
$targets[$key] = [
'key' => $key,
'title' => $row['ref_title'],
'kind' => $kind,
'count' => 0,
];
}
$targets[$key]['count']++;
}
usort($targets, function (array $a, array $b) {
return $b['count'] <=> $a['count'];
});
arsort($byKind);
return [
'total' => $total,
'hosts' => count($hosts),
'targets' => count($targets),
'missing' => $missing,
'byKind' => $byKind,
'top' => array_slice($targets, 0, 5),
'uniqueOk' => count($targets),
];
}
/**
* 批量改写某篇正文里的引用
*
* 每条改动都带 byte 偏移和原始短码:偏移处的内容对不上就跳过,
* 避免用户在别的窗口改过正文之后,这里按旧偏移删错东西。
*
* @param int $cid
* @param array $edits [['offset' => int, 'raw' => string, 'to' => string|null], ...]
* @return array{ok: bool, changed: int, skipped: int, error: string}
*/
public static function edit(int $cid, array $edits): array
{
$result = ['ok' => false, 'changed' => 0, 'skipped' => 0, 'error' => ''];
if ($cid <= 0 || empty($edits)) {
$result['error'] = '参数不完整';
return $result;
}
try {
$db = Db::get();
$row = $db->fetchRow(
$db->select('text')->from('table.contents')
->where('cid = ?', $cid)
->where('type IN ?', ['post', 'page'])
);
if (empty($row)) {
$result['error'] = '文章不存在';
return $result;
}
$text = (string) $row['text'];
// 从后往前改,前面的偏移才不会被打乱
usort($edits, function (array $a, array $b) {
return $b['offset'] <=> $a['offset'];
});
$changed = 0;
$skipped = 0;
foreach ($edits as $edit) {
$offset = (int) ($edit['offset'] ?? -1);
$raw = (string) ($edit['raw'] ?? '');
$to = $edit['to'] ?? null;
$length = strlen($raw);
if ($offset < 0 || '' === $raw || substr($text, $offset, $length) !== $raw) {
$skipped++;
continue;
}
if (null !== $to) {
$text = substr_replace($text, (string) $to, $offset, $length);
$changed++;
continue;
}
// 删除时如果短码独占一行,把那个换行一起带走,避免正文里留下空行
$start = $offset;
$size = $length;
$total = strlen($text);
$alone = (0 === $offset || "\n" === $text[$offset - 1])
&& ($offset + $length >= $total || "\n" === $text[$offset + $length]);
if ($alone) {
if ($offset + $length < $total) {
$size = $length + 1;
} elseif ($offset > 0) {
$start = $offset - 1;
$size = $length + 1;
}
}
$text = substr_replace($text, '', $start, $size);
$changed++;
}
if (0 === $changed) {
$result['error'] = '正文已变更,没有可修改的引用,请刷新后重试';
$result['skipped'] = $skipped;
return $result;
}
$db->query(
$db->update('table.contents')
->rows(['text' => $text, 'modified' => time()])
->where('cid = ?', $cid)
);
$result['ok'] = true;
$result['changed'] = $changed;
$result['skipped'] = $skipped;
} catch (\Throwable $e) {
$result['error'] = '写入失败:' . $e->getMessage();
}
return $result;
}
/**
* 作者名映射
*
* @return array<int, string>
*/
private static function authors(): array
{
try {
$db = Db::get();
$rows = $db->fetchAll($db->select('uid', 'name', 'screenName')->from('table.users'));
} catch (\Throwable $e) {
return [];
}
$map = [];
foreach ($rows as $row) {
$name = trim((string) ($row['screenName'] ?: $row['name']));
$map[(int) $row['uid']] = '' === $name ? '#' . $row['uid'] : $name;
}
return $map;
}
/**
* 按 ID 集合批量取一行行数据,返回 [主键 => 行]
*
* @param string $table
* @param string $pk
* @param array $columns
* @param array $ids
* @return array
*/
private static function fetchMap(string $table, string $pk, array $columns, array $ids): array
{
if (empty($ids)) {
return [];
}
try {
$db = Db::get();
$rows = $db->fetchAll(
$db->select(...$columns)->from('table.' . $table)->where($pk . ' IN ?', array_keys($ids))
);
} catch (\Throwable $e) {
return [];
}
$map = [];
foreach ($rows as $row) {
$map[(int) $row[$pk]] = $row;
}
return $map;
}
}