1611 lines
60 KiB
PHP
1611 lines
60 KiB
PHP
|
|
<?php
|
|||
|
|
/**
|
|||
|
|
* 文章自动同步到七牛云(支持标题变更追踪 + 分类目录)
|
|||
|
|
*
|
|||
|
|
* @package ArticleToObsidian
|
|||
|
|
* @author 石头厝
|
|||
|
|
* @version 2.2.1
|
|||
|
|
* @link https://www.shitoucuo.com/
|
|||
|
|
*/
|
|||
|
|
class ArticleToObsidian_Plugin implements Typecho_Plugin_Interface
|
|||
|
|
{
|
|||
|
|
/** 本插件的后台菜单文件(相对 usr/plugins) */
|
|||
|
|
const PANEL_FILE = 'ArticleToObsidian/manage.php';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 老插件(ArticleExport)的菜单文件。
|
|||
|
|
* 两个插件曾经被同时安装过,老插件 addPanel 用索引 3、removePanel 却用索引 1,
|
|||
|
|
* 于是每激活一次就往 child[3] 里塞一条「文章导出」,停用又删不掉,
|
|||
|
|
* 后台侧栏因此堆出好几个同名菜单,点进去还是 404。
|
|||
|
|
* 新版接管后必须把这些残留一起清掉,否则永远删不干净。
|
|||
|
|
*/
|
|||
|
|
const LEGACY_PANEL_FILE = 'ArticleExport/manage.php';
|
|||
|
|
|
|||
|
|
/** 前端「导出 MD」按钮走的动作名 */
|
|||
|
|
const EXPORT_ACTION = 'article_to_obsidian_export';
|
|||
|
|
|
|||
|
|
/** 插件版本 */
|
|||
|
|
const VERSION = '2.2.1';
|
|||
|
|
|
|||
|
|
/** 插件中文名(设置页顶部备份卡片标题用) */
|
|||
|
|
const PLUGIN_TITLE = '文章同步插件';
|
|||
|
|
|
|||
|
|
/** 备份文件名前缀 */
|
|||
|
|
const BACKUP_PREFIX = 'articletoobsidian-settings-';
|
|||
|
|
|
|||
|
|
/** 备份保留份数 */
|
|||
|
|
const BACKUP_KEEP = 5;
|
|||
|
|
|
|||
|
|
public static function activate()
|
|||
|
|
{
|
|||
|
|
self::initDataDir();
|
|||
|
|
self::installPanel();
|
|||
|
|
Helper::addAction(self::EXPORT_ACTION, 'ArticleToObsidian_ExportAction');
|
|||
|
|
Typecho_Plugin::factory('Widget_Contents_Post_Edit')->finishPublish = array('ArticleToObsidian_Plugin', 'autoSyncOnPublish');
|
|||
|
|
Typecho_Plugin::factory('Widget_Contents_Post_Edit')->update = array('ArticleToObsidian_Plugin', 'autoSyncOnUpdate');
|
|||
|
|
return '文章同步插件已激活';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static function deactivate()
|
|||
|
|
{
|
|||
|
|
Helper::removeAction(self::EXPORT_ACTION);
|
|||
|
|
self::removePanels();
|
|||
|
|
return '文章同步插件已禁用';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 注册后台菜单:先把历史残留清干净,再挂唯一的一条
|
|||
|
|
*/
|
|||
|
|
private static function installPanel()
|
|||
|
|
{
|
|||
|
|
self::removePanels();
|
|||
|
|
Helper::addPanel(3, self::PANEL_FILE, '文章导出', '文章导出与 Obsidian 同步', 'administrator');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 清掉本插件与老插件的全部菜单项
|
|||
|
|
*
|
|||
|
|
* Helper::removePanel($index, $file) 只处理指定索引下的条目,
|
|||
|
|
* 所以这里把所有可能用过的索引都扫一遍,重复项、错位项一起清。
|
|||
|
|
*/
|
|||
|
|
private static function removePanels()
|
|||
|
|
{
|
|||
|
|
for ($index = 0; $index <= 10; $index++) {
|
|||
|
|
Helper::removePanel($index, self::PANEL_FILE);
|
|||
|
|
Helper::removePanel($index, self::LEGACY_PANEL_FILE);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 菜单是否处于「脏」状态:老插件残留,或本插件不在/重复
|
|||
|
|
*
|
|||
|
|
* @return bool
|
|||
|
|
*/
|
|||
|
|
private static function panelNeedsRepair()
|
|||
|
|
{
|
|||
|
|
$panel = Helper::options()->panelTable;
|
|||
|
|
if (!is_array($panel) || empty($panel['child'])) {
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$mine = 0;
|
|||
|
|
foreach ($panel['child'] as $items) {
|
|||
|
|
foreach ((array) $items as $item) {
|
|||
|
|
if (!isset($item[2])) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$url = rawurldecode($item[2]);
|
|||
|
|
if (strpos($url, 'panel=' . self::LEGACY_PANEL_FILE) !== false) {
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
if (strpos($url, 'panel=' . self::PANEL_FILE) !== false) {
|
|||
|
|
$mine++;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return $mine !== 1;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function getDataDir()
|
|||
|
|
{
|
|||
|
|
return dirname(__FILE__) . '/data';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function initDataDir()
|
|||
|
|
{
|
|||
|
|
$dataDir = self::getDataDir();
|
|||
|
|
if (!file_exists($dataDir)) {
|
|||
|
|
mkdir($dataDir, 0755, true);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function getLogFile()
|
|||
|
|
{
|
|||
|
|
return self::getDataDir() . '/sync.log';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function getVersionFile($cid)
|
|||
|
|
{
|
|||
|
|
return self::getDataDir() . '/ver_' . $cid . '.txt';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function getHashFile($cid)
|
|||
|
|
{
|
|||
|
|
return self::getDataDir() . '/hash_' . $cid . '.txt';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static function config(Typecho_Widget_Helper_Form $form)
|
|||
|
|
{
|
|||
|
|
/*
|
|||
|
|
* 顺手修一次后台菜单:从老插件升级上来的人,options.panelTable 里
|
|||
|
|
* 通常还压着好几条「文章导出」残留,进一次设置页就自动收敛成一条。
|
|||
|
|
* 只有脏的时候才写库,正常情况下这里什么都不做。
|
|||
|
|
*/
|
|||
|
|
if (self::panelNeedsRepair()) {
|
|||
|
|
self::installPanel();
|
|||
|
|
Helper::addAction(self::EXPORT_ACTION, 'ArticleToObsidian_ExportAction');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/*
|
|||
|
|
* 顶部「备份 / 恢复」卡片(与 Qiniu / ExtMenu / MailNotifier 完全一致的服务端实现):
|
|||
|
|
* 按钮走本页 GET 动作,处理完 302 回本页;不嵌第二层 form。
|
|||
|
|
*/
|
|||
|
|
self::handleSettingsAction();
|
|||
|
|
$hero = new Typecho_Widget_Helper_Layout();
|
|||
|
|
$hero->html(self::settingsAssetCss() . self::heroCardHtml());
|
|||
|
|
$form->addItem($hero);
|
|||
|
|
|
|||
|
|
$autoSync = new Typecho_Widget_Helper_Form_Element_Radio(
|
|||
|
|
'autoSync',
|
|||
|
|
array('1' => '开启', '0' => '关闭'),
|
|||
|
|
'1',
|
|||
|
|
'自动同步到七牛云'
|
|||
|
|
);
|
|||
|
|
$form->addInput($autoSync);
|
|||
|
|
|
|||
|
|
$accessKey = new Typecho_Widget_Helper_Form_Element_Text(
|
|||
|
|
'accessKey',
|
|||
|
|
null,
|
|||
|
|
'',
|
|||
|
|
'AccessKey(AK)'
|
|||
|
|
);
|
|||
|
|
$form->addInput($accessKey);
|
|||
|
|
|
|||
|
|
$secretKey = new Typecho_Widget_Helper_Form_Element_Text(
|
|||
|
|
'secretKey',
|
|||
|
|
null,
|
|||
|
|
'',
|
|||
|
|
'SecretKey(SK)'
|
|||
|
|
);
|
|||
|
|
$form->addInput($secretKey);
|
|||
|
|
|
|||
|
|
$bucket = new Typecho_Widget_Helper_Form_Element_Text(
|
|||
|
|
'bucket',
|
|||
|
|
null,
|
|||
|
|
'',
|
|||
|
|
'Bucket(存储空间名称)'
|
|||
|
|
);
|
|||
|
|
$form->addInput($bucket);
|
|||
|
|
|
|||
|
|
$region = new Typecho_Widget_Helper_Form_Element_Select(
|
|||
|
|
'region',
|
|||
|
|
array(
|
|||
|
|
'z0' => '华东 (z0)',
|
|||
|
|
'z1' => '华北 (z1)',
|
|||
|
|
'z2' => '华南 (z2)',
|
|||
|
|
'as0' => '东南亚 (as0)',
|
|||
|
|
'na0' => '北美 (na0)',
|
|||
|
|
),
|
|||
|
|
'z2',
|
|||
|
|
'存储区域'
|
|||
|
|
);
|
|||
|
|
$form->addInput($region);
|
|||
|
|
|
|||
|
|
$uploadPath = new Typecho_Widget_Helper_Form_Element_Text(
|
|||
|
|
'uploadPath',
|
|||
|
|
null,
|
|||
|
|
'',
|
|||
|
|
'基础路径(留空为根目录,如:web_sangushui/)'
|
|||
|
|
);
|
|||
|
|
$form->addInput($uploadPath);
|
|||
|
|
|
|||
|
|
$directoryRule = new Typecho_Widget_Helper_Form_Element_Select(
|
|||
|
|
'directoryRule',
|
|||
|
|
array(
|
|||
|
|
'none' => '根目录(不创建分类目录)',
|
|||
|
|
'category' => '按文章分类创建目录',
|
|||
|
|
'year' => '按年份创建目录(如 2026/)',
|
|||
|
|
'year_category' => '按年份/分类创建目录(如 2026/技术文章/)',
|
|||
|
|
'category_year' => '按分类/年份创建目录(如 技术文章/2026/)',
|
|||
|
|
),
|
|||
|
|
'category',
|
|||
|
|
'七牛云目录规则',
|
|||
|
|
'选择文件在七牛云存储桶中的组织方式'
|
|||
|
|
);
|
|||
|
|
$form->addInput($directoryRule);
|
|||
|
|
|
|||
|
|
$showExportBtn = new Typecho_Widget_Helper_Form_Element_Radio(
|
|||
|
|
'showExportBtn',
|
|||
|
|
array('1' => '显示', '0' => '隐藏'),
|
|||
|
|
'1',
|
|||
|
|
'文章页「导出 MD」按钮',
|
|||
|
|
'主题的 parts/title.php 会调用 ArticleToObsidian_Plugin::renderExportBtn(),'
|
|||
|
|
. '开启后文章页标题下方多一个按钮,点击直接下载这篇的 Markdown 文件(可直接拖进 Obsidian 库)'
|
|||
|
|
);
|
|||
|
|
$form->addInput($showExportBtn);
|
|||
|
|
|
|||
|
|
$testHtml = '<div style="margin: 10px 0 20px 0; padding-top: 10px; border-top: 1px solid #eee;">
|
|||
|
|
<h3 style="margin: 0 0 15px 0; font-size: 14px; font-weight: bold;">命名规则</h3>
|
|||
|
|
<div style="font-size: 13px; color: #555;">
|
|||
|
|
<p><strong>目录规则说明:</strong></p>
|
|||
|
|
<ul style="margin: 5px 0 10px 20px;">
|
|||
|
|
<li>根目录:<code>不上传到任何分类目录</code></li>
|
|||
|
|
<li>按文章分类创建目录:<code>根据 Typecho 文章分类自动创建七牛云目录</code></li>
|
|||
|
|
<li>按年份创建目录:<code>如 2026/文件名.md</code></li>
|
|||
|
|
<li>按年份/分类创建目录:<code>如 2026/技术文章/文件名.md</code></li>
|
|||
|
|
<li>按分类/年份创建目录:<code>如 技术文章/2026/文件名.md</code></li>
|
|||
|
|
</ul>
|
|||
|
|
<p><strong>文件命名规则:</strong></p>
|
|||
|
|
<ul style="margin: 5px 0 0 20px;">
|
|||
|
|
<li>首次发布:<code>{标题}(v1)-{时间戳}.md</code></li>
|
|||
|
|
<li>标题未变:<code>{标题}(v{版本号})-{时间戳}.md</code></li>
|
|||
|
|
<li>标题已变:<code>{原标题}_改为_{新标题}(v{版本号})-{时间戳}.md</code></li>
|
|||
|
|
<li><strong>内容去重:</strong>如果文章内容没有变化,不会重复上传</li>
|
|||
|
|
<li><strong>重要:</strong>Typecho 数据库中的标题始终保持纯净(不含版本号后缀)</li>
|
|||
|
|
<li><strong>重要:</strong>MD 文件内的 title 字段始终保持纯净</li>
|
|||
|
|
</ul>
|
|||
|
|
</div>
|
|||
|
|
</div>';
|
|||
|
|
|
|||
|
|
$testField = new Typecho_Widget_Helper_Form_Element_Text('testField', null, null, null, $testHtml);
|
|||
|
|
$testField->input->setAttribute('style', 'display:none;');
|
|||
|
|
$form->addInput($testField);
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static function personalConfig(Typecho_Widget_Helper_Form $form) {}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 处理备份 / 恢复点击
|
|||
|
|
*/
|
|||
|
|
private static function handleSettingsAction()
|
|||
|
|
{
|
|||
|
|
if (!isset($_GET['_em']) || !is_scalar($_GET['_em'])) {
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$do = trim((string) $_GET['_em']);
|
|||
|
|
|
|||
|
|
// 只认 backup / restore。跳回来带的 backup_ok 等结果参数直接放行渲染,
|
|||
|
|
// 否则会自己追自己形成死循环。
|
|||
|
|
if ('backup' !== $do && 'restore' !== $do) {
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$user = self::currentUser();
|
|||
|
|
|
|||
|
|
if (!$user || !$user->pass('administrator', true)) {
|
|||
|
|
self::go('_em=auth');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$token = isset($_GET['_t']) && is_scalar($_GET['_t']) ? (string) $_GET['_t'] : '';
|
|||
|
|
|
|||
|
|
if ('' === self::token() || !hash_equals(self::token(), $token)) {
|
|||
|
|
self::go('_em=token');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ('backup' === $do) {
|
|||
|
|
$result = self::doBackup();
|
|||
|
|
|
|||
|
|
if (!empty($result['ok'])) {
|
|||
|
|
self::go(
|
|||
|
|
'_em=backup_ok&n=' . (int) $result['count']
|
|||
|
|
. '&t=' . (int) $result['created']
|
|||
|
|
. '&f=' . (int) $result['total']
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
self::go('_em=backup_fail&detail=' . rawurlencode((string) $result['message']));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ('restore' === $do) {
|
|||
|
|
$file = isset($_GET['file']) && is_scalar($_GET['file']) ? trim((string) $_GET['file']) : '';
|
|||
|
|
$result = self::doRestore($file);
|
|||
|
|
|
|||
|
|
if (!empty($result['ok'])) {
|
|||
|
|
self::go('_em=restore_ok&n=' . (int) $result['count'] . '&t=' . (int) $result['created']);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
self::go('_em=restore_fail&detail=' . rawurlencode((string) $result['message']));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 302 回设置页
|
|||
|
|
*
|
|||
|
|
* 不能只用 header('Location'):Typecho 的 ob 回调 Response::sendHeaders() 会按
|
|||
|
|
* Response 记的状态码(默认 200)重发,location 在但不跳。交给 Response 自己发。
|
|||
|
|
*/
|
|||
|
|
private static function go($query)
|
|||
|
|
{
|
|||
|
|
$url = self::configUrl($query);
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$response = \Typecho\Response::getInstance();
|
|||
|
|
$response->setStatus(302);
|
|||
|
|
$response->setHeader('Location', $url);
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
header('Location: ' . $url, true, 302);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
exit;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 本插件设置页地址
|
|||
|
|
*/
|
|||
|
|
private static function configUrl($query = '')
|
|||
|
|
{
|
|||
|
|
$adminUrl = '';
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$adminUrl = rtrim((string) self::options()->adminUrl, '/') . '/';
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
$adminUrl = '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$url = $adminUrl . 'options-plugin.php?config=ArticleToObsidian';
|
|||
|
|
|
|||
|
|
if ('' !== $query) {
|
|||
|
|
$url .= '&' . ltrim($query, '&');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return $url;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份 / 恢复令牌:站点 secret + 当前 uid
|
|||
|
|
*/
|
|||
|
|
private static function token()
|
|||
|
|
{
|
|||
|
|
$user = self::currentUser();
|
|||
|
|
$uid = ($user && $user->hasLogin()) ? (int) $user->uid : 0;
|
|||
|
|
|
|||
|
|
if ($uid <= 0) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$secret = (string) self::options()->secret;
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
$secret = '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ('' === $secret) {
|
|||
|
|
$secret = __FILE__;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return substr(hash_hmac('sha256', 'ArticleToObsidian|' . $uid, $secret), 0, 32);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 当前用户(兼容 1.2 / 1.3)
|
|||
|
|
*/
|
|||
|
|
private static function currentUser()
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
if (class_exists('\Widget\User')) {
|
|||
|
|
return \Widget\User::alloc();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (class_exists('Typecho_Widget')) {
|
|||
|
|
return Typecho_Widget::widget('Widget_User');
|
|||
|
|
}
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* Options(兼容 1.2 / 1.3)
|
|||
|
|
*/
|
|||
|
|
private static function options()
|
|||
|
|
{
|
|||
|
|
if (class_exists('\Widget\Options')) {
|
|||
|
|
return \Widget\Options::alloc();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return Typecho_Widget::widget('Widget_Options');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 顶部备份卡片(结构与样式照搬 MailNotifier / ExtMenu)
|
|||
|
|
*
|
|||
|
|
* 标题用插件中文名;备份时间 .cnot-hero-meta 放在 .cnot-hero-ops 内,
|
|||
|
|
* 靠 flex-basis:100% 换行到按钮下一行。只读 $_GET 结果参数,不做写操作。
|
|||
|
|
*/
|
|||
|
|
private static function heroCardHtml()
|
|||
|
|
{
|
|||
|
|
$list = array();
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$list = self::backups();
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
$list = array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$latest = empty($list) ? null : $list[0];
|
|||
|
|
$notice = self::noticeHtml();
|
|||
|
|
|
|||
|
|
if ($latest) {
|
|||
|
|
$meta = '上次备份 ' . self::e(date('Y-m-d H:i', $latest['created']))
|
|||
|
|
. ' · 当前 ' . count($list) . ' 份(上限 ' . intval(self::BACKUP_KEEP) . ' 份)';
|
|||
|
|
} else {
|
|||
|
|
$meta = '还没有备份,点「备份」把当前设置存一份';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$backupUrl = self::configUrl('_em=backup&_t=' . rawurlencode(self::token()));
|
|||
|
|
$restoreUrl = self::configUrl('_em=restore&_t=' . rawurlencode(self::token()));
|
|||
|
|
|
|||
|
|
$restoreBtn = $latest
|
|||
|
|
? '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl) . '"'
|
|||
|
|
. ' onclick="return confirm(\'恢复会用最新一份备份覆盖当前插件设置,确定继续?\');">恢复</a>'
|
|||
|
|
: '<span class="cnot-btn cnot-btn-ghost is-disabled" aria-disabled="true" title="还没有备份">恢复</span>';
|
|||
|
|
|
|||
|
|
$historyBtn = '';
|
|||
|
|
$historyBox = '';
|
|||
|
|
|
|||
|
|
if (count($list) > 1) {
|
|||
|
|
$rows = '';
|
|||
|
|
|
|||
|
|
foreach ($list as $index => $item) {
|
|||
|
|
$rows .= '<div class="cnot-backup-item">'
|
|||
|
|
. '<div class="cnot-backup-main">'
|
|||
|
|
. '<span class="cnot-backup-time">' . self::e(date('Y-m-d H:i:s', $item['created'])) . '</span>'
|
|||
|
|
. ($index === 0 ? '<span class="cnot-backup-tag">最新</span>' : '')
|
|||
|
|
. '<span class="cnot-backup-desc">' . intval($item['count']) . ' 项配置 · '
|
|||
|
|
. self::e(self::formatBytes($item['size']))
|
|||
|
|
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
|
|||
|
|
. '</span>'
|
|||
|
|
. '</div>'
|
|||
|
|
. '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl . '&file=' . rawurlencode($item['file'])) . '"'
|
|||
|
|
. ' onclick="return confirm(\'用 ' . self::e(date('Y-m-d H:i', $item['created'])) . ' 的这份备份覆盖当前插件设置?\');">恢复</a>'
|
|||
|
|
. '</div>';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$historyBtn = '<a class="cnot-btn cnot-btn-ghost" id="cnot-backups-btn" href="#cnot-backups"'
|
|||
|
|
. ' aria-expanded="false" aria-controls="cnot-backups">历史备份</a>';
|
|||
|
|
|
|||
|
|
$historyBox = '<div class="cnot-backups" id="cnot-backups" hidden>'
|
|||
|
|
. '<div class="cnot-backups-head"><strong>历史备份</strong><span>从新到旧,点「恢复」就用那一份覆盖当前设置</span></div>'
|
|||
|
|
. $rows
|
|||
|
|
. '</div>'
|
|||
|
|
. '<script>(function(){var box=document.getElementById("cnot-backups");'
|
|||
|
|
. 'var btn=document.getElementById("cnot-backups-btn");'
|
|||
|
|
. 'if(!box||!btn||!btn.addEventListener){return;}'
|
|||
|
|
. 'btn.addEventListener("click",function(e){'
|
|||
|
|
. 'if(e&&e.preventDefault){e.preventDefault();}'
|
|||
|
|
. 'var open=box.hasAttribute("hidden");'
|
|||
|
|
. 'if(open){box.removeAttribute("hidden");}else{box.setAttribute("hidden","hidden");}'
|
|||
|
|
. 'btn.textContent=open?"收起备份":"历史备份";'
|
|||
|
|
. 'btn.setAttribute("aria-expanded",open?"true":"false");'
|
|||
|
|
. 'return false;});'
|
|||
|
|
. '})();</script>';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return '<div class="cnot-hero">'
|
|||
|
|
. '<div class="cnot-hero-icon">'
|
|||
|
|
. '<svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="1.8"'
|
|||
|
|
. ' stroke-linecap="round" stroke-linejoin="round">'
|
|||
|
|
. '<path d="M4 7h16M6 7v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7"/>'
|
|||
|
|
. '<path d="M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>'
|
|||
|
|
. '<path d="M10 11h4M10 15h4"/></svg>'
|
|||
|
|
. '</div>'
|
|||
|
|
. '<div class="cnot-hero-text">'
|
|||
|
|
. '<div class="cnot-hero-title">'
|
|||
|
|
. '<h2>' . self::e(self::PLUGIN_TITLE) . '</h2>'
|
|||
|
|
. '</div>'
|
|||
|
|
. '<p>自动同步、AccessKey、SecretKey、空间名称、存储区域、上传路径、目录规则等设置都可以存成一份文件,改乱了点「恢复」就能退回上一次。</p>'
|
|||
|
|
. '<div class="cnot-hero-ops">'
|
|||
|
|
. '<a class="cnot-btn" href="' . self::e($backupUrl) . '">备份</a>'
|
|||
|
|
. $restoreBtn
|
|||
|
|
. $historyBtn
|
|||
|
|
. '<span class="cnot-hero-meta">' . $meta . '</span>'
|
|||
|
|
. '</div>'
|
|||
|
|
. '</div>'
|
|||
|
|
. '</div>'
|
|||
|
|
. $notice
|
|||
|
|
. $historyBox;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份结果提示条(读 _em 参数)
|
|||
|
|
*/
|
|||
|
|
private static function noticeHtml()
|
|||
|
|
{
|
|||
|
|
$code = isset($_GET['_em']) && is_scalar($_GET['_em']) ? (string) $_GET['_em'] : '';
|
|||
|
|
|
|||
|
|
if ('' === $code) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$get = array();
|
|||
|
|
|
|||
|
|
foreach (array('n', 't', 'detail', 'f') as $key) {
|
|||
|
|
$get[$key] = isset($_GET[$key]) && is_scalar($_GET[$key]) ? (string) $_GET[$key] : '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$count = (int) $get['n'];
|
|||
|
|
$time = (int) $get['t'];
|
|||
|
|
$total = (int) $get['f'];
|
|||
|
|
$ok = true;
|
|||
|
|
$text = '';
|
|||
|
|
|
|||
|
|
if ('backup_ok' === $code) {
|
|||
|
|
$text = '设置已备份:' . $count . ' 项配置,' . self::e(date('Y-m-d H:i:s', $time)) . '。'
|
|||
|
|
. ($total > 0 ? '当前共 ' . $total . ' 份(上限 ' . intval(self::BACKUP_KEEP) . ' 份)。' : '');
|
|||
|
|
} elseif ('restore_ok' === $code) {
|
|||
|
|
$text = '已恢复到 ' . self::e(date('Y-m-d H:i:s', $time)) . ' 的备份(' . $count
|
|||
|
|
. ' 项配置)。刷新本页即可看到表单里的值。';
|
|||
|
|
} elseif ('backup_fail' === $code || 'restore_fail' === $code) {
|
|||
|
|
$ok = false;
|
|||
|
|
$text = ('backup_fail' === $code ? '备份失败:' : '恢复失败:')
|
|||
|
|
. ('' !== $get['detail'] ? $get['detail'] : '未知原因');
|
|||
|
|
} elseif ('token' === $code) {
|
|||
|
|
$ok = false;
|
|||
|
|
$text = '安全令牌校验失败,请刷新本页后重试。';
|
|||
|
|
} elseif ('auth' === $code) {
|
|||
|
|
$ok = false;
|
|||
|
|
$text = '只有管理员可以备份或恢复插件设置。';
|
|||
|
|
} elseif ('unknown' === $code) {
|
|||
|
|
$ok = false;
|
|||
|
|
$text = '无法识别的操作。';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ('' === $text) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return '<div class="cnot-note ' . ($ok ? 'cnot-note-ok' : 'cnot-note-fail') . '">' . self::e($text) . '</div>';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份目录
|
|||
|
|
*/
|
|||
|
|
private static function backupDir()
|
|||
|
|
{
|
|||
|
|
return dirname(__FILE__) . '/data/backup';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 目录不存在就建,并禁止公网读取
|
|||
|
|
*/
|
|||
|
|
private static function ensureBackupDir()
|
|||
|
|
{
|
|||
|
|
$dir = self::backupDir();
|
|||
|
|
|
|||
|
|
if (!is_dir($dir)) {
|
|||
|
|
@mkdir($dir, 0755, true);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (!is_dir($dir)) {
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
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;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份列表(新 → 旧)
|
|||
|
|
*/
|
|||
|
|
private static function backups()
|
|||
|
|
{
|
|||
|
|
$dir = self::backupDir();
|
|||
|
|
|
|||
|
|
if (!is_dir($dir)) {
|
|||
|
|
return array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$files = (array) glob($dir . '/' . self::BACKUP_PREFIX . '*.php');
|
|||
|
|
$list = array();
|
|||
|
|
|
|||
|
|
foreach ($files as $file) {
|
|||
|
|
$name = basename($file);
|
|||
|
|
|
|||
|
|
if (!self::isBackupName($name)) {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$meta = self::readMeta($file);
|
|||
|
|
|
|||
|
|
$list[] = array(
|
|||
|
|
'file' => $name,
|
|||
|
|
'size' => (int) @filesize($file),
|
|||
|
|
'created' => !empty($meta['created']) ? (int) $meta['created'] : (int) @filemtime($file),
|
|||
|
|
'count' => !empty($meta['count']) ? (int) $meta['count'] : 0,
|
|||
|
|
'version' => isset($meta['version']) ? (string) $meta['version'] : '',
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
usort($list, array(__CLASS__, 'compareBackups'));
|
|||
|
|
|
|||
|
|
return $list;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份排序:新的在前
|
|||
|
|
*/
|
|||
|
|
public static function compareBackups($a, $b)
|
|||
|
|
{
|
|||
|
|
if ($a['created'] === $b['created']) {
|
|||
|
|
return strcmp($b['file'], $a['file']);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return $a['created'] < $b['created'] ? 1 : -1;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 读备份文件头里的 meta
|
|||
|
|
*/
|
|||
|
|
private static function readMeta($file)
|
|||
|
|
{
|
|||
|
|
$head = @file_get_contents($file, false, null, 0, 512);
|
|||
|
|
|
|||
|
|
if (false === $head || '' === $head) {
|
|||
|
|
return array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (preg_match('~ARTICLETOBSIDIAN-SETTINGS-BACKUP\s*(\{.*?\})\s*\*/~s', $head, $match)) {
|
|||
|
|
$meta = json_decode($match[1], true);
|
|||
|
|
|
|||
|
|
if (is_array($meta)) {
|
|||
|
|
return $meta;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 文件名是不是本插件生成的备份
|
|||
|
|
*/
|
|||
|
|
private static function isBackupName($name)
|
|||
|
|
{
|
|||
|
|
return (bool) preg_match(
|
|||
|
|
'/^' . preg_quote(self::BACKUP_PREFIX, '/') . '[0-9][0-9\-]*\.php$/',
|
|||
|
|
(string) $name
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份一次当前设置
|
|||
|
|
*/
|
|||
|
|
private static function doBackup()
|
|||
|
|
{
|
|||
|
|
$fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0, 'total' => 0);
|
|||
|
|
|
|||
|
|
$settings = self::storedConfig();
|
|||
|
|
|
|||
|
|
if (empty($settings)) {
|
|||
|
|
$fail['message'] = '还没有保存过任何设置,先点页面底部的「保存设置」再备份';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (!self::ensureBackupDir()) {
|
|||
|
|
$fail['message'] = '备份目录 data/backup 不可写,请给插件目录写入权限';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$created = time();
|
|||
|
|
$meta = array(
|
|||
|
|
'plugin' => 'ArticleToObsidian',
|
|||
|
|
'version' => self::VERSION,
|
|||
|
|
'created' => $created,
|
|||
|
|
'count' => count($settings),
|
|||
|
|
'siteUrl' => self::siteUrl(),
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
$json = json_encode(
|
|||
|
|
array_merge($meta, array('settings' => $settings)),
|
|||
|
|
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
if (false === $json) {
|
|||
|
|
$fail['message'] = '序列化设置失败';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$gz = function_exists('gzcompress') ? @gzcompress($json, 6) : false;
|
|||
|
|
$encoded = (false === $gz || '' === $gz) ? 'b64:' . base64_encode($json) : 'gz:' . base64_encode($gz);
|
|||
|
|
|
|||
|
|
$content = '<?php /* ARTICLETOBSIDIAN-SETTINGS-BACKUP '
|
|||
|
|
. json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
|||
|
|
. ' */ exit; ?>' . "\n" . $encoded;
|
|||
|
|
|
|||
|
|
$file = self::backupDir() . '/' . self::BACKUP_PREFIX . date('Ymd-His', $created) . '.php';
|
|||
|
|
|
|||
|
|
if (false === @file_put_contents($file, $content, LOCK_EX)) {
|
|||
|
|
$fail['message'] = '写入备份文件失败,请检查 data/backup 目录权限';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
self::pruneBackups();
|
|||
|
|
|
|||
|
|
return array(
|
|||
|
|
'ok' => true,
|
|||
|
|
'message' => '设置已备份',
|
|||
|
|
'count' => count($settings),
|
|||
|
|
'created' => $created,
|
|||
|
|
'total' => count(self::backups()),
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 只保留最近 BACKUP_KEEP 份
|
|||
|
|
*/
|
|||
|
|
private static function pruneBackups()
|
|||
|
|
{
|
|||
|
|
$list = self::backups();
|
|||
|
|
|
|||
|
|
if (count($list) <= self::BACKUP_KEEP) {
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
foreach (array_slice($list, self::BACKUP_KEEP) as $item) {
|
|||
|
|
@unlink(self::backupDir() . '/' . $item['file']);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 恢复一份备份(不传文件名 = 最新那份)
|
|||
|
|
*/
|
|||
|
|
private static function doRestore($file = '')
|
|||
|
|
{
|
|||
|
|
$fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0);
|
|||
|
|
|
|||
|
|
$list = self::backups();
|
|||
|
|
|
|||
|
|
if (empty($list)) {
|
|||
|
|
$fail['message'] = '还没有备份,先点一次「备份」';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$name = '' !== $file ? basename($file) : $list[0]['file'];
|
|||
|
|
|
|||
|
|
if (!self::isBackupName($name)) {
|
|||
|
|
$fail['message'] = '备份文件名不合法';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$path = self::backupDir() . '/' . $name;
|
|||
|
|
$content = @file_get_contents($path);
|
|||
|
|
|
|||
|
|
if (false === $content || '' === $content) {
|
|||
|
|
$fail['message'] = '读取备份文件失败:' . $name;
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$pos = strpos($content, '?>');
|
|||
|
|
|
|||
|
|
if (false === $pos) {
|
|||
|
|
$fail['message'] = '备份文件格式不正确';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$encoded = trim(substr($content, $pos + 2));
|
|||
|
|
|
|||
|
|
if (0 === strncmp($encoded, 'gz:', 3)) {
|
|||
|
|
$json = function_exists('gzuncompress')
|
|||
|
|
? @gzuncompress((string) base64_decode(substr($encoded, 3)))
|
|||
|
|
: false;
|
|||
|
|
} else {
|
|||
|
|
$json = base64_decode(substr($encoded, 4));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (false === $json || '' === $json) {
|
|||
|
|
$fail['message'] = '备份内容已损坏,无法解析';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$payload = json_decode($json, true);
|
|||
|
|
|
|||
|
|
if (!is_array($payload) || empty($payload['settings']) || !is_array($payload['settings'])) {
|
|||
|
|
$fail['message'] = '备份内容已损坏,没有找到设置';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (isset($payload['plugin']) && 'ArticleToObsidian' !== $payload['plugin']) {
|
|||
|
|
$fail['message'] = '这份备份不属于文章同步插件';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
if (class_exists('\Helper')) {
|
|||
|
|
\Helper::setOption('plugin:ArticleToObsidian', $payload['settings']);
|
|||
|
|
} else {
|
|||
|
|
Helper::setOption('plugin:ArticleToObsidian', $payload['settings']);
|
|||
|
|
}
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
$fail['message'] = '写回设置失败,请检查数据库权限';
|
|||
|
|
return $fail;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
return array(
|
|||
|
|
'ok' => true,
|
|||
|
|
'message' => '设置已恢复',
|
|||
|
|
'count' => count($payload['settings']),
|
|||
|
|
'created' => !empty($payload['created']) ? (int) $payload['created'] : $list[0]['created'],
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 当前已保存的整份设置(plugin:ArticleToObsidian)
|
|||
|
|
*/
|
|||
|
|
private static function storedConfig()
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$row = $db->fetchRow($db->select('value')->from('table.options')
|
|||
|
|
->where('name = ?', 'plugin:ArticleToObsidian'));
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
return array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (empty($row) || empty($row['value'])) {
|
|||
|
|
return array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$config = json_decode($row['value'], true);
|
|||
|
|
|
|||
|
|
return is_array($config) ? $config : array();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 站点地址(记进备份文件的环境信息)
|
|||
|
|
*/
|
|||
|
|
private static function siteUrl()
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
return (string) self::options()->siteUrl;
|
|||
|
|
} catch (\Throwable $e) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 文件大小的好读写法
|
|||
|
|
*/
|
|||
|
|
private static function formatBytes($bytes)
|
|||
|
|
{
|
|||
|
|
$bytes = max(0, (int) $bytes);
|
|||
|
|
|
|||
|
|
if ($bytes < 1024) {
|
|||
|
|
return $bytes . ' B';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ($bytes < 1048576) {
|
|||
|
|
return round($bytes / 1024, 1) . ' KB';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return round($bytes / 1048576, 1) . ' MB';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 转义输出
|
|||
|
|
*/
|
|||
|
|
private static function e($text)
|
|||
|
|
{
|
|||
|
|
return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 备份卡片样式:与 ExtMenu 统一后的 cnot-* 一致
|
|||
|
|
* (卡片 8px、按钮 4px、标题 14px、正文 12px、字体继承后台)
|
|||
|
|
*/
|
|||
|
|
private static function settingsAssetCss()
|
|||
|
|
{
|
|||
|
|
return <<<'CSS'
|
|||
|
|
<style>
|
|||
|
|
.cnot-hero,.cnot-note,.cnot-backups{box-sizing:border-box;width:100%;}
|
|||
|
|
.cnot-hero{position:relative;display:flex;align-items:flex-start;gap:18px;flex-wrap:wrap;margin:6px 0 12px;padding:22px 24px;border:1px solid rgba(126,96,60,.15);border-radius:8px;background:linear-gradient(135deg,rgba(255,253,248,.98),rgba(246,236,223,.86));box-shadow:0 14px 34px rgba(75,56,35,.075);overflow:hidden;}
|
|||
|
|
.cnot-hero:after{content:"";position:absolute;right:-44px;top:-50px;width:170px;height:170px;border-radius:50%;background:rgba(126,96,60,.065);}
|
|||
|
|
.cnot-hero-icon{position:relative;z-index:1;width:54px;height:54px;display:grid;place-items:center;flex:0 0 54px;border-radius:8px;color:#7f603d;background:linear-gradient(145deg,rgba(255,253,248,.88),rgba(239,225,207,.72));border:1px solid rgba(126,96,60,.18);font-size:25px;box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 12px 24px rgba(93,68,43,.08);}
|
|||
|
|
.cnot-hero-text{position:relative;z-index:1;min-width:0;flex:1 1 300px;}
|
|||
|
|
.cnot-hero h2{position:relative;z-index:1;margin:0;color:#2d2824;font-size:14px;line-height:1.5;font-weight:600;}
|
|||
|
|
.cnot-hero p{position:relative;z-index:1;margin:6px 0 0;color:#6f6153;font-size:12px;line-height:1.6;}
|
|||
|
|
.cnot-hero-title{position:relative;z-index:1;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
|
|||
|
|
.cnot-hero-ops{position:relative;z-index:1;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:12px;}
|
|||
|
|
.cnot-hero-meta{flex-basis:100%;margin-top:2px;color:#8d7b6a;font-size:12px;line-height:1.5;}
|
|||
|
|
.cnot-btn{height:32px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;border-radius:4px;text-decoration:none!important;color:#fff!important;background:linear-gradient(135deg,#8b633b,#a77b4c);box-shadow:0 4px 12px rgba(125,90,50,.16);font-size:12px;font-weight:600;white-space:nowrap;}
|
|||
|
|
.cnot-btn:hover{transform:translateY(-1px);}
|
|||
|
|
.cnot-hero .cnot-btn{height:30px;padding:0 12px;font-size:12px;}
|
|||
|
|
.cnot-btn-ghost{color:#6d4a2b!important;background:rgba(255,255,255,.92)!important;border:1px solid rgba(126,96,60,.22);box-shadow:none;}
|
|||
|
|
.cnot-btn-ghost.is-disabled{opacity:.42;cursor:not-allowed;box-shadow:none;}
|
|||
|
|
.cnot-btn-ghost.is-disabled:hover{transform:none;}
|
|||
|
|
.cnot-note{margin:-2px 0 16px;padding:9px 14px;border-radius:8px;font-size:12px;line-height:1.6;}
|
|||
|
|
.cnot-note-ok{color:#2f8a57;background:rgba(47,138,87,.10);border:1px solid rgba(47,138,87,.18);}
|
|||
|
|
.cnot-note-fail{color:#b4503f;background:rgba(180,80,63,.10);border:1px solid rgba(180,80,63,.18);}
|
|||
|
|
.cnot-backups{margin:-6px 0 18px;padding:4px 6px 6px;border:1px solid rgba(126,96,60,.14);border-radius:8px;background:rgba(255,255,255,.86);box-shadow:0 4px 16px rgba(75,56,35,.045);}
|
|||
|
|
.cnot-backups[hidden]{display:none;}
|
|||
|
|
.cnot-backups-head{display:flex;align-items:baseline;gap:9px;flex-wrap:wrap;padding:10px 11px 8px;}
|
|||
|
|
.cnot-backups-head strong{color:#342b24;font-size:13px;}
|
|||
|
|
.cnot-backups-head span{color:#8d7b6a;font-size:12px;line-height:1.5;}
|
|||
|
|
.cnot-backup-item{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 11px;border-radius:4px;}
|
|||
|
|
.cnot-backup-item+.cnot-backup-item{border-top:1px solid rgba(126,96,60,.10);}
|
|||
|
|
.cnot-backup-main{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;min-width:0;}
|
|||
|
|
.cnot-backup-time{color:#3f342a;font-size:12.5px;font-weight:600;font-variant-numeric:tabular-nums;}
|
|||
|
|
.cnot-backup-tag{padding:1px 7px;border-radius:4px;background:#8b633b;color:#fff;font-size:11px;font-weight:600;line-height:1.7;}
|
|||
|
|
.cnot-backup-desc{color:#8d7b6a;font-size:12px;}
|
|||
|
|
.cnot-backup-item .cnot-btn{flex:0 0 auto;height:28px;padding:0 12px;font-size:12px;}
|
|||
|
|
@media(max-width:680px){.cnot-hero{padding:16px 14px;align-items:flex-start}.cnot-hero-icon{width:44px;height:44px;flex-basis:44px;border-radius:8px}.cnot-hero h2{font-size:14px}.cnot-hero p{font-size:12px;line-height:1.6}.cnot-hero-title{gap:10px}.cnot-hero-ops{margin-top:10px;gap:8px}.cnot-hero-ops .cnot-btn{box-sizing:border-box;flex:1 1 0;min-width:0;height:32px;padding:0 8px;font-size:12px}.cnot-hero-meta{flex-basis:100%}.cnot-backups{padding:2px 4px 4px}.cnot-backups-head{padding:10px 9px 8px;gap:5px}.cnot-backup-item{padding:9px;gap:9px}.cnot-backup-item .cnot-btn{flex:0 0 auto;height:30px;padding:0 12px;font-size:12px}}
|
|||
|
|
.dark .cnot-hero{background:linear-gradient(135deg,#1b2635,#18212f);border-color:rgba(255,255,255,.10);box-shadow:0 14px 34px rgba(0,0,0,.28);}
|
|||
|
|
.dark .cnot-hero:after{background:rgba(208,168,119,.07);}
|
|||
|
|
.dark .cnot-hero-icon{color:#d0a877;background:linear-gradient(145deg,#202c3d,#1a2434);border-color:rgba(255,255,255,.10);box-shadow:inset 0 1px 0 rgba(255,255,255,.06),0 12px 24px rgba(0,0,0,.30);}
|
|||
|
|
.dark .cnot-hero h2{color:#e8eef7;}
|
|||
|
|
.dark .cnot-hero p{color:#9aa8bb;}
|
|||
|
|
.dark .cnot-btn{background:linear-gradient(135deg,#9d7247,#bb8c57);box-shadow:0 4px 12px rgba(0,0,0,.24);}
|
|||
|
|
.dark .cnot-hero-meta{color:#93a2b8;}
|
|||
|
|
.dark .cnot-btn-ghost{color:#e8d0ad!important;background:rgba(255,255,255,.06)!important;border-color:rgba(255,255,255,.14);box-shadow:none;}
|
|||
|
|
.dark .cnot-note-ok{color:#4ade80;background:rgba(74,222,128,.10);border-color:rgba(74,222,128,.20);}
|
|||
|
|
.dark .cnot-note-fail{color:#f87171;background:rgba(248,113,113,.10);border-color:rgba(248,113,113,.20);}
|
|||
|
|
.dark .cnot-backups{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 30px rgba(0,0,0,.22);}
|
|||
|
|
.dark .cnot-backups-head strong{color:#e8eef7;}
|
|||
|
|
.dark .cnot-backups-head span{color:#93a2b8;}
|
|||
|
|
.dark .cnot-backup-item+.cnot-backup-item{border-top-color:rgba(255,255,255,.08);}
|
|||
|
|
.dark .cnot-backup-time{color:#e8eef7;}
|
|||
|
|
.dark .cnot-backup-tag{background:#d0a877;color:#18212f;}
|
|||
|
|
.dark .cnot-backup-desc{color:#93a2b8;}
|
|||
|
|
/* 密钥类输入框:强制等宽字体 + 明确高对比文字色,避免下划线 _ 被第三方字体子集渲染成空格而误删。
|
|||
|
|
用 !important 覆盖 FontLibs 的全局 * {font-family:...!important};-webkit-text-fill-color 防止被浏览器/自动填充改写。 */
|
|||
|
|
input[name*="secretKey"],input[name*="accessKey"],input[name*="uploadPath"]{font-family:"SFMono-Regular",Consolas,"Liberation Mono",Menlo,"Courier New",monospace!important;font-size:13px!important;font-weight:400!important;letter-spacing:.3px;color:#2d2824!important;-webkit-text-fill-color:#2d2824!important;opacity:1!important;}
|
|||
|
|
.dark input[name*="secretKey"],.dark input[name*="accessKey"],.dark input[name*="uploadPath"]{color:#e8eef7!important;-webkit-text-fill-color:#e8eef7!important;}
|
|||
|
|
</style>
|
|||
|
|
CSS;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 前端文章页的「导出 MD」按钮
|
|||
|
|
*
|
|||
|
|
* 主题的 parts/title.php 里这样调用:
|
|||
|
|
* echo ArticleToObsidian_Plugin::renderExportBtn($this->cid);
|
|||
|
|
*
|
|||
|
|
* 返回字符串(不是 echo),主题才能用 try/catch 兜住,插件出问题也不会把整篇文章打成 500。
|
|||
|
|
*
|
|||
|
|
* @param int $cid 当前文章 id
|
|||
|
|
* @return string
|
|||
|
|
*/
|
|||
|
|
public static function renderExportBtn($cid = 0)
|
|||
|
|
{
|
|||
|
|
$cid = (int) $cid;
|
|||
|
|
if ($cid <= 0) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/*
|
|||
|
|
* 必须再确认插件真的处于「启用」状态。
|
|||
|
|
* Typecho 的自动加载器只要 usr/plugins/ArticleToObsidian/Plugin.php 还在磁盘上,
|
|||
|
|
* 主题里一句 class_exists() 就能把类加载进来——插件停用之后按钮还会照常显示,
|
|||
|
|
* 点下去却是 404(动作路由已经跟着停用撤掉了)。
|
|||
|
|
*/
|
|||
|
|
$exported = Typecho_Plugin::export();
|
|||
|
|
if (empty($exported['activated']['ArticleToObsidian'])) {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$config = Helper::options()->plugin('ArticleToObsidian');
|
|||
|
|
if ($config && (string) $config->showExportBtn === '0') {
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
} catch (Exception $e) {
|
|||
|
|
// 配置还没保存过也照常显示
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$url = Typecho_Common::url(
|
|||
|
|
'action/' . self::EXPORT_ACTION,
|
|||
|
|
Helper::options()->index
|
|||
|
|
);
|
|||
|
|
$url .= (strpos($url, '?') === false ? '?' : '&')
|
|||
|
|
. 'cid=' . $cid . '&_nonce=' . self::exportNonce($cid);
|
|||
|
|
|
|||
|
|
return '<a class="post-export-link" href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"'
|
|||
|
|
. ' rel="nofollow" title="把这篇 Markdown 下载到本地,可直接放进 Obsidian 库">导出 MD</a>';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 导出链接的校验串
|
|||
|
|
*
|
|||
|
|
* 按小时生成,链接不会永久有效;同时容忍上一小时的链接,
|
|||
|
|
* 免得页面被缓存(或用户开着页面过了一小时)之后点下去变成 403。
|
|||
|
|
*
|
|||
|
|
* @param int $cid
|
|||
|
|
* @param int|null $time
|
|||
|
|
* @return string
|
|||
|
|
*/
|
|||
|
|
public static function exportNonce($cid, $time = null)
|
|||
|
|
{
|
|||
|
|
$time = $time === null ? time() : (int) $time;
|
|||
|
|
return substr(md5('article_to_obsidian_export|' . (int) $cid . '|' . date('Y-m-d-H', $time)), 0, 16);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 生成一篇文章的 Markdown(frontmatter + 正文)
|
|||
|
|
*
|
|||
|
|
* 前端按钮和后台导出共用一份逻辑,保证两边产出的文件格式一模一样。
|
|||
|
|
*
|
|||
|
|
* @param array $post contents 表里的一行
|
|||
|
|
* @return string
|
|||
|
|
*/
|
|||
|
|
public static function buildMarkdown(array $post)
|
|||
|
|
{
|
|||
|
|
$cid = (int) $post['cid'];
|
|||
|
|
$title = isset($post['title']) ? (string) $post['title'] : '';
|
|||
|
|
$title = self::cleanTitle($title);
|
|||
|
|
$slug = isset($post['slug']) ? (string) $post['slug'] : '';
|
|||
|
|
$created = isset($post['created']) ? (int) $post['created'] : time();
|
|||
|
|
$modified = isset($post['modified']) ? (int) $post['modified'] : $created;
|
|||
|
|
|
|||
|
|
$categories = array();
|
|||
|
|
$tags = array();
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$rows = $db->fetchAll($db->select('table.metas.name', 'table.metas.type')
|
|||
|
|
->from('table.metas')
|
|||
|
|
->join('table.relationships', 'table.relationships.mid = table.metas.mid')
|
|||
|
|
->where('table.relationships.cid = ?', $cid));
|
|||
|
|
|
|||
|
|
foreach ($rows as $row) {
|
|||
|
|
if ($row['type'] === 'category') {
|
|||
|
|
$categories[] = $row['name'];
|
|||
|
|
} elseif ($row['type'] === 'tag') {
|
|||
|
|
$tags[] = $row['name'];
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
} catch (Exception $e) {
|
|||
|
|
// 分类标签取不到不影响正文导出
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$md = "---\n";
|
|||
|
|
$md .= 'title: ' . self::yamlValue($title) . "\n";
|
|||
|
|
$md .= "cid: {$cid}\n";
|
|||
|
|
$md .= 'slug: ' . self::yamlValue($slug) . "\n";
|
|||
|
|
if (!empty($categories)) {
|
|||
|
|
$md .= "category: " . self::yamlValue($categories[0]) . "\n";
|
|||
|
|
}
|
|||
|
|
if (!empty($tags)) {
|
|||
|
|
$md .= "tags:\n";
|
|||
|
|
foreach ($tags as $tag) {
|
|||
|
|
$md .= ' - ' . self::yamlValue($tag) . "\n";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
$md .= 'date: ' . date('Y-m-d H:i:s', $created) . "\n";
|
|||
|
|
$md .= 'updated: ' . date('Y-m-d H:i:s', $modified) . "\n";
|
|||
|
|
$md .= "---\n\n";
|
|||
|
|
$md .= str_replace('<!--more-->', '<!-- more -->', isset($post['text']) ? (string) $post['text'] : '');
|
|||
|
|
|
|||
|
|
return $md;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* frontmatter 取值:含特殊字符时加引号,避免把 YAML 弄坏
|
|||
|
|
*
|
|||
|
|
* @param string $value
|
|||
|
|
* @return string
|
|||
|
|
*/
|
|||
|
|
private static function yamlValue($value)
|
|||
|
|
{
|
|||
|
|
$value = trim((string) $value);
|
|||
|
|
if ($value === '') {
|
|||
|
|
return '""';
|
|||
|
|
}
|
|||
|
|
if (preg_match('/^[\w\x{4e00}-\x{9fa5}][\w\x{4e00}-\x{9fa5}\s\-\.\,\(\)]*$/u', $value)) {
|
|||
|
|
return $value;
|
|||
|
|
}
|
|||
|
|
return '"' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $value) . '"';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 下载文件名:去掉文件系统不认的字符
|
|||
|
|
*
|
|||
|
|
* @param string $title
|
|||
|
|
* @param int $cid
|
|||
|
|
* @return string
|
|||
|
|
*/
|
|||
|
|
public static function exportFilename($title, $cid)
|
|||
|
|
{
|
|||
|
|
$name = preg_replace('/[\\\\\/:*?"<>|\x00-\x1F]+/u', '-', (string) $title);
|
|||
|
|
$name = trim(preg_replace('/\s+/u', ' ', $name));
|
|||
|
|
if ($name === '') {
|
|||
|
|
$name = 'post-' . (int) $cid;
|
|||
|
|
}
|
|||
|
|
return mb_substr($name, 0, 60, 'UTF-8') . '.md';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function getArticleCategory($cid)
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$prefix = $db->getPrefix();
|
|||
|
|
|
|||
|
|
$category = $db->fetchRow($db->query(
|
|||
|
|
"SELECT m.name FROM " . $prefix . "metas m
|
|||
|
|
INNER JOIN " . $prefix . "relationships r ON m.mid = r.mid
|
|||
|
|
WHERE r.cid = " . intval($cid) . " AND m.type = 'category' LIMIT 1"
|
|||
|
|
));
|
|||
|
|
|
|||
|
|
if ($category && !empty($category['name'])) {
|
|||
|
|
return self::sanitizeFilename($category['name']);
|
|||
|
|
}
|
|||
|
|
return '未分类';
|
|||
|
|
} catch (Exception $e) {
|
|||
|
|
return '未分类';
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function buildQiniuPath($cid, $categoryName, $filename, $rule, $basePath)
|
|||
|
|
{
|
|||
|
|
$year = date('Y');
|
|||
|
|
$safeCategory = $categoryName;
|
|||
|
|
|
|||
|
|
$path = '';
|
|||
|
|
|
|||
|
|
switch ($rule) {
|
|||
|
|
case 'category':
|
|||
|
|
$path = $safeCategory . '/';
|
|||
|
|
break;
|
|||
|
|
case 'year':
|
|||
|
|
$path = $year . '/';
|
|||
|
|
break;
|
|||
|
|
case 'year_category':
|
|||
|
|
$path = $year . '/' . $safeCategory . '/';
|
|||
|
|
break;
|
|||
|
|
case 'category_year':
|
|||
|
|
$path = $safeCategory . '/' . $year . '/';
|
|||
|
|
break;
|
|||
|
|
case 'none':
|
|||
|
|
default:
|
|||
|
|
$path = '';
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (!empty($basePath)) {
|
|||
|
|
$basePath = rtrim($basePath, '/') . '/';
|
|||
|
|
$path = $basePath . $path;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return $path . $filename;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function generateUploadToken($accessKey, $secretKey, $bucket)
|
|||
|
|
{
|
|||
|
|
$deadline = time() + 3600;
|
|||
|
|
$putPolicy = array(
|
|||
|
|
'scope' => $bucket,
|
|||
|
|
'deadline' => $deadline
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
$putPolicyJson = json_encode($putPolicy);
|
|||
|
|
$encodedPutPolicy = base64_encode($putPolicyJson);
|
|||
|
|
$sign = hash_hmac('sha1', $encodedPutPolicy, $secretKey, true);
|
|||
|
|
$encodedSign = base64_encode($sign);
|
|||
|
|
|
|||
|
|
return $accessKey . ':' . $encodedSign . ':' . $encodedPutPolicy;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function isContentChanged($cid, $content)
|
|||
|
|
{
|
|||
|
|
$hashFile = self::getHashFile($cid);
|
|||
|
|
$newHash = md5($content);
|
|||
|
|
|
|||
|
|
if (file_exists($hashFile)) {
|
|||
|
|
$oldHash = file_get_contents($hashFile);
|
|||
|
|
if ($oldHash === $newHash) {
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
file_put_contents($hashFile, $newHash);
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static function autoSyncOnUpdate($contents, $widget)
|
|||
|
|
{
|
|||
|
|
self::autoSyncOnPublish($contents, $widget);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static function autoSyncOnPublish($contents, $widget)
|
|||
|
|
{
|
|||
|
|
$logFile = self::getLogFile();
|
|||
|
|
|
|||
|
|
$options = Helper::options()->plugin('ArticleToObsidian');
|
|||
|
|
|
|||
|
|
if ($options->autoSync != '1') {
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (empty($options->accessKey) || empty($options->secretKey) || empty($options->bucket)) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 配置不完整\n", FILE_APPEND);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$cid = $widget->cid ?? $contents['cid'] ?? 0;
|
|||
|
|
|
|||
|
|
// ========== 获取标题并立即净化 ==========
|
|||
|
|
$rawTitle = $widget->title ?? $contents['title'] ?? '';
|
|||
|
|
$currentTitle = self::cleanTitle($rawTitle);
|
|||
|
|
|
|||
|
|
$text = $widget->text ?? $contents['text'] ?? '';
|
|||
|
|
$created = $widget->created ?? $contents['created'] ?? time();
|
|||
|
|
$modified = $widget->modified ?? $contents['modified'] ?? time();
|
|||
|
|
|
|||
|
|
if (empty($currentTitle) || !$cid) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 无法获取文章信息\n", FILE_APPEND);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (!self::isContentChanged($cid, $text)) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 内容无变化,跳过同步\n", FILE_APPEND);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$categoryName = self::getArticleCategory($cid);
|
|||
|
|
|
|||
|
|
// 获取 original_title(也净化)
|
|||
|
|
$originalTitle = '';
|
|||
|
|
$currentVersion = 1;
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$prefix = $db->getPrefix();
|
|||
|
|
|
|||
|
|
$originalField = $db->fetchRow($db->query(
|
|||
|
|
"SELECT str_value FROM " . $prefix . "fields
|
|||
|
|
WHERE cid = " . intval($cid) . " AND name = 'original_title' LIMIT 1"
|
|||
|
|
));
|
|||
|
|
|
|||
|
|
$versionField = $db->fetchRow($db->query(
|
|||
|
|
"SELECT int_value FROM " . $prefix . "fields
|
|||
|
|
WHERE cid = " . intval($cid) . " AND name = 'version' LIMIT 1"
|
|||
|
|
));
|
|||
|
|
|
|||
|
|
if ($originalField && !empty($originalField['str_value'])) {
|
|||
|
|
$originalTitle = self::cleanTitle($originalField['str_value']);
|
|||
|
|
$currentVersion = $versionField ? intval($versionField['int_value']) : 1;
|
|||
|
|
} else {
|
|||
|
|
$originalTitle = $currentTitle;
|
|||
|
|
$currentVersion = 1;
|
|||
|
|
// 保存 original_title / version:有则更新,无则插入
|
|||
|
|
self::saveField($cid, 'original_title', 'str', $currentTitle);
|
|||
|
|
self::saveField($cid, 'version', 'int', 1);
|
|||
|
|
}
|
|||
|
|
} catch (Exception $e) {
|
|||
|
|
$originalTitle = $currentTitle;
|
|||
|
|
$currentVersion = 1;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 判断标题是否变化(用净化后的值对比)
|
|||
|
|
$newVersion = $currentVersion + 1;
|
|||
|
|
$titleChanged = ($currentTitle != $originalTitle);
|
|||
|
|
|
|||
|
|
// 更新版本号
|
|||
|
|
if ($titleChanged) {
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$db->query($db->update('table.fields')
|
|||
|
|
->rows(array('int_value' => $newVersion, 'str_value' => $currentTitle))
|
|||
|
|
->where('cid = ?', $cid)
|
|||
|
|
->where('name = ?', 'version'));
|
|||
|
|
|
|||
|
|
// 更新 original_title 为当前标题(作为新的原始标题)
|
|||
|
|
$db->query($db->update('table.fields')
|
|||
|
|
->rows(array('str_value' => $currentTitle))
|
|||
|
|
->where('cid = ?', $cid)
|
|||
|
|
->where('name = ?', 'original_title'));
|
|||
|
|
} catch (Exception $e) {}
|
|||
|
|
} else {
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$db->query($db->update('table.fields')
|
|||
|
|
->rows(array('int_value' => $newVersion))
|
|||
|
|
->where('cid = ?', $cid)
|
|||
|
|
->where('name = ?', 'version'));
|
|||
|
|
} catch (Exception $e) {}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ========== 生成文件名(带版本号和时间戳) ==========
|
|||
|
|
$datetime = date('Ymd_His', $modified);
|
|||
|
|
$safeTitle = self::sanitizeFilename($currentTitle);
|
|||
|
|
|
|||
|
|
if ($titleChanged) {
|
|||
|
|
$safeOriginalTitle = self::sanitizeFilename($originalTitle);
|
|||
|
|
$filename = $safeOriginalTitle . "_改为_" . $safeTitle . "(v{$newVersion})-{$datetime}.md";
|
|||
|
|
$action = "标题变更: {$originalTitle} → {$currentTitle} (v{$newVersion})";
|
|||
|
|
} else {
|
|||
|
|
$filename = $safeTitle . "(v{$newVersion})-{$datetime}.md";
|
|||
|
|
$action = "第{$newVersion}次修改";
|
|||
|
|
}
|
|||
|
|
// =================================================
|
|||
|
|
|
|||
|
|
$qiniuPath = self::buildQiniuPath(
|
|||
|
|
$cid,
|
|||
|
|
$categoryName,
|
|||
|
|
$filename,
|
|||
|
|
$options->directoryRule ?? 'category',
|
|||
|
|
$options->uploadPath ?? ''
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ========== {$action} ==========\n", FILE_APPEND);
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ID:{$cid}\n", FILE_APPEND);
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 当前标题(纯净):{$currentTitle}\n", FILE_APPEND);
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 原始标题(纯净):{$originalTitle}\n", FILE_APPEND);
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 文件名:{$filename}\n", FILE_APPEND);
|
|||
|
|
|
|||
|
|
$slug = $widget->slug ?? $contents['slug'] ?? '';
|
|||
|
|
if (empty($slug)) {
|
|||
|
|
$slug = Typecho_Common::slugName($currentTitle);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ========== 生成 MD 文件:title 使用纯净标题 ==========
|
|||
|
|
// 确保标题是纯净的,移除所有版本号和时间戳后缀
|
|||
|
|
$cleanTitleForFile = preg_replace('/\(v\d+\)-\d+$/', '', $currentTitle);
|
|||
|
|
$cleanTitleForFile = preg_replace('/^.*?_改为_/', '', $cleanTitleForFile);
|
|||
|
|
$cleanTitleForFile = trim($cleanTitleForFile);
|
|||
|
|
|
|||
|
|
$md = "---\n";
|
|||
|
|
$md .= "title: " . self::yamlValue($cleanTitleForFile) . "\n"; // 这里必须写入纯净标题
|
|||
|
|
$md .= "cid: {$cid}\n";
|
|||
|
|
$md .= "slug: " . self::yamlValue($slug) . "\n";
|
|||
|
|
$md .= "version: {$newVersion}\n";
|
|||
|
|
$md .= "original_title: " . self::yamlValue($originalTitle) . "\n";
|
|||
|
|
$md .= "category: " . self::yamlValue($categoryName) . "\n";
|
|||
|
|
$md .= "date: " . date('Y-m-d H:i:s', $created) . "\n";
|
|||
|
|
$md .= "updated: " . date('Y-m-d H:i:s', $modified) . "\n";
|
|||
|
|
$md .= "---\n\n";
|
|||
|
|
$md .= $text;
|
|||
|
|
// ====================================================
|
|||
|
|
|
|||
|
|
$tmpFile = sys_get_temp_dir() . '/article_' . $cid . '_' . time() . '.md';
|
|||
|
|
file_put_contents($tmpFile, $md);
|
|||
|
|
|
|||
|
|
$result = self::uploadToQiniuWithRetry($tmpFile, $qiniuPath, $options);
|
|||
|
|
|
|||
|
|
@unlink($tmpFile);
|
|||
|
|
|
|||
|
|
if ($result['success']) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ✅ 成功\n", FILE_APPEND);
|
|||
|
|
} else {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ❌ 失败: {$result['error']}\n", FILE_APPEND);
|
|||
|
|
}
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] ========== {$action}结束 ==========\n\n", FILE_APPEND);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 写 typecho_fields 里的自定义字段:有则更新,无则插入
|
|||
|
|
*
|
|||
|
|
* 老插件 ArticleExport 和本插件用的是同一组字段(original_title / version)。
|
|||
|
|
* 两个插件同时装着的时候,两边都会走"查不到就插入"的分支:
|
|||
|
|
* MySQL 上主键(cid,name)冲突、SQLite 上直接多出重复行,版本号还会一次加两次。
|
|||
|
|
* 统一走这里之后,同时跑也只会互相覆盖,不会再插重。
|
|||
|
|
*
|
|||
|
|
* @param int $cid
|
|||
|
|
* @param string $name
|
|||
|
|
* @param string $type str|int
|
|||
|
|
* @param mixed $value
|
|||
|
|
*/
|
|||
|
|
private static function saveField($cid, $name, $type, $value)
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$exists = $db->fetchRow($db->select('cid')->from('table.fields')
|
|||
|
|
->where('cid = ?', (int) $cid)
|
|||
|
|
->where('name = ?', $name)
|
|||
|
|
->limit(1));
|
|||
|
|
|
|||
|
|
$rows = array('type' => $type);
|
|||
|
|
$rows[$type === 'int' ? 'int_value' : 'str_value'] = $value;
|
|||
|
|
|
|||
|
|
if ($exists) {
|
|||
|
|
$db->query($db->update('table.fields')->rows($rows)
|
|||
|
|
->where('cid = ?', (int) $cid)
|
|||
|
|
->where('name = ?', $name));
|
|||
|
|
} else {
|
|||
|
|
$db->query($db->insert('table.fields')->rows(array_merge(
|
|||
|
|
array('cid' => (int) $cid, 'name' => $name),
|
|||
|
|
$rows
|
|||
|
|
)));
|
|||
|
|
}
|
|||
|
|
} catch (Exception $e) {
|
|||
|
|
file_put_contents(self::getLogFile(), "[" . date('Y-m-d H:i:s')
|
|||
|
|
. "] 字段 {$name} 写入失败: " . $e->getMessage() . "\n", FILE_APPEND);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 净化标题:去除版本号后缀和 _改为_ 前缀
|
|||
|
|
*/
|
|||
|
|
private static function cleanTitle($title)
|
|||
|
|
{
|
|||
|
|
if (empty($title)) return '';
|
|||
|
|
$clean = preg_replace('/\(v\d+\)-\d+$/', '', $title);
|
|||
|
|
$clean = preg_replace('/^.*?_改为_/', '', $clean);
|
|||
|
|
$clean = trim($clean);
|
|||
|
|
return empty($clean) ? $title : $clean;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function sanitizeFilename($filename)
|
|||
|
|
{
|
|||
|
|
$filename = self::cleanTitle($filename);
|
|||
|
|
$filename = preg_replace('/[\/:*?"<>|\\\]/', '-', $filename);
|
|||
|
|
$filename = mb_substr($filename, 0, 50, 'UTF-8');
|
|||
|
|
return $filename;
|
|||
|
|
}
|
|||
|
|
/**
|
|||
|
|
* 从数据库读取纯净标题
|
|||
|
|
*/
|
|||
|
|
private static function getCleanTitleFromDb($cid)
|
|||
|
|
{
|
|||
|
|
try {
|
|||
|
|
$db = Typecho_Db::get();
|
|||
|
|
$row = $db->fetchRow($db->query(
|
|||
|
|
"SELECT title FROM " . $db->getPrefix() . "contents WHERE cid = " . intval($cid)
|
|||
|
|
));
|
|||
|
|
if ($row && isset($row['title'])) {
|
|||
|
|
return self::cleanTitle($row['title']);
|
|||
|
|
}
|
|||
|
|
} catch (Exception $e) {}
|
|||
|
|
return '';
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
private static function uploadToQiniuWithRetry($localFile, $remotePath, $options, $maxRetries = 3)
|
|||
|
|
{
|
|||
|
|
$logFile = self::getLogFile();
|
|||
|
|
$result = ['success' => false, 'error' => ''];
|
|||
|
|
|
|||
|
|
for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
|
|||
|
|
if ($attempt > 1) {
|
|||
|
|
$delay = $attempt - 1;
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 第{$attempt}次重试,等待{$delay}秒...\n", FILE_APPEND);
|
|||
|
|
sleep($delay);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$result = self::uploadToQiniu($localFile, $remotePath, $options);
|
|||
|
|
|
|||
|
|
if ($result['success']) {
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$errorLower = strtolower($result['error']);
|
|||
|
|
|
|||
|
|
if (strpos($errorLower, 'badtoken') !== false ||
|
|||
|
|
strpos($errorLower, 'bad token') !== false ||
|
|||
|
|
strpos($errorLower, '401') !== false) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] Token无效,重新生成并重试\n", FILE_APPEND);
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (strpos($errorLower, 'could not resolve') !== false ||
|
|||
|
|
strpos($errorLower, 'timed out') !== false ||
|
|||
|
|
strpos($errorLower, 'connection') !== false ||
|
|||
|
|
strpos($errorLower, 'curl') !== false) {
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 网络错误,继续重试\n", FILE_APPEND);
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] 非可重试错误,停止重试: {$errorLower}\n", FILE_APPEND);
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return ['success' => false, 'error' => $result['error'] ?? '重试失败'];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function uploadToQiniu($localFile, $remotePath, $options)
|
|||
|
|
{
|
|||
|
|
$accessKey = trim($options->accessKey);
|
|||
|
|
$secretKey = trim($options->secretKey);
|
|||
|
|
$bucket = trim($options->bucket);
|
|||
|
|
$region = trim($options->region);
|
|||
|
|
|
|||
|
|
$uploadDomains = [
|
|||
|
|
'z0' => 'https://upload-z0.qiniup.com',
|
|||
|
|
'z1' => 'https://upload-z1.qiniup.com',
|
|||
|
|
'z2' => 'https://upload-z2.qiniup.com',
|
|||
|
|
'as0' => 'https://upload-as0.qiniup.com',
|
|||
|
|
'na0' => 'https://upload-na0.qiniup.com',
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
$backupDomains = [
|
|||
|
|
'z0' => 'https://up-z0.qiniup.com',
|
|||
|
|
'z1' => 'https://up-z1.qiniup.com',
|
|||
|
|
'z2' => 'https://up-z2.qiniup.com',
|
|||
|
|
'as0' => 'https://up-as0.qiniup.com',
|
|||
|
|
'na0' => 'https://up-na0.qiniup.com',
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
$uploadUrl = $uploadDomains[$region] ?? 'https://upload-z2.qiniup.com';
|
|||
|
|
$backupUrl = $backupDomains[$region] ?? 'https://up-z2.qiniup.com';
|
|||
|
|
|
|||
|
|
if (!file_exists($localFile)) {
|
|||
|
|
return ['success' => false, 'error' => '文件不存在: ' . $localFile];
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$uploadToken = self::generateUploadToken($accessKey, $secretKey, $bucket);
|
|||
|
|
|
|||
|
|
$filename = basename($remotePath);
|
|||
|
|
$curlFile = new CURLFile($localFile, 'text/markdown', $filename);
|
|||
|
|
|
|||
|
|
$postFields = [
|
|||
|
|
'token' => $uploadToken,
|
|||
|
|
'key' => $remotePath,
|
|||
|
|
'file' => $curlFile
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
$result = self::doUpload($uploadUrl, $postFields);
|
|||
|
|
|
|||
|
|
if (!$result['success']) {
|
|||
|
|
$errorMsg = strtolower($result['error']);
|
|||
|
|
if (strpos($errorMsg, 'could not resolve host') !== false ||
|
|||
|
|
strpos($errorMsg, 'connection timed out') !== false ||
|
|||
|
|
strpos($errorMsg, 'failed to connect') !== false ||
|
|||
|
|
strpos($errorMsg, 'curl') !== false) {
|
|||
|
|
|
|||
|
|
usleep(500000);
|
|||
|
|
$result = self::doUpload($backupUrl, $postFields);
|
|||
|
|
|
|||
|
|
if ($result['success']) {
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return $result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static function doUpload($url, $postFields)
|
|||
|
|
{
|
|||
|
|
$ch = curl_init();
|
|||
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|||
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|||
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
|
|||
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|||
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
|
|||
|
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
|
|||
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|||
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
|||
|
|
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
|
|||
|
|
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
|
|||
|
|
curl_setopt($ch, CURLOPT_USERAGENT, 'Typecho-ArticleToObsidian-Plugin/2.0.2');
|
|||
|
|
|
|||
|
|
$response = curl_exec($ch);
|
|||
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|||
|
|
$error = curl_error($ch);
|
|||
|
|
// curl_close() 自 PHP 8.0 起为空操作并标记废弃;仅为 PHP 7.x 保留真实关闭
|
|||
|
|
if (PHP_VERSION_ID < 80000) {
|
|||
|
|
curl_close($ch);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if ($httpCode == 200) {
|
|||
|
|
$result = json_decode($response, true);
|
|||
|
|
if (isset($result['key']) || isset($result['hash'])) {
|
|||
|
|
return ['success' => true, 'data' => $result];
|
|||
|
|
}
|
|||
|
|
return ['success' => false, 'error' => $response];
|
|||
|
|
} else {
|
|||
|
|
$errorMsg = $response ?: $error;
|
|||
|
|
return ['success' => false, 'error' => $errorMsg];
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|