…,短码到前端时会变成 {url-…}, * 所以这里先宽容地把整段收进来,再用 urlFrom() 把网址抠出来。 */ public const URL_PATTERN = '#\{url-([^{}\r\n]{1,400})\}#i'; /** 后台「引用管理」面板 */ private const PANEL_FILE = 'NiceQuote/Manage.php'; private const PANEL_INDEX = 3; private const PANEL_TITLE = '引用管理'; private const PANEL_DESC = '查看引用统计与明细,可修改、删除并同步清理正文'; /** * 编辑器弹窗搜索一次最多返回多少条 * * 只按标题匹配,命中量本身有限;上限留着是为了防止标题极短的词 * 在几十万篇的站点上把整张表拉出来,超出部分靠列表滚动查看。 */ private const SEARCH_LIMIT = 100; /** 面板是否已确认登记过(同一请求内只判断一次) */ private static bool $panelEnsured = false; /** 允许的引用类型 → Helper::widgetById 的表名 */ public const TYPES = [ 'post' => 'Contents', 'page' => 'Contents', 'comment' => 'Comments', 'user' => 'Users', 'meta' => 'Metas', 'category' => 'Metas', 'tag' => 'Metas', ]; /** 细分类型 → 卡片渲染类型 */ private const BASE = [ 'post' => 'post', 'page' => 'post', 'comment' => 'comment', 'user' => 'user', 'meta' => 'meta', 'category' => 'meta', 'tag' => 'meta', ]; /** * 细分类型归一化 * * @param string $type * @return string post|comment|user|meta */ public static function base(string $type): string { $type = strtolower($type); return self::BASE[$type] ?? $type; } /** * 从 {url-…} 的括号内文里取出网址 * * Markdown 解析器会把裸网址自动转成 …, * 短码因此可能长成 {url-https://x}。 * 两种写法都从里面抠第一个网址出来,抠不到就当作没写对。 * * @param string $inner * @return string|null */ public static function urlFrom(string $inner): ?string { if (!preg_match('#https?://[^\s"\'<>]+#i', $inner, $m)) { return null; } $url = trim(html_entity_decode($m[0], ENT_QUOTES, 'UTF-8')); $url = rtrim($url, '.,;:!?'); return '' === $url ? null : $url; } /** * 扫描一段正文里的全部引用短码 * * 代码块(pre / code)里的短码不会渲染,这里也必须跳过, * 否则后台的「引用管理」会列出根本不会显示、删了也没用的记录。 * * @param string $text * @return array */ public static function matches(string $text): array { if ('' === $text || false === strpos($text, '{')) { return []; } $parts = preg_split( '#(<(?:pre|code)\b[^>]*>.*?)#is', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); if (false === $parts) { return []; } $result = []; $offset = 0; foreach ($parts as $index => $part) { $length = strlen($part); // 奇数位是代码块,整段跳过 if (1 === $index % 2) { $offset += $length; continue; } if ('' !== $part) { $hits = []; if (preg_match_all(self::PATTERN, $part, $m, PREG_OFFSET_CAPTURE)) { foreach ($m[0] as $k => $hit) { $id = (int) $m[2][$k][0]; if ($id <= 0) { continue; } $hits[] = [ 'pos' => (int) $hit[1], 'raw' => $hit[0], 'type' => strtolower($m[1][$k][0]), 'id' => $id, 'url' => '', ]; } } if (preg_match_all(self::URL_PATTERN, $part, $m, PREG_OFFSET_CAPTURE)) { foreach ($m[0] as $k => $hit) { $url = self::urlFrom((string) $m[1][$k][0]); if (null === $url) { continue; } $hits[] = [ 'pos' => (int) $hit[1], 'raw' => $hit[0], 'type' => 'url', 'id' => 0, 'url' => $url, ]; } } // 两种短码混排时按出现位置还原顺序 usort($hits, function (array $a, array $b) { return $a['pos'] <=> $b['pos']; }); foreach ($hits as $hit) { $result[] = [ 'raw' => $hit['raw'], 'offset' => $offset + $hit['pos'], 'type' => $hit['type'], 'id' => $hit['id'], 'url' => $hit['url'], ]; } } $offset += $length; } return $result; } /** 防递归:引用卡片内部又会触发 contentEx */ private static int $depth = 0; /** 是否正在处理独立渲染入口(?NiceQuote=),此时不能再分配 Archive */ private static bool $routing = false; /** 资源是否已输出 */ private static bool $stylePrinted = false; private static bool $scriptPrinted = false; /** 配置与运行时选项的单例缓存 */ private static ?\Typecho\Config $config = null; private static ?array $options = null; /** * 激活插件 * * @return void */ public static function activate() { \Typecho\Plugin::factory('Widget_Archive')->handleInit = __CLASS__ . '::route'; \Typecho\Plugin::factory('Widget_Abstract_Contents')->contentEx = __CLASS__ . '::content'; \Typecho\Plugin::factory('admin/write-post.php')->bottom = __CLASS__ . '::editor'; \Typecho\Plugin::factory('admin/write-page.php')->bottom = __CLASS__ . '::editor'; self::ensurePanel(); } /** * 禁用插件 * * @return void */ public static function deactivate() { try { Helper::removePanel(self::PANEL_INDEX, self::PANEL_FILE); Remote::flush(); } catch (\Throwable $e) { } } /** * 前台/后台通用的「引用管理」地址 * * @param array $query 追加的查询参数 * @return string */ public static function panelUrl(array $query = []): string { $options = Helper::options(); $url = rtrim((string) $options->adminUrl, '/') . '/extending.php?panel=' . rawurlencode(self::PANEL_FILE); if (!empty($query)) { $url .= '&' . http_build_query($query); } return $url; } /** * 登记后台菜单(幂等) * * 升级过插件的站点不会重新走 activate(),所以写文章页和插件设置页也顺手补一次, * 保证菜单能在不重装插件的情况下出现。 * * @return bool */ public static function ensurePanel(): bool { if (self::$panelEnsured) { return true; } try { $table = Helper::options()->panelTable; $files = is_array($table) && isset($table['file']) ? array_map('strval', (array) $table['file']) : []; if (!in_array(urlencode(self::PANEL_FILE), $files, true)) { Helper::addPanel( self::PANEL_INDEX, self::PANEL_FILE, self::PANEL_TITLE, self::PANEL_DESC, 'administrator' ); } self::$panelEnsured = true; } catch (\Throwable $e) { return false; } return true; } /** * 插件配置面板 * * @param Form $form * @return void */ public static function config(Form $form) { // 老站升级后不会重新走 activate(),进设置页时把菜单补上 self::ensurePanel(); $form->addInput(new Select( 'mode', [ 'inline' => _t('内嵌卡片(推荐,无额外请求,样式跟随主题)'), 'iframe' => _t('框架嵌入(兼容旧版,独立渲染)'), ], 'inline', _t('渲染方式'), _t('内嵌模式直接把卡片写进正文,SEO 友好、不额外发请求;框架模式与 1.x 行为一致。') )); $form->addInput(new Select( 'skin', [ 'auto' => _t('跟随站点(推荐)'), 'dark' => _t('强制深色'), 'light' => _t('强制浅色'), ], 'auto', _t('配色'), _t('内嵌模式下「跟随站点」使用半透明背景,浅色深色主题都能自适应。') )); $form->addInput(new Text( 'accent', null, '#c0580c', _t('主色'), _t('标题与悬停边框的颜色,支持 #hex、rgb()、hsl(),例如 #c0580c。') )); $form->addInput(new Text( 'radius', null, '10', _t('圆角(px)'), _t('卡片圆角,填数字即可,例如 10。') )); // 兼容老配置:2.4 之前保存过 target,表单里少了这个键,设置页取值会报错。 // 2.5 起引用卡片固定在新窗口打开(用户引用没有链接),这里只留一个占位字段。 $form->addInput(new Hidden('target', null, '_blank')); $form->addInput(new Text( 'len', null, '120', _t('摘要字数'), _t('卡片描述最多显示多少个字,建议 60–160。') )); $form->addInput(new Select( 'feed', [ 'keep' => _t('保留短码'), 'text' => _t('输出纯链接'), 'card' => _t('输出卡片'), ], 'keep', _t('Feed / RSS 中的处理'), _t('订阅端多数不支持样式,建议「保留短码」或「输出纯链接」。') )); $form->addInput(new Text( 'fail', null, '引用内容不存在或已被删除', _t('失效提示'), _t('引用的内容被删除、未过审或未发布时显示的文字。') )); $form->addInput(new Text( 'per', null, '20', _t('引用管理每页条数'), _t('「引用管理」列表每页显示多少条,建议 10–50,允许 5–200。') )); } /** * 个人用户配置面板 * * @param Form $form * @return void */ public static function personalConfig(Form $form) { } /** * 读取插件配置(兼容尚未保存配置的情况) * * @return \Typecho\Config */ private static function cfg(): \Typecho\Config { if (null === self::$config) { try { self::$config = Helper::options()->plugin('NiceQuote'); } catch (\Throwable $e) { self::$config = new \Typecho\Config([]); } } return self::$config; } /** * 读取单个配置项 * * @param string $key * @param mixed $default * @return mixed */ private static function opt(string $key, $default = null) { $value = self::cfg()->{$key}; return (null === $value || '' === $value) ? $default : $value; } /** * 归一化后的运行时选项,供 Renderer 与 post.php 共用 * * @return array */ public static function options(): array { if (null !== self::$options) { return self::$options; } $accent = (string) self::opt('accent', '#c0580c'); if (!preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\([0-9.,%\s]+\)|hsla?\([0-9.,%\s]+\))$/', $accent)) { $accent = '#c0580c'; } $skin = self::opt('skin', 'auto'); if (!in_array($skin, ['auto', 'dark', 'light'], true)) { $skin = 'auto'; } self::$options = [ 'mode' => 'iframe' === self::opt('mode', 'inline') ? 'iframe' : 'inline', 'skin' => $skin, 'accent' => $accent, 'radius' => max(0, min(40, (int) self::opt('radius', 10))), 'len' => max(20, min(400, (int) self::opt('len', 120))), 'per' => max(5, min(200, (int) self::opt('per', 20))), 'fail' => (string) self::opt('fail', '引用内容不存在或已被删除'), 'pluginUrl' => (string) Helper::options()->pluginUrl . '/NiceQuote', 'version' => '2.10.0', ]; return self::$options; } /** * 正文过滤器:把短码替换成卡片 * * @param string $text * @param mixed $widget * @param string|null $last * @return string */ public static function content($text, $widget = null, $last = null) { $text = (string) (null === $last || '' === $last ? $text : $last); if ('' === $text || false === strpos($text, '{')) { return $text; } if (!preg_match(self::PATTERN, $text) && !preg_match(self::URL_PATTERN, $text)) { return $text; } // 引用卡片内部渲染正文时会再次进入本过滤器,直接放行,避免自我递归 if (self::$depth > 0) { return $text; } // 正在读取被引用内容的正文(Renderer::fetch),此时替换短码既没用也会递归 if (Renderer::busy()) { return $text; } $mode = self::options()['mode']; // Feed 里另走一套策略 if (self::inFeed()) { $feed = self::opt('feed', 'keep'); if ('keep' === $feed) { return $text; } $mode = 'card' === $feed ? 'inline' : 'text'; } $usedStyle = false; $usedFrame = false; $items = []; self::$depth++; try { $options = self::options(); // 代码块内的短码原样保留,方便写教程时举例 $parts = preg_split( '#(<(?:pre|code)\b[^>]*>.*?)#is', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); if (false === $parts) { return $text; } foreach ($parts as $index => $part) { if (1 === $index % 2) { continue; } $parts[$index] = preg_replace_callback( self::PATTERN, function (array $m) use ($mode, $options, &$usedStyle, &$usedFrame, &$items) { $type = strtolower($m[1]); $id = (int) $m[2]; if ($id <= 0) { return $m[0]; } if ('text' === $mode) { return Renderer::plain($type, $id) ?? $m[0]; } if ('iframe' === $mode) { $usedFrame = true; $html = self::frame($type, $id); } else { $usedStyle = true; $html = Renderer::render($type, $id, $options); // 失效引用就地显示提示,不参与下面的列表分组 if (false !== strpos($html, 'nq-missing')) { return $html; } } // 先落地成占位符,等整段替换完再判断哪些引用是连续排列的 $token = "\x02NQ" . count($items) . "\x03"; $items[$token] = ['html' => $html, 'type' => $type]; return $token; }, $part ); // 外部链接引用:{url-https://...} $parts[$index] = preg_replace_callback( self::URL_PATTERN, function (array $m) use ($mode, $options, &$usedStyle, &$usedFrame, &$items) { $url = self::urlFrom((string) $m[1]); if (null === $url) { return $m[0]; } if ('text' === $mode) { return Renderer::plain('url', 0, $url) ?? $m[0]; } if ('iframe' === $mode) { $usedFrame = true; $html = self::frame('url', 0, $url); } else { $usedStyle = true; $html = Renderer::renderUrl($url, $options); } $token = "\x02NQ" . count($items) . "\x03"; $items[$token] = ['html' => $html, 'type' => 'url']; return $token; }, $parts[$index] ); } $html = implode('', $parts); if (!empty($items)) { $html = self::group($html, $items); $html = self::tidy($html); } if ($usedStyle) { $html = self::style() . $html; } if ($usedFrame) { $html .= self::script(); } return $html; } finally { self::$depth--; } } /** * 把连续的多个引用合并成一个列表 * * 只有「相邻、中间仅隔空白或换行」的引用才算一组; * 中间夹了别的内容就各算各的,避免把整篇文章的引用都串成一大块。 * * @param string $html * @param array $items 占位符 => ['html' => string, 'type' => string] * @return string */ private static function group(string $html, array $items): string { $parts = preg_split('#(\x02NQ\d+\x03)#', $html, -1, PREG_SPLIT_DELIM_CAPTURE); if (!is_array($parts)) { return strtr($html, array_map(fn(array $item) => $item['html'], $items)); } $out = ''; $run = []; foreach ($parts as $part) { if (isset($items[$part])) { // 相邻的引用继续并进同一组,中间的空隙本来就要丢掉 $run[] = $part; continue; } if (empty($run)) { $out .= $part; } elseif (self::isGap($part)) { // 只是空白,先记着这组还没结束 continue; } else { $out .= self::emit($run, $items) . $part; $run = []; } } if (!empty($run)) { $out .= self::emit($run, $items); } return $out; } /** * 两个引用之间是否只隔了空白 * * 非 Markdown 正文会被 nl2br 成
,Markdown 则多半是裸换行,两种都要认。 * * @param string $text * @return bool */ private static function isGap(string $text): bool { return (bool) preg_match('#^(?:\s| |)*$#i', $text); } /** * 收拾卡片两侧多余的换行 * * 短码通常单独占一行,Markdown(或 AutoP)会把那一行的换行渲染成
; * 卡片本身是块级元素、又自带上下边距,多出来的
只会让它下面凭空空一行。 * 这里只删「紧贴卡片」的那几个,正文别处的换行不动。 * * @param string $html * @return string */ private static function tidy(string $html): string { $card = '(?:]*>\s*)'; // 卡片后面的
(单个引用,以及一组引用的最后一张) $html = preg_replace_callback( '#(' . $card . ')(\s*(?:\s*)+)#is', static function (array $m): string { return $m[1]; }, $html ) ?? $html; // 一组引用的末尾隔着 ,单独认一次 $html = preg_replace_callback( '#(' . $card . '\s*)(\s*(?:\s*)+)#is', static function (array $m): string { return $m[1]; }, $html ) ?? $html; // 卡片前面的
$html = preg_replace( '#(?:\s*)+(?=' . $card . '| 里,块级元素会被浏览器提前闭合 return '' . $body . ''; } /** * 卡片样式(每页只输出一次) * * @return string */ private static function style(): string { if (self::$stylePrinted) { return ''; } self::$stylePrinted = true; $options = self::options(); $css = @file_get_contents(__DIR__ . '/assets/card.css'); if (false === $css) { $css = ''; } return ''; } /** * iframe 高度自适应脚本(每页只输出一次) * * @return string */ private static function script(): string { if (self::$scriptPrinted) { return ''; } self::$scriptPrinted = true; return ''; } /** * 生成 iframe 引用 * * @param string $type * @param int $id * @param string $url 外部链接引用时使用 * @return string */ private static function frame(string $type, int $id, string $url = ''): string { $options = Helper::options(); $base = $options->index; $query = 'url' === $type ? 'NiceQuote=url&qurl=' . rawurlencode($url) : 'NiceQuote=' . $type . '&qid=' . $id; $link = $base . (false === strpos($base, '?') ? '?' : '&') . $query; return ''; } /** * 是否正在渲染 Feed * * 注意:这里不能调用 Widget\Archive::alloc(),它每次都会新建一个 Archive * 实例并跑一遍 execute(),从而再次触发 handleInit → route(),造成自递归。 * * @return bool */ private static function inFeed(): bool { static $inFeed = null; if (null !== $inFeed) { return $inFeed; } $inFeed = false; if (self::$routing) { return $inFeed; } try { $path = (string) \Typecho\Request::getInstance()->getPathInfo(); $inFeed = (bool) preg_match('#(^|/)feed(/|$)#i', $path); } catch (\Throwable $e) { $inFeed = false; } return $inFeed; } /** * 独立渲染入口:?NiceQuote=post&qid=1 * * @param mixed $archive * @param mixed $select * @return void */ public static function route($archive = null, $select = null) { $request = \Typecho\Request::getInstance(); // 后台编辑器的搜索接口 if (null !== $request->nqSearch) { self::search((string) $request->nqSearch, strtolower((string) $request->nqKind)); } // 后台编辑器插入外部链接时,先问一下标题摘要 if (null !== $request->nqUrl) { self::remoteJson((string) $request->nqUrl); } $type = $request->NiceQuote; if (null === $type || '' === $type) { return; } $type = strtolower((string) $type); // 外部链接引用单独一条路:认网址,不认 ID if ('url' === $type) { $url = trim((string) $request->qurl); if ('' === $url) { self::plain(_t('引用网址不能为空'), 400); } if (!Remote::valid($url)) { self::plain(_t('引用网址无效'), 400); } $nqType = 'url'; $nqId = 0; $nqUrl = $url; self::$routing = true; include __DIR__ . '/post.php'; exit; } if (!isset(self::TYPES[$type])) { self::plain(_t('引用类型不存在'), 404); } $id = (int) $request->qid; if ($id <= 0) { self::plain(_t('引用 ID 无效'), 400); } $nqType = $type; $nqId = $id; self::$routing = true; include __DIR__ . '/post.php'; exit; } /** * 输出纯文本并结束 * * @param string $message * @param int $status * @return void */ private static function plain(string $message, int $status = 200) { \Typecho\Response::getInstance()->setStatus($status)->setContentType('text/plain'); echo $message; exit; } /** * 后台编辑器搜索:按类型分别查文章 / 页面 / 评论 / 用户 / 分类 / 标签 * * 类型之间互不合并,避免「文章」里混进页面、「分类」里混进标签。 * * 只匹配标题(评论没有标题,匹配列表里显示的正文摘要),不搜正文; * 结果按时间倒序,最多 SEARCH_LIMIT 条,多出来的由前端滚动查看。 * * @param string $keyword * @param string $kind post|page|comment|user|category|tag,空表示全部 * @return void */ private static function search(string $keyword, string $kind = '') { try { $user = \Widget\User::alloc(); if (!$user->hasLogin() || !$user->pass('contributor', true)) { self::json(['items' => [], 'error' => 'forbidden'], 403); } } catch (\Throwable $e) { self::json(['items' => [], 'error' => 'forbidden'], 403); } if (!in_array($kind, ['post', 'page', 'comment', 'user', 'category', 'tag'], true)) { $kind = ''; } $keyword = trim($keyword); $items = []; if ('' !== $keyword) { $db = \Typecho\Db::get(); $like = '%' . $keyword . '%'; $isId = ctype_digit($keyword); try { if ('' === $kind || 'post' === $kind || 'page' === $kind) { $select = $db->select('cid', 'title', 'type', 'created') ->from('table.contents'); if ('' === $kind) { $select->where('type IN ?', ['post', 'page']); } else { $select->where('type = ?', $kind); } if ($isId) { $select->where('(cid = ? OR title LIKE ?)', (int) $keyword, $like); } else { $select->where('title LIKE ?', $like); } // 时间越近越靠前:先按发布时间倒序,同秒再按 cid 倒序 $select->order('created', \Typecho\Db::SORT_DESC) ->order('cid', \Typecho\Db::SORT_DESC); foreach ($db->fetchAll($select->limit(self::SEARCH_LIMIT)) as $row) { $items[] = [ 'type' => 'page' === $row['type'] ? 'page' : 'post', 'id' => (int) $row['cid'], 'title' => (string) $row['title'], 'extra' => 'page' === $row['type'] ? _t('页面') : _t('文章'), 'date' => self::day((int) $row['created']), ]; } } if ('' === $kind || 'category' === $kind || 'tag' === $kind) { $select = $db->select('mid', 'name', 'type', 'count') ->from('table.metas'); if ('' === $kind) { $select->where('type IN ?', ['category', 'tag']); } else { $select->where('type = ?', $kind); } if ($isId) { $select->where('(mid = ? OR name LIKE ?)', (int) $keyword, $like); } else { $select->where('name LIKE ?', $like); } // 分类 / 标签没有时间字段,用 mid 倒序近似「最近创建的在前」 $select->order('mid', \Typecho\Db::SORT_DESC); foreach ($db->fetchAll($select->limit(self::SEARCH_LIMIT)) as $row) { $items[] = [ 'type' => 'tag' === $row['type'] ? 'tag' : 'category', 'id' => (int) $row['mid'], 'title' => (string) $row['name'], 'extra' => ('tag' === $row['type'] ? _t('标签') : _t('分类')) . ' · ' . _t('%d 篇', (int) $row['count']), 'date' => '', ]; } } if ('' === $kind || 'user' === $kind) { $select = $db->select('uid', 'name', 'screenName', 'created') ->from('table.users'); if ($isId) { $select->where('(uid = ? OR name LIKE ? OR screenName LIKE ?)', (int) $keyword, $like, $like); } else { $select->where('name LIKE ? OR screenName LIKE ?', $like, $like); } // 最近注册的用户在前 $select->order('created', \Typecho\Db::SORT_DESC) ->order('uid', \Typecho\Db::SORT_DESC); foreach ($db->fetchAll($select->limit(self::SEARCH_LIMIT)) as $row) { $items[] = [ 'type' => 'user', 'id' => (int) $row['uid'], 'title' => (string) ($row['screenName'] ?: $row['name']), 'extra' => _t('用户') . ' · ' . $row['name'], 'date' => self::day((int) $row['created']), ]; } } if ('' === $kind || 'comment' === $kind) { $select = $db->select('coid', 'author', 'text', 'created') ->from('table.comments') ->where('status = ?', 'approved'); // 评论没有标题,列表里显示的就是正文摘要,因此只按正文匹配 //(作者名是右侧的附属信息,不再参与搜索) if ($isId) { $select->where('(coid = ? OR text LIKE ?)', (int) $keyword, $like); } else { $select->where('text LIKE ?', $like); } // 最新评论在前 $select->order('created', \Typecho\Db::SORT_DESC) ->order('coid', \Typecho\Db::SORT_DESC); foreach ($db->fetchAll($select->limit(self::SEARCH_LIMIT)) as $row) { $author = trim((string) $row['author']); $items[] = [ 'type' => 'comment', 'id' => (int) $row['coid'], 'title' => \Typecho\Common::subStr( trim(strip_tags((string) $row['text'])), 0, 28, '…' ), 'extra' => _t('评论') . ' · ' . ('' === $author ? _t('匿名') : $author), 'date' => self::day((int) $row['created']), ]; } } } catch (\Throwable $e) { self::json(['items' => [], 'error' => 'query'], 500); } } self::json(['items' => $items]); } /** * 时间戳 → 站点时区的「Y-m-d」,用于搜索结果右侧的日期 * * @param int $time * @return string 时间为空或无法格式化时返回空串 */ private static function day(int $time): string { if ($time <= 0) { return ''; } try { return (new \Typecho\Date($time))->format('Y-m-d'); } catch (\Throwable $e) { return ''; } } /** * 后台编辑器:抓一个外部链接的标题与摘要 * * 抓不到也不算失败 —— 前端拿不到标题时用网址兜底,照样能插进正文。 * * @param string $url * @return void */ private static function remoteJson(string $url) { try { $user = \Widget\User::alloc(); if (!$user->hasLogin() || !$user->pass('contributor', true)) { self::json(['error' => 'forbidden'], 403); } } catch (\Throwable $e) { self::json(['error' => 'forbidden'], 403); } $url = trim($url); if (!Remote::valid($url)) { self::json(['error' => 'invalid', 'message' => _t('网址格式不正确')], 400); } $meta = Remote::meta($url); if (null === $meta) { self::json([ 'error' => 'fetch', 'message' => _t('没能读取这个网址的标题,仍可插入链接'), 'url' => $url, ]); } self::json([ 'url' => (string) ($meta['url'] ?? $url), 'title' => (string) ($meta['title'] ?? ''), 'desc' => (string) ($meta['desc'] ?? ''), 'date' => (string) ($meta['date'] ?? ''), 'site' => (string) ($meta['site'] ?? ''), ]); } /** * 输出 JSON 并结束 * * @param array $data * @param int $status * @return void */ private static function json(array $data, int $status = 200) { \Typecho\Response::getInstance()->setStatus($status)->setContentType('application/json'); echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } /** * 后台写作页注入引用按钮 * * @return void */ public static function editor() { // 升级过插件的站点:打开写作页时补登记后台菜单 self::ensurePanel(); $options = Helper::options(); $base = $options->pluginUrl . '/NiceQuote'; $ver = self::options()['version']; $config = [ 'index' => (string) $options->index, 'plugin' => (string) $base, 'mode' => self::options()['mode'], 'panel' => self::panelUrl(), ]; echo '' . "\n"; echo '' . "\n"; echo '' . "\n"; echo '' . "\n"; } }