Files
typecho-qiniu/Plugin.php

2661 lines
96 KiB
PHP
Raw Normal View History

<?php
/**
* 七牛云存储+CDN+WebP+图片质量+EXIF信息
*
* @package Qiniu
* @author 石头厝
* @version 2.9.5
* @link https://www.shitoucuo.com/
* @since 1.2.0
*/
/**
* 说明(2.9.5 附件记录查询修复 —— EXIF 一直取不到的真因):
* 1. Typecho 存附件用 `json_encode($result)`(var/Widget/Upload.php),PHP 默认把斜杠
* 转义成 `\/`、非 ASCII 字符转成 `\uXXXX`。库里实际是:
* {"path":"blog\/shitoucuo\/st_IMG_2026.webp"}
* 而 2.9.4 及以前拿完整 path 去 `LIKE '%blog/shitoucuo/...%'` —— 查询串是 `/`、
* 库里是 `\/`,**永远匹配不到**,EXIF 因此一直静默为空(开关开着也不显示)。
* 2. 现在改用 basename 粗筛(文件名不含斜杠,转义影响不到),取回后把 `\/` 还原、
* 按 path 全等比对;中文文件名额外用 `json_encode` 后的 `\uXXXX` 形式再查一次。
* 3. 加单请求内的 `$_exifCache`,同一张图在正文/摘要/相关推荐多处出现时不重复查库。
*
* 说明(2.9.4 EXIF 数值解析):
* 1. 根因:`exif_read_data()` 不按 section 分组调用时,RATIONAL 类型返回的是**未约分的
* 分数字符串**(华为 P30 实测:曝光 `548000/1000000000`、光圈 `180/100`、
* 焦距 `5580/1000`)。老代码只处理了「数组形态」,字符串形态直接进 number_format(),
* 而 PHP 字符串转数字只取前缀 —— 光圈 180.0、焦距 5580.0,快门则原样贴出乱码。
* 现在统一走 `num()` 解析分数,快门再经 `formatShutter()` 写成 `1/2000` 这种写法。
* 2. 快门吸附标准档:厂商给的精确值带浮点误差(0.004228s),硬取整会得到 1/237
* 这种没人这么标的数字,所以吸附到最近标准快门档;偏离超过 1/6 档则按真实值输出。
* 3. ISO 兼容 EXIF 2.3 的 `PhotographicSensitivity` 字段名。
*
* 说明(2.9.3 拍摄时间与设置文案):
* 1. 拍摄时间(`date`)此前只抓不用,现已接到两处显示:正文悬停浮层第三行、
* 灯箱大图信息条第三行。字段同时加进页内数据表,否则大图查不到。
* 2. 设置项文案与真实行为对齐:写明「悬停显示 + 点开大图顶部显示」,并点明
* **只有 JPEG 会被读取**(PHP exif 扩展仅支持 JPEG/TIFF,PNG 即使带 eXIf 块也读不到)。
*
* 说明(2.9.2 画廊大图 EXIF):
* 1. `{flex}` 横排里不注入包裹层(否则破版),但**照样把 EXIF 收进页内数据表**,
* 由页脚一段脚本在灯箱打开大图时把信息贴到图片顶部 —— 缩略图不显示、大图显示。
* 2. 页内数据表(path → exif)只在文章详情页输出一次,键为 URL 解码后的对象键,
* 前端用同样的解码规则比对,避免中文文件名对不上。
* 3. 灯箱适配不绑定具体实现:ViewImage(主题自带)与 Fancybox/PhotoSwipe 的
* 大图容器都认,谁开图都能贴。
*
* 说明(2.9.1 EXIF 与画廊/正文结构兼容):
* 1. 包裹层 div → span。markdown 输出的图片是 `<p><img></p>`,在 `<p>` 里插 `<div>`
* 会被解析器提前闭合,主题 `.markdown-body p` 的 10px 下边距于是变成空行。
* 2. `{flex}` 画廊整块跳过:FlexPhoto 的横排布局按「figure 是 .flexphoto 的直接子项」
* 写死,EXIF 包裹层会把 figure 顶到孙级,多图必破版。宁可在画廊里不显示 EXIF。
* 3. findExif 改为「多取候选 + PHP 精确比对」:LIKE 里 `_`/`%` 是通配符,文件名前缀
* 会带来大量下划线,`limit(1)` 撞到无关行就静默丢 EXIF。
*
* 说明(2.9.0 文件名前缀):
* 新增「文件名前缀」设置,最终对象键为「保存路径前缀/文件名前缀_原文件名.扩展名」。
* 前缀只作用于新上传;修改(替换)附件时沿用原路径,不会改名 —— 改名等于换地址,
* 旧文章中已引用的图片会立刻裂开。
*
* 说明(2.7.1 未配置状态降级):
* 7. 「已启用但没填配置」时,插件注册的钩子仍然会被内核认为是接管的,
* attachmentHandle 返回空串会让附件列表的 data-url 全空(插入类功能全废),
* deleteHandle 返回 false 又让内核跳过自己的 unlink(本地文件变孤儿)。
* 现在两者都回退到内核默认行为:本地地址 / 本地 unlink。
* uploadHandle 与 modifyHandle 刻意不降级 —— 回退本地会让「文件在本地、
* 地址走七牛域名」导致配好配置后图片全裂,保持失败更安全。
*
* 说明(2.7.0 适配 Typecho 1.3):
* 1. 1.3 的 Widget\Upload::attachmentHandle() 传的是 Typecho\Config 对象,不再是数组,
* 且返回值声明为 string(钩子注册后无论插件返回什么都会原样返回),
* 原来 array 形参 + 可能返回 null 会直接 TypeError,后台任何带附件的页面都会 500。
* 2. 1.3 的 deleteHandle() 返回值声明为 bool,插件必须返回 bool,不能隐式返回 null。
* 3. 1.3 的 uploadHandle() 用 `false !== $result` 判定成功,失败必须返回 false,
* 原来返回 array('error'=>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.5';
/** 文件名前缀最大字符数(多字节按 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;
/**
* 本页图片的 EXIF 数据表(对象键 → exif 数组)
*
* 画廊里的图片不注入包裹层,但仍要收进来,供灯箱大图显示。
*
* @var array
*/
private static $_exifMap = array();
/**
* 单次请求内的 EXIF 查询缓存(对象键 → exif 数组)
*
* 同一张图可能在正文、摘要、相关推荐里各出现一次,缓存一下避免重复查库。
*
* @var array
*/
private static $_exifCache = array();
// 激活插件
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('开启后,文章详情页的图片在鼠标悬停时显示拍摄信息(相机型号、快门、光圈、ISO、焦距、拍摄时间);'
. '点开灯箱看大图时,同样的信息贴在图片顶部。'
. '信息在上传时读取,之后不再刷新 —— 因此只对开启开关后新上传的图片生效。'
. '仅支持 JPEG(jpg/jpeg):PHP 的 exif 扩展只读 JPEG/TIFF,PNG 里的参数读不到;'
. '开启 WebP 自动转换不影响,信息取自转换前的原图')
);
$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 '<div class="cnot-note cnot-note-ok">密钥已加密存储:表单里显示的是密文占位,'
. '直接保存不会改动,后台页面与页面源码里都没有明文。</div>';
}
return '<div class="cnot-note cnot-note-fail">密钥无法解密(站点的 secret 或域名变更过)。'
. '请在下方重新填写 AccessKey / SecretKey 后保存。</div>';
}
return '<div class="cnot-note cnot-note-fail">密钥目前仍以明文存储。'
. '点一次页面底部的「保存设置」即会自动加密,两个密钥框留空也不会丢值。</div>';
}
/* ------------------------------------------------------------------
* 设置页顶部:备份 / 恢复
*
* 照搬 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
? '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl) . '"'
. ' onclick="return confirm(\'恢复会用最新一份备份覆盖当前插件设置,确定继续?\');">恢复</a>'
: '<span class="cnot-btn cnot-btn-ghost is-disabled" aria-disabled="true" title="还没有备份">恢复</span>';
$historyBtn = '';
$historyBox = '';
if (count($list) > 1) {
$rows = '';
foreach ($list as $index => $item) {
$rows .= '<div class="cnot-backup-item">'
. '<div class="cnot-backup-main">'
. '<span class="cnot-backup-time">' . self::e(date('Y-m-d H:i:s', $item['created'])) . '</span>'
. ($index === 0 ? '<span class="cnot-backup-tag">最新</span>' : '')
. '<span class="cnot-backup-desc">' . intval($item['count']) . ' 项配置 · '
. self::e(self::formatBytes($item['size']))
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
. '</span>'
. '</div>'
. '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl . '&file=' . rawurlencode($item['file'])) . '"'
. ' onclick="return confirm(\'用 ' . self::e(date('Y-m-d H:i', $item['created'])) . ' 的这份备份覆盖当前插件设置?\');">恢复</a>'
. '</div>';
}
$historyBtn = '<a class="cnot-btn cnot-btn-ghost" id="cnot-backups-btn" href="#cnot-backups"'
. ' aria-expanded="false" aria-controls="cnot-backups">历史备份</a>';
$historyBox = '<div class="cnot-backups" id="cnot-backups" hidden>'
. '<div class="cnot-backups-head"><strong>历史备份</strong><span>从新到旧,点「恢复」就用那一份覆盖当前设置</span></div>'
. $rows
. '</div>'
. '<script>(function(){var box=document.getElementById("cnot-backups");'
. 'var btn=document.getElementById("cnot-backups-btn");'
. 'if(!box||!btn||!btn.addEventListener){return;}'
. 'btn.addEventListener("click",function(e){'
. 'if(e&&e.preventDefault){e.preventDefault();}'
. 'var open=box.hasAttribute("hidden");'
. 'if(open){box.removeAttribute("hidden");}else{box.setAttribute("hidden","hidden");}'
. 'btn.textContent=open?"收起备份":"历史备份";'
. 'btn.setAttribute("aria-expanded",open?"true":"false");'
. 'return false;});'
. '})();</script>';
}
return '<div class="cnot-hero">'
. '<div class="cnot-hero-icon">'
. '<svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="1.8"'
. ' stroke-linecap="round" stroke-linejoin="round">'
. '<path d="M4 7h16M6 7v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7"/>'
. '<path d="M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>'
. '<path d="M10 11h4M10 15h4"/></svg>'
. '</div>'
. '<div class="cnot-hero-text">'
. '<div class="cnot-hero-title">'
. '<h2>' . self::e(self::PLUGIN_TITLE) . '</h2>'
. '</div>'
. '<p>空间名称、密钥、域名、路径、文件名前缀、WebP、图片质量、EXIF 等设置都可以存成一份文件,改乱了点「恢复」就能退回上一次。</p>'
. '<div class="cnot-hero-ops">'
. '<a class="cnot-btn" href="' . self::e($backupUrl) . '">备份</a>'
. $restoreBtn
. $historyBtn
. '<span class="cnot-hero-meta">' . $meta . '</span>'
. '</div>'
. '</div>'
. '</div>'
. $notice
. $historyBox;
}
/**
* 备份结果提示条(读 _em 参数)
*/
private static function noticeHtml()
{
$code = isset($_GET['_em']) && is_scalar($_GET['_em']) ? (string) $_GET['_em'] : '';
if ('' === $code) {
return '';
}
$get = array();
foreach (array('n', 't', 'detail', 'f') as $key) {
$get[$key] = isset($_GET[$key]) && is_scalar($_GET[$key]) ? (string) $_GET[$key] : '';
}
$count = (int) $get['n'];
$time = (int) $get['t'];
$total = (int) $get['f'];
$ok = true;
$text = '';
if ('backup_ok' === $code) {
$text = '设置已备份:' . $count . ' 项配置,' . self::e(date('Y-m-d H:i:s', $time)) . '。'
. ($total > 0 ? '当前共 ' . $total . ' 份(上限 ' . intval(self::BACKUP_KEEP) . ' 份)。' : '');
} elseif ('restore_ok' === $code) {
$text = '已恢复到 ' . self::e(date('Y-m-d H:i:s', $time)) . ' 的备份(' . $count
. ' 项配置)。刷新本页即可看到表单里的值。';
} elseif ('backup_fail' === $code || 'restore_fail' === $code) {
$ok = false;
$text = ('backup_fail' === $code ? '备份失败:' : '恢复失败:')
. ('' !== $get['detail'] ? $get['detail'] : '未知原因');
} elseif ('token' === $code) {
$ok = false;
$text = '安全令牌校验失败,请刷新本页后重试。';
} elseif ('auth' === $code) {
$ok = false;
$text = '只有管理员可以备份或恢复插件设置。';
} elseif ('unknown' === $code) {
$ok = false;
$text = '无法识别的操作。';
}
if ('' === $text) {
return '';
}
return '<div class="cnot-note ' . ($ok ? 'cnot-note-ok' : 'cnot-note-fail') . '">' . self::e($text) . '</div>';
}
/**
* 备份目录
*/
private static function backupDir()
{
return dirname(__FILE__) . '/data/backup';
}
/**
* 目录不存在就建,并禁止公网读取
*/
private static function ensureBackupDir()
{
$dir = self::backupDir();
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
if (!is_dir($dir)) {
return false;
}
if (!is_file($dir . '/.htaccess')) {
@file_put_contents($dir . '/.htaccess', "Require all denied\nDeny from all\n");
}
if (!is_file($dir . '/index.html')) {
@file_put_contents($dir . '/index.html', '');
}
return true;
}
/**
* 备份列表(新 → 旧)
*/
private static function backups()
{
$dir = self::backupDir();
if (!is_dir($dir)) {
return array();
}
$files = (array) glob($dir . '/' . self::BACKUP_PREFIX . '*.php');
$list = array();
foreach ($files as $file) {
$name = basename($file);
if (!self::isBackupName($name)) {
continue;
}
$meta = self::readMeta($file);
$list[] = array(
'file' => $name,
'size' => (int) @filesize($file),
'created' => !empty($meta['created']) ? (int) $meta['created'] : (int) @filemtime($file),
'count' => !empty($meta['count']) ? (int) $meta['count'] : 0,
'version' => isset($meta['version']) ? (string) $meta['version'] : '',
);
}
usort($list, array(__CLASS__, 'compareBackups'));
return $list;
}
/**
* 备份排序:新的在前
*/
public static function compareBackups($a, $b)
{
if ($a['created'] === $b['created']) {
return strcmp($b['file'], $a['file']);
}
return $a['created'] < $b['created'] ? 1 : -1;
}
/**
* 读备份文件头里的 meta
*/
private static function readMeta($file)
{
$head = @file_get_contents($file, false, null, 0, 512);
if (false === $head || '' === $head) {
return array();
}
if (preg_match('~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 = '<?php /* QINIU-SETTINGS-BACKUP '
. json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
. ' */ exit; ?>' . "\n" . $encoded;
$file = self::backupDir() . '/' . self::BACKUP_PREFIX . date('Ymd-His', $created) . '.php';
if (false === @file_put_contents($file, $content, LOCK_EX)) {
$fail['message'] = '写入备份文件失败,请检查 data/backup 目录权限';
return $fail;
}
self::pruneBackups();
return array(
'ok' => true,
'message' => '设置已备份',
'count' => count($settings),
'created' => $created,
'total' => count(self::backups()),
);
}
/**
* 只保留最近 BACKUP_KEEP 份
*/
private static function pruneBackups()
{
$list = self::backups();
if (count($list) <= self::BACKUP_KEEP) {
return;
}
foreach (array_slice($list, self::BACKUP_KEEP) as $item) {
@unlink(self::backupDir() . '/' . $item['file']);
}
}
/**
* 恢复一份备份(不传文件名 = 最新那份)
*/
private static function doRestore($file = '')
{
$fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0);
$list = self::backups();
if (empty($list)) {
$fail['message'] = '还没有备份,先点一次「备份」';
return $fail;
}
$name = '' !== $file ? basename($file) : $list[0]['file'];
if (!self::isBackupName($name)) {
$fail['message'] = '备份文件名不合法';
return $fail;
}
$path = self::backupDir() . '/' . $name;
$content = @file_get_contents($path);
if (false === $content || '' === $content) {
$fail['message'] = '读取备份文件失败:' . $name;
return $fail;
}
$pos = strpos($content, '?>');
if (false === $pos) {
$fail['message'] = '备份文件格式不正确';
return $fail;
}
$encoded = trim(substr($content, $pos + 2));
if (0 === strncmp($encoded, 'gz:', 3)) {
$json = function_exists('gzuncompress')
? @gzuncompress((string) base64_decode(substr($encoded, 3)))
: false;
} else {
$json = base64_decode(substr($encoded, 4));
}
if (false === $json || '' === $json) {
$fail['message'] = '备份内容已损坏,无法解析';
return $fail;
}
$payload = json_decode($json, true);
if (!is_array($payload) || empty($payload['settings']) || !is_array($payload['settings'])) {
$fail['message'] = '备份内容已损坏,没有找到设置';
return $fail;
}
if (isset($payload['plugin']) && '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'
<style>
.cnot-hero,.cnot-note,.cnot-backups{box-sizing:border-box;width:100%;}
.cnot-hero{position:relative;display:flex;align-items:flex-start;gap:18px;flex-wrap:wrap;margin:6px 0 12px;padding:22px 24px;border:1px solid rgba(126,96,60,.15);border-radius:8px;background:linear-gradient(135deg,rgba(255,253,248,.98),rgba(246,236,223,.86));box-shadow:0 14px 34px rgba(75,56,35,.075);overflow:hidden;}
.cnot-hero:after{content:"";position:absolute;right:-44px;top:-50px;width:170px;height:170px;border-radius:50%;background:rgba(126,96,60,.065);}
.cnot-hero-icon{position:relative;z-index:1;width:54px;height:54px;display:grid;place-items:center;flex:0 0 54px;border-radius:8px;color:#7f603d;background:linear-gradient(145deg,rgba(255,253,248,.88),rgba(239,225,207,.72));border:1px solid rgba(126,96,60,.18);font-size:25px;box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 12px 24px rgba(93,68,43,.08);}
.cnot-hero-text{position:relative;z-index:1;min-width:0;flex:1 1 300px;}
.cnot-hero h2{position:relative;z-index:1;margin:0;color:#2d2824;font-size:14px;line-height:1.5;font-weight:600;}
.cnot-hero p{position:relative;z-index:1;margin:6px 0 0;color:#6f6153;font-size:12px;line-height:1.6;}
.cnot-hero-title{position:relative;z-index:1;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
.cnot-hero-ops{position:relative;z-index:1;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:12px;}
.cnot-hero-meta{flex-basis:100%;margin-top:2px;color:#8d7b6a;font-size:12px;line-height:1.5;}
.cnot-btn{height:32px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;border-radius:4px;text-decoration:none!important;color:#fff!important;background:linear-gradient(135deg,#8b633b,#a77b4c);box-shadow:0 4px 12px rgba(125,90,50,.16);font-size:12px;font-weight:600;white-space:nowrap;}
.cnot-btn:hover{transform:translateY(-1px);}
.cnot-hero .cnot-btn{height:30px;padding:0 12px;font-size:12px;}
.cnot-btn-ghost{color:#6d4a2b!important;background:rgba(255,255,255,.92)!important;border:1px solid rgba(126,96,60,.22);box-shadow:none;}
.cnot-btn-ghost.is-disabled{opacity:.42;cursor:not-allowed;box-shadow:none;}
.cnot-btn-ghost.is-disabled:hover{transform:none;}
.cnot-note{margin:-2px 0 16px;padding:9px 14px;border-radius:8px;font-size:12px;line-height:1.6;}
.cnot-note-ok{color:#2f8a57;background:rgba(47,138,87,.10);border:1px solid rgba(47,138,87,.18);}
.cnot-note-fail{color:#b4503f;background:rgba(180,80,63,.10);border:1px solid rgba(180,80,63,.18);}
.cnot-backups{margin:-6px 0 18px;padding:4px 6px 6px;border:1px solid rgba(126,96,60,.14);border-radius:8px;background:rgba(255,255,255,.86);box-shadow:0 4px 16px rgba(75,56,35,.045);}
.cnot-backups[hidden]{display:none;}
.cnot-backups-head{display:flex;align-items:baseline;gap:9px;flex-wrap:wrap;padding:10px 11px 8px;}
.cnot-backups-head strong{color:#342b24;font-size:13px;}
.cnot-backups-head span{color:#8d7b6a;font-size:12px;line-height:1.5;}
.cnot-backup-item{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 11px;border-radius:4px;}
.cnot-backup-item+.cnot-backup-item{border-top:1px solid rgba(126,96,60,.10);}
.cnot-backup-main{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;min-width:0;}
.cnot-backup-time{color:#3f342a;font-size:12.5px;font-weight:600;font-variant-numeric:tabular-nums;}
.cnot-backup-tag{padding:1px 7px;border-radius:4px;background:#8b633b;color:#fff;font-size:11px;font-weight:600;line-height:1.7;}
.cnot-backup-desc{color:#8d7b6a;font-size:12px;}
.cnot-backup-item .cnot-btn{flex:0 0 auto;height:28px;padding:0 12px;font-size:12px;}
@media(max-width:680px){.cnot-hero{padding:16px 14px;align-items:flex-start}.cnot-hero-icon{width:44px;height:44px;flex-basis:44px;border-radius:8px}.cnot-hero h2{font-size:14px}.cnot-hero p{font-size:12px;line-height:1.6}.cnot-hero-title{gap:10px}.cnot-hero-ops{margin-top:10px;gap:8px}.cnot-hero-ops .cnot-btn{box-sizing:border-box;flex:1 1 0;min-width:0;height:32px;padding:0 8px;font-size:12px}.cnot-hero-meta{flex-basis:100%}.cnot-backups{padding:2px 4px 4px}.cnot-backups-head{padding:10px 9px 8px;gap:5px}.cnot-backup-item{padding:9px;gap:9px}.cnot-backup-item .cnot-btn{flex:0 0 auto;height:30px;padding:0 12px;font-size:12px}}
.dark .cnot-hero{background:linear-gradient(135deg,#1b2635,#18212f);border-color:rgba(255,255,255,.10);box-shadow:0 14px 34px rgba(0,0,0,.28);}
.dark .cnot-hero:after{background:rgba(208,168,119,.07);}
.dark .cnot-hero-icon{color:#d0a877;background:linear-gradient(145deg,#202c3d,#1a2434);border-color:rgba(255,255,255,.10);box-shadow:inset 0 1px 0 rgba(255,255,255,.06),0 12px 24px rgba(0,0,0,.30);}
.dark .cnot-hero h2{color:#e8eef7;}
.dark .cnot-hero p{color:#9aa8bb;}
.dark .cnot-btn{background:linear-gradient(135deg,#9d7247,#bb8c57);box-shadow:0 4px 12px rgba(0,0,0,.24);}
.dark .cnot-hero-meta{color:#93a2b8;}
.dark .cnot-btn-ghost{color:#e8d0ad!important;background:rgba(255,255,255,.06)!important;border-color:rgba(255,255,255,.14);box-shadow:none;}
.dark .cnot-note-ok{color:#4ade80;background:rgba(74,222,128,.10);border-color:rgba(74,222,128,.20);}
.dark .cnot-note-fail{color:#f87171;background:rgba(248,113,113,.10);border-color:rgba(248,113,113,.20);}
.dark .cnot-backups{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 30px rgba(0,0,0,.22);}
.dark .cnot-backups-head strong{color:#e8eef7;}
.dark .cnot-backups-head span{color:#93a2b8;}
.dark .cnot-backup-item+.cnot-backup-item{border-top-color:rgba(255,255,255,.08);}
.dark .cnot-backup-time{color:#e8eef7;}
.dark .cnot-backup-tag{background:#d0a877;color:#18212f;}
.dark .cnot-backup-desc{color:#93a2b8;}
/* 密钥类输入框:强制等宽字体 + 明确高对比文字色,避免下划线 _ 被第三方字体子集渲染成空格而误删。
用 !important 覆盖 FontLibs 的全局 * {font-family:...!important};-webkit-text-fill-color 防止被浏览器/自动填充改写。 */
input[name*="secretkey"],input[name*="accesskey"],input[name*="savepath"],input[name="prefix"]{font-family:"SFMono-Regular",Consolas,"Liberation Mono",Menlo,"Courier New",monospace!important;font-size:13px!important;font-weight:400!important;letter-spacing:.3px;color:#2d2824!important;-webkit-text-fill-color:#2d2824!important;opacity:1!important;}
.dark input[name*="secretkey"],.dark input[name*="accesskey"],.dark input[name*="savepath"],.dark input[name="prefix"]{color:#e8eef7!important;-webkit-text-fill-color:#e8eef7!important;}
</style>
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 '<style type="text/css">' . self::css() . '</style>';
// 数据表 + 灯箱补丁:正文渲染时收集到的 EXIF 在这时候已经齐了
if (!empty(self::$_exifMap)) {
echo self::exifMapScript();
echo self::lightboxScript();
}
self::$_cssLoaded = true;
}
/**
* 页内 EXIF 数据表
*
* 用 script[type=application/json] 而不是 JS 字面量:不参与脚本执行,
* 中文与引号只需 JSON 转义一次;JSON_HEX_TAG 顺手把 `<` 转成 \u003C,避免提前闭合标签。
*
* @return string
*/
private static function exifMapScript()
{
$map = array();
foreach (self::$_exifMap as $path => $exif) {
$item = array();
foreach (array('camera', 'exposure', 'aperture', 'iso', 'focal_length', 'date') as $key) {
if (!empty($exif[$key])) {
$item[$key] = (string) $exif[$key];
}
}
if (!empty($item)) {
$map[$path] = $item;
}
}
if (empty($map)) {
return '';
}
$json = json_encode($map, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG);
if (false === $json) {
return '';
}
return '<script type="application/json" id="qiniu-exif-map">' . $json . '</script>';
}
/**
* 灯箱大图 EXIF 补丁
*
* 缩略图上的浮层靠 hover,大图上是整屏没有 hover 可言,所以改成跟灯箱走:
* 监听 DOM 变化,找到「正在显示的大图」,按 src 反查数据表,把一条信息条
* 贴到图片顶边。条子 pointer-events:none,不挡上一张/下一张与关闭。
*
* @return string
*/
private static function lightboxScript()
{
$script = <<<'JS'
(function () {
var node = document.getElementById('qiniu-exif-map');
if (!node) { return; }
var MAP = {};
try { MAP = JSON.parse(node.textContent || '{}') || {}; } catch (e) { return; }
if (!MAP || typeof MAP !== 'object') { return; }
/* 各灯箱的「大图」容器;主题用的是 ViewImage,另两种是常见备选 */
var BIG = '.view-image-lead img, .fancybox-slide--image img, .pswp__img';
var bar = null;
var shown = '';
function esc(text) {
var d = document.createElement('div');
d.appendChild(document.createTextNode(String(text)));
return d.innerHTML;
}
function keyOf(src) {
if (!src) { return ''; }
var path = String(src);
var proto = path.indexOf('//');
if (proto > -1) {
path = path.slice(proto + 2);
var slash = path.indexOf('/');
path = slash > -1 ? path.slice(slash) : '';
}
path = path.split('?')[0].split('#')[0];
try { path = decodeURIComponent(path); } catch (e) {}
return path.replace(/^\/+/, '');
}
function lookup(src) {
var path = keyOf(src);
if (!path) { return null; }
if (MAP[path]) { return MAP[path]; }
/* CDN 前缀 / 代理路径可能让整串对不上,退化为尾部比对 */
for (var key in MAP) {
if (!Object.prototype.hasOwnProperty.call(MAP, key)) { continue; }
if (key.length <= path.length ? path.slice(-key.length) === key : key.slice(-path.length) === path) {
return MAP[key];
}
}
return null;
}
function html(data) {
var out = '';
if (data.camera) { out += '<strong>' + esc(data.camera) + '</strong>'; }
var parts = [];
if (data.exposure) { parts.push('快门 ' + esc(data.exposure)); }
if (data.aperture) { parts.push('光圈 f/' + esc(data.aperture)); }
if (data.iso) { parts.push('ISO ' + esc(data.iso)); }
if (data.focal_length) { parts.push('焦距 ' + esc(data.focal_length) + 'mm'); }
if (parts.length) { out += '<span>' + parts.join(' · ') + '</span>'; }
if (data.date) { out += '<span>拍摄 ' + esc(data.date) + '</span>'; }
return out;
}
function place(img) {
if (!bar) { return; }
var rect = img.getBoundingClientRect();
var vw = window.innerWidth || document.documentElement.clientWidth || 0;
var width = Math.min(rect.width, vw - 16);
var left = rect.left + (rect.width - width) / 2;
if (left < 8) { left = Math.min(8, vw - width); }
bar.style.width = Math.max(width, 0) + 'px';
bar.style.left = Math.max(left, 0) + 'px';
bar.style.top = Math.max(rect.top, 0) + 'px';
}
function hide() {
shown = '';
if (bar) {
bar.className = 'qiniu-exif-lightbox';
bar.innerHTML = '';
}
}
function update() {
var img = document.querySelector(BIG);
if (!img) { hide(); return; }
var data = lookup(img.currentSrc || img.src);
if (!data) { hide(); return; }
var body = html(data);
if (!body) { hide(); return; }
if (!bar) {
bar = document.createElement('div');
bar.className = 'qiniu-exif-lightbox';
document.body.appendChild(bar);
}
if (shown !== (img.currentSrc || img.src)) {
shown = img.currentSrc || img.src;
bar.innerHTML = body;
}
if (bar.className.indexOf('is-on') === -1) {
bar.className = 'qiniu-exif-lightbox is-on';
}
place(img);
}
var pending = false;
function schedule() {
if (pending) { return; }
pending = true;
var run = function () { pending = false; update(); };
if (window.requestAnimationFrame) { window.requestAnimationFrame(run); } else { setTimeout(run, 16); }
}
if (window.MutationObserver) {
new MutationObserver(schedule).observe(document.body, {childList: true, subtree: true});
}
/* 大图是异步插入的(ViewImage 先占位再换 innerHTML),点多几次兜底 */
document.addEventListener('click', function () {
setTimeout(schedule, 60);
setTimeout(schedule, 320);
setTimeout(schedule, 640);
}, true);
document.addEventListener('load', function (e) {
if (e.target && e.target.tagName === 'IMG') { schedule(); }
}, true);
window.addEventListener('resize', schedule);
window.addEventListener('orientationchange', schedule);
schedule();
})();
JS;
return '<script>' . $script . '</script>';
}
/**
* EXIF 展示样式
*
* @return string
*/
private static function css()
{
// 包裹层用 span + line-height:0:图片在 <p> 里是行内元素,行高会在下方留出
// 几个像素的空隙;换成 span 后必须靠 vertical-align/line-height 收掉。
return '.qiniu-exif-container{display:inline-block;position:relative;max-width:100%;line-height:0;vertical-align:top;}'
. '.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;text-align:left;'
. '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 span{display:block;margin:3px 0;}'
. '.qiniu-exif-info strong{font-weight:600;color:#fff;}'
// 兜底:万一包裹层仍落进了 FlexPhoto 的画廊(例如主题/插件改过标记写法),
// 缩略图已被 4:3 裁切,浮层意义不大,直接不显示,避免盖住画面。
. '.flexphoto .qiniu-exif-info{display:none!important;}'
// 灯箱大图顶部的信息条:贴在大图顶边,跟随图片尺寸,不挡任何操作
. '.qiniu-exif-lightbox{position:fixed;top:0;left:0;display:block;z-index:2147483000;'
. 'pointer-events:none;background:rgba(0,0,0,0.78);color:#fff;text-align:left;'
. 'padding:10px 14px;border-radius:0 0 8px 8px;font-size:13px;line-height:1.5;'
. '-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);'
. 'box-shadow:0 4px 16px rgba(0,0,0,.28);opacity:0;visibility:hidden;'
. 'transition:opacity .2s ease,visibility .2s ease;}'
. '.qiniu-exif-lightbox.is-on{opacity:1;visibility:visible;}'
. '.qiniu-exif-lightbox strong{display:block;font-weight:600;color:#fff;}'
. '.qiniu-exif-lightbox span{display:block;margin-top:2px;color:rgba(255,255,255,.86);}';
}
/**
* 解析文章内容,为图片添加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, '<img')) {
return $content;
}
$domain = rtrim($option->domain, '/');
if ('' === $domain) {
return $content;
}
// 画廊区块整块跳过。两种形态都要认:
// - `{flex ...}...{/flex}`:本插件先执行,FlexPhoto 还没渲染
// - `<div class="flexphoto ...">`:FlexPhoto 先执行,标记已被替换
// FlexPhoto 的横排样式按「figure 是 .flexphoto 的直接子项」写死,
// 中间插一层包裹元素会把 figure 顶到孙级,多图横排必坏,宁可不显示 EXIF。
$parts = preg_split(
'/(\{flex[^}]*\}.*?\{\/flex\}|<div\b(?=[^>]*\bclass="[^"]*flexphoto)[^>]*>.*?<\/div>)/is',
$content,
-1,
PREG_SPLIT_DELIM_CAPTURE
);
if (!is_array($parts)) {
return self::wrapImages($content, $domain);
}
foreach ($parts as $index => $part) {
if ('' === $part) {
continue;
}
if (preg_match('/^(?:\{flex[^}]*\}|<div\b(?=[^>]*\bclass="[^"]*flexphoto))/i', $part)) {
// 画廊块不注入包裹层,但 EXIF 仍要收进本页数据表:
// 缩略图不显示,点开大图时由页脚脚本贴到图片顶部。
self::collectExif($part, $domain);
continue;
}
$parts[$index] = self::wrapImages($part, $domain);
}
return implode('', $parts);
}
/**
* 给一段 HTML 里的七牛图片套上 EXIF 浮层
*
* 包裹层用 span 而不是 div:markdown 的图片在 `<p>` 里,
* `<p>` 一旦遇到 `<div>` 会被解析器提前闭合,留下一段空段落。
*
* @param string $content
* @param string $domain
* @return string
*/
private static function wrapImages($content, $domain)
{
$pattern = '/<img\s+[^>]*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 = self::pathFromSrc($src, $domain);
if ('' === $path) {
return $imgTag;
}
$exifData = self::findExif($path);
if (empty($exifData)) {
return $imgTag;
}
// 灯箱大图共用同一份数据,顺手记进本页数据表
self::$_exifMap[$path] = $exifData;
$exifHtml = '<span class="qiniu-exif-info">';
if (!empty($exifData['camera'])) {
$exifHtml .= '<span><strong>' . htmlspecialchars($exifData['camera']) . '</strong></span>';
}
$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 .= '<span>' . implode(' ', $details) . '</span>';
}
if (!empty($exifData['date'])) {
$exifHtml .= '<span>拍摄:' . htmlspecialchars($exifData['date']) . '</span>';
}
$exifHtml .= '</span>';
return '<span class="qiniu-exif-container">' . $imgTag . $exifHtml . '</span>';
}, $content);
}
/**
* 从图片地址反推对象键
*
* HTML 里的地址可能是百分号编码(中文文件名尤甚),而附件表里存的是原始文件名,
* 所以统一解码后再比对;只剥 path 部分,域名可能带协议差异。
*
* @param string $src
* @param string $domain
* @return string
*/
private static function pathFromSrc($src, $domain)
{
$path = (string) parse_url(str_replace($domain, '', $src), PHP_URL_PATH);
$path = ltrim($path, '/');
if ('' === $path) {
return '';
}
return rawurldecode($path);
}
/**
* 收集一段 HTML 里七牛图片的 EXIF(不改写 HTML)
*
* 用于 `{flex}` 画廊:包裹层会破版,所以只取数据,不插节点。
*
* @param string $html
* @param string $domain
* @return void
*/
private static function collectExif($html, $domain)
{
if (false === strpos($html, '<img')) {
return;
}
// FlexPhoto 优先读 data-src(懒加载),两种都认
if (!preg_match_all('/<img\b[^>]*>/i', $html, $tags)) {
return;
}
foreach ($tags[0] as $tag) {
// FlexPhoto 优先读 data-src(懒加载时 src 常是占位图),两个都收,
// 免得灯箱拿到哪个地址都能对上号。
$candidates = array();
if (preg_match('/\bdata-src=["\']([^"\']+)["\']/i', $tag, $m)) {
$candidates[] = $m[1];
}
if (preg_match('/\bsrc=["\']([^"\']+)["\']/i', $tag, $m)) {
$candidates[] = $m[1];
}
foreach (array_unique($candidates) as $src) {
if ('' === $src || false === strpos($src, $domain)) {
continue;
}
$path = self::pathFromSrc($src, $domain);
if ('' === $path || isset(self::$_exifMap[$path])) {
continue;
}
$exif = self::findExif($path);
if (!empty($exif)) {
self::$_exifMap[$path] = $exif;
}
}
}
}
/**
* 从附件记录里读 EXIF
*
* 关键点:Typecho 存附件用的是 `json_encode($result)`(见 var/Widget/Upload.php),
* PHP 默认把斜杠转义成 `\/`,库里实际长这样:
*
* {"path":"blog\/shitoucuo\/st_IMG_2026.webp","type":"webp",...}
*
* 所以直接拿 `path` 去 LIKE 永远查不到 —— 查询串里是 `/`,库里是 `\/`。
* 2.9.4 及以前正是这么写的,EXIF 在这类环境下一直静默取不到。
*
* 现在改成用 basename(文件名不含斜杠,JSON 转义影响不到)做粗筛,
* 取回后再把 `\/` 还原成 `/` 解码,按 path 全等比对。
*
* @param string $path
* @return array
*/
private static function findExif($path)
{
if (isset(self::$_exifCache[$path])) {
return self::$_exifCache[$path];
}
$needle = basename($path);
if ('' === $needle) {
return array();
}
/*
* json_encode 除了转义斜杠,还会把非 ASCII 字符转成 \uXXXX:
* 封面.jpg → \u5c01\u9762.jpg
* 所以中文文件名得按「转义后的形式」去 LIKE,否则同样查不到。
* 两种写法都试:JSON 存储命中转义形式,serialize 存储命中原文。
*/
$needles = array($needle);
$escaped = (string) json_encode($needle);
if ('' !== $escaped) {
$escaped = trim($escaped, '"');
if ('' !== $escaped && $escaped !== $needle) {
$needles[] = $escaped;
}
}
try {
$db = Typecho_Db::get();
// LIKE 的 `_` / `%` 是通配符,文件名前缀又会带来大量下划线,
// 只取一条容易先撞到无关附件(随后 path 比对不过就静默丢 EXIF)。
// 这里多取几条候选,再在 PHP 里按 path 精确比对。
$rows = array();
foreach ($needles as $item) {
$part = $db->fetchAll($db->select()->from('table.contents')
->where('type = ?', 'attachment')
->where('text LIKE ?', '%' . $item . '%')
->limit(50));
$rows = array_merge($rows, (array) $part);
}
foreach ($rows as $row) {
if (empty($row['text'])) {
continue;
}
$raw = (string) $row['text'];
// JSON 存储:库里的 `\/` 先还原成 `/`、`\uXXXX` 还原成原字,
// 否则 path 比对永远不等。只对 JSON 做替换 —— serialize 串不转义斜杠,
// 替换也无副作用。
$decoded = str_replace('\\/', '/', $raw);
$attachment = json_decode($decoded, true);
if (!is_array($attachment)) {
// 1.2 及更早版本的可能序列化存储
$attachment = @unserialize($raw);
}
if (!is_array($attachment) || !isset($attachment['path']) || $attachment['path'] !== $path) {
continue;
}
if (!empty($attachment['exif']) && is_array($attachment['exif'])) {
self::$_exifCache[$path] = $attachment['exif'];
return $attachment['exif'];
}
}
} catch (Exception $e) {
// 查询失败不影响正文
} catch (Throwable $e) {
// PHP 7+ 的 Error 同样不能让正文崩掉
}
self::$_exifCache[$path] = array();
return array();
}
/**
* 把 EXIF 的数值统一转成 float
*
* PHP 的 exif_read_data() 在「不按 section 分组」的调用方式下,RATIONAL 类型会原样
* 返回**未约分的分数字符串**,而不是数组:
* 华为 P30(ELE-AL00)曝光 548000/1000000000、光圈 180/100、焦距 5580/1000。
* 老代码 `is_array($v) ? $v[0]/$v[1] : $v` 只处理了数组形态,字符串形态直接进入
* number_format(),而 PHP 转数字只取前缀 —— "180/100" 变成 180.0,输出「光圈 f/180.0」;
* 快门更是把 "548000/1000000000" 原样贴出去。所以这里统一按字符串解析。
*
* @param mixed $value 形如 "180/100"、"1/250"、[180, 100] 或纯数字
* @return float|null 无法解析或分母为 0 时返回 null
*/
private static function num($value)
{
if (is_array($value)) {
$num = isset($value[0]) ? (float) $value[0] : 0.0;
$den = isset($value[1]) ? (float) $value[1] : 1.0;
return (0.0 == $den) ? null : $num / $den;
}
$value = trim((string) $value);
if ('' === $value) {
return null;
}
if (false !== strpos($value, '/')) {
$parts = explode('/', $value, 2);
$den = (float) trim($parts[1]);
if (0.0 == $den) {
return null;
}
return (float) trim($parts[0]) / $den;
}
return is_numeric($value) ? (float) $value : null;
}
/**
* 快门速度格式化
*
* 分数 → 摄影习惯写法:0.000548s 显示为 `1/2000`,0.5s 显示为 `0.5s`。
* 倒数会吸附到标准快门档(1/250、1/2000 这种),因为厂商给的精确值往往是
* 0.004228s 这类浮点误差,直接取整会得到 1/237 这种没人这么标的数字。
* 偏离最近标准档超过 1/6 档(约 12%)时按真实值输出,不做硬套。
*
* @param float|null $seconds
* @return string
*/
private static function formatShutter($seconds)
{
if (null === $seconds || $seconds <= 0) {
return '';
}
if ($seconds >= 1) {
$text = number_format($seconds, 1, '.', '');
return rtrim(rtrim($text, '0'), '.') . 's';
}
$inverse = 1 / $seconds;
$standard = array(
2, 3, 4, 5, 6, 8, 10, 13, 15, 20, 25, 30, 40, 50, 60, 80,
100, 125, 160, 200, 250, 320, 400, 500, 640, 800,
1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000,
10000, 12800, 16000, 20000, 25600, 32000,
);
$best = 0;
$bestDistance = null;
foreach ($standard as $candidate) {
$distance = abs(log($inverse / $candidate));
if (null === $bestDistance || $distance < $bestDistance) {
$bestDistance = $distance;
$best = $candidate;
}
}
if ($best < 2 || null === $bestDistance || $bestDistance > 0.12) {
return '1/' . (int) round($inverse);
}
return '1/' . $best;
}
/**
* 提取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'])) {
$shutter = self::formatShutter(self::num($exif['ExposureTime']));
if ('' !== $shutter) {
$result['exposure'] = $shutter;
}
}
// 光圈值
if (!empty($exif['FNumber'])) {
$fnumber = self::num($exif['FNumber']);
if (null !== $fnumber && $fnumber > 0) {
$result['aperture'] = number_format($fnumber, 1);
}
}
// ISO:EXIF 2.3 改名为 PhotographicSensitivity,两种都认
$iso = null;
if (!empty($exif['ISOSpeedRatings'])) {
$iso = $exif['ISOSpeedRatings'];
} elseif (!empty($exif['PhotographicSensitivity'])) {
$iso = $exif['PhotographicSensitivity'];
}
if (is_array($iso)) {
$iso = reset($iso);
}
if (!empty($iso)) {
$result['iso'] = $iso;
}
// 焦距
if (!empty($exif['FocalLength'])) {
$focal = self::num($exif['FocalLength']);
if (null !== $focal && $focal > 0) {
$result['focal_length'] = number_format($focal, 1);
}
}
// 拍摄时间
// EXIF 的格式是 "2026:11:28 14:35:20"(年月日用冒号)。PHP 8 的 strtotime 认这种
// 写法,但相机没设时间时会给出 "0000:00:00 00:00:00",直接被解析成 1970 年,
// 所以先挡掉年份为 0 的情况,再校验解析结果。
if (!empty($exif['DateTimeOriginal'])) {
$raw = trim((string) $exif['DateTimeOriginal']);
if (0 !== strpos($raw, '0000')) {
$timestamp = strtotime($raw);
if (false !== $timestamp && (int) date('Y', $timestamp) > 1970) {
$result['date'] = date('Y-m-d H:i', $timestamp);
}
}
}
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);
}
}