From 8310fde59e2ff11351fab35bae5dbf12b0074391 Mon Sep 17 00:00:00 2001 From: XIGE Date: Thu, 3 Dec 2026 21:35:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=EF=BC=9ATypecho=20?= =?UTF-8?q?=E7=89=88=E4=B8=83=E7=89=9B=E4=BA=91=E5=AD=98=E5=82=A8=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=202.9.0=EF=BC=88=E5=90=AB=E6=96=87=E4=BB=B6=E5=90=8D?= =?UTF-8?q?=E5=89=8D=E7=BC=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 24 + CHANGELOG.md | 50 ++ CONTRIBUTING.md | 19 + LICENSE | 21 + Plugin.php | 2095 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 55 +- composer.json | 5 + composer.lock | 142 ++++ 8 files changed, 2410 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 Plugin.php create mode 100644 composer.json create mode 100644 composer.lock diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8d7d96a --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Runtime data, cache and logs +data/ +cache/ +*.log + +# Backups and temporary files +备份/ +*.bak +*.tmp +.DS_Store + +# Environment and secrets +.env +.env.* +*key*.txt +credentials*.json + +# Editor and build artifacts +.idea/ +.vscode/ +node_modules/ +vendor/ +dist/ +build/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c4c360a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,50 @@ +# Qiniu 更新日志 + +> 本文件记录本插件的所有修改与变化。仓库建立于 2026-12-03,此前历史见插件目录内的 `更新日志.MD`。 + +## 插件信息 + +- 名称:七牛云存储 +- 版本:2.9.0 +- 作者:石头厝 +- 说明:七牛云存储 + CDN + WebP + 图片质量 + EXIF 信息 + 文件名前缀 + +## 记录格式约定 + +每次修改按如下格式在**最上方**追加一条记录(新的在上): + +``` +## YYYY-MM-DD · 版本号 —— 一句话概述 + +- 改动点 1 +- 改动点 2 +- 影响范围 / 注意事项(若有) +``` + +## 2026-12-03 · 2.9.0 —— 新增「文件名前缀」设置 + +- 设置页新增「文件名前缀」(`prefix`),最终对象键为 `保存路径前缀/前缀_原文件名.扩展名`;留空不启用 +- 新增 `renderPrefix()`:变量替换(`{year}` `{month}` `{day}`)→ 空白剔除 → 非法字符抹平 → 连续下划线归一 → 40 字符截断 +- 前缀只加在文件名上:`/` `\` 会抹成 `_`,不会把前缀变成新目录层级 +- 表单侧用闭包按字符数校验(Typecho 内置 `maxLength` 按字节计,中文会被误判超限) +- 「替换附件」沿用原对象键、不加前缀:改名等于换地址,正文已插入的图片会失效 +- 升级无需停用再启用;前缀缺省为空,升级后行为与 2.8.3 一致 + +## 2026-12-03 · 2.8.3 —— 密钥加密存储,后台不再明文回显 + +- AccessKey / SecretKey 改为 AES-256-GCM 密文存库,表单只回填 `enc:v1:` 密文占位 +- 新增 `configHandle()` 接管保存:空值 = 保持原值,新值 = 加密写入 +- `getConfig()` 内解密,调用点零改动;历史明文原样兼容 +- 回滚到 2.8.3 之前需先把密钥改回明文 + +## 2026-12-03 · 2.8.2 —— 修复设置保存的 regexp 校验 TypeError + +- 「图片质量」的 `regexp` 规则改为闭包(`Typecho\Validate` 无 `regexp` 方法,PHP 8 下直接抛 `TypeError`) + +## 2026-11-22 · 2.8.1 —— PHP 8.5 兼容 + +- 七牛 SDK 4 处隐式可空参数(`Type $x = null`)改为显式可空(`?Type`),消除 `E_DEPRECATED` + +## 2026-11-22 · 2.8.0 —— 统一作者与链接 + +- `Plugin.php` 头部 `@author` 统一为「石头厝」,`@link` 统一为 `https://www.shitoucuo.com/` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0a57600 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本项目提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、静态资源与必要文档;不要提交 `data/`、`cache/`、调试日志、备份目录或 API Key 等敏感信息。 +- 变更涉及 Typecho 钩子或 PHP 版本兼容时,请确认兼容 Typecho 1.3 与 PHP 8.5。 +- 影响用户配置或后台展示的改动,请同步更新 `README.md` 与 `CHANGELOG.md`。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要变更请补充变更记录。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并附上插件版本、Typecho / PHP 版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7951bd8 --- /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..81889fa --- /dev/null +++ b/Plugin.php @@ -0,0 +1,2095 @@ +1) 会被当成一次成功上传写进 contents 表。 + * 4. 1.3 的 Widget\Options::plugin() 在配置不存在时抛 PluginException(500), + * 所有读取配置的地方都要兜底,否则「启用但没配置」会整站后台打不开。 + * 5. $widget->is('single') 只有 Widget\Archive 有,后台内容组件没有该方法, + * 原来在后台渲染摘要时会抛异常,必须用 method_exists 判断。 + * 6. composer 的 autoload 会 prepend 到 spl 队列,改成真正需要七牛 SDK 时才加载。 + */ +class Qiniu_Plugin implements Typecho_Plugin_Interface +{ + /** + * 插件版本 + */ + const VERSION = '2.9.0'; + + /** 文件名前缀最大字符数(多字节按 1 个字符计) */ + const PREFIX_MAX_LEN = 40; + + /** 插件中文名(设置页顶部备份卡片标题用) */ + const PLUGIN_TITLE = '七牛云存储'; + + /** 备份文件名前缀 */ + const BACKUP_PREFIX = 'qiniu-settings-'; + + /** 备份保留份数 */ + const BACKUP_KEEP = 5; + + /** + * CSS 是否已输出 + * + * @var bool + */ + private static $_cssLoaded = false; + + /** + * 配置缓存 + * + * @var Typecho_Config|null + */ + private static $_config = null; + + /** + * 七牛 SDK 是否已加载 + * + * @var bool + */ + private static $_sdkLoaded = false; + + // 激活插件 + public static function activate() + { + $upload = Typecho_Plugin::factory('Widget_Upload'); + $upload->uploadHandle = array('Qiniu_Plugin', 'uploadHandle'); + $upload->modifyHandle = array('Qiniu_Plugin', 'modifyHandle'); + $upload->deleteHandle = array('Qiniu_Plugin', 'deleteHandle'); + $upload->attachmentHandle = array('Qiniu_Plugin', 'attachmentHandle'); + + // 添加文章内容输出时的EXIF信息显示 + // 只挂 contentEx:excerptEx 会让 EXIF 文本混进摘要和 meta description + Typecho_Plugin::factory('Widget_Abstract_Contents')->contentEx = array('Qiniu_Plugin', 'parseContent'); + + // 使用安全的CSS加载方式 + Typecho_Plugin::factory('Widget_Archive')->footer = array('Qiniu_Plugin', 'footer'); + + // 1.3 的配置面板会直接读 Options::plugin(),配置行不存在时抛 PluginException, + // 表现是「刚启用就点设置 → 500」。启用时先落一份默认配置,保证配置页能正常打开。 + self::ensureConfigRow(); + + return _t('插件已激活,请先配置七牛云信息!'); + } + + /** + * 确保配置行存在(不然 1.3 打开插件设置页会 500) + */ + private static function ensureConfigRow() + { + try { + $db = Typecho_Db::get(); + $row = $db->fetchRow($db->select('name')->from('table.options') + ->where('name = ?', 'plugin:Qiniu')); + + if (!empty($row)) { + return; + } + + $db->query($db->insert('table.options')->rows(array( + 'name' => 'plugin:Qiniu', + 'user' => 0, + 'value' => json_encode(self::defaultConfig()), + ))); + } catch (Exception $e) { + // 写不进去也不该影响插件启用 + } + } + + // 禁用插件 + public static function deactivate() + { + return _t('插件已禁用'); + } + + // 插件配置面板 + public static function config(Typecho_Widget_Helper_Form $form) + { + // 顶部「备份 / 恢复」卡片:按钮走本页 GET 动作,处理完 302 回本页。 + // 只在设置页渲染,且用 Layout 输出纯 HTML,不嵌第二层 form。 + self::handleSettingsAction(); + $hero = new Typecho_Widget_Helper_Layout(); + $hero->html(self::settingsAssetCss() . self::heroCardHtml()); + $form->addItem($hero); + + // 密钥安全状态提示:已加密 / 仍为明文 / 无法解密,三种情况各给一句 + $keyState = self::secretStateHtml(); + if ('' !== $keyState) { + $keyBox = new Typecho_Widget_Helper_Layout(); + $keyBox->html($keyState); + $form->addItem($keyBox); + } + + $bucket = new Typecho_Widget_Helper_Form_Element_Text('bucket', null, null, _t('空间名称:'), _t('七牛云存储空间名称')); + $bucket->addRule('required', _t('"空间名称"不能为空!')); + $form->addInput($bucket); + + // 密钥两个字段:密码框 + 库内存密文。Typecho 会把库里的值回填到表单, + // 所以框里看到的是 enc:v1: 密文而不是明文;空值的语义是「保持原值」, + // 因此这里不能挂 required —— 空值代表不修改,不是错误。 + $accesskey = new Typecho_Widget_Helper_Form_Element_Password( + 'accesskey', + null, + null, + _t('AccessKey:'), + _t('已加密存储,此处不再回显;框内是密文占位,直接保存不会改动,更换密钥时清空后填新值') + ); + $accesskey->input->setAttribute('autocomplete', 'new-password'); + $accesskey->input->setAttribute('spellcheck', 'false'); + $form->addInput($accesskey); + + $secretkey = new Typecho_Widget_Helper_Form_Element_Password( + 'secretkey', + null, + null, + _t('SecretKey:'), + _t('已加密存储,此处不再回显;框内是密文占位,直接保存不会改动,更换密钥时清空后填新值') + ); + $secretkey->input->setAttribute('autocomplete', 'new-password'); + $secretkey->input->setAttribute('spellcheck', 'false'); + $form->addInput($secretkey); + + $domain = new Typecho_Widget_Helper_Form_Element_Text('domain', null, 'https://', _t('绑定域名:'), _t('空间绑定的域名,如:https://cdn.example.com')); + $form->addInput($domain->addRule('required', _t('请填写空间绑定的域名!'))); + + $savepath = new Typecho_Widget_Helper_Form_Element_Text('savepath', null, 'typecho/{year}/{month}/', _t('保存路径前缀'), _t('可使用变量:{year}, {month}, {day}, {random}')); + $form->addInput($savepath); + + // 文件名前缀:最终对象键为「路径前缀/文件名前缀_原文件名.扩展名」。 + // 不加 required —— 留空表示不启用,是最常见的默认状态。 + // maxLength 走闭包:Typecho 的 maxLength 用 strlen 计字节,中文会被判成 3 倍长度。 + $prefix = new Typecho_Widget_Helper_Form_Element_Text( + 'prefix', + null, + '', + _t('文件名前缀:'), + _t('上传时给文件名加前缀,最终存为「前缀_原文件名」。可使用变量:{year}, {month}, {day};' + . '留空则不添加前缀;最多 ' . self::PREFIX_MAX_LEN . ' 个字符。' + . '仅对之后的新上传生效,已上传的文件和「替换附件」不会改名') + ); + $prefix->addRule( + static function ($value) { + return self::strLen((string) $value) <= self::PREFIX_MAX_LEN; + }, + _t('文件名前缀最多 ' . self::PREFIX_MAX_LEN . ' 个字符!') + ); + $form->addInput($prefix); + + // WebP转换开关 + $webp = new Typecho_Widget_Helper_Form_Element_Radio( + 'webp', + array('0' => _t('关闭'), '1' => _t('开启')), + '0', + _t('WebP自动转换:'), + _t('开启后上传的JPEG/PNG图片将自动转换为WebP格式') + ); + $form->addInput($webp); + + // 图片质量设置 + $quality = new Typecho_Widget_Helper_Form_Element_Text( + 'quality', + null, + '85', + _t('图片质量:'), + _t('设置图片压缩质量(1-100),仅对JPEG/PNG/WEBP格式有效。85为推荐值') + ); + // 注意:Typecho 的 Typecho\Validate 没有 regexp 规则(内置仅 required / confirm / + // isInteger / isFloat / email / url / alpha / alphaNumeric / alphaDash / + // xssCheck / enum / minLength / maxLength),传入未定义的规则名会在 + // Validate::run() 的 call_user_func_array() 处抛 TypeError。 + // addRule() 的规则位支持 string|callable,这里用闭包做 1-100 范围校验。 + $quality->addRule('required', _t('图片质量不能为空!')) + ->addRule('isInteger', _t('必须输入数字!')) + ->addRule( + static function ($value) { + return (bool) preg_match('/^(100|[1-9]\d?)$/', (string) $value); + }, + _t('请输入1-100之间的数字!') + ); + $form->addInput($quality); + + // EXIF信息开关 + $exif = new Typecho_Widget_Helper_Form_Element_Radio( + 'exif', + array('0' => _t('关闭'), '1' => _t('开启')), + '0', + _t('EXIF信息显示:'), + _t('开启后文章图片悬停时会显示拍摄信息(相机型号、光圈、快门等)') + ); + $form->addInput($exif); + } + + /* ------------------------------------------------------------------ + * 密钥保护:加密存储 + 后台不回显 + * + * 七牛 AK/SK 是账号级凭证,泄漏等于对象存储被接管。这里做三件事: + * 1. 落库前用 AES-256-GCM 加密,密钥由站点 secret 派生,不额外落盘; + * 2. 设置页改用密码框:Typecho 回填的是密文,页面里不再有明文可读; + * 3. 历史明文在打开设置页时自动转成密文,读取侧继续兼容明文。 + * + * 强度边界(不夸大):派生密钥与密文同在 options 表,能挡住「后台被登录」 + * 「配置截图或导出泄漏」「只读到 plugin:Qiniu 这一行」;挡不住整库泄露。 + * 要防整库,得把密钥放到库外(环境变量 / 独立密钥文件),不在本版范围。 + * ---------------------------------------------------------------- */ + + /** 密文前缀,用于区分历史明文 */ + const CRYPT_PREFIX = 'enc:v1:'; + + /** + * 接管设置保存 + * + * 两个原因必须自己处理落库: + * 1. 密钥框里回填的是密文,用户清空后提交的就是空字符串;而内核的 + * configPlugin() 是 array_merge(旧值, 新值),空字符串会把密钥清掉, + * 所以这里要把「空」解释成「保持原值」; + * 2. 新值要先加密再写,不能交给内核。 + * + * 参数由 Widget\Plugins\Edit::configHandle() 传入; + * 启用插件时也会调一次($isInit = true),那次传的是表单默认值, + * 一旦写库就会把已存配置覆盖成空,所以直接跳过。 + * + * @param array $settings + * @param bool $isInit + */ + public static function configHandle($settings, $isInit = false) + { + if (!is_array($settings) || $isInit) { + return; + } + + $stored = self::storedConfig(); + $values = array_merge($stored, $settings); + $values += array('accesskey' => '', 'secretkey' => ''); + + foreach (array('accesskey', 'secretkey') as $key) { + $incoming = isset($settings[$key]) ? trim((string) $settings[$key]) : ''; + $old = isset($stored[$key]) ? (string) $stored[$key] : ''; + + // 留空 = 不修改:沿用旧值(旧值可能是密文,也可能是历史明文,统一加密) + $values[$key] = self::encryptSecret('' === $incoming ? $old : $incoming); + } + + self::writeConfig($values); + self::$_config = null; + + if ('' === $values['accesskey'] || '' === $values['secretkey']) { + self::setNotice('没有填写 AccessKey / SecretKey,插件暂不会接管上传(附件仍走本地)。'); + } + } + + /** + * 写回整份配置 + * + * @param array $values + */ + private static function writeConfig(array $values) + { + try { + $db = Typecho_Db::get(); + $row = $db->fetchRow($db->select('user')->from('table.options') + ->where('name = ?', 'plugin:Qiniu')); + + if (empty($row)) { + $db->query($db->insert('table.options')->rows(array( + 'name' => 'plugin:Qiniu', + 'user' => 0, + 'value' => json_encode($values), + ))); + } else { + $db->query($db->update('table.options') + ->rows(array('value' => json_encode($values))) + ->where('name = ?', 'plugin:Qiniu') + ->where('user = ?', $row['user'])); + } + } catch (\Throwable $e) { + // 主路径失败就退回内核/Helper 的写法,别让用户以为存上了却没落库 + try { + if (class_exists('\Helper')) { + \Helper::setOption('plugin:Qiniu', $values); + } else { + Helper::setOption('plugin:Qiniu', $values); + } + } catch (\Throwable $inner) { + self::setNotice('设置写入失败,请检查数据库权限:' . $inner->getMessage()); + } + } + } + + /** + * 后台提示(不在设置页也能安全调用) + * + * @param string $message + */ + private static function setNotice($message) + { + try { + if (class_exists('\Widget\Notice')) { + \Widget\Notice::alloc()->set($message); + } else { + Typecho_Widget::widget('Widget_Notice')->set($message); + } + } catch (\Throwable $e) { + // 拿不到 Notice 就放弃提示,不影响保存流程 + } + } + + /** + * 是否已是密文 + * + * @param string $value + * @return bool + */ + private static function isEncrypted($value) + { + return 0 === strpos((string) $value, self::CRYPT_PREFIX); + } + + /** + * 加密一个密钥字段 + * + * 服务器缺少 openssl 时退化为明文(宁可功能正常,也不能把密钥写坏), + * 此时设置页会继续提示「仍为明文」。 + * + * @param string $plain + * @return string + */ + private static function encryptSecret($plain) + { + $plain = (string) $plain; + + if ('' === $plain || self::isEncrypted($plain)) { + return $plain; + } + + if (!function_exists('openssl_encrypt')) { + return $plain; + } + + $iv = random_bytes(12); + $tag = ''; + $cipher = openssl_encrypt($plain, 'aes-256-gcm', self::cryptoKey(), OPENSSL_RAW_DATA, $iv, $tag); + + if (false === $cipher || '' === $tag) { + return $plain; + } + + return self::CRYPT_PREFIX . base64_encode($iv . $tag . $cipher); + } + + /** + * 解密一个密钥字段;历史明文原样返回 + * + * @param string $stored + * @return string + */ + private static function decryptSecret($stored) + { + $stored = (string) $stored; + + if (!self::isEncrypted($stored)) { + return $stored; + } + + $raw = base64_decode(substr($stored, strlen(self::CRYPT_PREFIX)), true); + + // iv(12) + tag(16) + ciphertext(>=1) + if (false === $raw || strlen($raw) < 29 || !function_exists('openssl_decrypt')) { + return ''; + } + + $plain = openssl_decrypt( + substr($raw, 28), + 'aes-256-gcm', + self::cryptoKey(), + OPENSSL_RAW_DATA, + substr($raw, 0, 12), + substr($raw, 12, 16) + ); + + return false === $plain ? '' : $plain; + } + + /** + * 加密密钥:由站点 secret 派生,换站点/换 secret 后旧密文失效(会提示重填) + * + * @return string + */ + private static function cryptoKey() + { + $seed = ''; + + try { + $options = self::options(); + $seed = (string) $options->secret; + + if ('' === $seed) { + $seed = (string) $options->siteUrl; + } + } catch (\Throwable $e) { + $seed = ''; + } + + if ('' === $seed) { + $seed = 'typecho-qiniu-fallback-seed'; + } + + return hash('sha256', $seed . '|Qiniu-Secret-V1', true); + } + + /** + * 设置页顶部的密钥状态提示 + * + * @return string + */ + private static function secretStateHtml() + { + $stored = self::storedConfig(); + $access = isset($stored['accesskey']) ? (string) $stored['accesskey'] : ''; + $secret = isset($stored['secretkey']) ? (string) $stored['secretkey'] : ''; + + if ('' === $access && '' === $secret) { + return ''; + } + + if (self::isEncrypted($access) && self::isEncrypted($secret)) { + if ('' !== self::decryptSecret($access) && '' !== self::decryptSecret($secret)) { + return '
密钥已加密存储:表单里显示的是密文占位,' + . '直接保存不会改动,后台页面与页面源码里都没有明文。
'; + } + + return '
密钥无法解密(站点的 secret 或域名变更过)。' + . '请在下方重新填写 AccessKey / SecretKey 后保存。
'; + } + + return '
密钥目前仍以明文存储。' + . '点一次页面底部的「保存设置」即会自动加密,两个密钥框留空也不会丢值。
'; + } + + /* ------------------------------------------------------------------ + * 设置页顶部:备份 / 恢复 + * + * 照搬 ExtMenu(源自 MailNotifier)的实现,按本插件的中文名、配置键适配。 + * 不新增路由、不新增钩子:按钮带参数访问本页,config() 里处理完 302 回本页, + * 结果用 _em 参数交给提示条显示。这样升级覆盖文件即可,不用停用再启用。 + * ---------------------------------------------------------------- */ + + /** + * 处理备份 / 恢复点击 + */ + 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=Qiniu'; + + 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', 'Qiniu|' . $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) . '

