refactor: 外链中转拆为内置插件 neatstudio.link-tracker

- 插件承载全部逻辑:redirects 迁移(hasTable 兼容旧库)、Redirect 模型、UrlRedirector、/go 路由+控制器、Filament 外链中转资源
- 核心只留 hook 接入点:
  - tracked_url() 助手走 link.redirect 过滤器(评论正文/作者网址/友链模板统一调用)
  - 正文外链改写移到插件的 post.rendered 过滤器(优先级 20,晚于会员付费过滤)
- 停用插件:链接恢复直连、内容不受影响;后台「管理 → 外链中转」查看点击量/启停
- 测试更新为插件上下文(含无过滤器降级断言);97 通过
This commit is contained in:
ak
2026-08-13 02:05:32 +08:00
parent 8f1ff6e3f9
commit f1b9d1e1c3
20 changed files with 118 additions and 62 deletions
-26
View File
@@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Blog\Controllers;
use App\Models\Redirect;
class GoController
{
/**
* 外链中转跳转:计数 + 302。停用的链接返回 410(可作二次拦截)。
*/
public function show(string $hash)
{
$redirect = Redirect::query()->where('hash', $hash)->firstOrFail();
if (! $redirect->isActive()) {
abort(410);
}
$redirect->hit();
return redirect()->away($redirect->target_url, 302);
}
}
+1 -25
View File
@@ -46,31 +46,7 @@ class PostContentRenderer
$html = app(\App\Blog\Support\PluginManager::class)->applyFilters('post.rendered', $html, $post);
// 兜底:任何情况下不把裸 [paid] 标签输出到页面(如会员插件被停用时)
$html = preg_replace('/\[(\/?paid)\]/i', '', $html);
// 外链中转:站外链接改写为 /go/{hash}(点击统计/拦截)
return $this->rewriteExternalLinks($html);
}
/**
* 把正文里的站外 <a href> 改写为 /go 中转地址(站内/相对/锚点/mailto 不变)。
*/
private function rewriteExternalLinks(string $html): string
{
return preg_replace_callback(
'/<a\s+([^>]*?href=["\'])([^"\']+)(["\'][^>]*)>(.*?)<\/a>/is',
function (array $m): string {
$url = html_entity_decode(trim($m[2]));
$go = go_url($url);
if ($go === $url) {
return $m[0];
}
return '<a '.$m[1].e($go).$m[3].'>'.$m[4].'</a>';
},
$html
);
return preg_replace('/\[(\/?paid)\]/i', '', $html);
}
/**
-72
View File
@@ -1,72 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Blog\Services;
use App\Models\Redirect;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
/**
* 外链中转:把站外链接改写为 /go/{hash},用于点击统计、二次拦截与未来广告位。
* 站内链接、相对路径、mailto/tel/锚点不中转。
*/
class UrlRedirector
{
public function goUrl(string $url): string
{
$url = trim((string) $url);
if (! $this->isExternal($url)) {
return $url;
}
return route('go.show', $this->hashFor($url));
}
public function isExternal(string $url): bool
{
if (! preg_match('#^https?://#i', $url)) {
return false;
}
$host = parse_url($url, PHP_URL_HOST);
if (! $host) {
return false;
}
$internalHost = parse_url((string) config('app.url'), PHP_URL_HOST);
return strcasecmp($host, (string) $internalHost) !== 0;
}
/**
* URL 对应的短 hash(确定性:同一 URL 复用同一条记录,并发安全)。
*/
public function hashFor(string $url): string
{
return Cache::remember('go.hash.'.md5($url), now()->addDay(), function () use ($url) {
$hash = substr(hash('sha256', $url), 0, 10);
for ($i = 0; $i < 3; $i++) {
try {
Redirect::create(['hash' => $hash, 'target_url' => $url]);
return $hash;
} catch (UniqueConstraintViolationException) {
$existing = Redirect::where('target_url', $url)->first();
if ($existing) {
return $existing->hash;
}
$hash = substr(hash('sha256', $url.$i), 0, 10);
}
}
return $hash;
});
}
}
@@ -1,90 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources;
use App\Filament\Resources\RedirectResource\Pages\ListRedirects;
use App\Models\Redirect;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class RedirectResource extends Resource
{
protected static \UnitEnum|string|null $navigationGroup = '管理';
protected static ?string $model = Redirect::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowUturnRight;
protected static ?string $navigationLabel = '外链中转';
protected static ?string $pluralModelLabel = '外链中转';
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('hash')
->label('短码')
->badge()
->color('gray'),
TextColumn::make('target_url')
->label('目标地址')
->limit(50)
->copyable()
->searchable(),
TextColumn::make('clicks')
->label('点击量')
->numeric()
->sortable(),
TextColumn::make('status')
->label('状态')
->badge()
->formatStateUsing(fn ($state) => $state === 'active' ? '启用' : '停用')
->color(fn ($state) => $state === 'active' ? 'success' : 'danger'),
TextColumn::make('last_clicked_at')
->label('最后点击')
->dateTime('Y-m-d H:i')
->placeholder('—')
->sortable(),
TextColumn::make('created_at')
->label('创建时间')
->dateTime('Y-m-d H:i')
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
\Filament\Tables\Filters\SelectFilter::make('status')
->label('状态')
->options(['active' => '启用', 'disabled' => '停用']),
], \Filament\Tables\Enums\FiltersLayout::AboveContent)
->recordActions([
Action::make('toggle')
->label(fn (Redirect $record) => $record->isActive() ? '停用' : '启用')
->color(fn (Redirect $record) => $record->isActive() ? 'danger' : 'success')
->action(fn (Redirect $record) => $record->update(['status' => $record->isActive() ? 'disabled' : 'active'])),
DeleteAction::make(),
])
->recordUrl(null)
->recordAction(null)
->defaultSort('clicks', 'desc');
}
public static function getPages(): array
{
return [
'index' => ListRedirects::route('/'),
];
}
}
@@ -1,13 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Resources\RedirectResource\Pages;
use App\Filament\Resources\RedirectResource;
use Filament\Resources\Pages\ListRecords;
class ListRedirects extends ListRecords
{
protected static string $resource = RedirectResource::class;
}
-29
View File
@@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Redirect extends Model
{
protected $fillable = [
'hash', 'target_url', 'clicks', 'status', 'last_clicked_at',
];
protected $casts = [
'last_clicked_at' => 'datetime',
];
public function isActive(): bool
{
return $this->status === 'active';
}
public function hit(): void
{
$this->increment('clicks');
$this->update(['last_clicked_at' => now()]);
}
}
+7 -6
View File
@@ -43,19 +43,20 @@ if (! function_exists('blog_setting')) {
}
}
if (! function_exists('go_url')) {
if (! function_exists('tracked_url')) {
/**
* 外链中转:站外链接改写为 /go/{hash}(点击统计/拦截),站内链接原样返回。
* 外链追踪钩子:核心视图统一调用,由插件(外链中转)改写为 /go/{hash}
* 插件停用时原样返回。站内链接等由插件自行判断。
*/
function go_url(string $url): string
function tracked_url(string $url): string
{
return app(\App\Blog\Services\UrlRedirector::class)->goUrl($url);
return app(\App\Blog\Support\PluginManager::class)->applyFilters('link.redirect', $url);
}
}
if (! function_exists('comment_body')) {
/**
* 评论正文:转义 + 自动链接 URL /go 中转,nofollow)。
* 评论正文:转义 + 自动链接 URL tracked_url 中转,nofollow)。
*/
function comment_body(string $text): string
{
@@ -63,7 +64,7 @@ if (! function_exists('comment_body')) {
$text = preg_replace_callback(
'#(https?://[^\s<>"\'()]+)#i',
fn (array $m) => '<a href="'.e(go_url($m[1])).'" target="_blank" rel="nofollow noopener">'.$m[1].'</a>',
fn (array $m) => '<a href="'.e(tracked_url($m[1])).'" target="_blank" rel="nofollow noopener">'.$m[1].'</a>',
$text
);