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:
@@ -0,0 +1,326 @@
|
||||
<?php
|
||||
|
||||
namespace TypechoPlugin\TinyImgUploader;
|
||||
|
||||
/**
|
||||
* 与 Typecho 运行环境无关的纯函数工具集。
|
||||
* Action.php、tools/probe.php、tests/util_test.php 都会加载它。
|
||||
*/
|
||||
class Util
|
||||
{
|
||||
/**
|
||||
* 把每行一项的 "key=value" / "Key: value" 文本解析成关联数组。
|
||||
* 空行、# 注释行忽略;值内部允许再次出现分隔符(如 Referer: https://)。
|
||||
*/
|
||||
public static function parsePairs($text, $separator = '=')
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (preg_split('/\r?\n/', (string) $text) as $line) {
|
||||
$line = trim($line);
|
||||
|
||||
if ($line === '' || $line[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$pos = strpos($line, $separator);
|
||||
|
||||
if ($pos === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = trim(substr($line, 0, $pos));
|
||||
$value = trim(substr($line, $pos + strlen($separator)));
|
||||
|
||||
if ($key !== '') {
|
||||
$result[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由上传接口地址推导一个同源 Referer。
|
||||
* https://host/tinyimg/functions/upload.php -> https://host/tinyimg/
|
||||
*/
|
||||
public static function deriveReferer($apiUrl)
|
||||
{
|
||||
$parts = parse_url((string) $apiUrl);
|
||||
|
||||
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$base = $parts['scheme'] . '://' . $parts['host'];
|
||||
|
||||
if (isset($parts['port'])) {
|
||||
$base .= ':' . $parts['port'];
|
||||
}
|
||||
|
||||
$path = isset($parts['path']) ? $parts['path'] : '/';
|
||||
$dir = preg_replace('#/[^/]*$#', '', $path);
|
||||
$dir = preg_replace('#/functions$#', '', $dir);
|
||||
|
||||
return $base . rtrim($dir, '/') . '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* 由上传接口地址生成连接自检地址(TinyImg 2.0 的 ?ping=1 通道)。
|
||||
* 只校验 Token、不接收文件,返回图床版本与管理员目录。
|
||||
*
|
||||
* https://host/functions/upload.php -> https://host/functions/upload.php?ping=1
|
||||
* https://host/functions/upload.php?x=1 -> https://host/functions/upload.php?x=1&ping=1
|
||||
*/
|
||||
public static function pingUrl($apiUrl)
|
||||
{
|
||||
$url = trim((string) $apiUrl);
|
||||
|
||||
if ($url === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 去掉可能存在的 #fragment,避免把 ping=1 拼到片段后面
|
||||
$hash = strpos($url, '#');
|
||||
if ($hash !== false) {
|
||||
$url = substr($url, 0, $hash);
|
||||
}
|
||||
|
||||
return $url . (strpos($url, '?') === false ? '?' : '&') . 'ping=1';
|
||||
}
|
||||
|
||||
/**
|
||||
* 把图床返回的绝对 / 协议相对 / 根相对 / 相对地址统一成 http(s) 绝对地址。
|
||||
*/
|
||||
public static function normalizeUrl($url, $baseUrl)
|
||||
{
|
||||
$url = trim((string) $url);
|
||||
|
||||
if ($url === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('#^https?://#i', $url)) {
|
||||
return $url;
|
||||
}
|
||||
|
||||
$parts = parse_url((string) $baseUrl);
|
||||
|
||||
if (!$parts || empty($parts['scheme']) || empty($parts['host'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$base = $parts['scheme'] . '://' . $parts['host'];
|
||||
|
||||
if (isset($parts['port'])) {
|
||||
$base .= ':' . $parts['port'];
|
||||
}
|
||||
|
||||
if (strpos($url, '//') === 0) {
|
||||
return $parts['scheme'] . ':' . $url;
|
||||
}
|
||||
|
||||
if (strpos($url, '/') === 0) {
|
||||
return $base . $url;
|
||||
}
|
||||
|
||||
$path = isset($parts['path']) ? $parts['path'] : '/';
|
||||
$dir = preg_replace('#/[^/]*$#', '', $path);
|
||||
|
||||
return $base . rtrim($dir, '/') . '/' . ltrim($url, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 在任意层级的数组里递归查找图片地址。
|
||||
*/
|
||||
public static function findUrl($value, $depth = 0)
|
||||
{
|
||||
if ($depth > 8 || !is_array($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (['url', 'link', 'src', 'image', 'original'] as $key) {
|
||||
if (isset($value[$key]) && is_string($value[$key])) {
|
||||
$candidate = trim($value[$key]);
|
||||
|
||||
// 绝对 / 协议相对 / 根相对地址,或任意以图片扩展名结尾的相对路径
|
||||
if (preg_match('#^(https?://|//|/)#i', $candidate)
|
||||
|| preg_match('#\.(jpe?g|png|gif|webp|bmp)(\?.*)?$#i', $candidate)) {
|
||||
return $candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($value as $item) {
|
||||
$found = self::findUrl($item, $depth + 1);
|
||||
|
||||
if ($found !== null) {
|
||||
return $found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把图床原始响应统一成 ['code' => 1|0, 'url' => string|null, 'msg' => string]。
|
||||
*
|
||||
* 兼容:
|
||||
* TinyImg 2.0 成功 {"code":1,"id":9,"url":"https://...","width":800,"height":600}
|
||||
* TinyImg 2.0 失败 {"code":0,"msg":"API Token 无效!"}
|
||||
* 其它图床 {"code":200,"data":{"url":"https://..."}}
|
||||
* 通用 {"success":true,"data":{"url":"..."}}
|
||||
*
|
||||
* 注意:TinyImg 语义里 code=0 表示失败,因此即使响应里带了 url 也判为失败。
|
||||
*/
|
||||
public static function parseResponse($body, $baseUrl = '')
|
||||
{
|
||||
$body = trim((string) $body);
|
||||
|
||||
if ($body === '') {
|
||||
return ['code' => 0, 'url' => null, 'msg' => '图床返回空内容(可能是 PHP 报错或 5xx)'];
|
||||
}
|
||||
|
||||
$data = json_decode($body, true);
|
||||
|
||||
if (!is_array($data)) {
|
||||
// 有些 PHP 程序会在 JSON 前面输出 BOM / notice,尝试截到第一个 { 或 [
|
||||
$trimmed = preg_replace('/^[^{[]*/', '', $body);
|
||||
$data = @json_decode($trimmed, true);
|
||||
}
|
||||
|
||||
if (!is_array($data)) {
|
||||
return ['code' => 0, 'url' => null, 'msg' => '图床返回的不是 JSON:' . self::clip($body, 160)];
|
||||
}
|
||||
|
||||
$rawUrl = self::findUrl($data);
|
||||
$code = isset($data['code']) ? (string) $data['code'] : '';
|
||||
|
||||
if ($rawUrl === null || $code === '0') {
|
||||
$msg = '图床未返回图片地址';
|
||||
|
||||
foreach (['msg', 'message', 'error', 'err'] as $key) {
|
||||
if (!empty($data[$key]) && is_string($data[$key])) {
|
||||
$msg = $data[$key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => 0,
|
||||
'url' => null,
|
||||
'msg' => $msg . ' | 原始响应:' . self::clip($body, 160),
|
||||
];
|
||||
}
|
||||
|
||||
$url = self::normalizeUrl($rawUrl, $baseUrl);
|
||||
|
||||
if ($url === null) {
|
||||
return ['code' => 0, 'url' => null, 'msg' => '无法解析图片地址:' . $rawUrl];
|
||||
}
|
||||
|
||||
return ['code' => 1, 'url' => $url, 'msg' => 'ok'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造管理员登录 Cookie(回退方案,两个字段)。
|
||||
*
|
||||
* 源码依据(TinyImg/functions/class/class.user.php):
|
||||
* functions/class/class.user.php:32-35 login()
|
||||
* $password = md5("tinyimg" . $admin['password']);
|
||||
* setcookie("user", $user['user'], ...); setcookie("password", $password, ...);
|
||||
* functions/class/class.user.php:41-52 check()
|
||||
* $user1 = $config['user'] . md5("tinyimg" . $config['password']);
|
||||
* $user2 = $_COOKIE['user'] . $_COOKIE['password'];
|
||||
* $user1 == $user2 ? 'islogin' : 'nologin'
|
||||
* functions/upload.php:15-23
|
||||
* islogin -> admindir,且跳过 limitnum();否则 -> userdir + 每日数量限制
|
||||
*
|
||||
* $secret 既可以填 config.php 里的明文密码,也可以填图床登录后 Cookie 中的
|
||||
* password 值(32 位十六进制 md5)。后者可避免明文密码存进 Typecho 数据库。
|
||||
* 返回的 user 已按 PHP setcookie() 的规则 urlencode,可直接放进 Cookie 头。
|
||||
*/
|
||||
public static function adminCookie($user, $secret)
|
||||
{
|
||||
$user = trim((string) $user);
|
||||
$secret = trim((string) $secret);
|
||||
|
||||
if ($user === '' || $secret === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$password = preg_match('/^[a-f0-9]{32}$/i', $secret)
|
||||
? strtolower($secret)
|
||||
: md5('tinyimg' . $secret);
|
||||
|
||||
return [
|
||||
'user' => rawurlencode($user),
|
||||
'password' => $password,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把鉴权字段合并进已有的 Cookie 头:同名字段覆盖,其它字段保留。
|
||||
*/
|
||||
public static function mergeCookie($existing, array $pairs)
|
||||
{
|
||||
$jar = [];
|
||||
|
||||
foreach (explode(';', (string) $existing) as $part) {
|
||||
$part = trim($part);
|
||||
|
||||
if ($part === '' || strpos($part, '=') === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
list($key, $value) = explode('=', $part, 2);
|
||||
$key = trim($key);
|
||||
|
||||
if ($key !== '') {
|
||||
$jar[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($pairs as $key => $value) {
|
||||
$jar[$key] = $value;
|
||||
}
|
||||
|
||||
$line = [];
|
||||
foreach ($jar as $key => $value) {
|
||||
$line[] = $key . '=' . $value;
|
||||
}
|
||||
|
||||
return implode('; ', $line);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断图片地址是否落在管理员上传目录。
|
||||
* TinyImg 的 URL 形如 https://host/upload/2611/hash.jpg。
|
||||
* 返回 null 表示未配置目录名、跳过判定;true / false 表示判定结果。
|
||||
*/
|
||||
public static function inAdminDir($url, $dir)
|
||||
{
|
||||
$dir = trim((string) $dir, "/ \t\n\r\0\x0B");
|
||||
|
||||
if ($dir === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = parse_url((string) $url, PHP_URL_PATH);
|
||||
|
||||
if (!is_string($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) preg_match('#/' . preg_quote($dir, '#') . '/#i', $path);
|
||||
}
|
||||
|
||||
public static function clip($text, $length)
|
||||
{
|
||||
$text = preg_replace('/\s+/u', ' ', (string) $text);
|
||||
|
||||
return function_exists('mb_substr')
|
||||
? mb_substr($text, 0, $length, 'UTF-8')
|
||||
: substr($text, 0, $length);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user