' + . '
' + . '

空间名称、密钥、域名、路径、文件名前缀、WebP、图片质量、EXIF 等设置都可以存成一份文件,改乱了点「恢复」就能退回上一次。

' + . '
' + . '备份' + . $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('~QINIU-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' => 'Qiniu', + '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']) && 'Qiniu' !== $payload['plugin']) { + $fail['message'] = '这份备份不属于七牛云存储插件'; + return $fail; + } + + $restored = $payload['settings']; + + // 旧备份里的密钥可能是明文,恢复时顺手加密,避免明文又被写回库里 + foreach (array('accesskey', 'secretkey') as $key) { + if (isset($restored[$key]) && '' !== (string) $restored[$key]) { + $restored[$key] = self::encryptSecret($restored[$key]); + } + } + + try { + if (class_exists('\Helper')) { + \Helper::setOption('plugin:Qiniu', $restored); + } else { + Helper::setOption('plugin:Qiniu', $restored); + } + } catch (\Throwable $e) { + $fail['message'] = '写回设置失败,请检查数据库权限'; + return $fail; + } + + self::$_config = null; + + return array( + 'ok' => true, + 'message' => '设置已恢复', + 'count' => count($payload['settings']), + 'created' => !empty($payload['created']) ? (int) $payload['created'] : $list[0]['created'], + ); + } + + /** + * 当前已保存的整份设置(plugin:Qiniu) + */ + private static function storedConfig() + { + try { + $db = Typecho_Db::get(); + $row = $db->fetchRow($db->select('value')->from('table.options') + ->where('name = ?', 'plugin:Qiniu')); + } 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; + } + + // 个人用户配置面板 + public static function personalConfig(Typecho_Widget_Helper_Form $form) + { + } + + /** + * 获得插件配置信息 + * + * Typecho 1.3 的 Options::plugin() 在配置不存在时会抛 PluginException, + * 这里统一兜底成一份带默认值的 Config,保证任何钩子都不会因为「没配置」而炸掉整页。 + * + * @return Typecho_Config + */ + public static function getConfig() + { + if (null !== self::$_config) { + return self::$_config; + } + + $values = self::defaultConfig(); + + try { + if (class_exists('\Widget\Options')) { + $config = \Widget\Options::alloc()->plugin('Qiniu'); + } else { + $config = Typecho_Widget::widget('Widget_Options')->plugin('Qiniu'); + } + + if (is_object($config)) { + foreach ($values as $key => $default) { + $value = $config->{$key}; + if (null !== $value && '' !== $value) { + $values[$key] = $value; + } + } + } + } catch (Throwable $e) { + // 未配置(PluginException)或读取失败,一律退回默认值,绝不让页面挂掉 + } + + // 密钥在库里是密文,这里解密后交给上层,调用处(Auth、isReady)无需感知; + // 历史明文不做转换,原样返回,保证老配置升级后立即可用。 + $values['accesskey'] = self::decryptSecret($values['accesskey']); + $values['secretkey'] = self::decryptSecret($values['secretkey']); + + self::$_config = class_exists('\Typecho\Config') + ? new \Typecho\Config($values) + : new Typecho_Config($values); + + return self::$_config; + } + + /** + * 默认配置 + * + * @return array + */ + private static function defaultConfig() + { + return array( + 'bucket' => '', + 'accesskey' => '', + 'secretkey' => '', + 'domain' => '', + 'savepath' => 'typecho/{year}/{month}/', + 'prefix' => '', + 'webp' => '0', + 'quality' => '85', + 'exif' => '0', + ); + } + + /** + * 配置是否完整 + * + * @param Typecho_Config $option + * @return bool + */ + private static function isReady($option) + { + return !empty($option->bucket) + && !empty($option->accesskey) + && !empty($option->secretkey) + && !empty($option->domain); + } + + /** + * 懒加载七牛 SDK + * + * composer 的 autoloader 会 prepend 到 spl_autoload 队列最前面, + * 放在文件顶部 require 会抢在 Typecho 自己的加载器之前处理所有类名, + * 其它插件/主题一旦有同名类就容易互相干扰。 + * 这里改成真正要调 SDK 时才加载。 + * + * @return bool + */ + private static function sdk() + { + if (self::$_sdkLoaded) { + return class_exists('\Qiniu\Auth'); + } + + $autoload = __DIR__ . '/vendor/autoload.php'; + if (!file_exists($autoload)) { + return false; + } + + require_once $autoload; + self::$_sdkLoaded = true; + + return class_exists('\Qiniu\Auth'); + } + + /** + * 从各种形态的参数里取出附件存储路径 + * + * 1.3 的 attachmentHandle(Config $attachment) 直接给附件对象; + * 1.2 和 deleteHandle() 给的是 array('attachment' => 附件对象)。 + * + * @param mixed $content + * @return string + */ + private static function extractAttachmentPath($content) + { + $path = self::readPath($content); + if ('' !== $path) { + return $path; + } + + if (is_array($content) && isset($content['attachment'])) { + return self::readPath($content['attachment']); + } + + if ($content instanceof ArrayAccess && isset($content['attachment'])) { + return self::readPath($content['attachment']); + } + + return ''; + } + + /** + * 从附件节点读取 path 字段 + * + * @param mixed $node + * @return string + */ + private static function readPath($node) + { + if (is_array($node)) { + return isset($node['path']) ? trim((string) $node['path']) : ''; + } + + if ($node instanceof ArrayAccess) { + return isset($node['path']) ? trim((string) $node['path']) : ''; + } + + if (is_object($node) && isset($node->path)) { + return trim((string) $node->path); + } + + return ''; + } + + /** + * 当前是否为文章/独立页面详情页 + * + * 只有 Widget\Archive 有 is(),后台的内容组件没有, + * 直接调用会走 Widget::__call() 输出一个不存在的属性,进而抛异常。 + * + * @param mixed $widget + * @return bool + */ + private static function isSingle($widget) + { + if (is_object($widget) && method_exists($widget, 'is')) { + return (bool) $widget->is('single'); + } + + return false; + } + + /** + * 安全的CSS加载方式 + * + * @param mixed $archive Widget\Archive 实例(1.3 会传进来,1.2 不传) + */ + public static function footer($archive = null) + { + if (self::$_cssLoaded) { + return; + } + + $option = self::getConfig(); + if (empty($option->exif)) { + return; + } + + // 1.3 会把 Widget\Archive 实例传进来,可以精确判断页面类型; + // 1.2 调用时没有参数,此时无法判断,直接输出 —— 样式只作用于 .qiniu-exif-*,不含该结构时不会生效。 + if (null !== $archive && !self::isSingle($archive)) { + return; + } + + echo ''; + self::$_cssLoaded = true; + } + + /** + * EXIF 展示样式 + * + * @return string + */ + private static function css() + { + return '.qiniu-exif-container{display:inline-block;position:relative;max-width:100%;}' + . '.qiniu-exif-info{position:absolute;top:0;left:0;right:0;background:rgba(0,0,0,0.85);color:#fff;' + . 'padding:8px 10px;font-size:12px;line-height:1.4;opacity:0;visibility:hidden;' + . 'transition:opacity .3s ease,visibility .3s ease;z-index:9999;border-radius:4px;' + . 'box-shadow:0 2px 8px rgba(0,0,0,.2);pointer-events:none;}' + . '.qiniu-exif-container:hover .qiniu-exif-info{opacity:1;visibility:visible;}' + . '.qiniu-exif-info div{margin:3px 0;}' + . '.qiniu-exif-info strong{font-weight:600;color:#fff;}'; + } + + /** + * 解析文章内容,为图片添加EXIF容器 + * + * @param string $content + * @param mixed $widget + * @param string $lastResult + * @return string + */ + public static function parseContent($content, $widget = null, $lastResult = null) + { + $content = $lastResult ? $lastResult : $content; + + $option = self::getConfig(); + if (empty($option->exif) || !self::isReady($option) || !self::isSingle($widget)) { + return $content; + } + + if (false === strpos($content, 'domain, '/'); + if ('' === $domain) { + return $content; + } + + $pattern = '/]*src=["\']([^"\']+)["\'][^>]*>/i'; + + return preg_replace_callback($pattern, function ($matches) use ($domain) { + $imgTag = $matches[0]; + $src = $matches[1]; + + // 检查是否是七牛云的图片 + if (false === strpos($src, $domain)) { + return $imgTag; + } + + // 从URL中提取文件路径 + $path = str_replace($domain, '', $src); + $path = ltrim((string) parse_url($path, PHP_URL_PATH), '/'); + + if ('' === $path) { + return $imgTag; + } + + $exifData = self::findExif($path); + + if (empty($exifData)) { + return $imgTag; + } + + $exifHtml = '
'; + + if (!empty($exifData['camera'])) { + $exifHtml .= '
' . htmlspecialchars($exifData['camera']) . '
'; + } + + $details = array(); + if (!empty($exifData['exposure'])) { + $details[] = '快门:' . htmlspecialchars($exifData['exposure']); + } + if (!empty($exifData['aperture'])) { + $details[] = '光圈:f/' . htmlspecialchars($exifData['aperture']); + } + if (!empty($exifData['iso'])) { + $details[] = 'ISO:' . htmlspecialchars($exifData['iso']); + } + if (!empty($exifData['focal_length'])) { + $details[] = '焦距:' . htmlspecialchars($exifData['focal_length']) . 'mm'; + } + + if (!empty($details)) { + $exifHtml .= '
' . implode(' ', $details) . '
'; + } + + $exifHtml .= '
'; + + return '
' . $imgTag . $exifHtml . '
'; + }, $content); + } + + /** + * 从附件记录里读 EXIF + * + * @param string $path + * @return array + */ + private static function findExif($path) + { + try { + $db = Typecho_Db::get(); + $row = $db->fetchRow($db->select()->from('table.contents') + ->where('type = ?', 'attachment') + ->where('text LIKE ?', '%' . $path . '%') + ->limit(1)); + + if (!$row || empty($row['text'])) { + return array(); + } + + $attachment = json_decode($row['text'], true); + if (!is_array($attachment)) { + // 1.2 及更早版本的可能序列化存储 + $attachment = @unserialize($row['text']); + } + + if (is_array($attachment) && isset($attachment['path']) && $attachment['path'] !== $path) { + return array(); + } + + if (is_array($attachment) && !empty($attachment['exif']) && is_array($attachment['exif'])) { + return $attachment['exif']; + } + } catch (Exception $e) { + // 查询失败不影响正文 + } + + return array(); + } + + /** + * 提取EXIF信息 + * + * @param string $filePath + * @return array + */ + private static function extractExif($filePath) + { + if (!function_exists('exif_read_data')) { + return array(); + } + + $exif = @exif_read_data($filePath); + if (!$exif) { + return array(); + } + + $result = array(); + + // 相机型号 + if (!empty($exif['Make']) || !empty($exif['Model'])) { + $make = !empty($exif['Make']) ? trim($exif['Make']) : ''; + $model = !empty($exif['Model']) ? trim($exif['Model']) : ''; + $result['camera'] = trim($make . ' ' . $model); + } + + // 曝光时间 + if (!empty($exif['ExposureTime'])) { + $result['exposure'] = $exif['ExposureTime']; + } + + // 光圈值 + if (!empty($exif['FNumber'])) { + $fnumber = is_array($exif['FNumber']) ? $exif['FNumber'][0] / $exif['FNumber'][1] : $exif['FNumber']; + $result['aperture'] = number_format($fnumber, 1); + } + + // ISO + if (!empty($exif['ISOSpeedRatings'])) { + $result['iso'] = is_array($exif['ISOSpeedRatings']) ? reset($exif['ISOSpeedRatings']) : $exif['ISOSpeedRatings']; + } + + // 焦距 + if (!empty($exif['FocalLength'])) { + if (is_array($exif['FocalLength'])) { + $focal = $exif['FocalLength'][0] / $exif['FocalLength'][1]; + } else { + $focal = $exif['FocalLength']; + } + $result['focal_length'] = number_format($focal, 1); + } + + // 拍摄时间 + if (!empty($exif['DateTimeOriginal'])) { + $result['date'] = date('Y-m-d H:i', strtotime($exif['DateTimeOriginal'])); + } + + return $result; + } + + /** + * 检测是否支持WebP转换 + * + * @return bool + */ + private static function canConvertWebp() + { + if (!extension_loaded('gd')) { + return false; + } + + $gdInfo = gd_info(); + return isset($gdInfo['WebP Support']) && $gdInfo['WebP Support']; + } + + /** + * 压缩图片并转换格式 + * + * @param string $sourcePath + * @param string $targetExt + * @param int $quality + * @return string 处理后的文件路径(失败时返回原路径) + */ + private static function compressAndConvert($sourcePath, $targetExt, $quality) + { + $imageInfo = @getimagesize($sourcePath); + if (!$imageInfo) { + return $sourcePath; + } + + $mime = $imageInfo['mime']; + + // 创建图像资源 + switch ($mime) { + case 'image/jpeg': + $image = @imagecreatefromjpeg($sourcePath); + break; + case 'image/png': + $image = @imagecreatefrompng($sourcePath); + if ($image) { + imagepalettetotruecolor($image); + imagealphablending($image, false); + imagesavealpha($image, true); + } + break; + case 'image/gif': + $image = @imagecreatefromgif($sourcePath); + break; + default: + return $sourcePath; + } + + if (!$image) { + return $sourcePath; + } + + $extension = 'jpeg' === $targetExt ? 'jpg' : $targetExt; + $tempFile = tempnam(sys_get_temp_dir(), 'img_') . '.' . $extension; + + $success = false; + switch ($targetExt) { + case 'jpg': + case 'jpeg': + $success = imagejpeg($image, $tempFile, $quality); + break; + case 'png': + $pngQuality = 9 - (int) round(($quality / 100) * 9); + $success = imagepng($image, $tempFile, $pngQuality); + break; + case 'webp': + if (self::canConvertWebp()) { + $success = imagewebp($image, $tempFile, $quality); + } + break; + } + + // imagedestroy() 自 PHP 8.0 起为空操作,8.5 起标记废弃;仅为 PHP 7.x 保留真实释放 + if (PHP_VERSION_ID < 80000) { + imagedestroy($image); + } + + if ($success && file_exists($tempFile)) { + return $tempFile; + } + + if (file_exists($tempFile)) { + @unlink($tempFile); + } + + return $sourcePath; + } + + /** + * 使用七牛基本图片处理 + * + * @param string $url + * @param Typecho_Config $option + * @return string + */ + private static function applyQiniuStyle($url, $option) + { + $quality = intval($option->quality); + if ($quality < 1 || $quality > 100) { + $quality = 85; + } + + $needQuality = $quality !== 85; + $needWebP = !empty($option->webp); + + if (!$needQuality && !$needWebP) { + return $url; + } + + $path = (string) parse_url($url, PHP_URL_PATH); + $currentExt = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + + if ($needWebP && 'webp' === $currentExt) { + $needWebP = false; + } + + $params = array(); + + if ($needQuality) { + $params[] = 'q/' . $quality; + } + + if ($needWebP) { + $params[] = 'format/webp'; + } + + if (empty($params)) { + return $url; + } + + $separator = (strpos($url, '?') === false) ? '?' : '&'; + + return $url . $separator . 'imageView2/2/' . implode('/', $params); + } + + /** + * 删除文件 + * + * @param string $filepath + * @return bool + */ + public static function deleteFile($filepath) + { + $option = self::getConfig(); + if (!self::isReady($option) || empty($filepath)) { + return false; + } + + if (!self::sdk()) { + return false; + } + + try { + $auth = new \Qiniu\Auth($option->accesskey, $option->secretkey); + $bucketMgr = new \Qiniu\Storage\BucketManager($auth); + + $err = $bucketMgr->delete($option->bucket, $filepath); + + return $err === null; + } catch (Exception $e) { + return false; + } + } + + /** + * 字符串长度(按字符计,缺 mbstring 时退化为字节) + * + * @param string $value + * @return int + */ + private static function strLen($value) + { + $value = (string) $value; + + return function_exists('mb_strlen') ? mb_strlen($value, 'UTF-8') : strlen($value); + } + + /** + * 渲染文件名前缀 + * + * 处理顺序:变量替换 → 非法字符抹平 → 收尾归一 → 超长截断。 + * 任一环节出错都退回空串,保证「前缀配错」不会连带上传失败。 + * + * @param string $prefix 设置里填的原始前缀 + * @param Typecho_Date $date 已构造的日期对象(与保存路径共用同一时间点) + * @return string 可直接拼进对象键的前缀;不需要加前缀时返回空串 + */ + private static function renderPrefix($prefix, $date) + { + $prefix = trim((string) $prefix); + + if ('' === $prefix) { + return ''; + } + + $prefix = (string) preg_replace( + array('/\{year\}/', '/\{month\}/', '/\{day\}/'), + array($date->year, $date->month, $date->day), + $prefix + ); + + // 先把空白(含换行/制表)整体去掉:它们常见于从别处复制粘贴, + // 留在键名里会变成 %20 或直接被截断,比去掉更难排查。 + $prefix = str_replace(array("\r", "\n", "\t", ' '), '', $prefix); + + // 斜杠会把「前缀」变成新的目录层级,冒号会破坏 URL 语义,其余是文件系统/URL 保留字符, + // 统一抹成下划线,与 safeName 的处理口径保持一致。 + $prefix = (string) preg_replace('/[<>:"\/\\\\|?*\x00-\x1F\x7F]/', '_', $prefix); + $prefix = (string) preg_replace('/_{2,}/', '_', $prefix); + $prefix = rtrim($prefix, '_'); + + if ('' === $prefix) { + return ''; + } + + if (self::strLen($prefix) > self::PREFIX_MAX_LEN) { + $prefix = function_exists('mb_substr') + ? mb_substr($prefix, 0, self::PREFIX_MAX_LEN, 'UTF-8') + : substr($prefix, 0, self::PREFIX_MAX_LEN); + $prefix = rtrim($prefix, '_'); + } + + return $prefix; + } + + /** + * 上传文件到七牛云 - 修复中文文件名问题 + * + * @param array $file + * @param array|null $content 修改附件时传入旧附件信息 + * @return array|bool 成功返回附件信息数组,失败返回 false + */ + public static function uploadFile($file, $content = null) + { + if (empty($file['name']) || !isset($file['tmp_name'])) { + return false; + } + + $option = self::getConfig(); + if (!self::isReady($option)) { + return false; + } + + if (!self::sdk()) { + return false; + } + + // 获取原始文件名 + $originalName = basename($file['name']); + + // 使用pathinfo正确处理中文字符 + $pathInfo = pathinfo($originalName); + $originalExt = isset($pathInfo['extension']) ? strtolower($pathInfo['extension']) : ''; + $baseName = isset($pathInfo['filename']) ? $pathInfo['filename'] : ''; + + // 校验扩展名 + if ('' === $originalExt || !Widget_Upload::checkFileType($originalExt)) { + return false; + } + + if (!file_exists($file['tmp_name'])) { + return false; + } + + $date = new Typecho_Date(); + + // 提取EXIF信息(必须在压缩转换之前,否则 EXIF 会丢) + $exifData = array(); + if (!empty($option->exif) && in_array($originalExt, array('jpg', 'jpeg'))) { + $exifData = self::extractExif($file['tmp_name']); + } + + // 处理图片压缩和转换 + $tempFile = null; + $uploadPath = $file['tmp_name']; + $finalExt = $originalExt; + + $supportedImages = array('jpg', 'jpeg', 'png', 'gif'); + if (in_array($originalExt, $supportedImages)) { + $quality = intval($option->quality); + $quality = max(1, min(100, $quality)); + + $targetExt = $originalExt; + if (!empty($option->webp) && 'gif' !== $originalExt && self::canConvertWebp()) { + $targetExt = 'webp'; + } + + if ($targetExt !== $originalExt || 85 !== $quality) { + $processedPath = self::compressAndConvert($file['tmp_name'], $targetExt, $quality); + + if ($processedPath !== $file['tmp_name']) { + $uploadPath = $processedPath; + $finalExt = $targetExt; + $tempFile = $processedPath; + } + } + } + + // 生成存储路径 - 保持原始文件名,只替换文件系统不允许的字符 + $safeName = preg_replace('/[<>:"\/\\\\|?*]/', '_', $baseName); + $safeName = trim($safeName); + if ('' === $safeName) { + $safeName = 'image_' . time(); + } + + if (null !== $content) { + // 修改附件:沿用旧路径 + $filePath = self::extractAttachmentPath($content); + if ('' === $filePath) { + if ($tempFile) { + @unlink($tempFile); + } + return false; + } + } else { + $savepath = (string) $option->savepath; + if ('' === $savepath) { + $savepath = 'typecho/{year}/{month}/'; + } + $savepath = preg_replace( + array('/\{year\}/', '/\{month\}/', '/\{day\}/', '/\{random\}/'), + array($date->year, $date->month, $date->day, uniqid()), + $savepath + ); + + // 文件名前缀:最终对象键 = 路径前缀 + 「前缀_原文件名.扩展名」 + $prefix = self::renderPrefix(isset($option->prefix) ? $option->prefix : '', $date); + if ('' !== $prefix) { + $safeName = $prefix . '_' . $safeName; + } + + $filePath = rtrim($savepath, '/') . '/' . $safeName . '.' . $finalExt; + } + + try { + $upManager = new \Qiniu\Storage\UploadManager(); + $auth = new \Qiniu\Auth($option->accesskey, $option->secretkey); + $token = $auth->uploadToken($option->bucket); + + // 七牛云SDK会自动处理文件名编码 + list($ret, $error) = $upManager->putFile($token, $filePath, $uploadPath); + + if ($tempFile && file_exists($tempFile) && $tempFile !== $file['tmp_name']) { + @unlink($tempFile); + } + + if (null !== $error) { + return false; + } + + $rawUrl = Typecho_Common::url($filePath, $option->domain); + $processedUrl = self::applyQiniuStyle($rawUrl, $option); + + $fileSize = @filesize($uploadPath); + + $result = array( + 'name' => $originalName, + 'path' => $filePath, + 'size' => $fileSize ? (int) $fileSize : 0, + 'type' => $finalExt, + 'mime' => 'webp' === $finalExt + ? 'image/webp' + : Typecho_Common::mimeContentType($uploadPath), + 'url' => $processedUrl, + ); + + if (!empty($exifData)) { + $result['exif'] = $exifData; + } + + return $result; + } catch (Exception $e) { + if ($tempFile && file_exists($tempFile) && $tempFile !== $file['tmp_name']) { + @unlink($tempFile); + } + return false; + } + } + + // 上传文件处理函数 + public static function uploadHandle($file) + { + return self::uploadFile($file); + } + + // 修改文件处理函数 + public static function modifyHandle($content, $file) + { + return self::uploadFile($file, $content); + } + + // 删除文件处理函数 + public static function deleteHandle($content) + { + $path = self::extractAttachmentPath($content); + if ('' === $path) { + return false; + } + + if (!self::isReady(self::getConfig())) { + // 未配置七牛:文件只在本地。这里必须自己 unlink —— + // 内核判断的是「有没有插件注册 deleteHandle」,注册了就跳过它自己的删除逻辑, + // 插件再返回 false,本地文件就没人删了,变成孤儿文件。 + $root = defined('__TYPECHO_UPLOAD_ROOT_DIR__') + ? __TYPECHO_UPLOAD_ROOT_DIR__ + : __TYPECHO_ROOT_DIR__; + + return (bool) @unlink($root . '/' . $path); + } + + return self::deleteFile($path); + } + + // 获取实际文件绝对访问路径 + public static function attachmentHandle($content) + { + $option = self::getConfig(); + $path = self::extractAttachmentPath($content); + + if (!self::isReady($option)) { + // 未配置七牛:回退成内核默认的本地地址。 + // 1.3 只要注册了这个钩子就直接采用返回值,返回空串会让附件列表 data-url 全空, + // 「插入所有图片」「单张插入」跟着一起失效。 + return self::localUrl($path); + } + + if ('' === $path) { + return ''; + } + + $rawUrl = Typecho_Common::url($path, $option->domain); + + return self::applyQiniuStyle($rawUrl, $option); + } + + /** + * 生成内核默认的本地访问地址(未配置七牛时使用) + * + * 等价于 Widget\Upload::attachmentHandle 在无插件接管时的返回值。 + * + * @param string $path + * @return string + */ + private static function localUrl($path) + { + if ('' === $path) { + return ''; + } + + if (defined('__TYPECHO_UPLOAD_URL__')) { + $base = __TYPECHO_UPLOAD_URL__; + } else { + try { + if (class_exists('\Widget\Options')) { + $base = \Widget\Options::alloc()->siteUrl; + } else { + $base = Typecho_Widget::widget('Widget_Options')->siteUrl; + } + } catch (Throwable $e) { + return ''; + } + } + + return Typecho_Common::url($path, $base); + } +} diff --git a/README.md b/README.md index e0bd77d..fbfa9e4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,55 @@ -# typecho-qiniu +# Qiniu(七牛云存储) +> 仓库:`typecho-qiniu` · 类型:Typecho 插件 · 版本:`2.9.0` · 作者:石头厝 + +把附件上传到七牛云对象存储,并用绑定域名走 CDN 输出;支持 WebP 自动转换、图片质量压缩、EXIF 拍摄信息展示,以及可配置的文件名前缀。本仓库仅包含插件实现代码与必要文档,不包含备份目录、运行时数据与 `vendor/` 依赖。 + +> 命名说明:`XIGE/Qiniu` 已被 Obsidian 版同名插件占用,Typecho 版单独建仓为 `typecho-qiniu`,避免两个项目的源码互相覆盖。 + +## 功能 + +- **上传接管**:接管 Typecho 的 `Widget_Upload` 四个钩子(上传、修改、删除、地址),附件存到七牛,正文与后台列表统一输出 CDN 地址。 +- **路径与前缀**:`保存路径前缀` 决定目录层级(支持 `{year}` `{month}` `{day}` `{random}`);`文件名前缀` 决定文件名前缀(支持 `{year}` `{month}` `{day}`),最终对象键为 `路径前缀/文件名前缀_原文件名.扩展名`。 +- **WebP 与压缩**:开启后 JPEG/PNG 上传即转 WebP(GIF 保持原格式),并可按 1-100 的质量值压缩;非 85 的取值或 WebP 输出会通过七牛图片处理参数在访问时生效。 +- **EXIF 展示**:开启后文章详情页图片悬停显示相机型号、快门、光圈、ISO、焦距。 +- **密钥加密**:AccessKey / SecretKey 以 AES-256-GCM 密文存库,后台表单只回填密文占位,页面与源码中不出现明文。 +- **设置备份 / 恢复**:设置页顶部可一键备份当前配置,保留最近 5 份,可从历史备份任选恢复;备份文件位于插件内 `data/backup/`,带 `.htaccess` 与空 `index.html` 禁止公网读取。 +- **未配置降级**:已启用但未填写配置时,附件回退本地地址与本地删除,不会出现「地址空、文件孤儿」。 + +## 环境要求 + +- Typecho 1.3.0 及以上(1.2.x 需要类名兼容层,本版本以 1.3 为基线)。 +- PHP 7.1 及以上,推荐 8.x;WebP 转换需要 GD 且开启 WebP 支持。 +- 七牛 PHP SDK(`qiniu/php-sdk`)通过 Composer 安装,`vendor/` 不入库。 + +## 安装与升级 + +1. 首次安装:把本仓库放到 `usr/plugins/Qiniu/`,在插件目录执行 `composer install` 安装 SDK,然后在后台启用。 +2. 升级:直接覆盖 `Plugin.php` 即可,无需停用再启用。 +3. 从 2.8.x 升级到 2.9.0:默认前缀为空,行为不变;填好「文件名前缀」并保存后才对新上传生效。 + +## 配置项说明 + +- **空间名称 / 绑定域名**:必填;域名需带协议,例如 `https://cdn.example.com`。 +- **AccessKey / SecretKey**:留空表示保持原值;框内若显示 `enc:v1:` 开头的密文,直接保存不会改动。 +- **保存路径前缀**:目录层级,默认 `typecho/{year}/{month}/`。 +- **文件名前缀**:只加在文件名上,不作为目录;斜杠与非法字符会被抹成下划线,空白字符直接删除,连续下划线归一,最长 40 个字符;留空不启用。 +- **WebP / 图片质量 / EXIF**:见上文功能说明。 + +## 行为边界 + +- 文件名前缀只作用于**新上传**。「替换附件」沿用原对象键,因为改名等于换地址,正文中已引用的图片会立即失效。 +- 修改前缀不会重命名历史文件;需要存量对象也带前缀时,应在七牛侧 `copy` + `delete` 迁移并同步更新 `contents` 表的 `path`。 +- 密钥由站点 `options.secret` 派生加密,换域名或换 secret 后旧密文失效,此时插件回退本地存储并在设置页提示重填。 + +## 开发与贡献 + +详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +## 授权 + +授权条款见 [LICENSE](LICENSE)(MIT License)。七牛 PHP SDK 版权归其作者所有。 + +## 变更记录 + +详见 [CHANGELOG.md](CHANGELOG.md)。 diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..97d16ff --- /dev/null +++ b/composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "qiniu/php-sdk": "^7.14" + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..e20d4a2 --- /dev/null +++ b/composer.lock @@ -0,0 +1,142 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "e53b7aa650906cf4c75020ac18b97155", + "packages": [ + { + "name": "myclabs/php-enum", + "version": "1.8.5", + "source": { + "type": "git", + "url": "https://github.com/myclabs/php-enum.git", + "reference": "e7be26966b7398204a234f8673fdad5ac6277802" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/php-enum/zipball/e7be26966b7398204a234f8673fdad5ac6277802", + "reference": "e7be26966b7398204a234f8673fdad5ac6277802", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": "^7.3 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "1.*", + "vimeo/psalm": "^4.6.2 || ^5.2" + }, + "type": "library", + "autoload": { + "psr-4": { + "MyCLabs\\Enum\\": "src/" + }, + "classmap": [ + "stubs/Stringable.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP Enum contributors", + "homepage": "https://github.com/myclabs/php-enum/graphs/contributors" + } + ], + "description": "PHP Enum implementation", + "homepage": "https://github.com/myclabs/php-enum", + "keywords": [ + "enum" + ], + "support": { + "issues": "https://github.com/myclabs/php-enum/issues", + "source": "https://github.com/myclabs/php-enum/tree/1.8.5" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/php-enum", + "type": "tidelift" + } + ], + "time": "2025-01-14T11:49:03+00:00" + }, + { + "name": "qiniu/php-sdk", + "version": "v7.14.0", + "source": { + "type": "git", + "url": "https://github.com/qiniu/php-sdk.git", + "reference": "ee752ffa7263ce99fca0bd7340cf13c486a3516c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/qiniu/php-sdk/zipball/ee752ffa7263ce99fca0bd7340cf13c486a3516c", + "reference": "ee752ffa7263ce99fca0bd7340cf13c486a3516c", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-xml": "*", + "myclabs/php-enum": "~1.5.2 || ~1.6.6 || ~1.7.7 || ~1.8.4", + "php": ">=5.3.3" + }, + "require-dev": { + "paragonie/random_compat": ">=2", + "phpunit/phpunit": "^4.8 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4", + "squizlabs/php_codesniffer": "^2.3 || ~3.6" + }, + "type": "library", + "autoload": { + "files": [ + "src/Qiniu/functions.php", + "src/Qiniu/Http/Middleware/Middleware.php" + ], + "psr-4": { + "Qiniu\\": "src/Qiniu" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Qiniu", + "email": "sdk@qiniu.com", + "homepage": "http://www.qiniu.com" + } + ], + "description": "Qiniu Resource (Cloud) Storage SDK for PHP", + "homepage": "http://developer.qiniu.com/", + "keywords": [ + "cloud", + "qiniu", + "sdk", + "storage" + ], + "support": { + "issues": "https://github.com/qiniu/php-sdk/issues", + "source": "https://github.com/qiniu/php-sdk/tree/v7.14.0" + }, + "time": "2024-10-25T08:39:01+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.0.0" +}