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
+497
View File
@@ -0,0 +1,497 @@
<?php
namespace TypechoPlugin\TinyImgUploader;
use Widget\ActionInterface;
use Widget\Base;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
/**
* 服务端上传代理:接收后台 Ajax 的图片文件,转发到自建图床,统一返回 JSON。
*
* 存在的理由:实测 TinyImg 的 functions/upload.php 不返回任何
* Access-Control-Allow-Origin,浏览器从博客后台直接 POST 会被同源策略拦截。
* 还负责在服务端注入 API Token 请求头或图床登录 Cookie(凭证不下发到浏览器),
* 以及设置页「测试连接」按钮用到的 ?ping=1 连通性探测。
*/
class Action extends Base implements ActionInterface
{
public function action()
{
$cfg = self::config();
$this->assertAuthorized($cfg);
// 设置页的「测试连接」按钮:do=test,不接收文件,只验证 Token 与图床版本
if ($this->param('do') === 'test') {
$this->testConnection($cfg);
}
if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '') !== 'POST') {
$this->json(['code' => 0, 'msg' => '仅支持 POST 上传']);
}
if (empty($_FILES['image']) || is_array($_FILES['image']['error'])) {
$this->json(['code' => 0, 'msg' => '没有收到图片文件(表单字段名应为 image)']);
}
$file = $_FILES['image'];
if ($file['error'] !== UPLOAD_ERR_OK) {
$this->json(['code' => 0, 'msg' => self::uploadErrorMessage($file['error'])]);
}
$tmp = $file['tmp_name'];
if (!is_uploaded_file($tmp)) {
$this->json(['code' => 0, 'msg' => '上传的临时文件无效']);
}
$maxBytes = max(1, (int) $cfg['maxSize']) * 1048576;
if ($file['size'] <= 0 || $file['size'] > $maxBytes) {
$this->json([
'code' => 0,
'msg' => '图片大小不合要求(当前 ' . ceil($file['size'] / 1024) . ' KB,上限 '
. $cfg['maxSize'] . ' MB)',
]);
}
// 用图片头真实校验类型,禁止 SVG / PHP 等可执行内容混过 image/* 判断
$image = self::imageMime($tmp);
if ($image === null) {
$this->json(['code' => 0, 'msg' => '仅支持 jpg / png / gif / webp / bmp 图片']);
}
$name = self::safeName($file['name'], $image['ext']);
$apiUrl = trim((string) $cfg['apiUrl']);
if (!preg_match('#^https?://#i', $apiUrl)) {
$this->json(['code' => 0, 'msg' => '上传接口地址必须以 http:// 或 https:// 开头']);
}
$byToken = $cfg['authMode'] === 'token';
$extra = Util::parsePairs($cfg['extraFields'], '=');
// Token 模式只用请求头传凭证,不再作为表单字段重复发送
if (!$byToken && $cfg['token'] !== '' && !isset($extra['token'])) {
$extra['token'] = $cfg['token'];
}
$headers = [
'User-Agent' => 'Mozilla/5.0 (compatible; TypechoTinyImgUploader/2.0)',
'Referer' => Util::deriveReferer($apiUrl),
'X-Requested-With' => 'XMLHttpRequest',
];
foreach (Util::parsePairs($cfg['headers'], ':') as $key => $value) {
$headers[$key] = $value;
}
$headers = array_filter($headers, function ($value) {
return $value !== '';
});
// 凭证只在服务端使用,浏览器收到的是同源 Action 地址,看不到任何图床秘密。
$asAdmin = $cfg['authMode'] !== 'guest';
if ($byToken) {
// 推荐方式:独立 API Token,只被图床的 functions/upload.php 识别
$apiToken = trim((string) $cfg['token']);
if ($apiToken === '') {
$this->json([
'code' => 0,
'msg' => '已开启 API Token 上传,但未填写 Token:请到图床后台「Token 设置」生成,'
. '填入插件设置后用「测试连接」验证',
]);
}
$headers['X-TinyImg-Token'] = $apiToken;
} elseif ($asAdmin) {
// 兼容方式:模拟图床后台登录 Cookie(TinyImg 1.x 原生逻辑)
$cookie = Util::adminCookie($cfg['adminUser'], $cfg['adminSecret']);
if ($cookie === null) {
$this->json([
'code' => 0,
'msg' => '已开启管理员上传,但未填写图床管理员账号或密码/Cookie,请到插件设置里补全',
]);
}
$existing = '';
foreach ($headers as $key => $value) {
if (strcasecmp($key, 'Cookie') === 0) {
$existing = $value;
unset($headers[$key]);
}
}
$headers['Cookie'] = Util::mergeCookie($existing, $cookie);
}
$fieldName = trim((string) $cfg['fieldName']);
if ($fieldName === '') {
$fieldName = 'file';
}
$fields = $extra;
$fields[$fieldName] = [
'file' => $tmp,
'mime' => $image['mime'],
'name' => $name,
];
$result = self::forward($apiUrl, $fields, $headers);
if ($result['error']) {
$this->json(['code' => 0, 'msg' => '转发到图床失败:' . $result['error']]);
}
if ($result['status'] && ($result['status'] < 200 || $result['status'] >= 300)) {
$this->json([
'code' => 0,
'msg' => '图床返回 HTTP ' . $result['status'] . ':' . Util::clip($result['body'], 200),
]);
}
$parsed = Util::parseResponse($result['body'], $apiUrl);
if ($parsed['code'] !== 1) {
$this->json([
'code' => 0,
'msg' => $parsed['msg'],
'raw' => Util::clip($result['body'], 300),
]);
}
$out = [
'code' => 1,
'url' => $parsed['url'],
'name' => $name,
'as' => $asAdmin ? 'admin' : 'guest',
];
// 图床在 Cookie 不匹配时不会报错,而是静默回落到游客目录。
// 用返回地址里的目录名反查一次,避免「以为改成管理员、其实没生效」。
if ($asAdmin && Util::inAdminDir($parsed['url'], $cfg['adminDir']) === false) {
$out['warn'] = $byToken
? '图片已上传,但地址里没有管理员目录「' . $cfg['adminDir']
. '」:图床没有按 Token 识别身份。请到图床后台「Token 设置」确认 Token 已启用,'
. '并与插件设置里的值完全一致;可用「测试连接」按钮复核。'
: '图片已上传,但地址里没有管理员目录「' . $cfg['adminDir']
. '」:图床没认出管理员身份,本次实际仍是游客上传。请核对图床 config.php 的 '
. 'user / password,或把「管理员上传目录名」改成你实际的 admindir。';
}
$this->json($out);
}
private static function config()
{
return Plugin::settings();
}
/** 从 Typecho Request 读取参数,取不到时回落到原始超全局(兼容不同 1.3 构建) */
private function param($key)
{
$value = $this->request->get($key);
if ($value === null && isset($_GET[$key])) {
$value = $_GET[$key];
}
if ($value === null && isset($_POST[$key])) {
$value = $_POST[$key];
}
return is_scalar($value) ? (string) $value : null;
}
/** 登录 + 用户组 + CSRF;校验失败一律返回 JSON,不做 302 跳转 */
private function assertAuthorized(array $cfg)
{
$group = $cfg['allowGroup'] === 'administrator' ? 'administrator' : 'contributor';
if (!$this->user->hasLogin() || !$this->user->pass($group, true)) {
$this->json([
'code' => 0,
'msg' => $group === 'administrator'
? '请先登录后台,且需要「管理员」权限'
: '请先登录后台,且账号至少具有「贡献者」权限',
]);
}
// 与 Widget\Security::protect() 等价,但校验失败时返回 JSON 而不是 302 跳转
$token = $this->param('_');
if (!$token || $token !== $this->security->getToken($this->request->getReferer())) {
$this->json(['code' => 0, 'msg' => '安全校验失败,请刷新页面后重试']);
}
}
/**
* 设置页「测试连接」:用输入框里的 Token 请求图床 upload.php?ping=1。
* 不上传任何文件、不写数据库;Token 只出现在服务端到图床的请求头里。
*/
private function testConnection(array $cfg)
{
if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '') !== 'POST') {
$this->json(['code' => 0, 'msg' => '测试连接需要 POST 请求']);
}
$token = trim((string) $this->param('token'));
if ($token === '') {
$token = trim((string) $cfg['token']); // 允许直接测已保存的 Token
}
if ($token === '') {
$this->json(['code' => 0, 'msg' => '请先在上方填入 API Token(可点击「测试连接」前不保存)']);
}
$apiUrl = trim((string) $cfg['apiUrl']);
if (!preg_match('#^https?://#i', $apiUrl) || strpos($apiUrl, 'img.example.com') !== false) {
$this->json([
'code' => 0,
'msg' => '「图床上传接口地址」仍是占位值或格式不对,请先改成你的实际地址(functions/upload.php)',
]);
}
$headers = [
'User-Agent' => 'Mozilla/5.0 (compatible; TypechoTinyImgUploader/2.0)',
'Referer' => Util::deriveReferer($apiUrl),
'X-Requested-With' => 'XMLHttpRequest',
'Accept' => 'application/json',
];
foreach (Util::parsePairs($cfg['headers'], ':') as $key => $value) {
if ($value !== '') {
$headers[$key] = $value;
}
}
// 强制覆盖,避免「附加请求头」里误配同名项导致测的不是当前 Token
$headers['X-TinyImg-Token'] = $token;
$result = self::forward(Util::pingUrl($apiUrl), [], array_filter($headers, function ($v) {
return $v !== '';
}));
if ($result['error']) {
$this->json(['code' => 0, 'msg' => '连接图床失败:' . $result['error']]);
}
if ($result['status'] && ($result['status'] < 200 || $result['status'] >= 300)) {
$this->json([
'code' => 0,
'msg' => '图床返回 HTTP ' . $result['status'],
'raw' => Util::clip($result['body'], 200),
]);
}
$data = json_decode(trim((string) $result['body']), true);
if (!is_array($data)) {
$this->json([
'code' => 0,
'msg' => '图床返回的不是 JSON:请确认已升级到 TinyImg 2.0(支持 ?ping=1),且接口地址正确',
'raw' => Util::clip($result['body'], 200),
]);
}
if (!isset($data['code']) || (string) $data['code'] !== '1') {
$this->json([
'code' => 0,
'msg' => isset($data['msg']) ? (string) $data['msg'] : 'Token 校验未通过',
'raw' => Util::clip($result['body'], 200),
]);
}
$out = [
'code' => 1,
'msg' => '连接成功,Token 有效',
'name' => isset($data['name']) ? (string) $data['name'] : '',
'version' => isset($data['version']) ? (string) $data['version'] : '',
'admin_dir' => isset($data['admin_dir']) ? (string) $data['admin_dir'] : '',
];
$reportedDir = $out['admin_dir'];
if ($reportedDir !== '' && $cfg['adminDir'] !== ''
&& strcasecmp($reportedDir, $cfg['adminDir']) !== 0) {
$out['warn'] = '图床报告的管理员目录是「' . $reportedDir . '」,插件填的是「'
. $cfg['adminDir'] . '」,请把插件设置改成一致,否则上传后会误报身份未生效';
}
if ($cfg['authMode'] !== 'token') {
$out['warn'] = (isset($out['warn']) ? $out['warn'] . ';' : '')
. '注意:当前鉴权方式为「' . $cfg['authMode'] . '」,实际上传不会使用这个 Token';
}
$this->json($out);
}
private static function imageMime($path)
{
$info = @getimagesize($path);
$mime = ($info && !empty($info['mime'])) ? $info['mime'] : '';
$allowed = [
'image/jpeg' => 'jpg',
'image/pjpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
'image/x-ms-bmp'=> 'bmp',
];
return isset($allowed[$mime]) ? ['mime' => $mime, 'ext' => $allowed[$mime]] : null;
}
private static function safeName($name, $ext)
{
$name = basename(str_replace('\\', '/', (string) $name));
$name = preg_replace('/[^\x20-\x7e]/', '', $name);
$name = str_replace(['"', "\r", "\n", '/'], '', $name);
$name = trim($name);
if ($name === '' || $name === '.' || $name === '..') {
$name = 'image';
}
if (!preg_match('/\.[a-z0-9]{2,5}$/i', $name)) {
$name .= '.' . $ext;
}
return $name;
}
private static function uploadErrorMessage($code)
{
$messages = [
UPLOAD_ERR_INI_SIZE => '超过服务器 upload_max_filesize 限制',
UPLOAD_ERR_FORM_SIZE => '超过表单 MAX_FILE_SIZE 限制',
UPLOAD_ERR_PARTIAL => '文件只上传了一部分',
UPLOAD_ERR_NO_FILE => '没有选择文件',
UPLOAD_ERR_NO_TMP_DIR => '服务器缺少临时目录',
UPLOAD_ERR_CANT_WRITE => '服务器写入临时文件失败',
UPLOAD_ERR_EXTENSION => 'PHP 扩展中止了上传',
];
return isset($messages[$code]) ? $messages[$code] : ('未知上传错误:' . $code);
}
/**
* 优先 curl;没有 curl 扩展时退回 stream 手工拼 multipart。
*/
private static function forward($url, array $fields, array $headers)
{
return function_exists('curl_init')
? self::forwardByCurl($url, $fields, $headers)
: self::forwardByStream($url, $fields, $headers);
}
private static function forwardByCurl($url, array $fields, array $headers)
{
$postFields = [];
foreach ($fields as $key => $value) {
$postFields[$key] = (is_array($value) && isset($value['file']))
? new \CURLFile($value['file'], $value['mime'], $value['name'])
: $value;
}
$lines = ['Expect:'];
foreach ($headers as $key => $value) {
$lines[] = $key . ': ' . $value;
}
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_HTTPHEADER => $lines,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 45,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$body = curl_exec($ch);
if ($body === false) {
$error = curl_error($ch);
curl_close($ch);
return ['error' => $error, 'status' => 0, 'body' => ''];
}
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ['error' => null, 'status' => $status, 'body' => (string) $body];
}
private static function forwardByStream($url, array $fields, array $headers)
{
$random = function_exists('random_bytes') ? bin2hex(random_bytes(8)) : md5(uniqid('', true));
$boundary = '----TypechoIU' . $random;
$body = '';
foreach ($fields as $key => $value) {
$safeKey = str_replace(['"', "\r", "\n"], '', $key);
$body .= '--' . $boundary . "\r\n";
if (is_array($value) && isset($value['file'])) {
$safeName = str_replace(['"', "\r", "\n"], '', $value['name']);
$body .= 'Content-Disposition: form-data; name="' . $safeKey
. '"; filename="' . $safeName . '"' . "\r\n";
$body .= 'Content-Type: ' . $value['mime'] . "\r\n\r\n";
$body .= file_get_contents($value['file']) . "\r\n";
} else {
$body .= 'Content-Disposition: form-data; name="' . $safeKey . '"' . "\r\n\r\n";
$body .= $value . "\r\n";
}
}
$body .= '--' . $boundary . "--\r\n";
$header = 'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n";
foreach ($headers as $key => $value) {
$header .= $key . ': ' . $value . "\r\n";
}
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => $header,
'content' => $body,
'timeout' => 45,
'ignore_errors' => true,
'follow_location' => 1,
'max_redirects' => 3,
],
]);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
$last = error_get_last();
return [
'error' => $last ? $last['message'] : '请求失败(allow_url_fopen 可能已关闭)',
'status' => 0,
'body' => '',
];
}
$status = 0;
if (isset($http_response_header[0]) && preg_match('#\s(\d{3})\s#', $http_response_header[0], $m)) {
$status = (int) $m[1];
}
return ['error' => null, 'status' => $status, 'body' => $response];
}
private function json(array $data)
{
$this->response->setContentType('application/json');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
}