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 = '
命名规则
目录规则说明:
- 根目录:
不上传到任何分类目录
- 按文章分类创建目录:
根据 Typecho 文章分类自动创建七牛云目录
- 按年份创建目录:
如 2026/文件名.md
- 按年份/分类创建目录:
如 2026/技术文章/文件名.md
- 按分类/年份创建目录:
如 技术文章/2026/文件名.md
文件命名规则:
- 首次发布:
{标题}(v1)-{时间戳}.md
- 标题未变:
{标题}(v{版本号})-{时间戳}.md
- 标题已变:
{原标题}_改为_{新标题}(v{版本号})-{时间戳}.md
- 内容去重:如果文章内容没有变化,不会重复上传
- 重要:Typecho 数据库中的标题始终保持纯净(不含版本号后缀)
- 重要:MD 文件内的 title 字段始终保持纯净
';
$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
? '恢复'
: '恢复';
$historyBtn = '';
$historyBox = '';
if (count($list) > 1) {
$rows = '';
foreach ($list as $index => $item) {
$rows .= ''
. '
'
. '' . self::e(date('Y-m-d H:i:s', $item['created'])) . ''
. ($index === 0 ? '最新' : '')
. '' . intval($item['count']) . ' 项配置 · '
. self::e(self::formatBytes($item['size']))
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
. ''
. '
'
. '
恢复'
. '
';
}
$historyBtn = '历史备份';
$historyBox = ''
. '
历史备份从新到旧,点「恢复」就用那一份覆盖当前设置
'
. $rows
. '
'
. '';
}
return ''
. '
'
. '
'
. '
'
. '
'
. '
'
. '
' . self::e(self::PLUGIN_TITLE) . '
'
. ''
. '
自动同步、AccessKey、SecretKey、空间名称、存储区域、上传路径、目录规则等设置都可以存成一份文件,改乱了点「恢复」就能退回上一次。
'
. '
'
. '
备份'
. $restoreBtn
. $historyBtn
. '
' . $meta . ''
. '
'
. '
'
. '
'
. $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 '' . self::e($text) . '
';
}
/**
* 备份目录
*/
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 = '' . "\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'
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 '导出 MD';
}
/**
* 导出链接的校验串
*
* 按小时生成,链接不会永久有效;同时容忍上一小时的链接,
* 免得页面被缓存(或用户开着页面过了一小时)之后点下去变成 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('', '', 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];
}
}
}