Files
ChangeLog/Plugin.php

2251 lines
82 KiB
PHP
Raw Permalink 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
/**
* 更新日志插件
*
* 站点更新日志
*
* @package ChangeLog
* @author 石头厝
* @version 2.0.10
* @link https://www.shitoucuo.com/
*/
/* 2.0.0 由 DevelopmentHistory 整体改名而来:
目录、类名(ChangeLog_Plugin / ChangeLog_Action)、表名({prefix}changelog)、
模板文件(page-lishi.php → page-changelog.php)、前端 CSS 前缀(cl-)
全部更换;激活时会把旧表 {prefix}development_history 里的记录搬过来,
并把已建好页面的模板字段改成 page-changelog.php。 */
class ChangeLog_Plugin implements Typecho_Plugin_Interface
{
/**
* 当前站点是不是 SQLite
*
* 1.2.1 之前这里全程按 MySQL 写:SHOW TABLES / SHOW COLUMNS / COMMENT / AFTER /
* ENGINE / YEAR()。SQLite 一条都不认,装上去不是启用时报错,就是前台渲染时
* 「no such function: YEAR」直接 500。下面几个方法把差异收在一处。
*
* @return bool
*/
private static function isSqlite()
{
try {
$db = Typecho_Db::get();
return stripos(get_class($db->getAdapter()), 'sqlite') !== false;
} catch (Exception $e) {
return false;
}
}
/**
* 表是否存在(不依赖 SHOW TABLES,两种数据库通用)
*
* @param string $tableName 已带前缀的表名
* @return bool
*/
private static function tableExists($tableName)
{
try {
$db = Typecho_Db::get();
$db->fetchAll($db->query("SELECT 1 FROM {$tableName} LIMIT 1"));
return true;
} catch (Exception $e) {
return false;
}
}
/**
* 取表的字段清单,统一成 array(字段名 => 字段类型)
*
* MySQL 用 SHOW COLUMNS(Field / Type),SQLite 用 PRAGMA table_info(name / type)。
*
* @param string $tableName 已带前缀的表名
* @return array
*/
private static function getTableColumns($tableName)
{
$db = Typecho_Db::get();
$columns = array();
try {
if (self::isSqlite()) {
$rows = $db->fetchAll($db->query("PRAGMA table_info({$tableName})"));
foreach ($rows as $row) {
$name = isset($row['name']) ? $row['name'] : '';
if ($name !== '') {
$columns[$name] = isset($row['type']) ? strtolower($row['type']) : '';
}
}
} else {
$rows = $db->fetchAll($db->query("SHOW COLUMNS FROM `{$tableName}`"));
foreach ($rows as $row) {
$name = isset($row['Field']) ? $row['Field'] : '';
if ($name !== '') {
$columns[$name] = isset($row['Type']) ? strtolower($row['Type']) : '';
}
}
}
} catch (Exception $e) {
// 探测失败就当没有字段,交给后面的补列逻辑处理
}
return $columns;
}
/**
* 建表语句:SQLite 不认 ENGINE / COMMENT / 反引号,单独一份
*
* @param string $tableName 已带前缀的表名
* @return string
*/
private static function createTableSql($tableName)
{
if (self::isSqlite()) {
return "CREATE TABLE {$tableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
event_date DATETIME NOT NULL,
post_cids VARCHAR(255) DEFAULT '',
created DATETIME,
modified DATETIME,
status TINYINT DEFAULT 1
)";
}
return "CREATE TABLE `{$tableName}` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`content` TEXT NOT NULL COMMENT '内容',
`event_date` DATETIME NOT NULL COMMENT '事件日期时间',
`post_cids` VARCHAR(255) DEFAULT '' COMMENT '关联文章CID,多个用逗号分隔',
`created` DATETIME NOT NULL COMMENT '创建时间',
`modified` DATETIME NOT NULL COMMENT '修改时间',
`status` TINYINT(1) DEFAULT 1 COMMENT '状态:1正常'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='更新日志记录表';";
}
/**
* 从旧插件 DevelopmentHistory 迁移数据(2.0.0 改名时加)
*
* 插件改名后表从 {prefix}development_history 变成 {prefix}changelog、
* 独立页模板从 page-lishi.php 变成 page-changelog.php。老站升级上来时
* 这里一次性把记录搬过来,并把已经建好的那个页面指向新模板。
*
* 幂等:新表里已经有数据就整段跳过,不会重复插入;旧表不删,
* 留给用户自己确认后再清理(避免自动删表的不可逆操作)。
*
* @param string $tableName 新表名(已带前缀)
* @return void
*/
private static function migrateLegacy($tableName)
{
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
$legacyTable = $prefix . 'development_history';
if ($legacyTable !== $tableName && self::tableExists($legacyTable)) {
try {
$newCount = $db->fetchRow($db->select('COUNT(*) as c')->from($tableName));
$newIsEmpty = empty($newCount['c']);
if ($newIsEmpty) {
$db->query("INSERT INTO {$tableName} (content, event_date, post_cids, created, modified, status)
SELECT content, event_date, post_cids, created, modified, status FROM {$legacyTable}");
error_log('[ChangeLog] migrate: 已从旧表 ' . $legacyTable . ' 迁移记录到 ' . $tableName);
}
} catch (Exception $e) {
// 迁移失败不阻断启用;旧表原样保留,数据不会丢
error_log('[ChangeLog] migrate table error: ' . $e->getMessage());
}
}
// 已建好的独立页:模板名跟着改,否则改完名那个页面会“模板不存在”
try {
$db->query("UPDATE {$prefix}contents SET template = 'page-changelog.php' WHERE template = 'page-lishi.php'");
} catch (Exception $e) {
error_log('[ChangeLog] migrate template error: ' . $e->getMessage());
}
}
/**
* 激活插件
*
* @return string
* @throws Typecho_Plugin_Exception
*/
public static function activate()
{
// 改名遗留清理:发布文章报错的根因是数据库 options.plugins 里
// 还残留指向旧类名 DevelopmentHistory_Plugin 的 finishPublish 句柄,
// PHP 8 下 call_user_func_array 找不到类会直接 500。必须先清掉再启用。
self::purgeLegacyHandles();
// 创建数据表
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
$tableName = $prefix . 'changelog';
// 检查主表是否存在(1.2.1:不再用 SHOW TABLES,SQLite 也能跑)
if (!self::tableExists($tableName)) {
// 表不存在,创建新表(不带title字段)
try {
$db->query(self::createTableSql($tableName));
} catch (Typecho_Db_Exception $e) {
throw new Typecho_Plugin_Exception('创建数据表失败: ' . $e->getMessage());
}
} else {
// 表已存在,检查是否有title字段,如果有则删除
$columns = self::getTableColumns($tableName);
if (isset($columns['title'])) {
// 删除title字段
try {
$db->query("ALTER TABLE `{$tableName}` DROP COLUMN `title`");
} catch (Typecho_Db_Exception $e) {
// 如果删除字段失败,可能是表结构问题,继续执行
}
}
// 检查是否有post_cids字段,如果没有则添加
if (!isset($columns['post_cids'])) {
$sql = self::isSqlite()
? "ALTER TABLE {$tableName} ADD COLUMN post_cids VARCHAR(255) DEFAULT ''"
: "ALTER TABLE `{$tableName}` ADD `post_cids` VARCHAR(255) DEFAULT '' COMMENT '关联文章CID,多个用逗号分隔' AFTER `event_date`";
try {
$db->query($sql);
} catch (Typecho_Db_Exception $e) {
// 如果添加字段失败,继续执行
}
}
// 检查 event_date 是否为 DATETIME(老版本是 DATE,只存年月日,会丢掉时分秒)
// SQLite 的字段类型是弱类型、也没有 MODIFY 语法,改类型没有意义,跳过
if (!self::isSqlite() && isset($columns['event_date']) && $columns['event_date'] !== 'datetime') {
try {
$db->query("ALTER TABLE `{$tableName}` MODIFY `event_date` DATETIME NOT NULL COMMENT '事件日期时间'");
} catch (Typecho_Db_Exception $e) {
// 如果修改字段失败,继续执行
}
}
}
// 2.0.0:从 DevelopmentHistory 搬数据(表名与页面模板都换了)
self::migrateLegacy($tableName);
// 添加管理菜单
Helper::addPanel(3, 'ChangeLog/manage-panel.php', '更新日志', '更新日志管理', 'administrator');
// 挂载发布文章钩子:发布文章时自动写入更新日志
// Typecho 1.3 里 Widget_Contents_Post_Edit 与 \Widget\Contents\Post\Edit
// 指向同一个组件,两个名字各注册一次会让钩子跑两遍(虽然写入有去重兜底,
// 但每篇文章都白跑一轮查询),所以这里只注册一次。
$postEditWidget = class_exists('Widget\Contents\Post\Edit')
? '\Widget\Contents\Post\Edit'
: 'Widget_Contents_Post_Edit';
Typecho_Plugin::factory($postEditWidget)->finishPublish = array('ChangeLog_Plugin', 'recordPublishedPost');
error_log('[ChangeLog] activate: finishPublish hook registered.');
return _t('更新日志插件已激活,请到插件设置中进行配置');
}
/**
* 禁用插件
*
* @return string
*/
public static function deactivate()
{
Helper::removePanel(3, 'ChangeLog/manage-panel.php');
// 注销发布文章钩子
// Typecho 1.2 的 Plugin::__set() 要求值为 callable,不能传 null,用空方法代替
$postEditWidget = class_exists('Widget\Contents\Post\Edit')
? '\Widget\Contents\Post\Edit'
: 'Widget_Contents_Post_Edit';
Typecho_Plugin::factory($postEditWidget)->finishPublish = array('ChangeLog_Plugin', 'hookNoop');
return _t('更新日志插件已禁用');
}
/**
* 清理旧插件 DevelopmentHistory 遗留的所有钩子句柄(2.0.4 新增)
*
* 背景:插件从 DevelopmentHistory 改名为 ChangeLog 后,插件目录/类名都换了,
* 但数据库 typecho_options 表的 plugins 行里,published 相关的钩子仍可能
* 残留 array('DevelopmentHistory_Plugin', 'hookNoop'/'recordPublishedPost')。
* PHP 8 下发布文章时 call_user_func_array 调用不存在的类会抛 TypeError,
* 表现就是「提交文章后弹出错误页」。靠类兼容壳只能兜住方法调用,
* 无法阻止残留句柄本身,所以这里从数据层面彻底清掉。
*
* Typecho 句柄结构(serialize 后存进 options.plugins):
* array(
* 'activated' => array('DevelopmentHistory' => array('handles' => ...), ...),
* 'handles' => array('组件:钩子' => array(权重 => array('类名','方法名'), ...), ...)
* )
*
* 只删除「类名以 DevelopmentHistory 开头」的回调,其他插件句柄一律保留;
* 同时移除 activated 里的旧登记。改完用 Plugin::init() 写回内存,
* 随后由 Widget\Plugins\Edit 的 activate 流程整体 serialize 落库。
*
* @return void
*/
private static function purgeLegacyHandles()
{
$legacyPrefix = 'DevelopmentHistory';
try {
// export()/init() 在新版 Typecho\Plugin 与旧版 Typecho_Plugin 上都存在
$plugins = Typecho_Plugin::export();
if (!is_array($plugins)) {
return;
}
$dirty = false;
// 1) 清理 handles:组件钩子下的所有回调数组
if (!empty($plugins['handles']) && is_array($plugins['handles'])) {
foreach ($plugins['handles'] as $component => $callbacks) {
if (!is_array($callbacks)) {
continue;
}
foreach ($callbacks as $weight => $callback) {
if (self::isLegacyCallback($callback, $legacyPrefix)) {
unset($plugins['handles'][$component][$weight]);
$dirty = true;
}
}
// 该钩子下已无任何回调,删掉整个键,避免留下空数组
if (empty($plugins['handles'][$component])) {
unset($plugins['handles'][$component]);
}
}
}
// 2) 清理 activated 里的旧插件登记(含其 handles 子项)
if (isset($plugins['activated'][$legacyPrefix])) {
unset($plugins['activated'][$legacyPrefix]);
$dirty = true;
}
// 3) 先把清理结果写回内存,由 activate 流程整体 serialize 落库。
// 必须在删配置行之前:后者若因版本差异抛错,也不能影响核心句柄清理。
if ($dirty) {
Typecho_Plugin::init($plugins);
error_log('[ChangeLog] purgeLegacyHandles: 已清除 DevelopmentHistory 遗留句柄');
}
// 4) 清理旧插件配置行(plugin:DevelopmentHistory / _plugin:DevelopmentHistory 等)
// 锦上添花,失败不影响发文;PHP 8 下可能是 TypeError,故用 Throwable。
try {
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
foreach (array($legacyPrefix, '_' . $legacyPrefix) as $cfgName) {
$db->query($db->delete($prefix . 'options')->where('name = ?', 'plugin:' . $cfgName));
// 兼容老命名:直接以插件名为 name 的配置行
$db->query($db->delete($prefix . 'options')->where('name = ?', $cfgName));
}
} catch (Throwable $e) {
// 忽略配置行删除失败
}
} catch (Throwable $e) {
// 清理失败不能阻断插件启用
error_log('[ChangeLog] purgeLegacyHandles error: ' . $e->getMessage());
}
}
/**
* 判断一个句柄回调是否指向旧插件类名
*
* 句柄回调可能是 array('类名','方法名')、类名字符串、闭包等,
* 这里只认「以 DevelopmentHistory 开头」的类名,大小写不敏感。
*
* @param mixed $callback
* @param string $legacyPrefix
* @return bool
*/
private static function isLegacyCallback($callback, $legacyPrefix)
{
if (is_array($callback) && isset($callback[0]) && is_string($callback[0])) {
return stripos($callback[0], $legacyPrefix) === 0;
}
if (is_string($callback)) {
return stripos($callback, $legacyPrefix . '::') === 0
|| stripos($callback, $legacyPrefix . '_') === 0;
}
return false;
}
/**
* 插件配置面板
*
* @param Typecho_Widget_Helper_Form $form
*/
public static function config(Typecho_Widget_Helper_Form $form)
{
echo '<h2>更新日志插件配置</h2>';
echo '<p>版本:2.0.10</p>';
echo '<hr>';
// 发布文章自动记录开关
$autoRecord = new Typecho_Widget_Helper_Form_Element_Radio(
'autoRecordOnPublish',
array(
'1' => _t('开启'),
'0' => _t('关闭')
),
'1',
_t('发布文章自动写入更新日志'),
_t('开启后,文章发布时会自动添加一条记录:首次发布写「发布文章《文章标题》」,之后每次编辑保存写「更新文章《文章标题》」,标题在前端显示为文章链接(新窗口打开)')
);
$form->addInput($autoRecord);
// 每页显示数量
$perPage = new Typecho_Widget_Helper_Form_Element_Text(
'perPage',
NULL,
'10',
_t('后台每页显示数量'),
_t('后台管理页面每页显示的更新记录数量,默认:10')
);
$perPage->input->setAttribute('class', 'mini');
$form->addInput($perPage->addRule('isInteger', _t('请输入整数')));
// 前端每页显示数量
$frontPerPage = new Typecho_Widget_Helper_Form_Element_Text(
'frontPerPage',
NULL,
'20',
_t('主题调用每页显示数量'),
_t('在主题中调用时每页显示的更新记录数量,默认:20')
);
$frontPerPage->input->setAttribute('class', 'mini');
$form->addInput($frontPerPage->addRule('isInteger', _t('请输入整数')));
// 时间格式
$dateFormat = new Typecho_Widget_Helper_Form_Element_Text(
'dateFormat',
NULL,
'Y.m.d',
_t('日期显示格式'),
_t('PHP日期格式,如:Y.m.d、Y-m-d、Y年m月d日等')
);
$form->addInput($dateFormat);
// 是否显示关联文章
$showRelatedPosts = new Typecho_Widget_Helper_Form_Element_Radio(
'showRelatedPosts',
array(
'1' => _t('显示'),
'0' => _t('不显示')
),
'1',
_t('显示关联文章'),
_t('是否在更新记录下方显示关联的文章链接')
);
$form->addInput($showRelatedPosts);
// 关联文章标题
$relatedPostsTitle = new Typecho_Widget_Helper_Form_Element_Text(
'relatedPostsTitle',
NULL,
'相关文章',
_t('关联文章标题'),
_t('关联文章部分的标题文本')
);
$form->addInput($relatedPostsTitle);
}
/**
* 个人用户配置
*
* @param Typecho_Widget_Helper_Form $form
*/
public static function personalConfig(Typecho_Widget_Helper_Form $form)
{
// 个人配置(如果需要)
}
/**
* 空钩子方法,用于注销 finishPublish(Typecho 1.2 不接受 null)
*/
public static function hookNoop()
{
}
/**
* 发布文章时自动写入更新日志
*
* 通过 finishPublish 钩子调用,$widget 为 Widget_Contents_Post_Edit 实例
*
* @param array $contents 文章内容
* @param object $widget 文章编辑 Widget
*/
public static function recordPublishedPost($contents, $widget)
{
try {
// 仅处理 type 为 post 的内容
if (!isset($widget->type) || $widget->type != 'post') {
return;
}
// 仅处理已发布的文章(草稿、隐藏文章不记录)
$status = isset($widget->status) ? $widget->status : (isset($contents['status']) ? $contents['status'] : '');
if ($status != 'publish') {
return;
}
// 读取插件配置,判断开关是否开启
//
// 2.0.3:Options::plugin() 在 plugin:ChangeLog 这行缺失时会抛
// PluginException(500)。原来这里没有兜底,异常被最外层 catch 静默吃掉,
// 表现就是「文章发得出去、日志里就是没有这条记录」,而且前台日志页照常
// (render() 那边一直有兜底),极难察觉。这里补上与 render() 一致的默认值。
try {
$options = Typecho_Widget::widget('Widget_Options');
$config = $options->plugin('ChangeLog');
$autoRecord = $config->autoRecordOnPublish;
} catch (Exception $e) {
$autoRecord = '1';
}
// 开关判断。Typecho\Config 的魔术方法写作 __isSet()(大写 S),
// PHP 方法名不区分大小写,所以它等同 __isset,isset($config->xxx) 可用。
// 值可能是字符串 '0' 也可能是整数 0(后台表单提交与手改配置都可能),
// 统一转成字符串比较,避免松散比较在不同 PHP 版本下的歧义。
if ($autoRecord !== null && (string) $autoRecord === '0') {
return;
}
$cid = isset($widget->cid) ? intval($widget->cid) : 0;
if ($cid <= 0) {
return;
}
// 标题:优先取数据库中的标题
$title = !empty($widget->title) ? $widget->title : (isset($contents['title']) ? $contents['title'] : '');
if ($title === '' || $title === NULL) {
return;
}
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
// 判断这次是「首次发布」还是「再次编辑」
//
// 2.0.9 起:以前只要该文章有过一条「发布文章」记录就直接跳过,导致文章
// 发布后再改内容、再保存,日志里什么都看不到。现在改为——
// · 日志里还没有这篇文章 → 记「发布文章《标题》」
// · 已经有 → 记「更新文章《标题》」(每次编辑保存都算一次更新)
// 匹配用 [post:cid] 精确识别(自带右方括号,cid=1 不会误判到 cid=10)。
$latest = $db->fetchRow($db->select('id', 'content', 'event_date')
->from($prefix . 'changelog')
->where('content LIKE ?', '%[post:' . $cid . ']%')
->order('id', Typecho_Db::SORT_DESC)
->limit(1));
// 同一次保存的重复触发保护:15 秒内已经为这篇文章写过记录就跳过。
// 钩子若被重复注册,两次调用发生在同一个请求内(间隔毫秒级),15 秒足够挡住;
// 窗口取小一点,是为了不影响「发布后发现错字,马上改完再保存」这类真实编辑。
if ($latest) {
$sinceDate = new Typecho_Date(Typecho_Date::gmtTime() - 15);
if (!empty($latest['event_date'])
&& strtotime($latest['event_date']) !== false
&& $latest['event_date'] > $sinceDate->format('Y-m-d H:i:s')) {
return;
}
}
$actionText = $latest ? '更新文章' : '发布文章';
$now = new Typecho_Date(Typecho_Date::gmtTime());
$insert = $db->insert($prefix . 'changelog')
->rows(array(
// 内联标记 [post:cid]标题[/post],前端渲染时替换为文章链接(新窗口打开)
'content' => $actionText . '《[post:' . $cid . ']' . $title . '[/post]》',
'event_date' => $now->format('Y-m-d H:i:s'),
'post_cids' => '',
'created' => $now->format('Y-m-d H:i:s'),
'modified' => $now->format('Y-m-d H:i:s'),
'status' => 1
));
$db->query($insert);
} catch (Throwable $e) {
// 自动记录失败不影响文章发布
// 用 Throwable 而不是 Exception:PHP 8 下 TypeError / Error 不算 Exception,
// 只抓 Exception 会让它们冒到发文流程里,把一次正常发布打成 500。
error_log('ChangeLog recordPublishedPost Error: ' . $e->getMessage());
}
}
/**
* 格式化事件日期时间:日期后空格显示时分秒
*
* 升级前的老记录只存了日期(时间为 00:00:00),这类记录只显示日期,
* 不显示没有意义的 00:00:00。
*
* @param string $value 数据库中的 event_date
* @param string $dateFormat PHP 日期格式
* @return string
*/
private static function formatEventDate($value, $dateFormat = 'Y.m.d')
{
$timestamp = strtotime((string) $value);
if ($timestamp === false) {
return '';
}
$date = date($dateFormat, $timestamp);
$time = date('H:i:s', $timestamp);
return $time === '00:00:00' ? $date : $date . ' ' . $time;
}
/**
* 内容末尾统一补一个中文分号「;」
*
* 库里已有的中英文分号(可能连着好几个)先去掉,再补代码里写死的这个,
* 保证前端每条内容结尾都是同一个「;」,不会出现「;;」「;;」。
* 只影响显示,不改数据库里的原文。
*
* @param string $content 原始内容
* @return string
*/
private static function appendSemicolon($content)
{
$content = rtrim((string) $content);
// 去掉结尾已有的分号:全角「;」和半角「;」,可能连着多个
$stripped = preg_replace('/[;;]+$/u', '', $content);
if ($stripped !== null) {
$content = rtrim($stripped);
}
if ($content === '') {
return '';
}
return $content . ';';
}
/**
* 将内容中的 [post:cid]标题[/post] 标记替换为文章链接
* 用于前端渲染,独立于"相关文章"绑定逻辑
*
* @param string $content 已经过 htmlspecialchars 处理的内容
* @return string
*/
private static function renderInlinePostLinks($content)
{
if (strpos($content, '[post:') === false) {
return $content;
}
return preg_replace_callback(
'/\[post:(\d+)\](.*?)\[\/post\]/s',
function ($matches) {
$cid = intval($matches[1]);
$title = $matches[2]; // 已转义
$url = self::getPostUrlByCid($cid);
if (empty($url)) {
// 文章不存在或未发布,退化为纯文本
return $title;
}
return '<a href="' . $url . '" class="history-post-link" target="_blank" rel="noopener">' . $title . '</a>';
},
$content
);
}
/**
* 根据文章 CID 获取文章访问地址(带静态缓存)
*
* @param int $cid
* @return string 空字符串表示文章不存在或未发布
*/
private static function getPostUrlByCid($cid)
{
static $cache = array();
if (isset($cache[$cid])) {
return $cache[$cid];
}
$url = '';
try {
$db = Typecho_Db::get();
$post = $db->fetchRow($db->select('cid, slug')
->from($db->getPrefix() . 'contents')
->where('cid = ?', $cid)
->where('type = ?', 'post')
->where('status = ?', 'publish')
->limit(1));
if ($post) {
$options = Typecho_Widget::widget('Widget_Options');
if (!empty($post['slug'])) {
$url = Typecho_Common::url($post['slug'] . '.html', $options->index);
} else {
$url = Typecho_Common::url('archives/' . $post['cid'], $options->index);
}
}
} catch (Exception $e) {
error_log('ChangeLog getPostUrlByCid Error: ' . $e->getMessage());
}
$cache[$cid] = $url;
return $url;
}
/**
* 渲染方法(用于在主题模板中调用)
*/
public static function render()
{
// 获取配置
$options = Typecho_Widget::widget('Widget_Options');
// 1.2.1:配置行缺失时不要让它把整页打成 500。
// Typecho 1.3 的 Options::plugin() 在找不到 plugin:ChangeLog 这行时
// 直接抛 PluginException(500),而插件启用后配置行可能因为建表失败等原因没写进去。
try {
$config = $options->plugin('ChangeLog');
} catch (Exception $e) {
$config = new Typecho_Config(array(
'autoRecordOnPublish' => '1',
'perPage' => '10',
'frontPerPage' => '20',
'dateFormat' => 'Y.m.d',
'showRelatedPosts' => '1',
'relatedPostsTitle' => '相关文章',
));
}
// 数据库操作
$db = Typecho_Db::get();
$prefix = $db->getPrefix();
// 1.2.1:表没建出来时给提示,不要让 SQL 异常冒到前台变 500
// (插件启用时若建表失败,Typecho 仍会把它标记为已启用,配置也可能没写进库)
if (!self::tableExists($prefix . 'changelog')) {
echo '<div class="development-history-empty">数据表尚未创建:请到后台「控制台 → 插件」把 ChangeLog 停用再启用一次,插件会自动建表。</div>';
return;
}
// 获取当前页面文件名
$currentFile = basename($_SERVER['PHP_SELF']);
// 统一使用 'y' 参数
$selectedYear = 0;
$currentPage = 1;
$searchKeyword = '';
// 读取 'y' 参数
if (isset($_GET['y']) && is_numeric($_GET['y'])) {
$selectedYear = intval($_GET['y']);
}
// 保持向后兼容:如果旧链接使用了 'year' 参数,也支持
if ($selectedYear == 0 && isset($_GET['year']) && is_numeric($_GET['year'])) {
$selectedYear = intval($_GET['year']);
}
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0) {
$currentPage = intval($_GET['page']);
}
// 读取搜索关键词参数 - 正确处理URL编码
if (isset($_GET['search']) && !empty($_GET['search'])) {
$searchKeyword = trim($_GET['search']);
// 解码URL编码的参数
$searchKeyword = urldecode($searchKeyword);
}
// URL构建函数 - 正确处理编码
// 加 function_exists 判断:主题在同一页面多次调用 render() 时不会重复定义导致致命错误
if (!function_exists('changelogBuildUrl')) {
function changelogBuildUrl($year = 0, $page = 1, $search = '') {
$currentFile = basename($_SERVER['PHP_SELF']);
$params = array();
if ($page > 1) {
$params['page'] = $page;
}
if ($year > 0) {
$params['y'] = $year;
}
if (!empty($search)) {
// 这里使用原始搜索词,http_build_query会自动编码
$params['search'] = $search;
}
if (empty($params)) {
return $currentFile;
}
return $currentFile . '?' . http_build_query($params);
}
}
// 年份筛选URL
// 同理,避免重复定义
if (!function_exists('changelogBuildYearUrl')) {
function changelogBuildYearUrl($year, $search = '') {
return changelogBuildUrl($year, 1, $search);
}
}
$perPage = isset($config->frontPerPage) ? intval($config->frontPerPage) : 20;
// 后台填了空值/0 时兜底,否则下面 ceil($total / $perPage) 会除零
if ($perPage < 1) {
$perPage = 20;
}
$offset = ($currentPage - 1) * $perPage;
// 构建查询条件
$where = 'status = ?';
$whereParams = array(1);
if ($selectedYear > 0) {
// 1.2.1:原来用 YEAR(event_date),SQLite 没有这个函数,一进年份筛选就 500。
// 改成日期区间比较,两种数据库都认,还能吃到 event_date 上的索引。
$where .= ' AND event_date >= ? AND event_date < ?';
$whereParams[] = sprintf('%04d-01-01 00:00:00', $selectedYear);
$whereParams[] = sprintf('%04d-01-01 00:00:00', $selectedYear + 1);
}
if (!empty($searchKeyword)) {
$where .= ' AND content LIKE ?';
$whereParams[] = '%' . $searchKeyword . '%';
}
// 查询数据
// 2.0.2:原来按 id 倒序排,而 id 只代表「写入顺序」。一旦导入历史数据,
// 后导入的记录 id 更大,会把早先写入的记录(后台发布文章自动记的那批)
// 整批挤到最后一页,页面上日期看起来完全乱序。
// 改成按事件时间倒序排,id 只在同一天同一时刻时做稳定次序(导入同一天的条目
// 会保持文件里的先后顺序,重复导入/导出也不会翻转)。
$query = $db->select()
->from($prefix . 'changelog')
->where($where, ...$whereParams)
->order('event_date', Typecho_Db::SORT_DESC)
->order('id', Typecho_Db::SORT_ASC)
->limit($perPage)
->offset($offset);
$entries = $db->fetchAll($query);
// 为每条记录获取关联的文章信息 - 修复URL生成
foreach ($entries as &$entry) {
if (!empty($entry['post_cids'])) {
$cids = array_filter(array_map('trim', explode(',', $entry['post_cids'])));
$posts = array();
foreach ($cids as $cid) {
if (is_numeric($cid)) {
$postQuery = $db->select('cid, title, slug, created')
->from($prefix . 'contents')
->where('cid = ?', intval($cid))
->where('type = ?', 'post')
->where('status = ?', 'publish')
->limit(1);
$post = $db->fetchRow($postQuery);
if ($post) {
// 修复:直接使用slug变量值
if (!empty($post['slug'])) {
$post['url'] = Typecho_Common::url($post['slug'] . '.html', $options->index);
} else {
$post['url'] = Typecho_Common::url('archives/' . $post['cid'], $options->index);
}
$posts[] = $post;
}
}
}
$entry['posts'] = $posts;
} else {
$entry['posts'] = array();
}
}
// 1.2.1:必须断开引用。上面用的是 foreach (... as &$entry),
// 循环结束后 $entry 仍指向数组最后一个元素;下面的输出循环
// foreach ($entries as $entry) 会把每次取到的值写回最后一条,
// 结果是整页每条记录都显示成最后一条的内容(列表看起来像被复制了)。
unset($entry);
// 获取总数
$countQuery = $db->select('COUNT(*) as count')
->from($prefix . 'changelog')
->where($where, ...$whereParams);
$totalResult = $db->fetchRow($countQuery);
$total = $totalResult['count'];
$totalPages = ceil($total / $perPage);
// 获取所有年份及记录数(考虑搜索条件)
$yearsWhere = 'status = ?';
$yearsParams = array(1);
if (!empty($searchKeyword)) {
$yearsWhere .= ' AND content LIKE ?';
$yearsParams[] = '%' . $searchKeyword . '%';
}
// 1.2.1:原来靠 GROUP BY YEAR(event_date) 让数据库算年份,SQLite 不认这个函数。
// 更新日志一年也就几十上百条,直接把 event_date 取回来在 PHP 里按前四位归并,
// 两种数据库都能跑,也不用担心 Query 构造器给函数名加引号。
$yearRows = $db->fetchAll(
$db->select('event_date')
->from($prefix . 'changelog')
->where($yearsWhere, ...$yearsParams)
);
$yearCounts = array();
foreach ($yearRows as $yearRow) {
$yearKey = substr((string) $yearRow['event_date'], 0, 4);
if ($yearKey === '' || !ctype_digit($yearKey)) {
continue;
}
$yearKey = intval($yearKey);
$yearCounts[$yearKey] = isset($yearCounts[$yearKey]) ? $yearCounts[$yearKey] + 1 : 1;
}
krsort($yearCounts);
$yearsData = array();
foreach ($yearCounts as $yearKey => $yearCount) {
$yearsData[] = array('year' => $yearKey, 'count' => $yearCount);
}
// 获取全部记录数(考虑搜索条件)
$totalAllWhere = 'status = ?';
$totalAllParams = array(1);
if (!empty($searchKeyword)) {
$totalAllWhere .= ' AND content LIKE ?';
$totalAllParams[] = '%' . $searchKeyword . '%';
}
$totalAllQuery = $db->select('COUNT(*) as count')
->from($prefix . 'changelog')
->where($totalAllWhere, ...$totalAllParams);
$totalAllResult = $db->fetchRow($totalAllQuery);
$totalAll = $totalAllResult['count'];
// 输出内容
if (empty($entries) && empty($searchKeyword) && $selectedYear == 0) {
echo '<div class="development-history-empty">暂无更新日志</div>';
return;
}
?>
<style>
.related-posts {
margin-top: 15px;
padding: 2px 0 2px 12px;
/* 与主模块一致:不铺底色,只用左侧红竖线分隔 */
background: transparent;
border-radius: 0;
border-left: 3px solid #dc2626;
}
.related-posts-title {
font-size: 13px;
font-weight: 600;
color: #495057;
margin-bottom: 8px;
display: flex;
align-items: center;
gap: 6px;
}
.related-posts ul li{
list-style: none;
}
.related-posts-list {
list-style: none;
padding: 0;
margin: 0;
}
.related-posts ul{
padding-left: 0px!important;
}
.related-post-item {
margin-bottom: 6px;
padding: 4px 10px;
background: transparent;
border-radius: 6px;
border: 1px solid rgba(36, 41, 47, 0.10);
transition: all 0.2s ease;
}
.related-post-item:last-child {
margin-bottom: 0;
}
.related-post-item:hover {
background-color: rgba(36, 41, 47, 0.05);
border-color: rgba(36, 41, 47, 0.20);
}
.related-post-link {
display: flex;
align-items: center;
gap: 8px;
text-decoration: none;
color: #495057;
font-size: 13px;
}
.related-post-link:hover {
color: #dc2626;
text-decoration: none;
}
/* 深色模式适配 */
.dark .related-posts {
margin-top: 15px;
padding: 2px 0 2px 12px;
background: transparent;
border-radius: 0;
border-left: 3px solid #dc2626;
}
.dark .related-posts-title {
font-size: 13px;
font-weight: 600;
color: #9ca3af;
margin-bottom: 8px;
display: flex;
align-items: center;
gap: 6px;
}
.dark .related-post-item {
margin-bottom: 6px;
padding: 4px 10px;
background: transparent;
border-radius: 6px;
border: 1px solid #30363d;
transition: all 0.2s ease;
}
.dark .related-post-item:hover {
background-color: rgba(255, 255, 255, 0.06);
border-color: #4b5563;
}
.dark .related-post-link {
display: flex;
align-items: center;
gap: 8px;
text-decoration: none;
color: #c9d1d9;
font-size: 13px;
}
.dark .related-post-link:hover {
color: #dc2626;
text-decoration: none;
}
.dark .related-post-link:before {
color: #8b949e;
}
</style>
<style>
/* 搜索框样式 - 优化版 */
.history-search-box {
margin: 0 auto 20px;
}
.search-form {
display: flex;
flex-direction: column;
gap: 18px;
max-width: 400px;
margin: 0 auto;
}
.search-input-row {
display: flex;
gap: 10px;
width: 100%;
}
.search-input {
flex-grow: 1;
padding: 12px 16px;
/* 无卡片后输入框不能靠"白底"来区分,改成透明 + 稍深的描边 */
border: 1px solid rgba(36, 41, 47, 0.18);
border-radius: 8px;
font-size: 15px;
transition: all 0.3s ease;
background: transparent;
color: #333;
}
.search-input:focus {
outline: none;
border-color: #dc2626;
box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}
.search-input::placeholder {
color: #6c757d;
opacity: 0.8;
}
.search-button-row {
display: flex;
justify-content: center;
gap: 10px;
width: 100%;
}
.search-button {
padding: 8px 30px;
background: linear-gradient(135deg, #dc2626, #b91c1c);
color: white;
border: none;
border-radius: 10px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
white-space: nowrap;
}
.search-button:hover {
background: linear-gradient(135deg, #b91c1c, #991b1b);
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(220, 38, 38, 0.3);
}
.search-button:active {
transform: translateY(0);
box-shadow: 0 1px 2px rgba(220, 38, 38, 0.2);
}
.clear-search-link {
padding: 12px 25px;
background: linear-gradient(135deg, #6c757d, #545b62);
color: white;
text-decoration: none;
border-radius: 6px;
font-size: 15px;
font-weight: 500;
transition: all 0.3s ease;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(108, 117, 125, 0.2);
}
.clear-search-link:hover {
background: linear-gradient(135deg, #545b62, #3d4246);
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(108, 117, 125, 0.3);
color: white;
text-decoration: none;
}
.clear-search-link:active {
transform: translateY(0);
box-shadow: 0 1px 2px rgba(108, 117, 125, 0.2);
}
.search-results-info {
margin-top: 15px;
/* 左对齐:没有底色时,居中的文字配左侧红竖线会显得两根东西互不相干 */
text-align: left;
font-size: 14px;
color: #495057;
padding: 4px 12px;
/* 不再铺底色,只用一条红竖线做标记 */
background: transparent;
border-radius: 0;
border-left: 3px solid #dc2626;
}
.search-results-info strong {
color: #b91c1c;
font-weight: 600;
}
/* 当前筛选提示条(原来是写死 #e7f3ff 蓝底的内联样式,深色下刺眼) */
.dh-filter-current {
text-align: left;
margin-bottom: 15px;
padding: 4px 12px;
background: transparent;
border-left: 3px solid #dc2626;
border-radius: 0;
}
.dh-filter-current-text {
font-size: 13px;
color: #495057;
}
.dh-filter-current-text strong {
color: #b91c1c;
font-weight: 600;
}
.dh-filter-current-link {
margin-left: 10px;
font-size: 12px;
color: #6b7280;
text-decoration: none;
transition: color 0.2s ease;
}
.dh-filter-current-link:hover {
color: #dc2626;
text-decoration: none;
}
/* 深色模式适配 */
/* 注意:sagrre 主题里有一条 `input,textarea{background-color:#faf8f1!important}`
(元素选择器 + !important),任何带选择器但不带 !important 的
background 都压不住它,搜索框在深色下才会还是惨白。
这里必须同样加 !important,靠 .dark .development-history-widget .search-input
的权重 (0,3,0) 超过主题的 (0,0,1) 才能生效。 */
.dark .search-input,
.dark .development-history-widget .search-input {
flex-grow: 1;
padding: 12px 16px;
border: 1px solid #30363d;
border-radius: 6px;
font-size: 15px;
transition: all 0.3s ease;
background-color: rgba(255, 255, 255, 0.05) !important;
background-image: none !important;
color: #c9d1d9 !important;
border-color: #30363d !important;
-webkit-text-fill-color: #c9d1d9;
color-scheme: dark;
}
.dark .search-input:focus,
.dark .development-history-widget .search-input:focus {
outline: none;
border-color: #dc2626 !important;
box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.18);
}
/* 主题同样把 placeholder 写死成红色 !important,深色下改成灰、降低亮度 */
.dark .search-input::placeholder,
.dark .development-history-widget .search-input::placeholder {
color: #6b7280 !important;
opacity: 0.9;
}
/* 浏览器自动填充会强行铺浅黄/白底,一并盖掉 */
.dark .search-input:-webkit-autofill,
.dark .search-input:-webkit-autofill:hover,
.dark .search-input:-webkit-autofill:focus {
-webkit-text-fill-color: #c9d1d9;
-webkit-box-shadow: 0 0 0 1000px #1a1c2b inset;
caret-color: #c9d1d9;
}
.dark .search-button {
background: linear-gradient(135deg, #dc2626, #b91c1c);
}
.dark .search-button:hover {
background: linear-gradient(135deg, #b91c1c, #991b1b);
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(220, 38, 38, 0.3);
}
.dark .clear-search-link {
background: linear-gradient(135deg, #6c757d, #545b62);
box-shadow: 0 2px 4px rgba(108, 117, 125, 0.2);
}
.dark .clear-search-link:hover {
background: linear-gradient(135deg, #545b62, #3d4246);
box-shadow: 0 4px 8px rgba(108, 117, 125, 0.3);
}
.dark .search-results-info {
margin-top: 15px;
text-align: left;
font-size: 14px;
color: #c9d1d9;
padding: 4px 12px;
background: transparent;
border-radius: 0;
border-left: 3px solid #dc2626;
}
.dark .search-results-info strong {
color: #dc2626;
}
.dark .dh-filter-current {
background: transparent;
border-left-color: #dc2626;
}
.dark .dh-filter-current-text {
color: #c9d1d9;
}
.dark .dh-filter-current-text strong {
color: #f87171;
}
.dark .dh-filter-current-link {
color: #8b949e;
}
.dark .dh-filter-current-link:hover {
color: #f87171;
}
@media (max-width: 768px) {
.search-input-row {
flex-direction: column;
}
.search-button-row {
flex-direction: column;
align-items: stretch;
}
.search-button,
.clear-search-link {
width: 100%;
text-align: center;
}
.search-form {
gap: 15px;
}
}
@media (min-width: 769px) {
.search-button-row {
justify-content: center;
}
}
</style>
<style>
.development-history-widget {
max-width: 100%;
/* 不做卡片:直接贴在页面背景上,靠留白 + 细线分隔,
深浅色都不给底色,避免和主题背景撞色 */
background: transparent;
border: 0;
border-radius: 0;
box-shadow: none;
}
.dark .development-history-widget h3{
margin-top:0px;
}
.widget-title {
text-align: center;
margin-bottom: 20px;
color: #333;
font-size: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #dc2626;
transition: all 0.3s ease;
}
.dark .year-list li+li{margin-top:0em;}
.year-list li+li{margin-top:0em;}
.dark .year-filter ul{padding-left:0rem;margin-bottom:0px;}
.year-filter ul{padding-left:0rem;margin-bottom:0px;}
.year-filter {
margin: 10px auto 18px;
padding: 12px 14px;
/* 原来是 #f8f9fa 灰块,现在是透明 + 一圈细线,不再是一块色 */
background: transparent;
border-radius: 10px;
border: 1px solid rgba(36, 41, 47, 0.10);
}
.year-filter-title {
font-size: 16px;
font-weight: 600;
color: #495057;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.year-filter-title:before {
content: "📅";
font-size: 14px;
}
.year-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 0;
padding: 0;
justify-content: center;
list-style: none;
}
.year-item {
display: inline-block;
}
.year-link {
display: inline-block;
padding: 6px 14px;
/* 芯片也不再铺白底,只用描边,免得在米色页面上形成白色小方块 */
background-color: transparent;
color: #495057;
text-decoration: none;
border-radius: 10px;
border: 1px solid rgba(36, 41, 47, 0.16);
font-size: 13px;
font-weight: 500;
transition: all 0.2s ease;
cursor: pointer;
}
.year-link:hover {
background-color: rgba(36, 41, 47, 0.06);
border-color: rgba(36, 41, 47, 0.28);
transform: translateY(-1px);
}
.year-link.active {
background-color: #dc2626;
color: white;
border-color: #dc2626;
font-weight: 600;
}
.year-count {
margin-left: 4px;
font-size: 11px;
opacity: 0.8;
font-weight: normal;
}
.history-list {
list-style: none;
padding: 0;
margin: 0;
}
.history-item {
padding: 12px 12px;
display: flex;
align-items: flex-start;
border-radius: 10px;
transition: background-color 0.3s ease;
}
.history-item:first-child {
border-bottom: none;
margin-top: 20px;
}
/* 没有卡片底色后,行与行之间补一条极细的分隔线,避免连成一片 */
.history-item + .history-item {
border-top: 1px solid rgba(36, 41, 47, 0.07);
}
.history-item:hover {
background-color: rgba(36, 41, 47, 0.035);
}
.history-content p{margin-bottom:0px;}
.dark .history-content p{margin-bottom:0px;}
/* 发布文章内联链接样式(独立于相关文章绑定) */
.history-post-link {
color: #dc2626;
text-decoration: none;
border-bottom: 1px dashed rgba(220, 38, 38, 0.5);
transition: color 0.2s ease, border-bottom-color 0.2s ease;
}
.history-post-link:hover {
color: #b91c1c;
border-bottom-color: #b91c1c;
}
.dark .history-post-link {
color: #ef4444;
border-bottom-color: rgba(239, 68, 68, 0.5);
}
.dark .history-post-link:hover {
color: #f87171;
border-bottom-color: #f87171;
}
.history-date {
font-weight: bold;
color: #dc2626;
font-size: 14px;
/* 宽度按内容自适应:没有时分秒的记录,日期后面不会留一段空白 */
flex-shrink: 0;
margin-right: 8px;
/* 左对齐:没有时分秒的老记录不会因为右对齐而在左边留一大块空格 */
text-align: left;
white-space: nowrap;
transition: all 0.3s ease;
}
.history-content {
color: #555;
line-height: 1.6;
font-size: 14px;
word-wrap: break-word;
flex-grow: 1;
}
.history-content p {
margin: 0;
}
/* 搜索命中高亮(深浅色各一套) */
mark.dh-mark {
background-color: #fff3cd;
color: #1f2328;
padding: 1px 3px;
border-radius: 2px;
}
.dark mark.dh-mark {
background-color: rgba(187, 128, 9, 0.28);
color: #c9d1d9;
}
.history-date::after {
content: ":";
color: #666;
font-weight: normal;
padding-left: 2px;
}
.development-history-empty {
text-align: center;
padding: 30px;
color: #999;
font-size: 14px;
border: 1px dashed rgba(36, 41, 47, 0.16);
border-radius: 10px;
background-color: transparent;
}
.history-item:last-child{margin-bottom:10px;}
.history-pagination {
text-align: center;
padding-top: 30px;
transition: all 0.3s ease;
border-top: 1px solid rgba(36, 41, 47, 0.10);
padding-bottom: 20px;
}
.pagination-container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.pagination-info {
font-size: 13px;
color: #666;
margin: 0 10px;
flex-shrink: 0;
}
.pagination-nav {
display: flex;
align-items: center;
gap: 5px;
}
.pagination-page {
display: flex;
align-items: center;
gap: 8px;
}
.pagination-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 36px;
height: 36px;
padding: 0 10px;
background: transparent;
color: #333;
text-decoration: none;
border: 1px solid rgba(36, 41, 47, 0.16);
border-radius: 50px;
font-size: 14px;
transition: all 0.2s ease;
line-height: 1;
}
.pagination-link:hover {
background: #dc2626;
color: white;
border-color: #dc2626;
transform: translateY(-1px);
}
.pagination-link.active {
background: #dc2626;
color: white;
border-color: #dc2626;
font-weight: 600;
}
.pagination-link.disabled {
color: #999;
background: transparent;
border-color: rgba(36, 41, 47, 0.10);
cursor: not-allowed;
opacity: 0.6;
}
.pagination-link.disabled:hover {
background: transparent;
color: #999;
border-color: rgba(36, 41, 47, 0.10);
transform: none;
}
.pagination-ellipsis {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 36px;
height: 36px;
padding: 0 10px;
color: #666;
font-size: 14px;
}
/* 深色模式适配 */
.dark .development-history-widget {
/* 深色下同样是透明的,原来那块 #161829 的深蓝底已经去掉 */
background: transparent;
border: 0;
box-shadow: none;
}
.dark .development-history-widget h2 {
margin-top:0px;
border-bottom-width: 0px;
}
.development-history-widget h2 {
margin-top:0px;
}
.dark .widget-title {
text-align: center;
margin-bottom: 20px;
color: #c9d1d9;
font-size: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #dc2626;
transition: all 0.3s ease;
}
.dark .year-filter {
margin: 10px auto 18px;
padding: 12px 14px;
/* 同样透明,只留描边 */
background: transparent;
border-radius: 10px;
border: 1px solid #30363d;
}
.dark .year-filter-title {
font-size: 16px;
font-weight: 600;
color: #c9d1d9;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.dark .year-link {
display: inline-block;
padding: 6px 14px;
background-color: transparent;
color: #c9d1d9;
text-decoration: none;
border-radius: 10px;
border: 1px solid #30363d;
font-size: 13px;
font-weight: 500;
transition: all 0.2s ease;
}
.dark .year-link:hover {
background-color: rgba(255, 255, 255, 0.07);
border-color: #4b5563;
transform: translateY(-1px);
}
.dark .year-link.active {
background-color: #dc2626;
color: #fff;
border-color: #dc2626;
}
.dark .history-item {
border-bottom-color: #30363d;
}
.dark .history-item + .history-item {
border-top-color: #2a2f36;
}
.dark .history-item:hover {
background-color: rgba(255, 255, 255, 0.04);
}
.dark .history-date {
color: #dc2626;
}
.dark .history-content {
color: #c9d1d9;
}
.dark .history-date::after {
color: #8b949e;
}
.dark .development-history-empty {
text-align: center;
padding: 30px;
color: #8b949e;
font-size: 14px;
border: 1px dashed #30363d;
border-radius: 10px;
background-color: transparent;
}
.dark .history-pagination {
border-top: 1px solid #30363d;
}
.dark .pagination-info {
color: #8b949e;
}
.dark .pagination-link {
background: transparent;
color: #c9d1d9;
border-color: #30363d;
}
.dark .pagination-link:hover {
background: #dc2626;
color: #fff;
border-color: #dc2626;
}
.dark .pagination-link.active {
background: #dc2626;
color: #fff;
border-color: #dc2626;
}
.dark .pagination-link.disabled {
color: #6b7280;
background: transparent;
border-color: #2d333b;
}
.dark .pagination-link.disabled:hover {
background: transparent;
color: #6b7280;
border-color: #2d333b;
}
.dark .pagination-ellipsis {
color: #8b949e;
}
@media (max-width: 768px) {
.development-history-widget {
padding: 12px;
}
.widget-title {
font-size: 18px;
}
.history-item {
padding: 10px 0;
flex-direction: column;
}
.history-date {
min-width: auto;
text-align: left;
margin-bottom: 5px;
margin-right: 0;
width: 100%;
}
.history-date::after {
content: "";
}
.pagination-container {
flex-direction: column;
gap: 10px;
}
.pagination-nav {
width: 100%;
justify-content: center;
}
.pagination-page {
flex-wrap: wrap;
justify-content: center;
margin: 5px 0;
}
.year-list {
justify-content: center;
}
}
@media (max-width: 480px) {
.pagination-link {
min-width: 32px;
height: 32px;
padding: 0 8px;
font-size: 13px;
}
.pagination-ellipsis {
min-width: 32px;
height: 32px;
font-size: 13px;
}
.year-link {
padding: 5px 10px;
font-size: 12px;
}
}
/* ------------------------------------------------------------
链接颜色兜底(sagrre 等主题有 `.markdown-body a{color:#dc2626}`)
那条规则权重是 (0,1,1),比插件里的单类选择器 .pagination-link 高,
会把"清除筛选""年份""页码""相关文章"的文字强行染成主题红,
灰底红字发糊。这里统一加 .development-history-widget 前缀把权重
提到 (0,2,0)/(0,3,0),保证插件内部这些控件用自己该有的颜色。
注意:常态写在前面、hover/active/disabled 写在后面,
这样同权重时状态色仍然生效。
------------------------------------------------------------ */
.development-history-widget .clear-search-link {
color: #fff;
}
.development-history-widget .year-link {
color: #495057;
}
.development-history-widget .pagination-link {
color: #333;
}
.development-history-widget .related-post-link {
color: #495057;
}
.development-history-widget .dh-filter-current-link {
color: #6b7280;
}
.development-history-widget .year-link:hover {
color: #495057;
}
.development-history-widget .year-link.active {
color: #fff;
}
.development-history-widget .pagination-link:hover,
.development-history-widget .pagination-link.active {
color: #fff;
}
.development-history-widget .pagination-link.disabled,
.development-history-widget .pagination-link.disabled:hover {
color: #999;
}
.development-history-widget .related-post-link:hover {
color: #dc2626;
}
.dark .development-history-widget .clear-search-link {
color: #fff;
}
.dark .development-history-widget .year-link {
color: #c9d1d9;
}
.dark .development-history-widget .pagination-link {
color: #c9d1d9;
}
.dark .development-history-widget .related-post-link {
color: #c9d1d9;
}
.dark .development-history-widget .dh-filter-current-link {
color: #8b949e;
}
.dark .development-history-widget .dh-filter-current-link:hover {
color: #f87171;
}
.dark .development-history-widget .year-link:hover {
color: #c9d1d9;
}
.dark .development-history-widget .year-link.active {
color: #fff;
}
.dark .development-history-widget .pagination-link:hover,
.dark .development-history-widget .pagination-link.active {
color: #fff;
}
.dark .development-history-widget .pagination-link.disabled,
.dark .development-history-widget .pagination-link.disabled:hover {
color: #6b7280;
}
.dark .development-history-widget .related-post-link:hover {
color: #dc2626;
}
</style>
<div class="development-history-widget">
<h2 class="widget-title">网站发展历史</h2>
<!-- 搜索框 -->
<div class="history-search-box">
<form method="get" action="<?php echo $currentFile; ?>" class="search-form">
<!-- 隐藏字段,保持当前年份筛选 -->
<?php if ($selectedYear > 0): ?>
<input type="hidden" name="y" value="<?php echo $selectedYear; ?>">
<?php endif; ?>
<div class="search-input-row">
<input type="text"
name="search"
class="search-input"
placeholder="输入关键词搜索历史记录..."
value="<?php echo htmlspecialchars($searchKeyword); ?>"
maxlength="100"
aria-label="搜索历史记录">
</div>
<div class="search-button-row">
<button type="submit" class="search-button">
搜索
</button>
<?php if (!empty($searchKeyword) || $selectedYear > 0): ?>
<a href="<?php echo $currentFile; ?>" class="clear-search-link">
✕ 清除筛选
</a>
<?php endif; ?>
</div>
</form>
</div>
<!-- 年份筛选器 -->
<?php if (!empty($yearsData)): ?>
<div class="year-filter">
<ul class="year-list">
<!-- 全部年份 -->
<li class="year-item">
<a href="<?php echo changelogBuildYearUrl(0, $searchKeyword); ?>"
class="year-link <?php echo $selectedYear == 0 ? 'active' : ''; ?>">
全部
<span class="year-count">(<?php echo $totalAll; ?>)</span>
</a>
</li>
<!-- 各年份 -->
<?php foreach ($yearsData as $yearData): ?>
<li class="year-item">
<?php
$year = $yearData['year'];
$hasData = $yearData['count'] > 0;
$url = changelogBuildYearUrl($year, $searchKeyword);
?>
<a href="<?php echo $url; ?>"
class="year-link <?php echo $selectedYear == $year ? 'active' : ''; ?>"
<?php if (!$hasData): ?>style="opacity:0.5; cursor:not-allowed;" onclick="return false;"<?php endif; ?>
title="<?php echo $hasData ? "查看{$year}年记录" : "{$year}年暂无记录"; ?>">
<?php echo $year; ?>
<span class="year-count">(<?php echo $yearData['count']; ?>)</span>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<!-- 当前筛选信息 -->
<?php if ($selectedYear > 0 || !empty($searchKeyword)): ?>
<div class="dh-filter-current">
<span class="dh-filter-current-text">
<?php if (!empty($searchKeyword)): ?>
搜索 "<strong><?php echo htmlspecialchars($searchKeyword); ?></strong>":找到 <?php echo $total; ?> 条记录<?php if ($selectedYear > 0): ?>(在 <?php echo $selectedYear; ?> 年中)<?php endif; ?>
<?php else: ?>
当前筛选:<strong><?php echo $selectedYear; ?></strong> 年(<?php echo $total; ?> 条记录)
<?php endif; ?>
<a href="<?php echo $currentFile; ?>" class="dh-filter-current-link">
清除筛选
</a>
</span>
</div>
<?php endif; ?>
<!-- 搜索结果为空提示 -->
<?php if (empty($entries) && (!empty($searchKeyword) || $selectedYear > 0)): ?>
<div class="development-history-empty">
<?php if (!empty($searchKeyword) && $selectedYear > 0): ?>
未找到包含 "<strong><?php echo htmlspecialchars($searchKeyword); ?></strong>" 的 <?php echo $selectedYear; ?> 年更新记录
<?php elseif (!empty($searchKeyword)): ?>
未找到包含 "<strong><?php echo htmlspecialchars($searchKeyword); ?></strong>" 的更新记录
<?php elseif ($selectedYear > 0): ?>
<?php echo $selectedYear; ?> 年暂无更新记录
<?php endif; ?>
<div style="margin-top: 10px;">
<a href="<?php echo $currentFile; ?>" class="dh-filter-current-link">查看全部记录</a>
</div>
</div>
<?php endif; ?>
<!-- 历史记录列表 -->
<?php if (!empty($entries)): ?>
<div class="history-list">
<?php foreach ($entries as $entry): ?>
<div class="history-item">
<div class="history-date">
<?php echo self::formatEventDate($entry['event_date'], isset($config->dateFormat) ? $config->dateFormat : 'Y.m.d'); ?>
</div>
<div class="history-content">
<p>
<?php
// 结尾统一补中文分号(先去库里已有的中英文分号),再转义
$content = htmlspecialchars(self::appendSemicolon($entry['content']));
// 将 [post:cid]标题[/post] 内联标记替换为文章链接(新窗口打开)
$content = self::renderInlinePostLinks($content);
// 如果有关键词,高亮显示
if (!empty($searchKeyword)) {
$content = preg_replace(
'/(' . preg_quote($searchKeyword, '/') . ')/i',
'<mark class="dh-mark">$1</mark>',
$content
);
}
echo nl2br($content);
?>
</p>
<?php
// 显示关联文章
if (isset($config->showRelatedPosts) && $config->showRelatedPosts == 1 && !empty($entry['posts'])):
?>
<div class="related-posts">
<div class="related-posts-title">
<?php echo isset($config->relatedPostsTitle) ? $config->relatedPostsTitle : '相关文章'; ?>
</div>
<ul class="related-posts-list">
<?php foreach ($entry['posts'] as $post): ?>
<li class="related-post-item">
<a href="<?php echo $post['url']; ?>" class="related-post-link" target="_blank" rel="noopener">
<?php echo htmlspecialchars($post['title']); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ($totalPages > 1): ?>
<div class="history-pagination">
<div class="pagination-container">
<!--<div class="pagination-info">
第 <?php echo $currentPage; ?> / <?php echo $totalPages; ?> 页
</div>-->
<div class="pagination-nav">
<?php if ($currentPage > 1): ?>
<a href="<?php echo changelogBuildUrl($selectedYear, $currentPage-1, $searchKeyword); ?>"
class="pagination-link" title="上一页">
上一页
</a>
<?php else: ?>
<span class="pagination-link disabled" title="上一页">上一页</span>
<?php endif; ?>
</div>
<div class="pagination-page">
<?php
// 显示页码逻辑
$start = max(1, $currentPage - 2);
$end = min($totalPages, $currentPage + 2);
// 显示第一页和省略号
if ($start > 1) {
echo '<a href="' . changelogBuildUrl($selectedYear, 1, $searchKeyword) . '" class="pagination-link">1</a>';
if ($start > 2) {
echo '<span class="pagination-ellipsis">...</span>';
}
}
// 显示页码
for ($i = $start; $i <= $end; $i++) {
if ($i == $currentPage) {
echo '<span class="pagination-link active">' . $i . '</span>';
} else {
echo '<a href="' . changelogBuildUrl($selectedYear, $i, $searchKeyword) . '" class="pagination-link">' . $i . '</a>';
}
}
// 显示最后页和省略号
if ($end < $totalPages) {
if ($end < $totalPages - 1) {
echo '<span class="pagination-ellipsis">...</span>';
}
echo '<a href="' . changelogBuildUrl($selectedYear, $totalPages, $searchKeyword) . '" class="pagination-link">' . $totalPages . '</a>';
}
?>
</div>
<div class="pagination-nav">
<?php if ($currentPage < $totalPages): ?>
<a href="<?php echo changelogBuildUrl($selectedYear, $currentPage+1, $searchKeyword); ?>"
class="pagination-link" title="下一页">
下一页
</a>
<?php else: ?>
<span class="pagination-link disabled" title="下一页">下一页</span>
<?php endif; ?>
</div>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<script>
// 注意:这里本来有一段「页面打开自动 focus 搜索框」,2026-11-23 已删除——
// 自动聚焦会把页面滚动到搜索框位置(移动端尤其明显,打开像跳到列表中间),
// 现在打开页面停在顶部,用户点搜索框才输入。
// 搜索表单提交时验证
var searchForm = document.querySelector('.search-form');
if (searchForm) {
searchForm.addEventListener('submit', function(e) {
var searchInput = this.querySelector('.search-input');
if (searchInput.value.trim() === '') {
e.preventDefault();
// 如果已经有年份筛选,保留年份参数
var yearParam = '';
window.location.href = 'index.php' + yearParam;
}
});
}
// 确保年份链接正确传递搜索参数
document.addEventListener('DOMContentLoaded', function() {
var searchKeyword = '';
var yearLinks = document.querySelectorAll('.year-link[href]');
yearLinks.forEach(function(link) {
var href = link.getAttribute('href');
if (searchKeyword && href.indexOf('search=') === -1) {
// 如果链接中没有搜索参数,但当前有搜索关键词,需要添加
var separator = href.indexOf('?') === -1 ? '?' : '&';
var newHref = href + separator + 'search=' + encodeURIComponent(searchKeyword);
link.setAttribute('href', newHref);
}
});
});
// 搜索框动画效果
document.addEventListener('DOMContentLoaded', function() {
var searchInput = document.querySelector('.search-input');
if (searchInput) {
searchInput.addEventListener('focus', function() {
this.parentElement.style.transform = 'scale(1.02)';
});
searchInput.addEventListener('blur', function() {
this.parentElement.style.transform = 'scale(1)';
});
}
});
</script>
<?php
}
}
/**
* 旧类名兼容壳(只为吃掉 Typecho 里残留的钩子句柄)
*
* Typecho 把插件的 finishPublish 句柄以「类名 + 方法名」存进 options.plugins,
* 停用插件时写入的是一条指向旧类的空钩子。改名之后插件的类已经不存在,
* 这些残留句柄在发布文章时会被 call_user_func_array 直接调用,
* PHP 8 抛出「Class "DevelopmentHistory_Plugin" not found」,文章能存进库
* 但页面是 500 —— 每发一篇炸一次。
*
* 这里补一个只含空方法的旧类名,让残留句柄有个落点,行为等同「什么都不做」。
* 旧插件目录还留着、且仍处于启用状态时它自己会声明这个类,class_exists
* 判断会跳过本段,不会出现「Cannot declare class」。
*/
if (!class_exists('DevelopmentHistory_Plugin')) {
class DevelopmentHistory_Plugin
{
/** 旧插件的注销钩子 */
public static function hookNoop()
{
}
/** 旧插件的自动记录钩子(兼容壳里不做事,避免两条记录写两张表) */
public static function recordPublishedPost($contents = null, $widget = null)
{
}
/**
* 未知旧方法兜底:残留句柄若指向上面没列出的旧方法,
* PHP 8 下会 fatal,这里统一吞掉,等同空操作。
*/
public static function __callStatic($name, $arguments)
{
return null;
}
}
}