From 5b735af44fc77f905a59266a77a38d21c9a02e64 Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:04:07 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 29 + CHANGELOG.md | 48 ++ CONTRIBUTING.md | 19 + ExportAction.php | 92 +++ LICENSE | 21 + Plugin.php | 1611 ++++++++++++++++++++++++++++++++++++++++++++++ README.md | 28 + manage.php | 841 ++++++++++++++++++++++++ 8 files changed, 2689 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 ExportAction.php create mode 100644 LICENSE create mode 100644 Plugin.php create mode 100644 manage.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..7372ee6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,48 @@ +# ArticleToObsidian 更新日志 + +> 本文件记录本插件的所有修改与变化。本次整理(2026-11-22)为规范化记录起点。 + +## 插件信息 + +- 名称:ArticleToObsidian +- 版本:2.2.1 +- 作者:三股水 +- 说明:文章自动同步到七牛云(支持标题变更追踪 + 分类目录) + +## 记录格式约定 + +每次修改按如下格式在**最上方**追加一条记录(新的在上): + +``` +## YYYY-MM-DD · 版本号 —— 一句话概述 + +- 改动点 1 +- 改动点 2 +- 影响范围 / 注意事项(若有) +- 对应备份:备份/YYYY-MM-DD-修改内容简短说明修改前/ +``` + +## 2026-11-22 · 2.2.1 —— 修复 PHP 8.5 兼容:curl_close 废弃告警 + +- `Plugin.php`(同步上传函数收尾处):裸调用 `curl_close($ch)` 改为 `if (PHP_VERSION_ID < 80000)` 包裹 +- 原因:`curl_close()` 自 PHP 8.0 起为空操作并标记废弃,PHP 8.5 下每次调用产生 E_DEPRECATED,污染 error_log / AJAX JSON 响应 +- 影响范围:仅同步请求收尾逻辑,请求行为、返回值与功能完全不变 +- 验证:PHP 8.3 / 8.0 `php -l` 通过 +- 对应备份:`备份/2026-11-22-PHP85兼容修复修改前/` + +--- + +## 2026-11-22 · 2.2.0 —— 统一作者与链接 + +- `Plugin.php` 头部 `@author` 统一为「石头厝」 +- `@link` 统一为 `https://www.shitoucuo.com/` +- 影响范围:仅头部元信息,不涉及功能代码 +- 对应备份:`备份/2026-11-22-统一作者和链接修改前/` + +--- + +## 2026-11-22 · 2.2.0 —— 建立规范化备份与更新日志 + +- 建立 `备份/` 文件夹并生成本次整理前全量备份 `备份/2026-11-22-规范化整理修改前/` +- 创建本更新日志,作为后续所有修改的记录起点 +- 说明:本次仅做规范化整理,未改动插件功能代码 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/ExportAction.php b/ExportAction.php new file mode 100644 index 0000000..14afc1f --- /dev/null +++ b/ExportAction.php @@ -0,0 +1,92 @@ +export(); + } + + private function export() + { + $cid = (int) $this->request->get('cid'); + $nonce = (string) $this->request->get('_nonce'); + + if ($cid <= 0 || !$this->nonceValid($cid, $nonce)) { + $this->fail('导出链接已失效,刷新文章页后重新点击即可。', 403); + } + + $db = Typecho_Db::get(); + $post = $db->fetchRow($db->select('cid', 'title', 'text', 'created', 'modified', 'slug', 'status') + ->from('table.contents') + ->where('cid = ?', $cid) + ->where('type = ?', 'post') + ->limit(1)); + + if (!$post) { + $this->fail('文章不存在。', 404); + } + + if ($post['status'] !== 'publish') { + $this->fail('文章尚未发布,不能导出。', 403); + } + + $markdown = ArticleToObsidian_Plugin::buildMarkdown($post); + $filename = ArticleToObsidian_Plugin::exportFilename($post['title'], $cid); + + // 中文文件名:给老浏览器一个纯 ASCII 兜底名,再按 RFC 5987 补上真实文件名 + $fallback = 'post-' . $cid . '.md'; + + $this->response->setStatus(200); + $this->response->setHeader( + 'Content-Disposition', + 'attachment; filename="' . $fallback . '"; filename*=UTF-8\'\'' . rawurlencode($filename) + ); + $this->response->setHeader('X-Content-Type-Options', 'nosniff'); + $this->response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate'); + $this->response->throwContent($markdown, 'text/markdown'); + } + + /** + * 校验串:当前小时或上一小时都算有效 + * + * @param int $cid + * @param string $nonce + * @return bool + */ + private function nonceValid($cid, $nonce) + { + if ($nonce === '') { + return false; + } + + $now = time(); + foreach (array($now, $now - 3600) as $time) { + if (hash_equals(ArticleToObsidian_Plugin::exportNonce($cid, $time), $nonce)) { + return true; + } + } + + return false; + } + + /** + * @param string $message + * @param int $status + */ + private function fail($message, $status = 400) + { + // 状态码必须走 Response 对象:Typecho 最后会用它自己的 status 覆盖 header(), + // 直接 http_response_code() 是无效的(试过,永远 200)。 + $this->response->setStatus($status); + $this->response->throwContent($message, 'text/plain'); + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e3e16f1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 三股水 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugin.php b/Plugin.php new file mode 100644 index 0000000..8ea0b96 --- /dev/null +++ b/Plugin.php @@ -0,0 +1,1611 @@ +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 = '
+

