599 lines
20 KiB
PHP
599 lines
20 KiB
PHP
<?php
|
||
class ChangeLog_Action
|
||
{
|
||
/**
|
||
* 数据库对象
|
||
*/
|
||
private $db;
|
||
private $prefix;
|
||
|
||
/**
|
||
* 请求对象
|
||
*/
|
||
private $request;
|
||
|
||
/**
|
||
* 响应对象
|
||
*/
|
||
private $response;
|
||
|
||
/**
|
||
* 构造函数
|
||
*/
|
||
public function __construct($request = null, $response = null)
|
||
{
|
||
$this->db = Typecho_Db::get();
|
||
$this->prefix = $this->db->getPrefix();
|
||
$this->request = $request ?: Typecho_Request::getInstance();
|
||
$this->response = $response ?: Typecho_Response::getInstance();
|
||
|
||
// 老版本 event_date 是 DATE 类型,会丢掉时分秒,这里做一次自动升级
|
||
$this->ensureEventDateColumn();
|
||
}
|
||
|
||
/**
|
||
* 当前站点是不是 SQLite(与 Plugin::isSqlite() 同口径)
|
||
*
|
||
* @return bool
|
||
*/
|
||
private function isSqliteDb()
|
||
{
|
||
try {
|
||
return stripos(get_class($this->db->getAdapter()), 'sqlite') !== false;
|
||
} catch (Throwable $e) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 确保 event_date 列已升级为 DATETIME
|
||
*
|
||
* 旧版本建表时 event_date 是 DATE,只存年月日。插件文件更新后如果没有
|
||
* 重新启用插件,activate() 不会执行,这里做一次轻量结构检查并自动升级,
|
||
* 避免写入的时分秒被 DATE 列悄悄截断。每个请求最多检查一次。
|
||
*
|
||
* @return void
|
||
*/
|
||
private function ensureEventDateColumn()
|
||
{
|
||
static $checked = false;
|
||
|
||
if ($checked) {
|
||
return;
|
||
}
|
||
$checked = true;
|
||
|
||
// 2.0.1:SQLite 必须在这里早退。
|
||
// 2.0.0 及以前无条件跑 MySQL 的 SHOW COLUMNS,SQLite 不认这种语法,
|
||
// 于是每走一次 Action(后台增删改、导入导出)就往 error_log 写一条
|
||
// 「near "SHOW": syntax error」。功能本来就没事:SQLite 建表时
|
||
// event_date 就是 DATETIME,而且列类型只是「亲和性」,写 'Y-m-d H:i:s'
|
||
// 不会被截断,没有升级的必要。Plugin::getTableColumns() 早就分了
|
||
// PRAGMA / SHOW 两条路,这里当时漏了。
|
||
if ($this->isSqliteDb()) {
|
||
return;
|
||
}
|
||
|
||
try {
|
||
$tableName = $this->prefix . 'changelog';
|
||
$columns = $this->db->fetchAll($this->db->query("SHOW COLUMNS FROM `{$tableName}` LIKE 'event_date'"));
|
||
|
||
if (empty($columns)) {
|
||
return;
|
||
}
|
||
|
||
$type = isset($columns[0]['Type']) ? strtolower($columns[0]['Type']) : '';
|
||
if ($type === 'datetime') {
|
||
return;
|
||
}
|
||
|
||
$this->db->query("ALTER TABLE `{$tableName}` MODIFY `event_date` DATETIME NOT NULL COMMENT '事件日期时间'");
|
||
} catch (Throwable $e) {
|
||
// 升级失败不阻断页面,写入时仍按原逻辑执行
|
||
error_log('ChangeLog ensureEventDateColumn Error: ' . $e->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 归一化事件日期时间为 Y-m-d H:i:s
|
||
*
|
||
* 支持的写法:
|
||
* 2026-10-27
|
||
* 2026-10-27 11:07:16 / 2026-10-27 11:07
|
||
* 2026-10-27T11:07:16(datetime-local 的提交格式)
|
||
* 2026.10.27 11:07:16(导入文本里常见的写法)
|
||
* 不带时间部分时按 00:00:00 处理。
|
||
*
|
||
* @param string $value
|
||
* @return string
|
||
* @throws Exception 日期或时间非法时抛出
|
||
*/
|
||
private function normalizeEventDate($value)
|
||
{
|
||
$value = trim((string) $value);
|
||
|
||
// 统一分隔符:T、点、斜杠都换成标准写法
|
||
$normalized = str_replace(array('T', '.', '/'), array(' ', '-', '-'), $value);
|
||
$normalized = preg_replace('/\s+/', ' ', $normalized);
|
||
|
||
if (!preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})(?: (\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?$/', $normalized, $matches)) {
|
||
throw new Exception("日期格式错误,应为 YYYY-MM-DD HH:MM:SS(时间可省略)");
|
||
}
|
||
|
||
$year = intval($matches[1]);
|
||
$month = intval($matches[2]);
|
||
$day = intval($matches[3]);
|
||
$hour = (isset($matches[4]) && $matches[4] !== '') ? intval($matches[4]) : 0;
|
||
$minute = (isset($matches[5]) && $matches[5] !== '') ? intval($matches[5]) : 0;
|
||
$second = (isset($matches[6]) && $matches[6] !== '') ? intval($matches[6]) : 0;
|
||
|
||
if (!checkdate($month, $day, $year)) {
|
||
throw new Exception("无效的日期:{$value}");
|
||
}
|
||
|
||
if ($hour > 23 || $minute > 59 || $second > 59) {
|
||
throw new Exception("无效的时间:{$value}");
|
||
}
|
||
|
||
return sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year, $month, $day, $hour, $minute, $second);
|
||
}
|
||
|
||
/**
|
||
* 格式化事件日期时间:日期后空格显示时分秒
|
||
*
|
||
* 升级前的老记录只存了日期(时间为 00:00:00),这类记录只显示日期,
|
||
* 不显示没有意义的 00:00:00。
|
||
*
|
||
* @param string $value 数据库中的 event_date
|
||
* @param string $dateFormat PHP 日期格式
|
||
* @return string
|
||
*/
|
||
private 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;
|
||
}
|
||
|
||
/**
|
||
* 添加更新记录 - 修复:使用Typecho正确的SQL构建方法
|
||
*/
|
||
public function addEntry($data)
|
||
{
|
||
try {
|
||
$now = new Typecho_Date(Typecho_Date::gmtTime());
|
||
|
||
$insert = array(
|
||
'content' => $data['content'],
|
||
'event_date' => $data['event_date'],
|
||
'post_cids' => isset($data['post_cids']) ? $this->cleanCids($data['post_cids']) : '',
|
||
'created' => $now->format('Y-m-d H:i:s'),
|
||
'modified' => $now->format('Y-m-d H:i:s'),
|
||
'status' => 1
|
||
);
|
||
|
||
// 使用Typecho的查询构建器,但先验证数据
|
||
$this->validateInsertData($insert);
|
||
|
||
// 修复:正确构建并执行插入查询
|
||
// 在Typecho中,insert()->rows()需要调用query()方法来执行
|
||
$query = $this->db->insert($this->prefix . 'changelog')->rows($insert);
|
||
|
||
// 执行查询
|
||
$this->db->query($query);
|
||
|
||
// 获取自增ID
|
||
// 注意:不能写成 $db->select('LAST_INSERT_ID() as id') 而不带 from(),
|
||
// Typecho 的查询构建器会生成 "SELECT LAST_INSERT_ID() as id FROM"(表名缺失),
|
||
// MySQL 直接报 1064 near '' at line 1,于是数据已经插入成功却抛出"发布失败"
|
||
return $this->getLastInsertId();
|
||
|
||
} catch (Exception $e) {
|
||
error_log("addEntry Error: " . $e->getMessage());
|
||
error_log("Data: " . print_r($data, true));
|
||
throw new Exception("发布失败: " . $e->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 安全地获取刚插入记录的自增ID
|
||
*
|
||
* 走数据库适配器的 lastInsertId(),而不是拼一条 SELECT 查询;
|
||
* 取不到时退回"查最大 id"的兜底方案,保证不会因为取 ID 失败而让
|
||
* 已经成功的插入操作报错。
|
||
*
|
||
* @return int
|
||
*/
|
||
private function getLastInsertId()
|
||
{
|
||
if (method_exists($this->db, 'getAdapter')) {
|
||
try {
|
||
$adapter = $this->db->getAdapter();
|
||
if (is_object($adapter) && method_exists($adapter, 'lastInsertId')) {
|
||
$id = (int) $adapter->lastInsertId();
|
||
if ($id > 0) {
|
||
return $id;
|
||
}
|
||
}
|
||
} catch (Throwable $e) {
|
||
// 适配器不支持时忽略,继续走兜底方案
|
||
}
|
||
}
|
||
|
||
// 兜底:取当前最大 id(表按 id 自增,刚插入的即最大 id)
|
||
$query = $this->db->select('id')
|
||
->from($this->prefix . 'changelog')
|
||
->order('id', Typecho_Db::SORT_DESC)
|
||
->limit(1);
|
||
$row = $this->db->fetchRow($query);
|
||
|
||
return $row && isset($row['id']) ? (int) $row['id'] : 0;
|
||
}
|
||
|
||
/**
|
||
* 验证插入数据
|
||
*/
|
||
private function validateInsertData(&$data)
|
||
{
|
||
// 确保所有必需字段都有值
|
||
if (empty($data['content'])) {
|
||
throw new Exception("内容不能为空");
|
||
}
|
||
|
||
if (empty($data['event_date'])) {
|
||
throw new Exception("日期不能为空");
|
||
}
|
||
|
||
// 验证日期时间并统一成 Y-m-d H:i:s(只填日期时按 00:00:00 处理)
|
||
$data['event_date'] = $this->normalizeEventDate($data['event_date']);
|
||
|
||
// 清理和转义内容
|
||
$data['content'] = trim($data['content']);
|
||
if (empty($data['content'])) {
|
||
throw new Exception("内容不能为空");
|
||
}
|
||
|
||
// 确保所有字段都是字符串
|
||
foreach ($data as $key => $value) {
|
||
if (!is_string($value) && !is_numeric($value)) {
|
||
$data[$key] = (string)$value;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量添加更新记录(按事件时间排序插入,越近的ID越大)
|
||
*/
|
||
public function batchAddEntries($entries)
|
||
{
|
||
// 按事件时间排序,越近的时间越晚插入,这样ID越大
|
||
usort($entries, function($a, $b) {
|
||
return strtotime($a['event_date']) - strtotime($b['event_date']);
|
||
});
|
||
|
||
$now = new Typecho_Date(Typecho_Date::gmtTime());
|
||
$nowStr = $now->format('Y-m-d H:i:s');
|
||
|
||
foreach ($entries as $entry) {
|
||
$insert = array(
|
||
'content' => $entry['content'],
|
||
'event_date' => $this->normalizeEventDate($entry['event_date']),
|
||
'post_cids' => '',
|
||
'created' => $nowStr,
|
||
'modified' => $nowStr,
|
||
'status' => 1
|
||
);
|
||
|
||
$query = $this->db->insert($this->prefix . 'changelog')->rows($insert);
|
||
$this->db->query($query);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 更新更新记录
|
||
*/
|
||
public function updateEntry($data)
|
||
{
|
||
try {
|
||
$now = new Typecho_Date(Typecho_Date::gmtTime());
|
||
|
||
$update = array(
|
||
'content' => $data['edit_content'],
|
||
'event_date' => $this->normalizeEventDate($data['edit_event_date']),
|
||
'post_cids' => isset($data['edit_post_cids']) ? $this->cleanCids($data['edit_post_cids']) : '',
|
||
'modified' => $now->format('Y-m-d H:i:s')
|
||
);
|
||
|
||
$query = $this->db->update($this->prefix . 'changelog')
|
||
->rows($update)
|
||
->where('id = ?', intval($data['edit_id']));
|
||
|
||
$this->db->query($query);
|
||
|
||
} catch (Exception $e) {
|
||
error_log("updateEntry Error: " . $e->getMessage());
|
||
throw new Exception("更新失败: " . $e->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 删除更新记录
|
||
*/
|
||
public function deleteEntry($id)
|
||
{
|
||
$query = $this->db->delete($this->prefix . 'changelog')->where('id = ?', intval($id));
|
||
$this->db->query($query);
|
||
}
|
||
|
||
/**
|
||
* 批量删除
|
||
*/
|
||
public function deleteEntries($ids)
|
||
{
|
||
foreach ($ids as $id) {
|
||
$this->deleteEntry(intval($id));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取更新记录
|
||
*
|
||
* 2.0.10:$keyword 非空时按「内容」模糊匹配(后台管理列表的搜索框用)。
|
||
* 关键词一律走参数绑定,不拼进 SQL;% 和 _ 不做转义 —— 这样搜
|
||
* xiaoaji_2026 这类带下划线的内容能按字面量命中,代价只是手输 % 会变成
|
||
* 模糊通配(等于放宽条件,不会出错)。
|
||
*/
|
||
public function getEntries($page = 1, $perPage = 10, $keyword = '')
|
||
{
|
||
$offset = ($page - 1) * $perPage;
|
||
|
||
// 2.0.2:与前台同口径,按事件时间倒序,id 只做同刻稳定次序
|
||
$query = $this->db->select()
|
||
->from($this->prefix . 'changelog')
|
||
->where('status = ?', 1);
|
||
|
||
$keyword = trim((string) $keyword);
|
||
if ($keyword !== '') {
|
||
$query->where('content LIKE ?', '%' . $keyword . '%');
|
||
}
|
||
|
||
$query->order('event_date', Typecho_Db::SORT_DESC)
|
||
->order('id', Typecho_Db::SORT_ASC)
|
||
->limit($perPage)
|
||
->offset($offset);
|
||
|
||
return $this->db->fetchAll($query);
|
||
}
|
||
|
||
/**
|
||
* 获取所有更新记录(用于导出)
|
||
*/
|
||
public function getAllEntries()
|
||
{
|
||
// 2.0.2:导出也按事件时间倒序(与页面一致);再导入时 batchAddEntries
|
||
// 会按时间升序重新插入,同刻条目保持原相对顺序,来回导不会打乱
|
||
$query = $this->db->select()
|
||
->from($this->prefix . 'changelog')
|
||
->where('status = ?', 1)
|
||
->order('event_date', Typecho_Db::SORT_DESC)
|
||
->order('id', Typecho_Db::SORT_ASC);
|
||
|
||
return $this->db->fetchAll($query);
|
||
}
|
||
|
||
/**
|
||
* 获取总记录数
|
||
*
|
||
* 2.0.10:传了 $keyword 就只数匹配的记录(后台分页要用),不传则是全库总数
|
||
* (统计卡片「总记录数」用,搜索时不应该跟着变小)。
|
||
*/
|
||
public function getTotalCount($keyword = '')
|
||
{
|
||
$query = $this->db->select('COUNT(*) as count')
|
||
->from($this->prefix . 'changelog')
|
||
->where('status = ?', 1);
|
||
|
||
$keyword = trim((string) $keyword);
|
||
if ($keyword !== '') {
|
||
$query->where('content LIKE ?', '%' . $keyword . '%');
|
||
}
|
||
|
||
$result = $this->db->fetchRow($query);
|
||
return $result['count'];
|
||
}
|
||
|
||
/**
|
||
* 获取单条记录
|
||
*/
|
||
public function getEntry($id)
|
||
{
|
||
$query = $this->db->select()
|
||
->from($this->prefix . 'changelog')
|
||
->where('id = ?', $id)
|
||
->limit(1);
|
||
|
||
return $this->db->fetchRow($query);
|
||
}
|
||
|
||
/**
|
||
* 根据文章CID获取文章信息
|
||
*/
|
||
public function getPostByCid($cid)
|
||
{
|
||
try {
|
||
$query = $this->db->select('cid, title, slug, created')
|
||
->from($this->prefix . 'contents')
|
||
->where('cid = ?', intval($cid))
|
||
->where('type = ?', 'post')
|
||
->where('status = ?', 'publish')
|
||
->limit(1);
|
||
|
||
$post = $this->db->fetchRow($query);
|
||
|
||
if ($post) {
|
||
$options = Typecho_Widget::widget('Widget_Options');
|
||
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);
|
||
}
|
||
}
|
||
|
||
return $post;
|
||
} catch (Exception $e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 清理CID字符串
|
||
*/
|
||
private function cleanCids($cids)
|
||
{
|
||
if (empty($cids)) {
|
||
return '';
|
||
}
|
||
|
||
$cidsArray = array_filter(array_map('trim', explode(',', $cids)));
|
||
$validCids = array();
|
||
|
||
foreach ($cidsArray as $cid) {
|
||
if (is_numeric($cid) && $cid > 0) {
|
||
$validCids[] = intval($cid);
|
||
}
|
||
}
|
||
|
||
// 去重并返回逗号分隔的字符串
|
||
return implode(',', array_unique($validCids));
|
||
}
|
||
|
||
/**
|
||
* 导出数据为文本格式
|
||
*/
|
||
public function exportData()
|
||
{
|
||
$entries = $this->getAllEntries();
|
||
$content = '';
|
||
|
||
foreach ($entries as $entry) {
|
||
// 使用 Y.m.d H:i:s 格式导出,日期后空格接时分秒
|
||
$date = $this->formatEventDate($entry['event_date'], 'Y.m.d');
|
||
$text = str_replace(array("\r\n", "\r", "\n"), " ", $entry['content']);
|
||
$content .= $date . ' ' . $text . "\n";
|
||
}
|
||
|
||
return $content;
|
||
}
|
||
|
||
/**
|
||
* 导入数据(增强版,支持调试)
|
||
*/
|
||
public function importData($text)
|
||
{
|
||
// 标准化换行符
|
||
$text = str_replace("\r\n", "\n", $text);
|
||
$text = str_replace("\r", "\n", $text);
|
||
|
||
$lines = explode("\n", $text);
|
||
$imported = 0;
|
||
$failed = 0;
|
||
$failReasons = array(); // 记录失败原因
|
||
$entries = array();
|
||
|
||
foreach ($lines as $lineNum => $line) {
|
||
$line = trim($line);
|
||
if (empty($line)) continue;
|
||
|
||
// 移除行尾的分号(如果有)
|
||
if (substr($line, -1) === ';') {
|
||
$line = substr($line, 0, -1);
|
||
$line = trim($line);
|
||
}
|
||
|
||
// 找到第一个空格的位置来分割日期和内容
|
||
$firstSpacePos = strpos($line, ' ');
|
||
if ($firstSpacePos === false) {
|
||
$failed++;
|
||
$failReasons[] = "第 " . ($lineNum + 1) . " 行:找不到空格分隔日期和内容 - '{$line}'";
|
||
continue;
|
||
}
|
||
|
||
$date = trim(substr($line, 0, $firstSpacePos));
|
||
$content = trim(substr($line, $firstSpacePos + 1));
|
||
|
||
// 验证日期格式 - 支持单个数字的月份和日期
|
||
// 允许的格式:YYYY.M.D, YYYY.MM.D, YYYY.M.DD, YYYY.MM.DD
|
||
$datePattern = '/^(\d{4})\.(\d{1,2})\.(\d{1,2})$/';
|
||
if (!preg_match($datePattern, $date, $matches)) {
|
||
$failed++;
|
||
$failReasons[] = "第 " . ($lineNum + 1) . " 行:日期格式错误,应为 YYYY.M[M].D[D] - '{$date}'";
|
||
continue;
|
||
}
|
||
|
||
// 检查日期是否有效
|
||
$year = intval($matches[1]);
|
||
$month = intval($matches[2]);
|
||
$day = intval($matches[3]);
|
||
|
||
if (!checkdate($month, $day, $year)) {
|
||
$failed++;
|
||
$failReasons[] = "第 " . ($lineNum + 1) . " 行:无效的日期 - {$date}";
|
||
continue;
|
||
}
|
||
|
||
// 日期后可能紧跟时分秒(导出文件就是这种格式),有就取出来,没有按 00:00:00 处理
|
||
$timePart = '00:00:00';
|
||
$restParts = preg_split('/\s+/', $content, 2);
|
||
$maybeTime = isset($restParts[0]) ? trim($restParts[0]) : '';
|
||
|
||
if (preg_match('/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/', $maybeTime, $timeMatches)) {
|
||
$hour = intval($timeMatches[1]);
|
||
$minute = intval($timeMatches[2]);
|
||
$second = (isset($timeMatches[3]) && $timeMatches[3] !== '') ? intval($timeMatches[3]) : 0;
|
||
|
||
if ($hour > 23 || $minute > 59 || $second > 59) {
|
||
$failed++;
|
||
$failReasons[] = "第 " . ($lineNum + 1) . " 行:无效的时间 - {$maybeTime}";
|
||
continue;
|
||
}
|
||
|
||
$timePart = sprintf('%02d:%02d:%02d', $hour, $minute, $second);
|
||
$content = isset($restParts[1]) ? trim($restParts[1]) : '';
|
||
}
|
||
|
||
// 转换日期格式为 Y-m-d H:i:s 以便数据库存储,补零成两位数字
|
||
$dbDate = sprintf('%04d-%02d-%02d', $year, $month, $day) . ' ' . $timePart;
|
||
|
||
// 验证内容
|
||
if (empty($content)) {
|
||
$failed++;
|
||
$failReasons[] = "第 " . ($lineNum + 1) . " 行:内容为空";
|
||
continue;
|
||
}
|
||
|
||
$entries[] = array(
|
||
'event_date' => $dbDate,
|
||
'content' => $content
|
||
);
|
||
$imported++;
|
||
}
|
||
|
||
if (!empty($entries)) {
|
||
$this->batchAddEntries($entries);
|
||
}
|
||
|
||
// 返回包含失败原因的结果
|
||
return array(
|
||
'imported' => $imported,
|
||
'failed' => $failed,
|
||
'fail_reasons' => $failReasons
|
||
);
|
||
}
|
||
} |