TinyImgUploader 2.0.0:Typecho 1.3 图片上传插件(对接 TinyImg 图床)

在撰写文章 / 页面的右侧栏增加图片上传窗口,选图后上传到自建 TinyImg
图床,并把 Markdown 链接插入编辑器光标处。

主要功能
1. 侧栏卡片 + 弹窗上传
   - 挂在 admin/write-post.php 与 write-page.php 的 option 钩子
   - 支持点选、拖入、Ctrl+V 粘贴,上传前可预览
   - 用 getSelection / replaceSelection 插入光标处并触发 input 事件,
     草稿自动保存与实时预览都能同步

2. 三种图床鉴权方式
   - token(默认):X-TinyImg-Token 请求头,未配置则明确拒绝
   - admin:模拟图床后台登录 Cookie(无需改图床,但凭证等价于后台密码)
   - guest:游客上传,图片进 temp/ 并受每日配额限制
   - token / admin 两种模式强制服务端代理,凭证绝不下发浏览器

3. 「测试连接」按钮
   - 读取输入框当前值,无需先保存
   - 经博客同源 Action(带 CSRF)调用图床 functions/upload.php?ping=1
   - 返回图床版本、鉴权方式与管理员目录,并比对是否落在 upload/

4. 为什么必须走服务端代理
   - 实测图床 upload.php 不返回 Access-Control-Allow-Origin,
     浏览器从博客后台直接 POST 会被同源策略拦截

5. 服务端校验
   - 登录态 + 用户组(可选「仅管理员」) + CSRF 令牌
   - 上传大小上限、getimagesize 真实图片头校验(拦 SVG / 伪装脚本)
   - 未认出管理员身份时返回 warn,前端不自动关闭弹窗

6. 附带工具与测试
   - tools/probe.php:命令行连通性自检(只读探测 / 真实上传 / 目录判定)
   - tools/cookie.php:本地计算图床管理员 Cookie 值,不联网
   - tests/:六组共 207 项,含故意错误实现的反证