命名规则

+
+

目录规则说明:

+ +

文件命名规则:

+ +
+
'; + + $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 = '' + . ''; + } + + 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]; + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index 9199a62..51e6862 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,30 @@ # ArticleToObsidian +> 仓库:`ArticleToObsidian` · 类型:Typecho 插件 · 版本:`2.2.1` · 作者:三股水 + +文章自动同步到七牛云,支持标题变更追踪与分类目录。 + +本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。 + +## 目录结构 + +- `ExportAction.php` +- `Plugin.php` +- `manage.php` + +## 安装与使用 + +1. 将本仓库目录复制到 Typecho 站点的 `usr/plugins/<仓库名>/`。 +2. 在 Typecho 后台「插件」管理中启用并按站点配置。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/manage.php b/manage.php new file mode 100644 index 0000000..d44e1c6 --- /dev/null +++ b/manage.php @@ -0,0 +1,841 @@ +getPrefix(); + +// ==================== 导出处理 ==================== +if (isset($_POST['do_export'])) { + $exportType = $_POST['export_type']; + $exportValue = $_POST['export_value']; + $batch = isset($_POST['batch']) ? intval($_POST['batch']) : 0; + $batchSize = 300; // 每批导出300篇 + + // 构建查询条件 + $whereClause = ""; + if ($exportType == 'year' && !empty($exportValue)) { + $year = intval($exportValue); + $start = strtotime($year . '-01-01'); + $end = strtotime($year . '-12-31'); + $whereClause = " AND created >= " . intval($start) . " AND created <= " . intval($end); + } elseif ($exportType == 'category' && !empty($exportValue)) { + $mid = intval($exportValue); + $whereClause = " AND cid IN (SELECT cid FROM " . $prefix . "relationships WHERE mid = " . $mid . ")"; + } elseif ($exportType == 'tag' && !empty($exportValue)) { + $mid = intval($exportValue); + $whereClause = " AND cid IN (SELECT cid FROM " . $prefix . "relationships WHERE mid = " . $mid . ")"; + } + + // 获取总文章数 + $totalSql = "SELECT COUNT(*) as total FROM " . $prefix . "contents WHERE type = 'post' AND status = 'publish'" . $whereClause; + $totalResult = $db->fetchRow($db->query($totalSql)); + $totalPosts = $totalResult['total']; + + // 如果是第一次请求(非分批),检查是否需要分批 + if ($batch === 0 && $totalPosts > $batchSize) { + // 需要分批导出,返回提示页面 + $totalBatches = ceil($totalPosts / $batchSize); + + /* 这一页是 target="_blank" 打开的独立页面(没有 header.php / + menu.php,不在 #newadmin 框架里),拿不到 NewAdmin 的深浅色, + 直接读同一个 cookie 跟随后台主题 —— 用户在后台选了深色, + 这里就跟着是深色,两边观感一致。 */ + $isDarkPage = (isset($_COOKIE['dark']) && $_COOKIE['dark'] === 'dark'); + ?> + + > + + + 分批导出 + + + +
+

📦 文章数量较多,建议分批导出

+
+

📊 共找到 篇文章

+

⚡ 每批导出 篇,共 批

+

💡 建议分批导出,避免超时或内存不足

