diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..e1f6429
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,9 @@
+# 统一按 LF 存储,避免 Windows 检出成 CRLF 后部署到 Linux 出问题
+* text=auto eol=lf
+
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.webp binary
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2a53530
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+# ---- 测试沙箱与临时产物 ----
+.ti_setting_tmp/
+.ti_*/
+*.tmp
+*.tmp.js
+/js_*.js
+
+# ---- 本地环境 ----
+.DS_Store
+Thumbs.db
+*.log
diff --git a/Action.php b/Action.php
new file mode 100644
index 0000000..ead2274
--- /dev/null
+++ b/Action.php
@@ -0,0 +1,497 @@
+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;
+ }
+}
diff --git a/Plugin.php b/Plugin.php
new file mode 100644
index 0000000..73c5b52
--- /dev/null
+++ b/Plugin.php
@@ -0,0 +1,807 @@
+ 确认 -> 上传到自建 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' => '',
+ ];
+
+ 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% 原文件名。想和极简图床页面完全一致可填 。')
+ );
+ $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 = ''
+ . ''
+ . ''
+ . ''
+ . ''
+ . _t('测试会读取上方输入框里的 Token(无需先保存),验证图床是否认这个 Token,并返回图床版本与管理员目录。')
+ . '';
+
+ if ($testUrl === '') {
+ return $html . '' . _t('无法生成安全令牌,请刷新设置页后重试') . '';
+ }
+
+ $js = <<<'TIJS'
+
+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 ' ' . _t('选图并确认后上传到自建图床,自动把 Markdown 插入光标处;也可拖入图片或在弹窗内 Ctrl+V 粘贴。单张不超过 ')
+ . $limit . ' MB。 '
+ . _t('当前站点未开启 Markdown,插入的图片语法可能不会被解析。') . ' ' . _t('图床身份:') . '' . $identity . '';
+ if ($missing) {
+ echo ' ' . $hint . '';
+ }
+ echo ' '
+ . _t('插件设置里的「图床上传接口地址」仍是占位值,请先改成你的实际地址,并用「测试连接」验证。')
+ . '