版本:2.0.0
This commit is contained in:
terry
2026-11-05 17:33:44 +08:00
parent 33e9371f00
commit 8ac51d3160
14 changed files with 3398 additions and 2 deletions
+73
View File
@@ -0,0 +1,73 @@
<?php
use TypechoPlugin\TinyImgUploader\Util;
require_once __DIR__ . '/../Util.php';
/**
* 生成管理员登录 Cookie(回退方案;纯本地计算,不联网、不上传任何东西)。
*
* php tools/cookie.php 管理员账号 '明文密码'
* php tools/cookie.php 管理员账号 --md5=32位十六进制值
*
* 依据 TinyImg/functions/class/class.user.php:
* login(): $password = md5("tinyimg" . $admin['password']); setcookie("password", $password, ...);
* check(): $config['user'] . md5("tinyimg" . $config['password']) === $_COOKIE['user'] . $_COOKIE['password']
*
* 推荐把输出的 32 位值填进插件设置,而不是明文密码:这样数据库里不存密码明文。
*/
if (PHP_SAPI !== 'cli') {
exit('仅允许在命令行运行' . PHP_EOL);
}
$args = array_slice($argv, 1);
$user = '';
$secret = '';
foreach ($args as $arg) {
if (strpos($arg, '--md5=') === 0) {
$secret = substr($arg, 6);
} elseif ($arg === '--help' || $arg === '-h') {
echo "用法:php tools/cookie.php 管理员账号 '明文密码'\n"
. " php tools/cookie.php 管理员账号 --md5=32位值\n\n"
. "只做本地 md5 计算,不会访问图床、不会上传图片。\n"
. "注意:明文密码写在命令行会留在 shell 历史里,用完后建议清理历史。\n";
exit(0);
} elseif ($user === '') {
$user = $arg;
} elseif ($secret === '') {
$secret = $arg;
}
}
if ($user === '' || $secret === '') {
exit("缺少参数。用法:php tools/cookie.php 管理员账号 '明文密码'(或 --help)\n");
}
if (!preg_match('/^[a-f0-9]{32}$/i', $secret)) {
echo "提示:检测到明文密码,将按 md5(\"tinyimg\" . 密码) 计算 Cookie 值。\n\n";
}
$cookie = Util::adminCookie($user, $secret);
if ($cookie === null) {
exit("账号或密码为空,无法生成 Cookie\n");
}
echo "=== TinyImg 2.0 管理员登录 Cookie(回退方案) ===" . PHP_EOL . PHP_EOL;
echo '图床管理员账号 : ' . $user . PHP_EOL;
echo 'password Cookie 值 : ' . $cookie['password'] . PHP_EOL;
echo '完整 Cookie 头 : ' . Util::mergeCookie('', $cookie) . PHP_EOL;
echo PHP_EOL;
echo "填到插件设置:" . PHP_EOL;
echo ' 图床管理员账号 = ' . $user . PHP_EOL;
echo ' 图床管理员密码 / 登录 Cookie 值 = ' . $cookie['password'] . PHP_EOL;
echo PHP_EOL;
echo "验证(会真实上传 1 张图片,请在博客服务器或本机有 curl 扩展时执行):" . PHP_EOL;
echo ' php tools/probe.php --url=https://你的图床/functions/upload.php --file=./test.png'
. ' --admin-user=' . $user . ' --admin-secret=' . $cookie['password'] . PHP_EOL;
echo PHP_EOL;
echo "本工具不联网;Cookie 值等同于图床登录凭证,请勿提交到公开仓库。\n";
echo "注意:TinyImg 2.0 已把 Cookie 盐改为 tinyimg,升级后旧 Cookie 会失效,需重新登录。\n";
echo "推荐用默认的 API Token 模式:到图床后台「Token 设置」生成,填进插件设置并点「测试连接」。\n";
+424
View File
@@ -0,0 +1,424 @@
<?php
use TypechoPlugin\TinyImgUploader\Util;
require_once __DIR__ . '/../Util.php';
/**
* 图床上传接口自检工具(命令行,仅用于排错,插件运行不依赖它)
*
* php tools/probe.php
* 只读探测:发一个 GET,检查接口是否可达、CORS 头、返回格式。不会上传任何图片。
*
* php tools/probe.php --url=https://你的图床/functions/upload.php
* 指定接口地址(默认是占位地址,实战请务必传 --url)。
*
* php tools/probe.php --url=... --token=你的Token --ping
* 只做连接自检:POST ?ping=1,不上传任何文件,打印图床版本与管理员目录。
*
* php tools/probe.php --url=... --file=./test.png --token=你的Token
* 用 API Token(X-TinyImg-Token 请求头,与插件一致)真实上传一张图片并判定目录。
*
* php tools/probe.php --url=... --file=./test.png --admin-user=账号 --admin-secret=密码
* 用管理员 Cookie 上传(回退方案)。--admin-secret 可填明文密码或 32 位 Cookie 值。
*/
if (PHP_SAPI !== 'cli') {
exit('仅允许在命令行运行' . PHP_EOL);
}
$opt = getopt('', [
'url::', 'file::', 'field::', 'token::', 'header::',
'admin-user::', 'admin-secret::', 'admin-dir::', 'ping', 'help',
]);
if (isset($opt['help'])) {
echo <<<'HELP'
用法:
php tools/probe.php
只读探测(GET,不上传图片)
php tools/probe.php --url=接口地址
指定上传接口(默认是占位地址,实战必须传 --url)
php tools/probe.php --url=... --token=你的Token --ping
连接自检:POST ?ping=1,不上传文件,输出图床版本与管理员目录(等价于插件「测试连接」)
php tools/probe.php --url=... --file=./test.png
真实上传一张图片
API Token 上传(推荐,TinyImg 2.0 原生支持):
php tools/probe.php --url=... --file=./test.png --token=你的Token
Token 通过 X-TinyImg-Token 请求头发送,与插件行为一致
管理员 Cookie 上传(回退方案):
php tools/probe.php --url=... --file=./test.png --admin-user=账号 --admin-secret=密码
--admin-secret 可填明文密码,也可填 32 位 md5 值(用 tools/cookie.php 生成)
上传模式会检查图片地址是否落在 upload 目录,没落进去则以非零状态退出。
可选参数:
--field=字段名 默认 file
--header="K: V" 附加请求头,可重复
--admin-dir=目录 管理员上传目录名,默认 upload(对应 config.php 的 admindir)
--help 显示本说明
HELP;
exit(0);
}
$url = isset($opt['url']) ? trim($opt['url'])
: 'https://img.example.com/functions/upload.php';
$field = isset($opt['field']) ? trim($opt['field']) : 'file';
$token = isset($opt['token']) ? trim($opt['token']) : '';
$file = isset($opt['file']) ? trim($opt['file']) : '';
if (!preg_match('#^https?://#i', $url)) {
exit('接口地址必须以 http:// 或 https:// 开头' . PHP_EOL);
}
$headers = [
'User-Agent' => 'Mozilla/5.0 (compatible; TypechoTinyImgUploader-Probe/1.0)',
'Referer' => Util::deriveReferer($url),
'X-Requested-With' => 'XMLHttpRequest',
];
if (isset($opt['header'])) {
$lines = is_array($opt['header']) ? $opt['header'] : [$opt['header']];
foreach ($lines as $line) {
$pos = strpos($line, ':');
if ($pos !== false) {
$headers[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
}
}
}
$headers = array_filter($headers, function ($value) {
return $value !== '';
});
$byToken = $token !== '';
$ping = isset($opt['ping']);
if ($byToken && (isset($opt['admin-user']) || isset($opt['admin-secret']))) {
exit('不能同时使用 --token 与 --admin-user/--admin-secret,请二选一' . PHP_EOL);
}
// 与插件一致:Token 只走请求头,不进表单字段、不出现在 URL
if ($byToken) {
$headers['X-TinyImg-Token'] = $token;
}
$asAdmin = isset($opt['admin-user']) || isset($opt['admin-secret']);
$cookiePair = null;
if ($asAdmin) {
$cookiePair = Util::adminCookie(
isset($opt['admin-user']) ? $opt['admin-user'] : '',
isset($opt['admin-secret']) ? $opt['admin-secret'] : ''
);
if ($cookiePair === null) {
exit('管理员模式需要同时提供 --admin-user 和 --admin-secret' . PHP_EOL);
}
$existing = '';
foreach ($headers as $key => $value) {
if (strcasecmp($key, 'Cookie') === 0) {
$existing = $value;
unset($headers[$key]);
}
}
$headers['Cookie'] = Util::mergeCookie($existing, $cookiePair);
}
$adminDir = isset($opt['admin-dir']) ? $opt['admin-dir'] : 'upload';
function probe_request($url, array $headers, $fields = null)
{
if (!function_exists('curl_init')) {
return probe_request_stream($url, $headers, $fields);
}
$lines = ['Expect:'];
foreach ($headers as $key => $value) {
$lines[] = $key . ': ' . $value;
}
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => $lines,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 45,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
if ($fields !== null) {
$postFields = [];
foreach ($fields as $key => $value) {
$postFields[$key] = (is_array($value) && isset($value['__file']))
? new CURLFile($value['__file'], $value['mime'], $value['name'])
: $value;
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
$raw = curl_exec($ch);
if ($raw === false) {
$error = curl_error($ch);
curl_close($ch);
return ['error' => $error];
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'error' => null,
'status' => $status,
'header' => substr($raw, 0, $headerSize),
'body' => substr($raw, $headerSize),
];
}
/**
* 没有 curl 扩展时的等价实现:GET 或手工拼 multipart POST。
*/
function probe_request_stream($url, array $headers, $fields = null)
{
$header = '';
foreach ($headers as $key => $value) {
$header .= $key . ': ' . $value . "\r\n";
}
$method = 'GET';
$content = null;
if ($fields !== null) {
$method = 'POST';
$boundary = '----ProbeIU' . md5(uniqid('', true));
$content = '';
foreach ($fields as $key => $value) {
$content .= '--' . $boundary . "\r\n";
if (is_array($value) && isset($value['__file'])) {
$name = str_replace(['"', "\r", "\n"], '', $value['name']);
$content .= 'Content-Disposition: form-data; name="' . $key
. '"; filename="' . $name . '"' . "\r\n";
$content .= 'Content-Type: ' . $value['mime'] . "\r\n\r\n";
$content .= file_get_contents($value['__file']) . "\r\n";
} else {
$content .= 'Content-Disposition: form-data; name="' . $key . '"' . "\r\n\r\n";
$content .= $value . "\r\n";
}
}
$content .= '--' . $boundary . "--\r\n";
$header .= 'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n";
}
$options = [
'method' => $method,
'header' => $header,
'timeout' => 45,
'ignore_errors' => true,
'follow_location' => 1,
'max_redirects' => 3,
];
if ($content !== null) {
$options['content'] = $content;
}
$context = stream_context_create(['http' => $options]);
$body = @file_get_contents($url, false, $context);
if ($body === false) {
$last = error_get_last();
$message = $last ? $last['message'] : '请求失败(allow_url_fopen 可能已关闭)';
if (stripos($message, 'No such file or directory') !== false && stripos($url, 'https://') === 0) {
$message .= ' —— 可能是该 PHP 未启用 openssl,https:// wrapper 不可用;'
. '请在博客服务器上用带 curl 扩展的 PHP 运行本工具';
}
return ['error' => $message];
}
$status = 0;
$rawHeader = '';
if (isset($http_response_header) && is_array($http_response_header)) {
$rawHeader = implode("\r\n", $http_response_header);
foreach ($http_response_header as $line) {
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $line, $m)) {
$status = (int) $m[1];
}
}
}
return ['error' => null, 'status' => $status, 'header' => $rawHeader, 'body' => $body];
}
function out($label, $value)
{
// 按终端显示宽度补齐,中文按 2 列算,避免中文标签对不齐
$width = function_exists('mb_strwidth') ? mb_strwidth($label, 'UTF-8') : strlen($label);
echo $label . str_repeat(' ', max(1, 20 - $width)) . ': ' . $value . PHP_EOL;
}
echo PHP_EOL . '=== TinyImg 上传接口自检 ===' . PHP_EOL;
out('接口地址', $url);
out('Referer', isset($headers['Referer']) ? $headers['Referer'] : '(未设置)');
out('上传身份', $byToken
? 'API Token(X-TinyImg-Token 头)'
: ($asAdmin ? '管理员(附带登录 Cookie)' : '游客(无凭证)'));
if ($byToken) {
out('API Token', substr($token, 0, 6) . '…(已脱敏)');
}
if ($asAdmin || $byToken) {
out('管理员目录', $adminDir === '' ? '(留空,跳过目录判定)' : $adminDir);
}
if ($asAdmin) {
out('Cookie', 'user=' . $cookiePair['user'] . '; password='
. substr($cookiePair['password'], 0, 8) . '…(已脱敏)');
}
if ($ping) {
if (!$byToken) {
exit('--ping 需要同时提供 --token(与插件「测试连接」使用同一条通道)' . PHP_EOL);
}
$pingUrl = Util::pingUrl($url);
out('自检地址', $pingUrl);
echo PHP_EOL . '模式:连接自检(POST ?ping=1,不上传任何文件)' . PHP_EOL;
$response = probe_request($pingUrl, $headers, []);
if ($response['error']) {
out('错误', $response['error']);
exit(1);
}
out('HTTP 状态', $response['status']);
out('原始响应', Util::clip($response['body'], 300));
$data = json_decode(trim($response['body']), true);
if (!is_array($data) || !isset($data['code']) || (string) $data['code'] !== '1') {
out('结论', '失败:' . (is_array($data) && isset($data['msg']) ? $data['msg'] : '图床未返回成功的 JSON'));
echo PHP_EOL . '排查:确认图床已升级到 TinyImg 2.0(支持 ?ping=1)、Token 已在后台「Token 设置」启用。' . PHP_EOL;
exit(1);
}
out('结论', '通过:Token 有效');
out('图床', (isset($data['name']) ? $data['name'] : '?') . ' ' . (isset($data['version']) ? $data['version'] : '?'));
out('管理员目录', isset($data['admin_dir']) ? $data['admin_dir'] : '(未返回)');
if (isset($data['admin_dir']) && strcasecmp($data['admin_dir'], $adminDir) !== 0) {
out('目录比对', '不一致:插件应把「管理员上传目录名」设为 ' . $data['admin_dir']);
exit(1);
}
out('目录比对', '一致');
exit(0);
}
if ($file === '') {
echo PHP_EOL . '模式:只读探测(GET,不会上传任何图片)' . PHP_EOL;
$response = probe_request($url, $headers, null);
if ($response['error']) {
out('错误', $response['error']);
exit(1);
}
out('HTTP 状态', $response['status']);
out(
'CORS 响应头',
stripos($response['header'], 'access-control-allow-origin') !== false
? '有(浏览器直连可行)'
: '无(浏览器直连会被同源策略拦截,插件需使用服务端代理)'
);
out('响应体', Util::clip($response['body'], 300));
$parsed = Util::parseResponse($response['body'], $url);
out('解析结论', $parsed['code'] === 1 ? ('可用,URL = ' . $parsed['url']) : $parsed['msg']);
echo PHP_EOL . '说明:GET 返回「非法请求」是正常现象,只说明接口存在且拒绝无文件的请求。'
. PHP_EOL . ' 要验证真实上传 / 管理员身份是否生效,请加 --file=本地图片路径。' . PHP_EOL;
exit(0);
}
if (!is_file($file)) {
exit('找不到图片文件:' . $file . PHP_EOL);
}
$info = @getimagesize($file);
if (!$info || empty($info['mime'])) {
exit('文件不是有效图片:' . $file . PHP_EOL);
}
echo PHP_EOL . '模式:真实上传(会往图床写入 1 张图片)' . PHP_EOL;
out('本地文件', $file . ' (' . ceil(filesize($file) / 1024) . ' KB, ' . $info['mime'] . ')');
// Token 已放进请求头,这里不再重复作为表单字段,保证探测的是插件真实使用的路径
$fields = [];
// 用普通数组描述文件,避免在没有 curl 扩展的机器上依赖 CURLFile 类
$fields[$field] = [
'__file' => $file,
'mime' => $info['mime'],
'name' => basename($file),
];
$response = probe_request($url, $headers, $fields);
if ($response['error']) {
out('错误', $response['error']);
exit(1);
}
out('HTTP 状态', $response['status']);
out('原始响应', Util::clip($response['body'], 300));
$parsed = Util::parseResponse($response['body'], $url);
if ($parsed['code'] === 1) {
out('图片地址', $parsed['url']);
out('Markdown', '![](' . $parsed['url'] . ')');
if ($asAdmin || $byToken) {
$inAdmin = Util::inAdminDir($parsed['url'], $adminDir);
if ($inAdmin === true) {
out('管理员目录判定', '通过:图片进了 ' . $adminDir . '/,鉴权身份已生效');
} elseif ($inAdmin === false) {
out('管理员目录判定', '未通过:地址里没有 /' . $adminDir . '/,本次实际仍是游客上传');
echo PHP_EOL . ($byToken
? '失败:图床没有按 Token 识别身份。请到图床后台「Token 设置」确认 Token 已启用,'
. PHP_EOL . ' 且与 --token 完全一致;可先跑一次 --ping 做连接自检。'
: '失败:图床没认出管理员身份(Cookie 不匹配时图床不会报错,只会静默改目录)。'
. PHP_EOL . ' 请核对 config.php 的 user / password,或用 tools/cookie.php 重新生成 Cookie 值。')
. PHP_EOL;
exit(1);
} else {
out('管理员目录判定', '已跳过(--admin-dir 留空)');
}
}
echo PHP_EOL . '成功:接口可用,插件可使用默认的服务端代理模式。' . PHP_EOL;
exit(0);
}
out('失败原因', $parsed['msg']);
echo PHP_EOL . '排查:检查字段名(--field)、图片是否超过 2 MB、Token 是否与图床后台「Token 设置」一致;'
. PHP_EOL . ' 可先加 --ping 做连接自检;若返回「API Token 无效!」说明图床侧 Token 未启用或不一致。' . PHP_EOL;
exit(1);