606 lines
18 KiB
PHP
606 lines
18 KiB
PHP
<?php
|
||
/**
|
||
* AIAssist 插件设置备份 / 恢复
|
||
*
|
||
* 备的是「插件设置」,不是运行日志 —— debug.log 只写尾部几十行,本来就不需要
|
||
* 备份;真正怕丢的是这一页配置(AI 服务商、两家的 API Key、模型名那一整套),
|
||
* 被清空或改错之后发布文章 AI 就静默不干活,而且很难当场发现。
|
||
*
|
||
* 所以这里只做两件事:
|
||
* 备份 —— 把 options 表里的 plugin:AIAssist 存一份到 data/backup/
|
||
* 恢复 —— 用指定的一份手动备份覆盖回去(不指定就是最新那份)
|
||
*
|
||
* 刻意不做自动备份、不做定时任务:设置就一页表单,手动点一下足够。
|
||
* 但保留最近 N 份(默认 5,可配置 3–20),设置页能把历史列出来挑一份恢复 ——
|
||
* 「备份了但回不去那份对的」比没有备份更难受。
|
||
*
|
||
* 兼容性说明:Typecho 1.1/1.2 把插件配置存成 serialize 字符串,1.2 之后
|
||
* (含 1.3)存成 JSON。这里不写死格式,而是看库里现存的字符串长什么样,
|
||
* 再决定用哪种方式写回去 —— 换个版本迁移站点也不会写坏。
|
||
*
|
||
* @package AIAssist
|
||
*/
|
||
|
||
if (!defined('__TYPECHO_ROOT_DIR__')) {
|
||
exit;
|
||
}
|
||
|
||
class AIAssist_Settings
|
||
{
|
||
/** options 表里插件配置的 name */
|
||
const OPTION_NAME = 'plugin:AIAssist';
|
||
|
||
/** 最多保留几份手动备份(默认值,实际取设置项 backupKeep) */
|
||
const BACKUP_KEEP = 5;
|
||
|
||
/** 备份保留份数的取值范围 */
|
||
const BACKUP_KEEP_MIN = 3;
|
||
const BACKUP_KEEP_MAX = 20;
|
||
|
||
/** 备份文件名前缀 */
|
||
const BACKUP_PREFIX = 'aiassist-settings-';
|
||
|
||
/** options 表里插件配置所在字段 */
|
||
const TABLE = 'table.options';
|
||
|
||
/** 备份文件头标记 */
|
||
const BACKUP_MARK = 'AIASSIST-SETTINGS-BACKUP';
|
||
|
||
/**
|
||
* 取数据库对象
|
||
*/
|
||
public static function db()
|
||
{
|
||
if (class_exists('Typecho_Db')) {
|
||
try {
|
||
return Typecho_Db::get();
|
||
} catch (Exception $e) {
|
||
} catch (Throwable $e) {
|
||
}
|
||
}
|
||
if (class_exists('Typecho\\Db')) {
|
||
try {
|
||
return \Typecho\Db::get();
|
||
} catch (Exception $e) {
|
||
} catch (Throwable $e) {
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 读库里存的原始字符串(没记录返回 null)
|
||
*/
|
||
public static function readRaw()
|
||
{
|
||
return self::readRawByName(self::OPTION_NAME);
|
||
}
|
||
|
||
/**
|
||
* 按 options.name 读原始值
|
||
*
|
||
* @param string $name
|
||
* @return string|null
|
||
*/
|
||
private static function readRawByName($name)
|
||
{
|
||
$db = self::db();
|
||
if (!$db) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
$row = $db->fetchRow(
|
||
$db->select()->from(self::TABLE)
|
||
->where('name = ?', $name)
|
||
->limit(1)
|
||
);
|
||
if (!$row || !isset($row['value']) || $row['value'] === '') {
|
||
return null;
|
||
}
|
||
return (string) $row['value'];
|
||
} catch (Exception $e) {
|
||
self::logError('读取插件配置失败:' . $e->getMessage());
|
||
} catch (Throwable $e) {
|
||
self::logError('读取插件配置失败:' . $e->getMessage());
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 当前插件设置(解码后)
|
||
*
|
||
* @return array
|
||
*/
|
||
public static function read()
|
||
{
|
||
$raw = self::readRaw();
|
||
if ($raw === null || $raw === '') {
|
||
return array();
|
||
}
|
||
|
||
$isSerialized = strpos($raw, 'a:') === 0 || $raw === 'b:0;';
|
||
$data = $isSerialized ? @unserialize($raw) : json_decode($raw, true);
|
||
|
||
return is_array($data) ? $data : array();
|
||
}
|
||
|
||
/**
|
||
* 把一个设置数组写回 options 表
|
||
*
|
||
* @param array $settings
|
||
* @return bool
|
||
*/
|
||
public static function write(array $settings)
|
||
{
|
||
$db = self::db();
|
||
if (!$db) {
|
||
return false;
|
||
}
|
||
|
||
$value = self::encode($settings);
|
||
if ($value === false || $value === '') {
|
||
return false;
|
||
}
|
||
|
||
try {
|
||
$rows = $db->fetchAll(
|
||
$db->select('name', 'user')->from(self::TABLE)
|
||
->where('name = ?', self::OPTION_NAME)
|
||
);
|
||
$rows = (array) $rows;
|
||
|
||
if (empty($rows)) {
|
||
$db->query($db->insert(self::TABLE)->rows(array(
|
||
'name' => self::OPTION_NAME,
|
||
'value' => $value,
|
||
'user' => 0,
|
||
)));
|
||
return true;
|
||
}
|
||
|
||
foreach ($rows as $row) {
|
||
$db->query(
|
||
$db->update(self::TABLE)
|
||
->rows(array('value' => $value))
|
||
->where('name = ?', self::OPTION_NAME)
|
||
->where('user = ?', intval($row['user']))
|
||
);
|
||
}
|
||
|
||
return true;
|
||
} catch (Exception $e) {
|
||
self::logError('写回插件配置失败:' . $e->getMessage());
|
||
} catch (Throwable $e) {
|
||
self::logError('写回插件配置失败:' . $e->getMessage());
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 按「这个站当前用的格式」编码
|
||
*
|
||
* 判断依据是库里现存的字符串:以 a: 开头就是 serialize(Typecho 1.1/1.2),
|
||
* 否则按 JSON(1.2+)。一条记录都没有时才退回去看版本号。
|
||
*/
|
||
private static function encode(array $settings)
|
||
{
|
||
$raw = self::readRaw();
|
||
|
||
if ($raw !== null && $raw !== '') {
|
||
if (strpos($raw, 'a:') === 0) {
|
||
return serialize($settings);
|
||
}
|
||
return self::jsonEncode($settings);
|
||
}
|
||
|
||
$version = '';
|
||
try {
|
||
if (class_exists('Typecho_Common') && defined('Typecho_Common::VERSION')) {
|
||
$version = Typecho_Common::VERSION;
|
||
} elseif (class_exists('Typecho\\Common') && defined('Typecho\\Common::VERSION')) {
|
||
$version = \Typecho\Common::VERSION;
|
||
}
|
||
} catch (Exception $e) {
|
||
} catch (Throwable $e) {
|
||
}
|
||
|
||
if ($version !== '' && version_compare($version, '1.2', '<')) {
|
||
return serialize($settings);
|
||
}
|
||
|
||
return self::jsonEncode($settings);
|
||
}
|
||
|
||
/* ------------------------------------------------------------------
|
||
* 备份文件
|
||
* ------------------------------------------------------------------ */
|
||
|
||
public static function backupDir()
|
||
{
|
||
return dirname(__FILE__) . '/data/backup';
|
||
}
|
||
|
||
/**
|
||
* 备份最多保留几份(读设置项 backupKeep)
|
||
*
|
||
* 读不到、写成空、写成非数字都回落默认值;超出范围就夹到上下限,
|
||
* 免得有人填个 0 把自己的备份全删了。
|
||
*
|
||
* @return int
|
||
*/
|
||
public static function backupKeep()
|
||
{
|
||
$default = self::BACKUP_KEEP;
|
||
|
||
$settings = self::read();
|
||
$raw = isset($settings['backupKeep']) ? trim((string) $settings['backupKeep']) : '';
|
||
if ($raw === '' || !preg_match('/^\d+$/', $raw)) {
|
||
return $default;
|
||
}
|
||
|
||
$value = intval($raw);
|
||
if ($value < self::BACKUP_KEEP_MIN) {
|
||
return self::BACKUP_KEEP_MIN;
|
||
}
|
||
if ($value > self::BACKUP_KEEP_MAX) {
|
||
return self::BACKUP_KEEP_MAX;
|
||
}
|
||
|
||
return $value;
|
||
}
|
||
|
||
private static function ensureBackupDir()
|
||
{
|
||
$dir = self::backupDir();
|
||
|
||
if (!is_dir($dir)) {
|
||
@mkdir($dir, 0755, true);
|
||
}
|
||
if (!is_dir($dir)) {
|
||
return false;
|
||
}
|
||
|
||
/*
|
||
* 备份里有 AI 服务商的 API Key,属于「不该被公网读到」的东西。
|
||
* 插件目录一般是能直接访问的,所以两层保护:
|
||
* 文件本体是 .php(直接访问只会执行 exit,看不到内容)
|
||
* 目录里再放 .htaccess(Apache 直接拒掉整个目录)
|
||
*/
|
||
if (!is_file($dir . '/.htaccess')) {
|
||
@file_put_contents($dir . '/.htaccess', "Require all denied\nDeny from all\n");
|
||
}
|
||
if (!is_file($dir . '/index.html')) {
|
||
@file_put_contents($dir . '/index.html', '');
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 手动备份一次插件设置
|
||
*
|
||
* @return array ok / message / file / count / created
|
||
*/
|
||
public static function backup()
|
||
{
|
||
$fail = array('ok' => false, 'message' => '', 'file' => '', 'count' => 0, 'created' => 0);
|
||
|
||
$settings = self::read();
|
||
if (empty($settings)) {
|
||
$fail['message'] = '还没读到插件设置,请先保存一次插件设置再备份';
|
||
return $fail;
|
||
}
|
||
|
||
if (!self::ensureBackupDir()) {
|
||
$fail['message'] = '备份目录 data/backup 不可写,请给该目录写入权限';
|
||
return $fail;
|
||
}
|
||
|
||
$created = time();
|
||
$meta = array(
|
||
'plugin' => 'AIAssist',
|
||
'version' => self::version(),
|
||
'created' => $created,
|
||
'count' => count($settings),
|
||
'siteUrl' => self::siteUrl(),
|
||
);
|
||
|
||
$payload = array_merge($meta, array('settings' => $settings));
|
||
$json = self::jsonEncode($payload);
|
||
if ($json === false) {
|
||
$fail['message'] = '序列化设置失败';
|
||
return $fail;
|
||
}
|
||
|
||
if (function_exists('gzcompress')) {
|
||
$gz = @gzcompress($json, 6);
|
||
$encoded = ($gz === false || $gz === '') ? base64_encode($json) : 'gz:' . base64_encode($gz);
|
||
} else {
|
||
$encoded = 'b64:' . base64_encode($json);
|
||
}
|
||
|
||
$content = '<?php /* ' . self::BACKUP_MARK . ' ' . self::jsonEncode($meta)
|
||
. ' */ exit; ?>' . "\n" . $encoded;
|
||
|
||
$file = self::backupDir() . '/' . self::BACKUP_PREFIX . date('Ymd-His', $created) . '.php';
|
||
if (@file_put_contents($file, $content, LOCK_EX) === false) {
|
||
$fail['message'] = '写入备份文件失败,请检查 data/backup 目录权限';
|
||
return $fail;
|
||
}
|
||
|
||
$removed = self::pruneBackups();
|
||
$total = count(self::backups());
|
||
|
||
return array(
|
||
'ok' => true,
|
||
'message' => '设置已备份',
|
||
'file' => basename($file),
|
||
'count' => count($settings),
|
||
'created' => $created,
|
||
'keep' => self::backupKeep(),
|
||
'total' => $total,
|
||
'removed' => $removed,
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 备份列表(新 → 旧)
|
||
*/
|
||
public static function backups()
|
||
{
|
||
$dir = self::backupDir();
|
||
if (!is_dir($dir)) {
|
||
return array();
|
||
}
|
||
|
||
$files = (array) glob($dir . '/' . self::BACKUP_PREFIX . '*.php');
|
||
if (empty($files)) {
|
||
return array();
|
||
}
|
||
|
||
$list = array();
|
||
foreach ($files as $file) {
|
||
$meta = self::readMeta($file);
|
||
$list[] = array(
|
||
'file' => basename($file),
|
||
'size' => (int) @filesize($file),
|
||
'created' => !empty($meta['created']) ? intval($meta['created']) : (int) @filemtime($file),
|
||
'count' => !empty($meta['count']) ? intval($meta['count']) : 0,
|
||
'version' => isset($meta['version']) ? (string) $meta['version'] : '',
|
||
);
|
||
}
|
||
|
||
// 文件名排序在时间跨度大时不可靠,改成按备份时间倒序
|
||
usort($list, function ($a, $b) {
|
||
if ($a['created'] === $b['created']) {
|
||
return strcmp($b['file'], $a['file']);
|
||
}
|
||
return $a['created'] < $b['created'] ? 1 : -1;
|
||
});
|
||
|
||
return $list;
|
||
}
|
||
|
||
/**
|
||
* 最近一次手动备份,没有则 null
|
||
*/
|
||
public static function latest()
|
||
{
|
||
$list = self::backups();
|
||
return empty($list) ? null : $list[0];
|
||
}
|
||
|
||
private static function readMeta($file)
|
||
{
|
||
$head = @file_get_contents($file, false, null, 0, 512);
|
||
if ($head === false || $head === '') {
|
||
return array();
|
||
}
|
||
if (preg_match('~' . self::BACKUP_MARK . '\s*(\{.*?\})\s*\*/~s', $head, $m)) {
|
||
$meta = json_decode($m[1], true);
|
||
if (is_array($meta)) {
|
||
return $meta;
|
||
}
|
||
}
|
||
return array();
|
||
}
|
||
|
||
/**
|
||
* 只保留最近 backupKeep() 份,多出来的从最旧的开始删
|
||
*
|
||
* @return int 实际删掉几份
|
||
*/
|
||
private static function pruneBackups()
|
||
{
|
||
$keep = self::backupKeep();
|
||
$list = self::backups();
|
||
if (count($list) <= $keep) {
|
||
return 0;
|
||
}
|
||
|
||
$removed = 0;
|
||
foreach (array_slice($list, $keep) as $item) {
|
||
if (@unlink(self::backupDir() . '/' . $item['file'])) {
|
||
$removed++;
|
||
}
|
||
}
|
||
|
||
return $removed;
|
||
}
|
||
|
||
/**
|
||
* 恢复一份手动备份
|
||
*
|
||
* 不传文件名 = 最新那一份(顶部「恢复」按钮);传了就是历史备份列表里点的那一份。
|
||
* 文件名会过 basename + isBackupName 白名单,不收路径。
|
||
*
|
||
* @param string $file 指定文件名(留空 = 最新一份)
|
||
* @return array ok / message / count / created
|
||
*/
|
||
public static function restoreLatest($file = '')
|
||
{
|
||
$fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0);
|
||
|
||
$latest = self::latest();
|
||
if (!$latest) {
|
||
$fail['message'] = '还没有手动备份,先点一次「备份」';
|
||
return $fail;
|
||
}
|
||
|
||
$name = $file !== '' ? basename($file) : $latest['file'];
|
||
if (!self::isBackupName($name)) {
|
||
$fail['message'] = '备份文件名不合法';
|
||
return $fail;
|
||
}
|
||
|
||
$path = self::backupDir() . '/' . $name;
|
||
if (!is_file($path)) {
|
||
$fail['message'] = '备份文件不存在:' . $name;
|
||
return $fail;
|
||
}
|
||
|
||
$content = @file_get_contents($path);
|
||
if ($content === false || $content === '') {
|
||
$fail['message'] = '读取备份文件失败';
|
||
return $fail;
|
||
}
|
||
|
||
$pos = strpos($content, '?>');
|
||
if ($pos === false) {
|
||
$fail['message'] = '备份文件格式不正确';
|
||
return $fail;
|
||
}
|
||
|
||
$encoded = trim(substr($content, $pos + 2));
|
||
if (strncmp($encoded, 'gz:', 3) === 0) {
|
||
$json = function_exists('gzuncompress')
|
||
? @gzuncompress((string) base64_decode(substr($encoded, 3)))
|
||
: false;
|
||
} elseif (strncmp($encoded, 'b64:', 4) === 0) {
|
||
$json = base64_decode(substr($encoded, 4));
|
||
} else {
|
||
// 没有前缀:按 base64 直接解,失败再当明文 JSON
|
||
$json = base64_decode($encoded);
|
||
if ($json === false || substr(ltrim($json), 0, 1) !== '{') {
|
||
$json = $encoded;
|
||
}
|
||
}
|
||
|
||
if ($json === false || $json === '') {
|
||
$fail['message'] = '备份文件内容已损坏,无法解析';
|
||
return $fail;
|
||
}
|
||
|
||
$payload = json_decode($json, true);
|
||
if (!is_array($payload) || !isset($payload['settings']) || !is_array($payload['settings'])) {
|
||
$fail['message'] = '备份文件内容已损坏,没有找到设置';
|
||
return $fail;
|
||
}
|
||
if (isset($payload['plugin']) && $payload['plugin'] !== 'AIAssist') {
|
||
$fail['message'] = '这份备份不属于 AIAssist';
|
||
return $fail;
|
||
}
|
||
if (empty($payload['settings'])) {
|
||
$fail['message'] = '备份里的设置是空的,已停止恢复';
|
||
return $fail;
|
||
}
|
||
|
||
if (!self::write($payload['settings'])) {
|
||
$fail['message'] = '写回设置失败,请检查数据库权限';
|
||
return $fail;
|
||
}
|
||
|
||
return array(
|
||
'ok' => true,
|
||
'message' => '设置已恢复',
|
||
'count' => count($payload['settings']),
|
||
'created' => !empty($payload['created']) ? intval($payload['created']) : intval($latest['created']),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 文件名是不是本插件生成的备份
|
||
*
|
||
* @param string $name
|
||
* @return bool
|
||
*/
|
||
public static function isBackupName($name)
|
||
{
|
||
$name = (string) $name;
|
||
return (bool) preg_match(
|
||
'/^' . preg_quote(self::BACKUP_PREFIX, '/') . '[0-9][0-9\-]*\.php$/',
|
||
$name
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 删除一份备份(目前界面没开放,留着给以后用)
|
||
*/
|
||
public static function removeBackup($file)
|
||
{
|
||
$name = basename((string) $file);
|
||
if (!self::isBackupName($name)) {
|
||
return false;
|
||
}
|
||
|
||
$path = self::backupDir() . '/' . $name;
|
||
return is_file($path) ? @unlink($path) : false;
|
||
}
|
||
|
||
/**
|
||
* 插件版本号(写进备份文件头,方便日后辨认)
|
||
*/
|
||
public static function version()
|
||
{
|
||
if (class_exists('AIAssist_Plugin') && defined('AIAssist_Plugin::VERSION')) {
|
||
return (string) AIAssist_Plugin::VERSION;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
public static function siteUrl()
|
||
{
|
||
try {
|
||
if (class_exists('Helper') && method_exists('Helper', 'options')) {
|
||
$options = Helper::options();
|
||
if ($options && isset($options->siteUrl)) {
|
||
return (string) $options->siteUrl;
|
||
}
|
||
}
|
||
} catch (Exception $e) {
|
||
} catch (Throwable $e) {
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* JSON 编码(中文不转义,失败返回 false)
|
||
*/
|
||
public static function jsonEncode($data)
|
||
{
|
||
$flags = 0;
|
||
if (defined('JSON_UNESCAPED_UNICODE')) {
|
||
$flags |= JSON_UNESCAPED_UNICODE;
|
||
}
|
||
if (defined('JSON_UNESCAPED_SLASHES')) {
|
||
$flags |= JSON_UNESCAPED_SLASHES;
|
||
}
|
||
|
||
$json = json_encode($data, $flags);
|
||
return $json === false ? false : $json;
|
||
}
|
||
|
||
/**
|
||
* 出错只写日志,不让备份功能把设置页拖崩
|
||
*/
|
||
private static function logError($message)
|
||
{
|
||
if (function_exists('error_log')) {
|
||
@error_log('[AIAssist] ' . $message);
|
||
}
|
||
}
|
||
}
|