+
+
+ +
+ 📄 第 批 (第 - 篇) +
+ + + + + +
+
+ +
+
+
+ + + + + +
+
+
+ + + fetchAll($db->query($sql)); + + if (empty($posts)) { + die('没有找到符合条件的文章'); + } + + $zip = new ZipArchive(); + $batchSuffix = ($batch !== 0 && $batch !== 'all') ? "_batch{$batch}" : ""; + $tmpFile = sys_get_temp_dir() . '/export_' . uniqid() . $batchSuffix . '.zip'; + $zip->open($tmpFile, ZipArchive::CREATE); + + $exportCount = 0; + foreach ($posts as $post) { + $cid = $post['cid']; + + $cat = $db->fetchRow($db->query("SELECT m.name FROM " . $prefix . "metas m INNER JOIN " . $prefix . "relationships r ON m.mid=r.mid WHERE r.cid=$cid AND m.type='category' LIMIT 1")); + $catName = $cat ? $cat['name'] : '未分类'; + + $tags = $db->fetchAll($db->query("SELECT m.name FROM " . $prefix . "metas m INNER JOIN " . $prefix . "relationships r ON m.mid=r.mid WHERE r.cid=$cid AND m.type='tag'")); + $tagNames = array_column($tags, 'name'); + $tagStr = implode(',', $tagNames); + + $date = date('Y-m-d', $post['created']); + $filename = preg_replace('/[\/:*?"<>|]/', '-', $post['title']) . "-{$date}.md"; + + $md = "---\ntitle: {$post['title']}\ndate: " . date('Y-m-d H:i:s', $post['created']) . "\n"; + if ($catName != '未分类') $md .= "category: [{$catName}]\n"; + if ($tagStr) $md .= "tags: [{$tagStr}]\n"; + $md .= "---\n\n{$post['text']}"; + + $zip->addFromString($filename, $md); + $exportCount++; + } + + $zip->close(); + + $filename = 'export_' . date('Ymd'); + if ($exportType == 'year' && !empty($exportValue)) { + $filename .= "_{$exportValue}年"; + } elseif ($exportType == 'category' && !empty($exportValue)) { + $catName = $db->fetchRow($db->query("SELECT name FROM " . $prefix . "metas WHERE mid = " . intval($exportValue))); + $filename .= "_{$catName['name']}"; + } elseif ($exportType == 'tag' && !empty($exportValue)) { + $tagName = $db->fetchRow($db->query("SELECT name FROM " . $prefix . "metas WHERE mid = " . intval($exportValue))); + $filename .= "_{$tagName['name']}"; + } + if ($batch !== 0 && $batch !== 'all') { + $filename .= "_第{$batch}批"; + } + $filename .= '.zip'; + + header('Content-Type: application/zip'); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Content-Length: ' . filesize($tmpFile)); + readfile($tmpFile); + unlink($tmpFile); + exit; +} + +// ==================== 获取数据 ==================== +// 获取有文章的年份列表(含文章数量) +// 不用 FROM_UNIXTIME/YEAR():那是 MySQL 专有函数,SQLite 上直接报 +// "no such function: FROM_UNIXTIME",整页 500。改在 PHP 里按 created 归档。 +$yearMap = array(); +$yearRows = $db->fetchAll($db->query("SELECT created FROM " . $prefix . "contents WHERE type = 'post' AND status = 'publish'")); +foreach ($yearRows as $yearRow) { + $yearKey = date('Y', (int) $yearRow['created']); + $yearMap[$yearKey] = isset($yearMap[$yearKey]) ? $yearMap[$yearKey] + 1 : 1; +} +krsort($yearMap); +$years = array(); +foreach ($yearMap as $yearKey => $yearCount) { + $years[] = array('year' => $yearKey, 'count' => $yearCount); +} + +// 获取分类列表(含文章数量) +$categories = $db->fetchAll($db->query("SELECT m.mid, m.name, COUNT(r.cid) as count FROM " . $prefix . "metas m LEFT JOIN " . $prefix . "relationships r ON m.mid=r.mid WHERE m.type='category' GROUP BY m.mid ORDER BY m.`order`")); + +// 获取标签列表(含文章数量) +$tagsList = $db->fetchAll($db->query("SELECT m.mid, m.name, COUNT(r.cid) as count FROM " . $prefix . "metas m LEFT JOIN " . $prefix . "relationships r ON m.mid=r.mid WHERE m.type='tag' GROUP BY m.mid ORDER BY m.name LIMIT 100")); + +include 'header.php'; +include 'menu.php'; +?> + + + +
+
+

文章导出

+
+
+
+

文章导出工具

+

将文章导出为Obsidian支持的Markdown格式ZIP压缩包

+
+
+
+

💡 插件特色

+
    +
  • 导出格式为ZIP压缩包,一篇一个 .md 文件,包含完整 Frontmatter(标题、日期、分类、标签等)
  • +
  • 支持按年份、分类、标签筛选导出特定范围的文章
  • +
  • 文章数量较多时(超过300篇),会自动提示分批导出,避免超时
  • +
+
+ +
+
+
+ + +
+ + +
+ + + + +
+ +
+ + + 年 + + + +
+
+
+ + + + + + +
+ + +
+
+
+
+
+
+ + + + + + \ No newline at end of file