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
+807
View File
@@ -0,0 +1,807 @@
<?php
namespace TypechoPlugin\TinyImgUploader;
use Typecho\Plugin\PluginInterface;
use Typecho\Widget\Helper\Form;
use Typecho\Widget\Helper\Form\Element\Password;
use Typecho\Widget\Helper\Form\Element\Radio;
use Typecho\Widget\Helper\Form\Element\Text;
use Typecho\Widget\Helper\Form\Element\Textarea;
use Utils\Helper;
use Widget\Options;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
/**
* 撰写文章 / 页面右侧栏的图床上传窗口。
* 选择图片 -> 确认 -> 上传到自建 TinyImg 图床 -> 把 Markdown 插入光标处。
*
* @package TinyImgUploader
* @author BuddyRobot
* @version 2.0.0
* @since 1.3.0
*/
class Plugin implements PluginInterface
{
/** 插件目录名,也是设置项的命名空间 */
const NAME = 'TinyImgUploader';
/** Action 名,对应 /action/tinyimg-uploader */
const ACTION = 'tinyimg-uploader';
/** 允许显式留空的设置项:留空表示「跳过管理员目录校验」 */
const NULLABLE = ['adminDir'];
/** 设置项默认值 */
const DEFAULTS = [
// 占位地址:部署后请改成自己图床的 functions/upload.php 绝对地址
'apiUrl' => 'https://img.example.com/functions/upload.php',
'fieldName' => 'file',
'mode' => 'proxy',
'authMode' => 'token',
'adminUser' => '',
'adminSecret' => '',
'adminDir' => 'upload',
'allowGroup' => 'contributor',
'token' => '',
'extraFields' => '',
'headers' => '',
'maxSize' => '2',
'template' => '![%alt%](%url%)',
];
public static function activate()
{
// 侧栏卡片:admin/write-post.php:119 / admin/write-page.php:145
\Typecho\Plugin::factory('admin/write-post.php')->option = __CLASS__ . '::renderOption';
\Typecho\Plugin::factory('admin/write-page.php')->option = __CLASS__ . '::renderOption';
// 弹窗与脚本:页面底部,此时 jQuery 已加载
\Typecho\Plugin::factory('admin/write-post.php')->bottom = __CLASS__ . '::renderFooter';
\Typecho\Plugin::factory('admin/write-page.php')->bottom = __CLASS__ . '::renderFooter';
Helper::addAction(self::ACTION, Action::class);
return _t('图床上传已启用;请在设置里填写图床 functions/upload.php 地址,并填入图床后台「Token 设置」页生成的 API Token,然后点「测试连接」验证');
}
public static function deactivate()
{
Helper::removeAction(self::ACTION);
}
public static function config(Form $form)
{
$apiUrl = new Text(
'apiUrl',
null,
self::DEFAULTS['apiUrl'],
_t('图床上传接口地址'),
_t('TinyImg 2.0 的上传端点:https://你的图床域名/functions/upload.php。默认值是占位地址,必须改成你的实际地址;以 http:// 或 https:// 开头。')
);
$apiUrl->addRule('required', _t('请填写上传接口地址'));
$apiUrl->input->setAttribute('class', 'w-100 text');
$form->addInput($apiUrl);
$authMode = new Radio(
'authMode',
[
'token' => _t('API Token(推荐,TinyImg 2.0 原生支持)'),
'admin' => _t('管理员 Cookie(回退方案,凭证等价于后台密码)'),
'guest' => _t('游客上传(图片进 temp 目录,受每日数量限制)'),
],
self::DEFAULTS['authMode'],
_t('上传到图床的鉴权方式'),
_t('Token 用 X-TinyImg-Token 请求头,由图床后台「Token 设置」页生成,只在服务端出现;Cookie 模式模拟图床后台登录态。详见 README 的鉴权方案对比。')
);
$form->addInput($authMode);
$adminUser = new Text(
'adminUser',
null,
'',
_t('图床管理员账号'),
_t('图床 config.php 里 user 配置项的值,必须与图床完全一致(区分大小写)。')
);
$form->addInput($adminUser);
// 个别 Typecho 构建可能没有 Password 元素,降级成普通输入框以免设置页直接 500
$secretElement = class_exists('Typecho\\Widget\\Helper\\Form\\Element\\Password')
? Password::class
: Text::class;
$adminSecret = new $secretElement(
'adminSecret',
null,
'',
_t('图床管理员密码 / 登录 Cookie 值'),
_t('可填明文密码(插件自动算 md5("tinyimg" + 密码) 作为 Cookie);更推荐用 tools/cookie.php 算出 32 位值后填入,或直接复制图床登录后 Cookie 里的 password 值,避免明文密码存入数据库。')
);
$form->addInput($adminSecret);
$adminDir = new Text(
'adminDir',
null,
self::DEFAULTS['adminDir'],
_t('管理员上传目录名'),
_t('图床 config.php 里 admindir 的值,默认 upload。上传后用它检查是否真的以管理员身份生效;留空则跳过该检查。')
);
$form->addInput($adminDir);
$allowGroup = new Radio(
'allowGroup',
[
'contributor' => _t('贡献者及以上(默认)'),
'administrator' => _t('仅博客管理员可用'),
],
self::DEFAULTS['allowGroup'],
_t('允许使用该插件的博客用户组'),
_t('这是 Typecho 侧的权限,与上面的图床身份无关;两处都设为管理员即实现「仅管理员以管理员身份上传」。')
);
$form->addInput($allowGroup);
$fieldName = new Text(
'fieldName',
null,
self::DEFAULTS['fieldName'],
_t('文件表单字段名'),
_t('TinyImg 2.0 为 file;其它图床可能是 image、smfile 等,按接口文档填写。')
);
$form->addInput($fieldName);
$mode = new Radio(
'mode',
[
'proxy' => _t('服务端代理(推荐,无需图床开放 CORS)'),
'direct' => _t('浏览器直连(需图床返回 CORS 响应头)'),
],
self::DEFAULTS['mode'],
_t('上传方式'),
_t('实测本图床未返回 Access-Control-Allow-Origin,默认必须用服务端代理;Token / Cookie 模式会强制走代理,防止凭证下发到浏览器。')
);
$form->addInput($mode);
$maxSize = new Text(
'maxSize',
null,
self::DEFAULTS['maxSize'],
_t('单张图片上限(MB)'),
_t('TinyImg 2.0 源码里硬编码 file_max_size = 2097152(2 MB),填大于 2 会被图床拒绝。')
);
$maxSize->addRule('required', _t('请填写大小上限'));
$maxSize->addRule('isInteger', _t('请填写整数'));
$form->addInput($maxSize);
$template = new Text(
'template',
null,
self::DEFAULTS['template'],
_t('插入 Markdown 模板'),
_t('可用占位符:%url% 图片地址、%alt% 不含扩展名的文件名、%name% 原文件名。想和极简图床页面完全一致可填 ![](%url%)。')
);
$template->input->setAttribute('class', 'w-100 mono');
$form->addInput($template);
$token = new $secretElement(
'token',
null,
'',
_t('图床 API Token'),
_t('在图床后台「Token 设置」页生成或复制,粘贴到此处,两处必须完全一致。Token 模式用 X-TinyImg-Token 请求头在服务端发送,不写入撰写页、不出现在 URL;Cookie / 游客模式下本项留空。')
. self::testButtonHtml()
);
$token->input->setAttribute('class', 'w-100 mono');
$form->addInput($token);
$extraFields = new Textarea(
'extraFields',
null,
'',
_t('附加表单字段(可选)'),
_t('每行一项,格式 key=value,例如 uid=1。用于需要 uid / apiType / folder 等参数的图床。')
);
$form->addInput($extraFields);
$headers = new Textarea(
'headers',
null,
'',
_t('附加请求头(可选,仅代理模式)'),
_t('每行一项,格式 Key: Value。例如需要登录态时填 Cookie: xxxx,或覆盖 Referer。默认已自动带 User-Agent、Referer、X-Requested-With。')
);
$form->addInput($headers);
}
public static function personalConfig(Form $form)
{
}
/**
* 设置页「测试连接」按钮的 HTML(由 config() 放进 Token 字段的说明里)。
*
* 走博客同源的 /action/tinyimg-uploader?do=test,由 PHP 携带 Token 去请求
* 图床的 functions/upload.php?ping=1,因此不受跨域限制、也不会把图床地址
* 或 Token 暴露给撰写文章页。URL 里的 _ 参数是 Typecho 的 CSRF 令牌。
*
* 单独做成 public 方法,便于 tests/render_test.php 直接断言而不必 stub 整套表单类。
*/
public static function testButtonHtml()
{
$testUrl = '';
try {
if (class_exists('\\Widget\\Security')) {
$testUrl = \Widget\Security::alloc()->getIndex('/action/' . self::ACTION . '?do=test');
}
} catch (\Throwable $e) {
$testUrl = '';
}
$jsonUrl = json_encode(
(string) $testUrl,
JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT
);
$html = '<span id="ti-test-wrap" style="display:block;margin-top:10px;">'
. '<button type="button" class="btn" id="ti-test-btn">' . _t('测试连接') . '</button>'
. '<span id="ti-test-result" style="margin-left:10px;line-height:1.8;"></span>'
. '</span>'
. '<span style="display:block;margin-top:4px;color:#999;">'
. _t('测试会读取上方输入框里的 Token(无需先保存),验证图床是否认这个 Token,并返回图床版本与管理员目录。')
. '</span>';
if ($testUrl === '') {
return $html . '<span style="color:#c0392b;">' . _t('无法生成安全令牌,请刷新设置页后重试') . '</span>';
}
$js = <<<'TIJS'
<script>
(function () {
'use strict';
var URL = __TEST_URL__;
var btn = document.getElementById('ti-test-btn');
var out = document.getElementById('ti-test-result');
if (!btn || !out) { return; }
function done() {
btn.disabled = false;
btn.textContent = '测试连接';
}
function fail(msg) {
out.textContent = '✗ ' + msg;
out.style.color = '#c0392b';
}
btn.onclick = function () {
var input = document.querySelector('input[name="token"]');
var fd = new FormData();
fd.append('token', input ? input.value : '');
fd.append('do', 'test');
btn.disabled = true;
btn.textContent = '测试中…';
out.textContent = '';
out.style.color = '';
fetch(URL, { method: 'POST', body: fd, credentials: 'same-origin' })
.then(function (r) { return r.text(); })
.then(function (text) {
var d = null;
try { d = JSON.parse(text); } catch (e) { d = null; }
if (!d) {
fail('服务器返回的不是 JSON(可能安全令牌已过期,请刷新设置页重试)');
done();
return;
}
var msg = d.msg || '';
if (d.name) { msg += ' · ' + d.name + ' ' + (d.version || ''); }
if (d.admin_dir) { msg += ' · 管理员目录 ' + d.admin_dir; }
if (d.warn) { msg += ' · ' + d.warn; }
if (d.code == 1) {
out.textContent = '✓ ' + msg;
out.style.color = d.warn ? '#c47f00' : '#27865b';
} else {
out.textContent = '✗ ' + msg + (d.raw ? ' · ' + d.raw : '');
out.style.color = '#c0392b';
}
done();
})
.catch(function (e) {
fail('请求失败:' + (e && e.message ? e.message : '网络错误'));
done();
});
};
})();
</script>
TIJS;
return $html . str_replace('__TEST_URL__', $jsonUrl, $js);
}
/**
* 读取设置,缺失项回落默认值。禁用插件会清空设置,这里做兜底避免出现 500。
* Action 也复用本方法,保证权限校验与转发行为读的是同一份配置。
*/
public static function settings()
{
try {
$saved = Options::alloc()->plugin(self::NAME)->toArray();
} catch (\Typecho\Plugin\Exception $e) {
$saved = [];
}
foreach (self::DEFAULTS as $key => $default) {
$exists = array_key_exists($key, $saved);
// adminDir 允许显式留空(表示跳过目录校验)
$nullableEmpty = $exists && $saved[$key] === '' && in_array($key, self::NULLABLE, true);
if (!$exists || ($saved[$key] === '' && !$nullableEmpty)) {
$saved[$key] = $default;
}
}
return $saved;
}
/**
* 「仅博客管理员可用」时,非管理员连侧栏卡片都不显示。
* Action 里仍会再做一次权限校验,这里是纯粹的界面收敛。
*/
private static function canUse(array $cfg)
{
if ($cfg['allowGroup'] !== 'administrator' || !class_exists('\\Widget\\User')) {
return true;
}
$user = \Widget\User::alloc();
return (bool) ($user->hasLogin() && $user->pass('administrator', true));
}
/**
* option 钩子:右侧「选项」标签页内的上传卡片。
*/
public static function renderOption($content)
{
$cfg = self::settings();
if (!self::canUse($cfg)) {
return;
}
$limit = htmlspecialchars((string) $cfg['maxSize'], ENT_QUOTES, 'UTF-8');
echo '<section class="typecho-post-option" id="iu-box">';
echo '<label class="typecho-label">' . _t('图床上传') . '</label>';
echo '<p><button type="button" class="btn primary w-100" id="iu-open">' . _t('选择图片上传') . '</button></p>';
echo '<p class="description">' . _t('选图并确认后上传到自建图床,自动把 Markdown 插入光标处;也可拖入图片或在弹窗内 Ctrl+V 粘贴。单张不超过 ')
. $limit . ' MB。</p>';
if (!Options::alloc()->markdown) {
echo '<p class="description" style="color:#c0392b">'
. _t('当前站点未开启 Markdown,插入的图片语法可能不会被解析。') . '</p>';
}
$mode = $cfg['authMode'];
$identity = $mode === 'token' ? _t('API Token')
: ($mode === 'admin' ? _t('管理员 Cookie') : _t('游客'));
$missing = ($mode === 'token' && $cfg['token'] === '')
|| ($mode === 'admin' && ($cfg['adminUser'] === '' || $cfg['adminSecret'] === ''));
$hint = $mode === 'token'
? _t('(未填写 API Token,上传会被拒绝;请到图床后台「Token 设置」页生成后填入插件设置)')
: _t('(未填写管理员账号或密码/Cookie,上传会被拒绝)');
echo '<p class="description">' . _t('图床身份:') . '<strong>' . $identity . '</strong>';
if ($missing) {
echo ' <span style="color:#c0392b">' . $hint . '</span>';
}
echo '</p>';
// 默认接口地址是占位符,没改过就上传必然失败,这里提前拦住并给出明确指引
if (strpos($cfg['apiUrl'], 'img.example.com') !== false) {
echo '<p class="description" style="color:#c0392b">'
. _t('插件设置里的「图床上传接口地址」仍是占位值,请先改成你的实际地址,并用「测试连接」验证。')
. '</p>';
}
echo '<p class="description" id="iu-status"></p>';
echo '</section>';
}
/**
* bottom 钩子:弹窗 DOM、样式、交互脚本。
*/
public static function renderFooter($content)
{
$cfg = self::settings();
$actionUrl = \Widget\Security::alloc()->getIndex('/action/' . self::ACTION);
// Token / Cookie 模式携带服务端凭证,绝不允许把请求切到浏览器直连
$mode = ($cfg['mode'] === 'direct' && $cfg['authMode'] === 'guest') ? 'direct' : 'proxy';
$jsCfg = [
'mode' => $mode,
'template' => (string) $cfg['template'],
'maxSize' => max(1, (int) $cfg['maxSize']),
'actionUrl' => $actionUrl,
];
// 直连模式必须把接口信息下发到浏览器;代理模式下 token 只留在服务端。
if ($jsCfg['mode'] === 'direct') {
$jsCfg['apiUrl'] = (string) $cfg['apiUrl'];
$jsCfg['fieldName'] = (string) $cfg['fieldName'];
$jsCfg['token'] = (string) $cfg['token'];
$jsCfg['extra'] = Util::parsePairs($cfg['extraFields'], '=');
}
$flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG
| JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
echo '<script>window.IU_CFG=' . json_encode($jsCfg, $flags) . ';</script>';
echo <<<'IUCSS'
<style>
.iu-modal { display: none; position: fixed; inset: 0; z-index: 9999; font-size: 14px; color: #444; }
.iu-modal.iu-open { display: block; }
.iu-mask { position: absolute; inset: 0; background: rgba(0,0,0,.45); }
.iu-dialog { position: relative; width: 560px; max-width: 92vw; margin: 8vh auto 0; background: #fff;
border-radius: 8px; box-shadow: 0 14px 44px rgba(0,0,0,.28); overflow: hidden; }
.iu-head { padding: 12px 16px; border-bottom: 1px solid #eee; font-size: 15px; color: #333; }
.iu-head strong { font-weight: 600; }
.iu-close { float: right; border: 0; background: none; font-size: 22px; line-height: 1;
color: #999; cursor: pointer; padding: 0 4px; }
.iu-close:hover { color: #333; }
.iu-body { padding: 16px; }
.iu-drop { border: 1px dashed #bbb; border-radius: 6px; padding: 22px 10px; text-align: center;
color: #777; background: #fafafa; cursor: pointer; transition: .15s; }
.iu-drop:hover, .iu-drop.iu-hover, #iu-box.iu-hover { border-color: #467b96; background: #f2f8fb; }
.iu-hidden { display: none; }
.iu-preview { display: block; max-width: 100%; max-height: 240px; margin: 14px auto 0;
border: 1px solid #eee; border-radius: 4px; }
.iu-meta { margin: 10px 0 0; color: #666; word-break: break-all; }
.iu-progress { display: none; height: 6px; margin-top: 12px; background: #eee; border-radius: 3px; overflow: hidden; }
.iu-progress > i { display: block; width: 0; height: 100%; background: #467b96; transition: width .15s; }
.iu-error { min-height: 1.2em; margin: 8px 0 0; color: #c0392b; word-break: break-all; }
.iu-foot { padding: 12px 16px; border-top: 1px solid #eee; text-align: right; background: #fcfcfc; }
.iu-foot .btn { margin-left: 8px; }
.iu-tip { float: left; color: #999; line-height: 30px; font-size: 12px; }
@media (max-width: 600px) { .iu-tip { display: none; } }
</style>
IUCSS;
echo <<<'IUHTML'
<div id="iu-modal" class="iu-modal">
<div class="iu-mask"></div>
<div class="iu-dialog" role="dialog" aria-modal="true" aria-label="上传图片到图床">
<div class="iu-head">
<strong>上传图片到图床</strong>
<button type="button" class="iu-close" title="关闭">&times;</button>
</div>
<div class="iu-body">
<div id="iu-drop" class="iu-drop">点击选择图片,或拖入 / Ctrl+V 粘贴</div>
<input type="file" id="iu-file" class="iu-hidden" accept="image/*">
<img id="iu-preview" class="iu-preview" alt="图片预览">
<p id="iu-meta" class="iu-meta"></p>
<div class="iu-progress"><i></i></div>
<p id="iu-error" class="iu-error"></p>
</div>
<div class="iu-foot">
<span class="iu-tip">确认后上传并插入 Markdown 到光标处</span>
<button type="button" class="btn" id="iu-cancel">取消</button>
<button type="button" class="btn primary" id="iu-confirm" disabled>确认上传</button>
</div>
</div>
</div>
IUHTML;
echo <<<'IUJS'
<script>
(function ($) {
'use strict';
var cfg = window.IU_CFG || {};
var $modal = $('#iu-modal');
var $file = $('#iu-file');
var $drop = $('#iu-drop');
var $preview = $('#iu-preview');
var $meta = $('#iu-meta');
var $error = $('#iu-error');
var $confirm = $('#iu-confirm');
var $bar = $('.iu-progress > i');
var $status = $('#iu-status');
var current = null;
var previewUrl = null;
var busy = false;
function readableSize(n) {
return n >= 1048576 ? (n / 1048576).toFixed(2) + ' MB' : Math.ceil(n / 1024) + ' KB';
}
function showError(msg) {
$error.text(msg || '');
}
function showStatus(msg, color) {
if ($status.length) {
$status.text(msg).css('color', color || '');
}
}
function reset() {
if (previewUrl) {
URL.revokeObjectURL(previewUrl);
previewUrl = null;
}
current = null;
$file.val('');
$preview.hide().removeAttr('src');
$meta.text('');
$confirm.prop('disabled', true).text('确认上传');
$('.iu-progress').hide();
$bar.css('width', '0');
showError('');
}
function open(file) {
$modal.addClass('iu-open');
if (file) {
pick(file);
}
}
function close() {
if (busy) {
return;
}
$modal.removeClass('iu-open');
reset();
}
function pick(file) {
showError('');
if (!file) {
return;
}
if (!/^image\//.test(file.type || '')) {
showError('请选择图片文件(jpg / png / gif / webp / bmp)');
return;
}
if (!file.size) {
showError('图片内容为空');
return;
}
if (file.size > (cfg.maxSize || 2) * 1048576) {
showError('图片 ' + readableSize(file.size) + ' 超过 ' + cfg.maxSize + ' MB 限制');
return;
}
if (previewUrl) {
URL.revokeObjectURL(previewUrl);
}
current = file;
previewUrl = URL.createObjectURL(file);
$preview.attr('src', previewUrl).show();
$meta.text(file.name + ' · ' + readableSize(file.size));
$confirm.prop('disabled', false);
}
// 直连模式下图床返回格式不统一,递归找出图片地址
function extractUrl(obj, depth) {
if (!obj || typeof obj !== 'object' || depth > 8) {
return null;
}
var keys = ['url', 'link', 'src', 'image', 'original'];
var i, value;
for (i = 0; i < keys.length; i++) {
value = obj[keys[i]];
if (typeof value === 'string' && /^(https?:\/\/|\/\/|\/)/i.test(value.trim())) {
return value.trim();
}
}
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var found = extractUrl(obj[key], depth + 1);
if (found) {
return found;
}
}
}
return null;
}
// 插入光标处:复用 Typecho 的 jquery.selection API,并触发 input 让草稿自动保存 / 预览刷新
function insertMarkdown(url, name) {
var $text = $('#text');
if (!$text.length) {
return false;
}
var el = $text[0];
var alt = (name || '').replace(/\.[^.]+$/, '').replace(/[\[\]()]/g, '');
var md = (cfg.template || '![%alt%](%url%)')
.replace(/%url%/g, function () { return url; })
.replace(/%alt%/g, function () { return alt; })
.replace(/%name%/g, function () { return name || ''; });
var start, end;
if ($.fn.getSelection) {
var sel = $text.getSelection();
start = sel ? sel.start : 0;
end = sel ? sel.end : 0;
} else {
start = el.selectionStart || 0;
end = el.selectionEnd || 0;
}
var text = $text.val();
var before = text.substring(0, start);
var after = text.substring(end);
var chunk = (before && !/\n$/.test(before) ? '\n' : '')
+ md
+ (after && !/^\n/.test(after) ? '\n' : '');
if ($.fn.replaceSelection) {
$text.replaceSelection(chunk);
if ($.fn.setSelection) {
$text.setSelection(start + chunk.length, start + chunk.length);
}
} else if (el.setRangeText) {
el.setRangeText(chunk, start, end, 'end');
} else {
$text.val(before + chunk + after);
}
$text.trigger('input').trigger('change');
$text.focus();
return true;
}
function finish() {
busy = false;
$confirm.prop('disabled', false).text('确认上传');
}
function upload() {
if (!current || busy) {
return;
}
busy = true;
showError('');
$confirm.prop('disabled', true).text('上传中…');
$('.iu-progress').show();
$bar.css('width', '5%');
var fd = new FormData();
var url;
if (cfg.mode === 'direct') {
url = cfg.apiUrl;
$.each(cfg.extra || {}, function (key, value) {
fd.append(key, value);
});
if (cfg.token) {
fd.append('token', cfg.token);
}
fd.append(cfg.fieldName || 'file', current, current.name);
} else {
url = cfg.actionUrl;
fd.append('image', current, current.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
$bar.css('width', Math.min(95, 5 + 70 * e.loaded / e.total) + '%');
}
};
xhr.onload = function () {
finish();
var data = null;
try {
data = JSON.parse(xhr.responseText);
} catch (e) {
data = null;
}
if (!data) {
$bar.css('width', '0');
showError('服务器返回的不是 JSON(HTTP ' + xhr.status
+ ')。常见原因:安全令牌过期或未登录,请刷新撰写页面后重试。');
return;
}
var imageUrl = (data.code == 1 && data.url) ? data.url : extractUrl(data, 0);
if (xhr.status >= 200 && xhr.status < 300 && imageUrl) {
$bar.css('width', '100%');
var name = current ? current.name : 'image';
if (insertMarkdown(imageUrl, name)) {
showStatus('已插入(' + (data.as === 'admin' ? '管理员' : '游客')
+ '):' + imageUrl, data.warn ? '#c47f00' : '#27865b');
if (data.warn) {
// 身份没生效时保留弹窗,否则自动关闭会把警告掩盖掉
showError(data.warn);
} else {
setTimeout(function () { close(); }, 300);
}
} else {
showError('已上传 ' + imageUrl + ',但未找到编辑框 #text,请手动复制该地址。');
}
} else {
$bar.css('width', '0');
showError('上传失败:' + (data.msg || ('HTTP ' + xhr.status)));
}
};
xhr.onerror = function () {
finish();
$bar.css('width', '0');
showError('网络错误或请求被浏览器拦截(跨域 / HTTPS 混合内容)。');
};
xhr.send(fd);
}
function swallow(e) {
e.preventDefault();
e.stopPropagation();
}
$('#iu-open').on('click', function () { open(); });
$drop.on('click', function () { $file.trigger('click'); });
$file.on('change', function () {
if (this.files && this.files[0]) {
pick(this.files[0]);
}
});
$confirm.on('click', upload);
$('#iu-cancel, .iu-close, .iu-mask').on('click', close);
$(document).on('keydown', function (e) {
if (e.key === 'Escape') {
close();
}
});
$(document)
.on('dragover', '#iu-box, #iu-drop', function (e) {
swallow(e);
$(this).addClass('iu-hover');
})
.on('dragleave', '#iu-box, #iu-drop', function () {
$(this).removeClass('iu-hover');
})
.on('drop', '#iu-box, #iu-drop', function (e) {
swallow(e);
$(this).removeClass('iu-hover');
var dt = e.originalEvent && e.originalEvent.dataTransfer;
if (dt && dt.files && dt.files[0]) {
open(dt.files[0]);
}
});
// 捕获阶段拦截粘贴,避免弹窗打开时同时触发 Typecho 自带的「粘贴上传到本地附件」
document.addEventListener('paste', function (e) {
if (!$modal.hasClass('iu-open')) {
return;
}
var cd = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData);
var items = cd && cd.items;
if (!items) {
return;
}
for (var i = 0; i < items.length; i++) {
if (items[i].kind === 'file' && /^image\//.test(items[i].type)) {
var file = items[i].getAsFile();
if (file) {
e.preventDefault();
e.stopPropagation();
pick(file);
return;
}
}
}
}, true);
$preview.hide();
})(jQuery);
</script>
IUJS;
}
}