From 30e75c8a75c084a5b87fd2336b56aac38cbc448b Mon Sep 17 00:00:00 2001
From: XIGE <710062962@qq.com>
Date: Thu, 26 Nov 2026 15:25:08 +0800
Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?=
=?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?=
=?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 24 +
CHANGELOG.md | 45 +
CONTRIBUTING.md | 19 +
LICENSE | 21 +
Plugin.php | 2641 +++++++++++++++++++++++++++++++++++++++++++++++
README.md | 48 +-
6 files changed, 2797 insertions(+), 1 deletion(-)
create mode 100644 .gitignore
create mode 100644 CHANGELOG.md
create mode 100644 CONTRIBUTING.md
create mode 100644 LICENSE
create mode 100644 Plugin.php
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8d7d96a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,24 @@
+# Runtime data, cache and logs
+data/
+cache/
+*.log
+
+# Backups and temporary files
+备份/
+*.bak
+*.tmp
+.DS_Store
+
+# Environment and secrets
+.env
+.env.*
+*key*.txt
+credentials*.json
+
+# Editor and build artifacts
+.idea/
+.vscode/
+node_modules/
+vendor/
+dist/
+build/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..58b9192
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,45 @@
+# ExtMenu 更新日志
+
+> 本文件记录本插件的所有修改与变化。本次整理(2026-11-22)为规范化记录起点。
+
+## 插件信息
+
+- 名称:扩展管理
+- 版本:1.4.0
+- 作者:石头厝
+- 说明:后台菜单改名/排序/图标/显隐,插件面板收进「扩展管理」,设置可备份恢复
+
+## 记录格式约定
+
+每次修改按如下格式在**最上方**追加一条记录(新的在上):
+
+```
+## YYYY-MM-DD · 版本号 —— 一句话概述
+
+- 改动点 1
+- 改动点 2
+- 影响范围 / 注意事项(若有)
+- 对应备份:备份/YYYY-MM-DD-修改内容简短说明修改前/
+```
+
+## 2026-11-22 · 1.4.0 —— 补齐头部版本与链接
+
+- `Plugin.php` 文件头注释(Typecho 后台插件信息读取的第一段)补齐 `@version 1.4.0`、`@link https://www.shitoucuo.com/`
+- 版本号取自本插件更新日志既有版本(类注释中已有同值),后台插件列表版本显示不再为空
+- 另将 `@link` 补上末尾斜杠,与其他插件统一
+- 对应备份:`备份/2026-11-22-补版本和链接修改前/`
+
+## 2026-11-22 · 1.4.0 —— 统一作者与链接
+
+- `Plugin.php` 头部 `@author` 统一为「石头厝」
+- `@link` 统一为 `https://www.shitoucuo.com/`
+- 影响范围:仅头部元信息,不涉及功能代码
+- 对应备份:`备份/2026-11-22-统一作者和链接修改前/`
+
+---
+
+## 2026-11-22 · 1.4.0 —— 建立规范化备份与更新日志
+
+- 建立 `备份/` 文件夹并生成本次整理前全量备份 `备份/2026-11-22-规范化整理修改前/`
+- 创建本更新日志,作为后续所有修改的记录起点
+- 说明:本次仅做规范化整理,未改动插件功能代码
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..0a57600
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,19 @@
+# 贡献指南
+
+欢迎对本项目提出改进建议或提交代码。
+
+## 提交前检查
+
+- 仅提交插件实现代码、静态资源与必要文档;不要提交 `data/`、`cache/`、调试日志、备份目录或 API Key 等敏感信息。
+- 变更涉及 Typecho 钩子或 PHP 版本兼容时,请确认兼容 Typecho 1.3 与 PHP 8.5。
+- 影响用户配置或后台展示的改动,请同步更新 `README.md` 与 `CHANGELOG.md`。
+
+## 提交流程
+
+1. Fork 仓库并创建功能分支。
+2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
+3. 重要变更请补充变更记录。
+
+## 问题反馈
+
+请通过仓库 Issue 反馈问题,并附上插件版本、Typecho / PHP 版本与复现步骤。
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..7951bd8
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 石头厝
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Plugin.php b/Plugin.php
new file mode 100644
index 0000000..e804012
--- /dev/null
+++ b/Plugin.php
@@ -0,0 +1,2641 @@
+ 默认名称) */
+ private static $coreMenus = array(1 => '控制台', 2 => '撰写', 3 => '管理', 4 => '设置');
+
+ /**
+ * 核心菜单下的二级菜单
+ *
+ * 每项是 [原版后台的名称, 链接, 美化后台里的名称],链接必须和 Widget\Menu /
+ * NewAdmin 里写的完全一致 —— 二级菜单的标识由「父级 + 链接」算出来,对不上就被
+ * 当成另一项了。
+ *
+ * 这里只列平时可见的项。编辑文章、分类编辑、附件编辑这类「只在对应页面出现」的
+ * 上下文菜单不列:它们的名字本身就是内容标题,改名和排序都没有意义,
+ * 渲染时也原样跳过(见 mapChildren)。
+ *
+ * @var array
+ */
+ private static $coreChildren = array(
+ 1 => array(
+ array('概要', 'index.php'),
+ array('个人设置', 'profile.php', '设置'),
+ array('插件', 'plugins.php'),
+ array('外观', 'themes.php'),
+ array('备份', 'backup.php'),
+ ),
+ 2 => array(
+ array('撰写文章', 'write-post.php'),
+ array('创建页面', 'write-page.php'),
+ ),
+ 3 => array(
+ array('文章', 'manage-posts.php'),
+ array('独立页面', 'manage-pages.php', '页面'),
+ array('评论', 'manage-comments.php'),
+ array('分类', 'manage-categories.php'),
+ array('标签', 'manage-tags.php'),
+ array('文件', 'manage-medias.php'),
+ array('用户', 'manage-users.php'),
+ ),
+ 4 => array(
+ array('基本', 'options-general.php'),
+ array('评论', 'options-discussion.php'),
+ array('阅读', 'options-reading.php'),
+ array('永久链接', 'options-permalink.php', '链接'),
+ ),
+ );
+
+ /**
+ * 菜单树缓存(顶级 id => 定义)
+ *
+ * @var array|null
+ */
+ private static $tree = null;
+
+ /**
+ * 二级菜单默认值索引(二级 id => 定义)
+ *
+ * @var array|null
+ */
+ private static $kidIndex = null;
+
+ /**
+ * 当前是否装了美化后台 NewAdmin(缓存)
+ *
+ * @var bool|null
+ */
+ private static $newAdmin = null;
+
+ /**
+ * NewAdmin 图标雪碧图里可用的菜单图标
+ *
+ * @var array
+ */
+ private static $icons = array(
+ '' => '跟随默认',
+ 'dianpu' => '店铺 / 应用',
+ 'faxian' => '发现',
+ 'guanyingjilu' => '列表记录',
+ 'daichuli' => '待处理',
+ 'jiankong' => '监控',
+ 'huiyi' => '会议',
+ 'duizhang' => '对账',
+ 'huiyuanka' => '卡片',
+ 'pingtai' => '平台',
+ 'bianji' => '编辑',
+ 'qiyeguanli' => '企业管理',
+ 'shezhi' => '设置',
+ 'shouye' => '首页',
+ 'yinle' => '音乐',
+ );
+
+ /**
+ * 启用插件
+ *
+ * 注意:钩子必须在这里注册。Typecho 是在 activate() 返回之后才调用
+ * Plugin::export() 落库的,写在别处(比如 __construct)不会被记住。
+ */
+ public static function activate()
+ {
+ if (!self::supported()) {
+ throw new \Typecho\Plugin\Exception(
+ '当前 Typecho 版本不支持自定义主菜单,本插件需要 1.3.0 及以上'
+ );
+ }
+
+ Typecho_Plugin::factory('admin/common.php')->begin = array(__CLASS__, 'onAdminBegin');
+ Typecho_Plugin::factory('admin/header.php')->header = array(__CLASS__, 'onAdminHeader');
+ Typecho_Plugin::factory('admin/menu.php')->nodes = array(__CLASS__, 'onMenuNodes');
+
+ $moved = self::collect();
+
+ return '「' . self::MENU_NAME . '」菜单已建立'
+ . ($moved > 0 ? ',已收纳 ' . $moved . ' 个插件面板' : '(当前没有需要收纳的面板)');
+ }
+
+ /**
+ * 禁用插件
+ *
+ * 面板不能留在已经消失的父菜单里,统一放回「管理」,
+ * 免得插件停用后这些页面在后台彻底找不回来。
+ */
+ public static function deactivate()
+ {
+ $count = self::restore();
+
+ return '「' . self::MENU_NAME . '」菜单已移除'
+ . ($count > 0 ? ',' . $count . ' 个面板已放回「管理」' : '');
+ }
+
+ public static function config(Typecho_Widget_Helper_Form $form)
+ {
+ // 顶部卡片:设置备份 / 恢复。只是纯 HTML,按钮走本页的 GET 动作,
+ // 不嵌第二层 form(Typecho 的保存表单里套 form 是非法 HTML,浏览器会拆掉)
+ $hero = new Typecho_Widget_Helper_Layout();
+ $hero->html(self::heroCardHtml());
+ $form->addItem($hero);
+
+ $form->addInput(new Typecho_Widget_Helper_Form_Element_Radio(
+ 'autoCollect',
+ array('1' => '自动收纳', '0' => '不自动收纳'),
+ '1',
+ '自动收纳新插件的面板',
+ '开启后,之后启用新插件时它注册的面板会被自动挪进「' . self::MENU_NAME . '」;'
+ . '关闭则只保留本次收纳的结果,新面板仍落在原菜单下。'
+ ));
+
+ // ---- 顶级菜单 + 它下面的二级菜单 ----
+ foreach (self::treeDefs() as $id => $def) {
+ $label = $def['n'];
+
+ self::addText($form, 'mn_' . $id, $label . ' · 显示名称', '留空保持原名');
+ self::addOrder($form, 'mo_' . $id, $label . ' · 排序', $def['o']);
+ self::addIcon($form, 'mi_' . $id, $label . ' · 图标');
+ self::addVisible($form, 'mv_' . $id, $label . ' · 显示');
+
+ foreach ($def['kids'] as $kid => $kd) {
+ $sub = $label . ' » ' . $kd['n'];
+
+ self::addText(
+ $form,
+ 'cn_' . $kid,
+ $sub . ' · 显示名称',
+ '留空保持原名',
+ self::childOpt('n', $kid, '')
+ );
+ self::addOrder(
+ $form,
+ 'co_' . $kid,
+ $sub . ' · 排序',
+ $kd['o'],
+ self::childOpt('o', $kid, '')
+ );
+ self::addVisible(
+ $form,
+ 'cv_' . $kid,
+ $sub . ' · 显示',
+ self::childOpt('v', $kid, '1')
+ );
+ }
+ }
+
+ // 历史遗留的配置键(比如插件被删掉后留下的 cn_xxx)在这里补一个隐藏域,
+ // 否则 Widget\Plugins\Config 用 getInput() 取不到字段会直接报错。
+ $added = $form->getInputs();
+
+ foreach (self::storedConfig() as $key => $value) {
+ if (!isset($added[$key]) && (is_scalar($value) || null === $value)) {
+ $form->addInput(new Typecho_Widget_Helper_Form_Element_Hidden($key, null, (string) $value));
+ $added[$key] = true;
+ }
+ }
+ }
+
+ public static function personalConfig(Typecho_Widget_Helper_Form $form)
+ {
+ }
+
+ /* ------------------------------------------------------------------
+ * 设置备份 / 恢复
+ * ---------------------------------------------------------------- */
+
+ /**
+ * 处理设置页顶部「备份 / 恢复 / 历史备份」的点击
+ *
+ * 既不新增路由(不用写 routingTable,覆盖升级也不用重新启用插件),
+ * 也不在保存表单里再嵌一层 form(Typecho 的保存表单里套 form 是非法 HTML,
+ * 浏览器会把内层拆掉,点备份反而变成一次「保存设置」)。
+ * 做法是按钮直接带参数访问本页,处理完 302 回本页,用 _em 参数把结果交给
+ * heroCardHtml() 显示。
+ */
+ private static function handleSettingsAction()
+ {
+ if (!isset($_GET['_em']) || !is_scalar($_GET['_em'])) {
+ return;
+ }
+
+ $do = trim((string) $_GET['_em']);
+
+ // 只认识 backup / restore。其余(含跳回来时带的 backup_ok / restore_fail 之类)
+ // 一律不处理,直接把页面渲染出来 —— 那些只是给提示条读的结果参数,
+ // 再跳一次就会自己追自己,变成死循环。
+ if ('backup' !== $do && 'restore' !== $do) {
+ return;
+ }
+
+ // 插件设置页本身就要管理员权限,这里再判一次,防的是
+ // 「页面已经打开、中途换了账号」这类边界情况
+ $user = \Widget\User::alloc();
+
+ if (!$user || !$user->pass('administrator', true)) {
+ self::go('_em=auth');
+ }
+
+ $token = isset($_GET['_t']) && is_scalar($_GET['_t']) ? (string) $_GET['_t'] : '';
+
+ if ('' === self::token() || !hash_equals(self::token(), $token)) {
+ self::go('_em=token');
+ }
+
+ if ('backup' === $do) {
+ $result = self::doBackup();
+
+ if (!empty($result['ok'])) {
+ self::go(
+ '_em=backup_ok&n=' . (int) $result['count']
+ . '&t=' . (int) $result['created']
+ . '&f=' . (int) $result['total']
+ );
+ }
+
+ self::go('_em=backup_fail&detail=' . rawurlencode((string) $result['message']));
+ }
+
+ if ('restore' === $do) {
+ // 不传 file 就是恢复最新一份;传了由 doRestore() 再校验文件名
+ $file = isset($_GET['file']) && is_scalar($_GET['file']) ? trim((string) $_GET['file']) : '';
+ $result = self::doRestore($file);
+
+ if (!empty($result['ok'])) {
+ self::go('_em=restore_ok&n=' . (int) $result['count'] . '&t=' . (int) $result['created']);
+ }
+
+ self::go('_em=restore_fail&detail=' . rawurlencode((string) $result['message']));
+ }
+ }
+
+ /**
+ * 302 回设置页
+ *
+ * 不能只用 header('Location: ...'):Typecho 用 ob_start 的回调在输出结束时统一
+ * 发送响应头(Typecho\Response::sendHeaders()),那里会把状态码按 Response 自己
+ * 记的值重发一遍,默认 200,位置头还在但浏览器不会跳。所以状态码和位置头都交给
+ * Response 记,让它自己发。
+ */
+ private static function go($query)
+ {
+ $url = self::configUrl($query);
+
+ try {
+ $response = \Typecho\Response::getInstance();
+ $response->setStatus(302);
+ $response->setHeader('Location', $url);
+ } catch (\Throwable $e) {
+ header('Location: ' . $url, true, 302);
+ }
+
+ exit;
+ }
+
+ /**
+ * 本插件设置页地址
+ */
+ private static function configUrl($query = '')
+ {
+ $adminUrl = '';
+
+ try {
+ $adminUrl = rtrim((string) Helper::options()->adminUrl, '/') . '/';
+ } catch (\Throwable $e) {
+ $adminUrl = '';
+ }
+
+ $url = $adminUrl . 'options-plugin.php?config=ExtMenu';
+
+ if ('' !== $query) {
+ $url .= '&' . ltrim($query, '&');
+ }
+
+ return $url;
+ }
+
+ /**
+ * 备份 / 恢复用的令牌
+ *
+ * 用站点 secret + 当前用户 uid 算,别人拿到链接也伪造不出来;
+ * 没登录时返回空串,调用方会当成校验失败。
+ */
+ private static function token()
+ {
+ $uid = 0;
+
+ try {
+ $user = \Widget\User::alloc();
+
+ if ($user && $user->hasLogin()) {
+ $uid = (int) $user->uid;
+ }
+ } catch (\Throwable $e) {
+ $uid = 0;
+ }
+
+ if ($uid <= 0) {
+ return '';
+ }
+
+ try {
+ $secret = (string) Helper::options()->secret;
+ } catch (\Throwable $e) {
+ $secret = '';
+ }
+
+ if ('' === $secret) {
+ $secret = __FILE__;
+ }
+
+ return substr(hash_hmac('sha256', 'ExtMenu|' . $uid, $secret), 0, 32);
+ }
+
+ /**
+ * 设置页顶部的备份卡片
+ *
+ * 只读 $_GET 里的结果参数来显示提示,不在这里做任何写操作。
+ */
+ /**
+ * 设置页顶部的备份卡片
+ *
+ * 结构与样式完整照搬 MailNotifier(cnot-* 类名原样保留),只把插件名、描述
+ * 和动作地址换成扩展管理自己的。布局要点:标题用 h2 显示插件名;备份时间
+ * .cnot-hero-meta 放在 .cnot-hero-ops 内,靠 flex-basis:100% 换行到按钮下一行。
+ *
+ * 只读 $_GET 里的结果参数来显示提示,不在这里做任何写操作。
+ */
+ private static function heroCardHtml()
+ {
+ $list = array();
+
+ try {
+ $list = self::backups();
+ } catch (\Throwable $e) {
+ $list = array();
+ }
+ $latest = empty($list) ? null : $list[0];
+
+ $keep = self::BACKUP_KEEP;
+ $notice = self::noticeHtml();
+
+ if ($latest) {
+ $meta = '上次备份 ' . self::e(date('Y-m-d H:i', $latest['created']))
+ . ' · 当前 ' . count($list) . ' 份(上限 ' . intval($keep) . ' 份)';
+ } else {
+ $meta = '还没有备份,点「备份」把当前设置存一份';
+ }
+
+ $backupUrl = self::configUrl('_em=backup&_t=' . rawurlencode(self::token()));
+ $restoreUrl = self::configUrl('_em=restore&_t=' . rawurlencode(self::token()));
+
+ $restoreBtn = $latest
+ ? '恢复'
+ : '恢复';
+
+ /* 历史备份:只有一份时「恢复」就是它,不必再展开列表 */
+ $historyBtn = '';
+ $historyBox = '';
+ if (count($list) > 1) {
+ $rows = '';
+ foreach ($list as $index => $item) {
+ $rows .= '
'
+ . '
'
+ . '' . self::e(date('Y-m-d H:i:s', $item['created'])) . ''
+ . ($index === 0 ? '最新' : '')
+ . '' . intval($item['count']) . ' 项配置 · '
+ . self::e(self::formatBytes($item['size']))
+ . ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
+ . ''
+ . '
'
+ . '
恢复'
+ . '
';
+ }
+
+ $historyBtn = '历史备份';
+
+ $historyBox = ''
+ . '
历史备份从新到旧,点「恢复」就用那一份覆盖当前设置
'
+ . $rows
+ . '
'
+ . '';
+ }
+
+ return ''
+ . '
'
+ . '
'
+ . '
'
+ . '
'
+ . '
'
+ . '
' . self::e(self::MENU_NAME) . '
'
+ . ''
+ . '
后台菜单改名、排序、显示隐藏,以及插件面板的收纳设置,都可以存成一份文件;改乱了点「恢复」就能退回上一次。
'
+ . '
'
+ . '
备份'
+ . $restoreBtn
+ . $historyBtn
+ . '
' . $meta . ''
+ . '
'
+ . '
'
+ . '
'
+ . $notice
+ . $historyBox;
+ }
+
+ /**
+ * 备份结果提示条(读 _em 参数)
+ */
+ private static function noticeHtml()
+ {
+ $code = isset($_GET['_em']) && is_scalar($_GET['_em']) ? (string) $_GET['_em'] : '';
+
+ if ('' === $code) {
+ return '';
+ }
+
+ $get = array();
+
+ foreach (array('n', 't', 'detail', 'f') as $key) {
+ $get[$key] = isset($_GET[$key]) && is_scalar($_GET[$key]) ? (string) $_GET[$key] : '';
+ }
+
+ $count = (int) $get['n'];
+ $time = (int) $get['t'];
+ $total = (int) $get['f'];
+ $ok = true;
+ $text = '';
+
+ if ('backup_ok' === $code) {
+ $text = '设置已备份:' . $count . ' 项配置,' . self::e(date('Y-m-d H:i:s', $time)) . '。'
+ . ($total > 0 ? '当前共 ' . $total . ' 份(上限 ' . intval(self::BACKUP_KEEP) . ' 份)。' : '');
+ } elseif ('restore_ok' === $code) {
+ $text = '已恢复到 ' . self::e(date('Y-m-d H:i:s', $time)) . ' 的备份(' . $count
+ . ' 项配置)。刷新本页即可看到表单里的值。';
+ } elseif ('backup_fail' === $code || 'restore_fail' === $code) {
+ $ok = false;
+ $text = ('backup_fail' === $code ? '备份失败:' : '恢复失败:')
+ . ('' !== $get['detail'] ? $get['detail'] : '未知原因');
+ } elseif ('token' === $code) {
+ $ok = false;
+ $text = '安全令牌校验失败,请刷新本页后重试。';
+ } elseif ('auth' === $code) {
+ $ok = false;
+ $text = '只有管理员可以备份或恢复插件设置。';
+ } elseif ('unknown' === $code) {
+ $ok = false;
+ $text = '无法识别的操作。';
+ }
+
+ if ('' === $text) {
+ return '';
+ }
+
+ return '' . self::e($text) . '
';
+ }
+
+ /**
+ * 备份文件目录
+ */
+ private static function backupDir()
+ {
+ return dirname(__FILE__) . '/data/backup';
+ }
+
+ /**
+ * 目录不存在就建,并补上「别让公网读到」的保护
+ *
+ * 备份里是整份插件设置,虽然不含密码,但没必要公开可下载:
+ * 文件本体是 .php(直接访问只会 exit),目录里再放 .htaccess 拒掉。
+ */
+ private static function ensureBackupDir()
+ {
+ $dir = self::backupDir();
+
+ if (!is_dir($dir)) {
+ @mkdir($dir, 0755, true);
+ }
+
+ if (!is_dir($dir)) {
+ return false;
+ }
+
+ if (!is_file($dir . '/.htaccess')) {
+ @file_put_contents($dir . '/.htaccess', "Require all denied\nDeny from all\n");
+ }
+
+ if (!is_file($dir . '/index.html')) {
+ @file_put_contents($dir . '/index.html', '');
+ }
+
+ return true;
+ }
+
+ /**
+ * 备份列表(新 → 旧)
+ */
+ private static function backups()
+ {
+ $dir = self::backupDir();
+
+ if (!is_dir($dir)) {
+ return array();
+ }
+
+ $files = (array) glob($dir . '/' . self::BACKUP_PREFIX . '*.php');
+ $list = array();
+
+ foreach ($files as $file) {
+ $name = basename($file);
+
+ if (!self::isBackupName($name)) {
+ continue;
+ }
+
+ $meta = self::readMeta($file);
+
+ $list[] = array(
+ 'file' => $name,
+ 'size' => (int) @filesize($file),
+ 'created' => !empty($meta['created']) ? (int) $meta['created'] : (int) @filemtime($file),
+ 'count' => !empty($meta['count']) ? (int) $meta['count'] : 0,
+ 'version' => isset($meta['version']) ? (string) $meta['version'] : '',
+ );
+ }
+
+ // 同一秒内可能备份两次,文件名相同,按时间倒序后按文件名兜底
+ usort($list, array(__CLASS__, 'compareBackups'));
+
+ return $list;
+ }
+
+ /**
+ * 备份排序:新的在前
+ */
+ public static function compareBackups($a, $b)
+ {
+ if ($a['created'] === $b['created']) {
+ return strcmp($b['file'], $a['file']);
+ }
+
+ return $a['created'] < $b['created'] ? 1 : -1;
+ }
+
+ /**
+ * 读备份文件头里的 meta
+ */
+ private static function readMeta($file)
+ {
+ $head = @file_get_contents($file, false, null, 0, 512);
+
+ if (false === $head || '' === $head) {
+ return array();
+ }
+
+ if (preg_match('~EM-SETTINGS-BACKUP\s*(\{.*?\})\s*\*/~s', $head, $match)) {
+ $meta = json_decode($match[1], true);
+
+ if (is_array($meta)) {
+ return $meta;
+ }
+ }
+
+ return array();
+ }
+
+ /**
+ * 文件名是不是本插件生成的备份
+ */
+ private static function isBackupName($name)
+ {
+ return (bool) preg_match(
+ '/^' . preg_quote(self::BACKUP_PREFIX, '/') . '[0-9][0-9\-]*\.php$/',
+ (string) $name
+ );
+ }
+
+ /**
+ * 备份一次当前设置
+ *
+ * @return array ok / message / count / created / total
+ */
+ private static function doBackup()
+ {
+ $fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0, 'total' => 0);
+
+ $settings = self::storedConfig();
+
+ if (empty($settings)) {
+ $fail['message'] = '还没有保存过任何设置,先点页面底部的「保存设置」再备份';
+ return $fail;
+ }
+
+ if (!self::ensureBackupDir()) {
+ $fail['message'] = '备份目录 data/backup 不可写,请给插件目录写入权限';
+ return $fail;
+ }
+
+ $created = time();
+ $meta = array(
+ 'plugin' => 'ExtMenu',
+ 'version' => self::version(),
+ 'created' => $created,
+ 'count' => count($settings),
+ 'siteUrl' => self::siteUrl(),
+ );
+
+ $json = json_encode(
+ array_merge($meta, array('settings' => $settings)),
+ JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
+ );
+
+ if (false === $json) {
+ $fail['message'] = '序列化设置失败';
+ return $fail;
+ }
+
+ // 有 zlib 就压一下,没有就纯 base64;恢复时两种都认
+ $gz = function_exists('gzcompress') ? @gzcompress($json, 6) : false;
+ $encoded = (false === $gz || '' === $gz) ? 'b64:' . base64_encode($json) : 'gz:' . base64_encode($gz);
+
+ $content = '' . "\n" . $encoded;
+
+ $file = self::backupDir() . '/' . self::BACKUP_PREFIX . date('Ymd-His', $created) . '.php';
+
+ if (false === @file_put_contents($file, $content, LOCK_EX)) {
+ $fail['message'] = '写入备份文件失败,请检查 data/backup 目录权限';
+ return $fail;
+ }
+
+ self::pruneBackups();
+
+ return array(
+ 'ok' => true,
+ 'message' => '设置已备份',
+ 'count' => count($settings),
+ 'created' => $created,
+ 'total' => count(self::backups()),
+ );
+ }
+
+ /**
+ * 只保留最近 BACKUP_KEEP 份,多出来的从最旧的开始删
+ */
+ private static function pruneBackups()
+ {
+ $list = self::backups();
+
+ if (count($list) <= self::BACKUP_KEEP) {
+ return;
+ }
+
+ foreach (array_slice($list, self::BACKUP_KEEP) as $item) {
+ @unlink(self::backupDir() . '/' . $item['file']);
+ }
+ }
+
+ /**
+ * 恢复一份备份(不传文件名 = 最新那一份)
+ *
+ * @return array ok / message / count / created
+ */
+ private static function doRestore($file = '')
+ {
+ $fail = array('ok' => false, 'message' => '', 'count' => 0, 'created' => 0);
+
+ $list = self::backups();
+
+ if (empty($list)) {
+ $fail['message'] = '还没有备份,先点一次「备份设置」';
+ return $fail;
+ }
+
+ $name = '' !== $file ? basename($file) : $list[0]['file'];
+
+ if (!self::isBackupName($name)) {
+ $fail['message'] = '备份文件名不合法';
+ return $fail;
+ }
+
+ $path = self::backupDir() . '/' . $name;
+ $content = @file_get_contents($path);
+
+ if (false === $content || '' === $content) {
+ $fail['message'] = '读取备份文件失败:' . $name;
+ return $fail;
+ }
+
+ $pos = strpos($content, '?>');
+
+ if (false === $pos) {
+ $fail['message'] = '备份文件格式不正确';
+ return $fail;
+ }
+
+ $encoded = trim(substr($content, $pos + 2));
+
+ if (0 === strncmp($encoded, 'gz:', 3)) {
+ $json = function_exists('gzuncompress')
+ ? @gzuncompress((string) base64_decode(substr($encoded, 3)))
+ : false;
+ } else {
+ $json = base64_decode(substr($encoded, 4));
+ }
+
+ if (false === $json || '' === $json) {
+ $fail['message'] = '备份内容已损坏,无法解析';
+ return $fail;
+ }
+
+ $payload = json_decode($json, true);
+
+ if (!is_array($payload) || empty($payload['settings']) || !is_array($payload['settings'])) {
+ $fail['message'] = '备份内容已损坏,没有找到设置';
+ return $fail;
+ }
+
+ if (isset($payload['plugin']) && 'ExtMenu' !== $payload['plugin']) {
+ $fail['message'] = '这份备份不属于扩展管理插件';
+ return $fail;
+ }
+
+ try {
+ // 整份覆盖:configPlugin() 是 array_merge,删不掉备份里没有的键
+ Helper::setOption('plugin:ExtMenu', $payload['settings']);
+ } catch (\Throwable $e) {
+ $fail['message'] = '写回设置失败,请检查数据库权限';
+ return $fail;
+ }
+
+ return array(
+ 'ok' => true,
+ 'message' => '设置已恢复',
+ 'count' => count($payload['settings']),
+ 'created' => !empty($payload['created']) ? (int) $payload['created'] : $list[0]['created'],
+ );
+ }
+
+ /**
+ * 文件大小的好读写法
+ */
+ private static function formatBytes($bytes)
+ {
+ $bytes = max(0, (int) $bytes);
+
+ if ($bytes < 1024) {
+ return $bytes . ' B';
+ }
+
+ if ($bytes < 1048576) {
+ return round($bytes / 1024, 1) . ' KB';
+ }
+
+ return round($bytes / 1048576, 1) . ' MB';
+ }
+
+ /**
+ * 插件版本(与文件头 @version 一致,备份文件里也记这个号)
+ */
+ private static function version()
+ {
+ return '1.4.0';
+ }
+
+ /**
+ * 站点地址(给备份文件记一份环境信息)
+ */
+ private static function siteUrl()
+ {
+ try {
+ return (string) Helper::options()->siteUrl;
+ } catch (\Throwable $e) {
+ return '';
+ }
+ }
+
+ /**
+ * 转义输出
+ */
+ private static function e($text)
+ {
+ return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
+ }
+
+ /**
+ * 每次打开后台时做一次维护
+ *
+ * 只在真的需要改动时才写库,正常情况下就是读一次已加载的 panelTable 然后返回。
+ */
+ public static function onAdminBegin()
+ {
+ if (!defined('__TYPECHO_ADMIN__')) {
+ return;
+ }
+
+ try {
+ self::migrate();
+ } catch (\Throwable $e) {
+ // 旧配置迁移失败不能连累后台打开,静默跳过
+ }
+
+ // 清理「有父菜单、没有对应子菜单」的孤儿项。
+ // 核心 Widget\Menu 对每个 parent[k] 都执行 foreach ($childNodes[10 + k]),
+ // 若 child[10 + k] 缺失就会抛 Undefined array key / foreach null 的 Warning。
+ // 从 1.5.0 回退时,1.5.0 新增的自定义顶级菜单只留下 parent、child 已被本插件
+ // 的 collect() 清掉,正是这种孤儿;这里在渲染前删掉它们,后台即可恢复正常。
+ // 与自动收纳开关无关,必须无条件执行。
+ try {
+ self::repairOrphans();
+ } catch (\Throwable $e) {
+ // 清理失败不能连累后台打开
+ }
+
+ if ('1' !== (string) self::opt('autoCollect', '1')) {
+ return;
+ }
+
+ try {
+ self::collect();
+ } catch (\Throwable $e) {
+ // 菜单维护失败不能连累后台打开,静默跳过
+ }
+ }
+
+ /**
+ * 把 1.2.0 的 pn_ / po_ / pv_ 键搬到 cn_ / co_ / cv_
+ *
+ * 1.2.0 只给「扩展管理」下的面板做了定制,键名带 p 前缀。1.3.0 起所有二级
+ * 菜单共用一套键,前缀改成 c。读取时本来可以直接回退到旧键,但插件设置页是
+ * Widget\Plugins\Config 用已保存的值覆盖表单字段的 —— 旧键的值到不了输入框,
+ * 用户会以为自定义丢了。所以在后台入口做一次搬迁,搬完把旧键删掉。
+ */
+ private static function migrate()
+ {
+ $config = self::storedConfig();
+
+ if (empty($config)) {
+ return;
+ }
+
+ $dirty = false;
+
+ foreach ($config as $key => $value) {
+ if (!preg_match('/^p([nov])_(.+)$/', (string) $key, $match)) {
+ continue;
+ }
+
+ $dirty = true;
+ $new = 'c' . $match[1] . '_' . $match[2];
+
+ if (
+ null !== $value && '' !== $value
+ && (!isset($config[$new]) || null === $config[$new] || '' === $config[$new])
+ ) {
+ $config[$new] = $value;
+ }
+
+ unset($config[$key]);
+ }
+
+ if (!$dirty) {
+ return;
+ }
+
+ try {
+ // configPlugin() 是 array_merge,删不掉旧键,这里整份覆盖
+ Helper::setOption('plugin:ExtMenu', $config);
+ } catch (\Throwable $e) {
+ // 写库失败就保持原样,下次进后台再试
+ }
+ }
+
+ /**
+ * 清理孤儿父菜单:有 parent[k]、却没有对应 child[10 + k] 的残留项
+ *
+ * 核心 Widget\Menu 对每个 parent[k] 都执行 foreach ($childNodes[10 + k]),
+ * child 缺失就会抛 Undefined array key / foreach null 的 Warning。
+ * 从 1.5.0 回退到 1.4.0 时,1.5.0 新增的自定义顶级菜单只留下 parent,
+ * 它对应的 child 已被 collect() 当空组删掉,正是这种孤儿。
+ *
+ * 这里在菜单渲染之前把它们删掉:清理后 parent 与 child 一一对应,
+ * 系统进入稳定态,后续 collect() 搬运面板不会再制造新的孤儿。
+ * 正常项目中 parent 只有「扩展管理」一项,且有非空 child,不会被误删。
+ */
+ private static function repairOrphans()
+ {
+ $table = self::table();
+ $dirty = false;
+
+ foreach (array_keys($table['parent']) as $key) {
+ $index = 10 + (int) $key;
+
+ // 对应 child 存在且是非空数组 = 正常父菜单
+ if (isset($table['child'][$index]) && is_array($table['child'][$index]) && !empty($table['child'][$index])) {
+ continue;
+ }
+
+ // 其余情况:child 缺失 / 为空 / 类型不对,父菜单是孤儿,删掉
+ unset($table['parent'][$key]);
+ unset($table['child'][$index]);
+ $dirty = true;
+ }
+
+ if ($dirty) {
+ self::save($table);
+ }
+ }
+
+ /**
+ * 原版后台:注入菜单调整脚本;设置页:注入卡片式布局
+ *
+ * 原版 admin/menu.php 里没有可以替换菜单数组的钩子(Widget\Menu 直接输出 HTML),
+ * 所以只能等 DOM 出来之后再调整。装了 NewAdmin 时不执行菜单部分 —— 它自己渲染侧边栏,
+ * 走的是 onMenuNodes()。设置页的布局优化与两套后台无关,始终执行。
+ */
+ public static function onAdminHeader($header)
+ {
+ if (!defined('__TYPECHO_ADMIN__')) {
+ return $header;
+ }
+
+ if (self::isConfigPage()) {
+ // 设置页顶部「备份 / 恢复」:处理完 302 回本页,_em 参数带结果
+ try {
+ self::handleSettingsAction();
+ } catch (\Throwable $e) {
+ // 动作失败不能白屏
+ }
+
+ try {
+ $header .= self::configAssets();
+ } catch (\Throwable $e) {
+ // 布局优化失败不影响保存
+ }
+ }
+
+ // 美化后台走 onMenuNodes() 在 PHP 侧改数组,不必再输出 DOM 脚本
+ if (self::usingNewAdmin()) {
+ // 唯一例外是「概要」:它是 NewAdmin 里写死的一段 HTML,老版本的
+ // NewAdmin 不会把它交给过滤器。这段脚本只在 DOM 和对不上的时候补一刀,
+ // 新版已经被 PHP 改好的话就是空转。
+ try {
+ $header .= self::summaryScript();
+ } catch (\Throwable $e) {
+ // 兜底脚本失败不影响后台
+ }
+
+ return $header;
+ }
+
+ try {
+ $config = self::stockConfig();
+ } catch (\Throwable $e) {
+ return $header;
+ }
+
+ if (empty($config)) {
+ return $header;
+ }
+
+ $json = json_encode(
+ $config,
+ JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
+ );
+
+ if (false === $json) {
+ return $header;
+ }
+
+ return $header . "\n";
+ }
+
+ /**
+ * 美化后台里「概要」这一项的兜底脚本
+ *
+ * 「概要」在 NewAdmin 的 output() 里原本是一段写死的 HTML,不在 panelTable 里,
+ * 只能由 NewAdmin 把它塞进菜单数组(2.6.2 起)才改得动。老版本没有这一步,
+ * 于是这里退回到改 DOM:改名只动文字节点、换图标只动 svg 的引用,
+ * 不会把图标节点一起冲掉;隐藏就直接摘掉整个 li。
+ *
+ * 脚本先比对再动手,新版 NewAdmin 已经把结果渲染好时什么也不会做,
+ * 所以两套逻辑同时存在也不会打架。
+ */
+ private static function summaryScript()
+ {
+ $title = (string) self::opt('mn_msum', '');
+ $icon = (string) self::opt('mi_msum', '');
+ $hide = self::hidden('mv_msum');
+
+ if ('' === $title && '' === $icon && !$hide) {
+ return '';
+ }
+
+ $data = array(
+ 't' => $title,
+ 'i' => ('' !== $icon && isset(self::$icons[$icon])) ? $icon : '',
+ 'h' => $hide,
+ );
+
+ $json = json_encode(
+ $data,
+ JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
+ );
+
+ if (false === $json) {
+ return '';
+ }
+
+ return "\n";
+ }
+
+ /**
+ * 美化后台(NewAdmin)在渲染侧边栏前会经过这里
+ *
+ * NewAdmin 的 output() 复制了一份 Widget\Menu 的逻辑,菜单数组是现成的,
+ * 直接改名字、换顺序、塞图标、去掉隐藏项即可,不用碰 DOM。
+ *
+ * @param array $menu
+ * @return array
+ */
+ public static function onMenuNodes($menu)
+ {
+ if (!is_array($menu) || empty($menu)) {
+ return $menu;
+ }
+
+ $table = self::table();
+ $rows = array();
+ $seq = 0;
+
+ foreach ($menu as $key => $node) {
+ // 0 号是 Widget\Menu 里的占位(登录/注册用的游客菜单),不会渲染出来,
+ // 但会占掉一个序号,导致后面的默认排序值整体错位。
+ if (!is_array($node) || 0 === $key) {
+ continue;
+ }
+
+ $seq++;
+ $id = self::menuId($key, $table);
+
+ // 隐藏项直接从渲染数组里去掉,后台就不会输出它
+ if (self::hidden('mv_' . $id)) {
+ continue;
+ }
+
+ $node = self::styleNode($node, $id);
+
+ if (!empty($node[3]) && is_array($node[3])) {
+ $visible = 0;
+ $node[3] = self::mapChildren($id, $node[3], $visible);
+
+ // 二级菜单全被隐藏时不要留下一个点不进去的空父级
+ if (0 === $visible) {
+ continue;
+ }
+
+ $node[1] = true;
+ }
+
+ $rows[] = array(
+ self::orderOf('mo_' . $id, self::defaultOrder($id, $seq * 10)),
+ $seq,
+ $key,
+ $node
+ );
+ }
+
+ if (empty($rows)) {
+ return array();
+ }
+
+ usort($rows, array(__CLASS__, 'compareRows'));
+
+ $sorted = array();
+
+ foreach ($rows as $row) {
+ $sorted[$row[2]] = $row[3];
+ }
+
+ return $sorted;
+ }
+
+ /**
+ * 套用顶级菜单的名称和图标
+ *
+ * @param array $node
+ * @param string $id
+ * @return array
+ */
+ private static function styleNode(array $node, $id)
+ {
+ $title = (string) self::opt('mn_' . $id, '');
+
+ if ('' !== $title) {
+ $node[0] = $title;
+ }
+
+ $icon = (string) self::opt('mi_' . $id, '');
+
+ if ('' !== $icon && isset(self::$icons[$icon])) {
+ $node[4] = $icon;
+ }
+
+ return $node;
+ }
+
+ /**
+ * 排序用的比较函数(同序号时保持原有先后)
+ */
+ public static function compareRows($a, $b)
+ {
+ if ($a[0] == $b[0]) {
+ return $a[1] - $b[1];
+ }
+
+ return $a[0] < $b[0] ? -1 : 1;
+ }
+
+ /* ------------------------------------------------------------------
+ * 表单字段
+ * ---------------------------------------------------------------- */
+
+ /**
+ * 文本项(名称)
+ *
+ * @param mixed $value 默认值,null 时读同名配置项
+ */
+ private static function addText(Typecho_Widget_Helper_Form $form, $name, $label, $placeholder, $value = null)
+ {
+ $element = new Typecho_Widget_Helper_Form_Element_Text(
+ $name,
+ null,
+ null === $value ? self::opt($name, '') : $value,
+ $label,
+ null
+ );
+
+ if ($element->input) {
+ $element->input->setAttribute('placeholder', $placeholder);
+ }
+
+ $form->addInput($element);
+ }
+
+ /**
+ * 排序项
+ *
+ * placeholder 直接给默认序号,用户一眼能看出留空时的相对位置。
+ *
+ * @param mixed $value 默认值,null 时读同名配置项
+ */
+ private static function addOrder(Typecho_Widget_Helper_Form $form, $name, $label, $default, $value = null)
+ {
+ $element = new Typecho_Widget_Helper_Form_Element_Text(
+ $name,
+ null,
+ null === $value ? self::opt($name, '') : $value,
+ $label,
+ null
+ );
+
+ if ($element->input) {
+ $element->input->setAttribute('placeholder', (string) $default);
+ $element->input->setAttribute('inputmode', 'numeric');
+ }
+
+ $form->addInput($element);
+ }
+
+ /**
+ * 图标项(只对美化后台有意义)
+ */
+ private static function addIcon(Typecho_Widget_Helper_Form $form, $name, $label)
+ {
+ $form->addInput(new Typecho_Widget_Helper_Form_Element_Select(
+ $name,
+ self::$icons,
+ self::opt($name, ''),
+ $label,
+ null
+ ));
+ }
+
+ /**
+ * 显示 / 隐藏
+ *
+ * @param mixed $value 默认值,null 时读同名配置项
+ */
+ private static function addVisible(Typecho_Widget_Helper_Form $form, $name, $label, $value = null)
+ {
+ $form->addInput(new Typecho_Widget_Helper_Form_Element_Select(
+ $name,
+ array('1' => '显示', '0' => '隐藏'),
+ null === $value ? self::opt($name, '1') : $value,
+ $label,
+ null
+ ));
+ }
+
+ /**
+ * 是否被设为隐藏
+ */
+ private static function hidden($name)
+ {
+ return '0' === (string) self::opt($name, '1');
+ }
+
+ /* ------------------------------------------------------------------
+ * 设置页:把扁平的表单字段重排成一棵菜单树
+ * ---------------------------------------------------------------- */
+
+ /**
+ * 当前是否在「扩展管理」的插件设置页
+ */
+ private static function isConfigPage()
+ {
+ $uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
+
+ if (false === strpos($uri, 'options-plugin.php')) {
+ return false;
+ }
+
+ return isset($_GET['config']) && 'ExtMenu' === $_GET['config'];
+ }
+
+ /**
+ * 设置页的样式 + 重排脚本
+ *
+ * Typecho 的插件配置表单是一串扁平的 ul.typecho-option,没有分组概念,
+ * 几十个字段竖排下来又长又难对应。这里按字段名前缀把它们收进一棵树:
+ * 顶级菜单一行(名称 / 排序 / 图标 / 显隐),它的二级菜单挂在下面,
+ * 默认收起、点菜单名展开(也可以「展开全部」)。
+ *
+ * 用 JS 而不是改核心渲染,是因为 Widget\Plugins\Config 只认平铺的元素列表;
+ * 不能两全时选了「不改核心 + 无 JS 时仍可用」这条路:
+ * 无 JS 时字段照旧竖排,label 里带着「父级 » 子级」,功能不受影响。
+ */
+ private static function configAssets()
+ {
+ $tree = array();
+
+ foreach (self::treeDefs() as $id => $def) {
+ $kids = array();
+
+ foreach ($def['kids'] as $kid => $kd) {
+ $kids[] = array('k' => $kid, 'n' => $kd['n']);
+ }
+
+ $tree[] = array('k' => $id, 'n' => $def['n'], 'c' => $kids);
+ }
+
+ $meta = array('t' => $tree, 'm' => self::MENU_NAME);
+ $json = json_encode(
+ $meta,
+ JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
+ );
+
+ if (false === $json) {
+ return '';
+ }
+
+ $css = <<<'CSS'
+
+CSS;
+
+ $js = <<<'JS'
+
+JS;
+
+ return $css . "\n" . str_replace('__META__', $json, $js);
+ }
+
+ /* ------------------------------------------------------------------
+ * 内部实现
+ * ---------------------------------------------------------------- */
+
+ /**
+ * 当前 Typecho 是否具备自定义父菜单的能力
+ */
+ private static function supported()
+ {
+ return method_exists('Helper', 'addMenu');
+ }
+
+ /**
+ * 读取 panelTable,缺失的键补成空数组
+ */
+ private static function table()
+ {
+ $table = Helper::options()->panelTable;
+ $table = is_array($table) ? $table : array();
+
+ foreach (array('parent', 'child', 'file') as $key) {
+ if (!isset($table[$key]) || !is_array($table[$key])) {
+ $table[$key] = array();
+ }
+ }
+
+ return $table;
+ }
+
+ /**
+ * 写回 panelTable
+ *
+ * parent / child 的键不能重排:Widget\Menu 用 10 + 父菜单键 定位子菜单,
+ * 一旦 array_values 压平,父子就对不上了。只有内层条目和 file 可以重排。
+ */
+ private static function save(array $table)
+ {
+ foreach ($table['child'] as $index => $items) {
+ $table['child'][$index] = array_values($items);
+ }
+
+ $table['file'] = array_values($table['file']);
+
+ Helper::setOption('panelTable', $table);
+ }
+
+ /**
+ * 「扩展管理」在 panelTable['parent'] 里的键,没有则返回 null
+ */
+ private static function menuKey(array $parent)
+ {
+ $key = array_search(self::MENU_NAME, $parent, true);
+
+ return false === $key ? null : $key;
+ }
+
+ /**
+ * 当前是否装了美化后台 NewAdmin
+ *
+ * 只有它把「概要」提成独立的顶级入口,也只有它走 PHP 侧的菜单过滤,
+ * 设置页要不要列「概要」这一项取决于它。
+ */
+ private static function usingNewAdmin()
+ {
+ if (null !== self::$newAdmin) {
+ return self::$newAdmin;
+ }
+
+ self::$newAdmin = false;
+
+ try {
+ $plugins = Helper::options()->plugins;
+ self::$newAdmin = is_array($plugins)
+ && !empty($plugins['activated'])
+ && isset($plugins['activated']['NewAdmin']);
+ } catch (\Throwable $e) {
+ self::$newAdmin = false;
+ }
+
+ return self::$newAdmin;
+ }
+
+ /**
+ * 设置页 / 渲染共用的菜单树
+ *
+ * 顶级菜单 id => ['n' => 显示名称, 'o' => 默认序号, 'kids' => [二级 id => ['n','o']]]
+ *
+ * 结构要和两套后台的实际渲染一致:核心菜单的二级项来自 $coreChildren,
+ * 插件面板来自 panelTable;美化后台把「概要」提成了独立顶级入口,
+ * 所以它既是顶级菜单(msum),又不出现在「控制台」的二级里。
+ *
+ * @return array
+ */
+ private static function treeDefs()
+ {
+ if (null !== self::$tree) {
+ return self::$tree;
+ }
+
+ $table = self::table();
+ $newAdmin = self::usingNewAdmin();
+ $tree = array();
+ $seq = 0;
+
+ // 美化后台的「概要」是写死的顶级入口,不在 panelTable 里
+ if ($newAdmin) {
+ $tree['msum'] = array('n' => _t('概要'), 'o' => 5, 'kids' => array());
+ }
+
+ foreach (self::$coreMenus as $index => $label) {
+ $seq++;
+ $name = _t($label);
+
+ // 美化后台(NewAdmin)把「控制台」显示成「核心」,两个名字都标出来,
+ // 免得在设置里找不到对应项
+ if (1 === $index) {
+ $name .= ' / ' . _t('核心');
+ }
+
+ $tree[self::menuId($index, $table)] = array(
+ 'n' => $name,
+ 'o' => $seq * 10,
+ 'kids' => self::kidDefs($index, $table, $newAdmin),
+ );
+ }
+
+ foreach ($table['parent'] as $key => $name) {
+ $seq++;
+ $index = 10 + $key;
+ $tree[self::menuId($index, $table)] = array(
+ 'n' => (string) $name,
+ 'o' => $seq * 10,
+ 'kids' => self::kidDefs($index, $table, $newAdmin),
+ );
+ }
+
+ self::$tree = $tree;
+ self::$kidIndex = array();
+
+ foreach ($tree as $def) {
+ foreach ($def['kids'] as $kid => $kd) {
+ self::$kidIndex[$kid] = $kd;
+ }
+ }
+
+ return $tree;
+ }
+
+ /**
+ * 某个顶级菜单下的二级菜单
+ *
+ * @param int $index 菜单索引(核心 1~4,自定义 10 + panelTable 键)
+ * @param array $table
+ * @param bool $newAdmin
+ * @return array
+ */
+ private static function kidDefs($index, array $table, $newAdmin)
+ {
+ $kids = array();
+ $seq = 0;
+ $parentId = self::menuId($index, $table);
+
+ if (isset(self::$coreChildren[$index])) {
+ foreach (self::$coreChildren[$index] as $def) {
+ // 美化后台顶部已有独立的「概要」入口,控制台下的同名项不渲染
+ if ($newAdmin && 1 === $index && 'index.php' === $def[1]) {
+ continue;
+ }
+
+ $name = (isset($def[2]) && $newAdmin) ? $def[2] : $def[0];
+ $kids[self::childId($parentId, $def[1])] = array(
+ 'n' => _t($name),
+ 'o' => ++$seq * 10,
+ );
+ }
+ }
+
+ if (!empty($table['child'][$index])) {
+ foreach ($table['child'][$index] as $item) {
+ $slug = self::slug(self::panelFromUrl(isset($item[2]) ? $item[2] : ''));
+
+ if ('' === $slug || isset($kids[$slug])) {
+ continue;
+ }
+
+ $kids[$slug] = array(
+ 'n' => isset($item[0]) ? (string) $item[0] : $slug,
+ 'o' => ++$seq * 10,
+ );
+ }
+ }
+
+ return $kids;
+ }
+
+ /**
+ * 菜单索引 => 配置标识
+ *
+ * 原版后台的四个菜单是写死的 1~4,自定义菜单的索引则是 10 + panelTable 里的键。
+ * 后者不能拿来当标识:panelTable['parent'] 里的键在停用再启用之后会往后漂
+ * (PHP 数组 unset 过末尾元素后,下次 [] 追加不会回到 0),配置就会对不上号。
+ * 所以自定义菜单用菜单名的指纹做标识 —— 菜单名只在插件启用时写入一次,不会变。
+ */
+ private static function menuId($key, array $table)
+ {
+ // 美化后台的「概要」不是 panelTable 里的菜单,用固定标识
+ if ('summary' === $key) {
+ return 'msum';
+ }
+
+ $key = (int) $key;
+
+ if ($key >= 1 && $key <= 4) {
+ return 'm' . $key;
+ }
+
+ $name = isset($table['parent'][$key - 10]) ? (string) $table['parent'][$key - 10] : '';
+
+ if ('' === $name) {
+ return 'm' . $key;
+ }
+
+ return 'x' . substr(md5($name), 0, 8);
+ }
+
+ /**
+ * 二级菜单的配置标识
+ *
+ * 插件面板用面板路径生成的 slug(EditHistory/manage-panel.php =>
+ * EditHistory_manage_panel_php),和面板在哪个父菜单下无关,
+ * 所以「扩展管理」收纳前后配置都能对上。
+ *
+ * 核心菜单项没有路径可依,用「父级 + 链接」的指纹:链接写的是相对地址
+ * (index.php / write-post.php),渲染时拿到的是完整地址,
+ * 所以只取路径末段和查询串来算,两边一致。
+ */
+ private static function childId($parentId, $url)
+ {
+ $panel = self::panelFromUrl($url);
+
+ if ('' !== $panel) {
+ return self::slug($panel);
+ }
+
+ $path = parse_url((string) $url, PHP_URL_PATH);
+ $base = basename(is_string($path) ? $path : '');
+
+ $query = parse_url((string) $url, PHP_URL_QUERY);
+
+ if (is_string($query) && '' !== $query) {
+ $base .= '?' . $query;
+ }
+
+ return 'c' . substr(md5($parentId . '|' . $base), 0, 8);
+ }
+
+ /**
+ * 二级菜单的配置项,新键没有再找 1.2.0 的旧键(pn_ / po_ / pv_)
+ */
+ private static function childOpt($field, $id, $default = null)
+ {
+ $value = self::opt('c' . $field . '_' . $id, null);
+
+ if (null === $value) {
+ $value = self::opt('p' . $field . '_' . $id, null);
+ }
+
+ return null === $value ? $default : $value;
+ }
+
+ /**
+ * 二级菜单是否被设为隐藏
+ */
+ private static function childHidden($id)
+ {
+ return '0' === (string) self::childOpt('v', $id, '1');
+ }
+
+ /**
+ * 二级菜单的改名,没设置为空串
+ */
+ private static function childTitle($id)
+ {
+ return (string) self::childOpt('n', $id, '');
+ }
+
+ /**
+ * 顶级菜单的默认排序(按设置页里的顺序,和渲染时的取序一致)
+ */
+ private static function defaultOrder($id, $fallback)
+ {
+ $tree = self::treeDefs();
+
+ return isset($tree[$id]) ? $tree[$id]['o'] : $fallback;
+ }
+
+ /**
+ * 二级菜单的默认排序
+ */
+ private static function childDefaultOrder($id, $fallback)
+ {
+ self::treeDefs();
+
+ return isset(self::$kidIndex[$id]) ? self::$kidIndex[$id]['o'] : $fallback;
+ }
+
+ /**
+ * 按设置重排 / 改名 / 隐藏某个顶级菜单下的二级菜单
+ *
+ * 只在特定页面出现的上下文菜单(编辑文章、分类编辑、附件编辑……)和权限不足的项
+ * 原样保留在原来的兄弟旁边:它们的名字就是内容标题,位置和高亮都由核心决定,
+ * 改了反而会让「当前菜单」指错地方。
+ *
+ * @param string $parentId 所属顶级菜单的标识
+ * @param array $children
+ * @param int $visible 出参:剩下几个正常显示的二级菜单
+ * @return array
+ */
+ private static function mapChildren($parentId, array $children, &$visible = null)
+ {
+ $list = array();
+ $context = array();
+ $seq = 0;
+
+ foreach ($children as $key => $child) {
+ if (!is_array($child)) {
+ continue;
+ }
+
+ if (!empty($child[4]) || !empty($child[6])) {
+ $context[$key] = $child;
+ continue;
+ }
+
+ $seq++;
+ $id = self::childId($parentId, isset($child[2]) ? $child[2] : '');
+
+ // 隐藏项直接不出现在渲染数组里
+ if (self::childHidden($id)) {
+ continue;
+ }
+
+ $title = self::childTitle($id);
+
+ if ('' !== $title) {
+ $child[0] = $title;
+ }
+
+ $list[$key] = array(
+ self::orderOf('co_' . $id, self::childDefaultOrder($id, $seq * 10)),
+ $seq,
+ $key,
+ $child
+ );
+ }
+
+ $visible = count($list);
+
+ if (empty($context)) {
+ usort($list, array(__CLASS__, 'compareRows'));
+
+ $sorted = array();
+
+ foreach ($list as $row) {
+ $sorted[$row[2]] = $row[3];
+ }
+
+ return $sorted;
+ }
+
+ // 上下文菜单跟着「原来在它前面的那个可见兄弟」走
+ $kept = array();
+
+ foreach ($list as $row) {
+ $kept[$row[2]] = true;
+ }
+
+ $anchor = array();
+ $last = null;
+
+ foreach (array_keys($children) as $key) {
+ if (isset($context[$key])) {
+ $anchor[$key] = $last;
+ continue;
+ }
+
+ if (isset($kept[$key])) {
+ $last = $key;
+ }
+ }
+
+ usort($list, array(__CLASS__, 'compareRows'));
+
+ $sorted = array();
+
+ foreach ($list as $row) {
+ $sorted[] = array($row[2], $row[3]);
+ }
+
+ foreach ($anchor as $key => $after) {
+ $at = 0;
+
+ if (null !== $after) {
+ foreach ($sorted as $i => $row) {
+ if ($row[0] === $after) {
+ $at = $i + 1;
+ break;
+ }
+ }
+ }
+
+ while (isset($sorted[$at]) && isset($context[$sorted[$at][0]])) {
+ $at++;
+ }
+
+ array_splice($sorted, $at, 0, array(array($key, $context[$key])));
+ }
+
+ $sorted2 = array();
+
+ foreach ($sorted as $row) {
+ $sorted2[$row[0]] = $row[1];
+ }
+
+ return $sorted2;
+ }
+
+ /**
+ * 原版后台要用的改名 / 排序 / 隐藏数据
+ *
+ * 原版后台的菜单是 PHP 直接 echo 出来的,没有可替换的钩子,
+ * 只能把「要和默认不一样的地方」交给一小段 JS 去改 DOM。
+ * 全都是默认值时返回空数组(不输出 JS)。
+ *
+ * @return array
+ */
+ private static function stockConfig()
+ {
+ $table = self::table();
+ $parents = array();
+ $touched = false;
+ $seq = 0;
+
+ foreach (self::$coreMenus as $index => $label) {
+ $seq++;
+ $id = self::menuId($index, $table);
+ $entry = self::stockParent($id, _t($label), $seq * 10, $touched);
+ $kids = self::stockChildren($index, $table, $id, $touched);
+
+ if (!empty($kids)) {
+ $entry['c'] = $kids;
+ }
+
+ $parents[] = $entry;
+ }
+
+ foreach ($table['parent'] as $key => $name) {
+ $seq++;
+ $index = 10 + $key;
+ $id = self::menuId($index, $table);
+ $entry = self::stockParent($id, (string) $name, $seq * 10, $touched);
+ $kids = self::stockChildren($index, $table, $id, $touched);
+
+ if (!empty($kids)) {
+ $entry['c'] = $kids;
+ }
+
+ $parents[] = $entry;
+ }
+
+ if (!$touched) {
+ return array();
+ }
+
+ return array('p' => $parents);
+ }
+
+ /**
+ * 原版后台:一个顶级菜单的定制数据
+ *
+ * @param string $id
+ * @param string $from 页面上显示的原始名称(JS 靠它找 DOM 节点)
+ * @param float $default
+ * @param bool $touched
+ * @return array
+ */
+ private static function stockParent($id, $from, $default, &$touched)
+ {
+ $title = (string) self::opt('mn_' . $id, '');
+ $order = self::orderOf('mo_' . $id, self::defaultOrder($id, $default), $custom);
+ $hide = self::hidden('mv_' . $id);
+
+ if ('' !== $title || $custom || $hide) {
+ $touched = true;
+ }
+
+ return array(
+ 'f' => $from,
+ 't' => $title === $from ? '' : $title,
+ 'o' => $order,
+ 'h' => $hide,
+ );
+ }
+
+ /**
+ * 原版后台:一个顶级菜单下所有二级菜单的定制数据
+ *
+ * @param int $index
+ * @param array $table
+ * @param string $parentId
+ * @param bool $touched
+ * @return array
+ */
+ private static function stockChildren($index, array $table, $parentId, &$touched)
+ {
+ $items = array();
+ $seq = 0;
+
+ if (isset(self::$coreChildren[$index])) {
+ foreach (self::$coreChildren[$index] as $def) {
+ $seq++;
+ $id = self::childId($parentId, $def[1]);
+ $items[] = self::stockChild($id, _t($def[0]), $seq * 10, $touched);
+ }
+ }
+
+ if (!empty($table['child'][$index])) {
+ foreach ($table['child'][$index] as $item) {
+ $seq++;
+ $id = self::slug(self::panelFromUrl(isset($item[2]) ? $item[2] : ''));
+
+ if ('' === $id) {
+ continue;
+ }
+
+ $items[] = self::stockChild(
+ $id,
+ isset($item[0]) ? (string) $item[0] : '',
+ $seq * 10,
+ $touched
+ );
+ }
+ }
+
+ return $items;
+ }
+
+ /**
+ * 原版后台:一个二级菜单的定制数据
+ */
+ private static function stockChild($id, $from, $default, &$touched)
+ {
+ $title = self::childTitle($id);
+ $order = self::orderOf('co_' . $id, self::childDefaultOrder($id, $default), $custom);
+ $hide = self::childHidden($id);
+
+ if ('' !== $title || $custom || $hide) {
+ $touched = true;
+ }
+
+ return array(
+ 'f' => $from,
+ 't' => $title === $from ? '' : $title,
+ 'o' => $order,
+ 'h' => $hide,
+ );
+ }
+
+ /**
+ * 把散落在各菜单下的插件面板收进「扩展管理」
+ *
+ * @return int 本次搬迁的条目数
+ */
+ private static function collect()
+ {
+ $table = self::table();
+ $dirty = false;
+ $moved = 0;
+
+ $table = self::prune($table, $dirty);
+
+ $menuKey = self::menuKey($table['parent']);
+
+ if (null === $menuKey) {
+ // 没有可收的面板就不建空菜单,否则 Widget\Menu 会渲染出一个空父级
+ if (self::countPanels($table['child']) < 1) {
+ if ($dirty) {
+ self::save($table);
+ }
+ return 0;
+ }
+
+ $table['parent'][] = self::MENU_NAME;
+ end($table['parent']);
+ $menuKey = key($table['parent']);
+ $dirty = true;
+ }
+
+ // Widget\Menu 里的映射是 $parentNodes[10 + key],子菜单索引必须与之一致
+ $menuIndex = 10 + $menuKey;
+
+ foreach (array_keys($table['child']) as $index) {
+ if ((int) $index === (int) $menuIndex) {
+ continue;
+ }
+
+ if (empty($table['child'][$index])) {
+ unset($table['child'][$index]);
+ $dirty = true;
+ continue;
+ }
+
+ if (!isset($table['child'][$menuIndex])) {
+ $table['child'][$menuIndex] = array();
+ }
+
+ foreach ($table['child'][$index] as $item) {
+ $table['child'][$menuIndex][] = $item;
+ $moved++;
+ }
+
+ unset($table['child'][$index]);
+ $dirty = true;
+ }
+
+ // 面板全被清空(插件都停用了)时连菜单一起去掉
+ if (empty($table['child'][$menuIndex])) {
+ unset($table['child'][$menuIndex]);
+
+ $key = self::menuKey($table['parent']);
+
+ if (null !== $key) {
+ unset($table['parent'][$key]);
+ }
+
+ $dirty = true;
+ }
+
+ if ($dirty) {
+ self::save($table);
+ }
+
+ return $moved;
+ }
+
+ /**
+ * 把所有面板放回「管理」并移除父菜单
+ *
+ * @return int 搬迁的条目数
+ */
+ private static function restore()
+ {
+ $table = self::table();
+ $menuKey = self::menuKey($table['parent']);
+
+ if (null === $menuKey) {
+ return 0;
+ }
+
+ $menuIndex = 10 + $menuKey;
+ $items = isset($table['child'][$menuIndex]) ? $table['child'][$menuIndex] : array();
+
+ unset($table['child'][$menuIndex]);
+
+ if (!empty($items)) {
+ if (!isset($table['child'][self::FALLBACK_INDEX])) {
+ $table['child'][self::FALLBACK_INDEX] = array();
+ }
+
+ foreach ($items as $item) {
+ $table['child'][self::FALLBACK_INDEX][] = $item;
+ }
+ }
+
+ unset($table['parent'][$menuKey]);
+
+ self::save($table);
+
+ return count($items);
+ }
+
+ /**
+ * 清掉失效的面板条目
+ *
+ * 两个来源:
+ * 1) 插件停用时调用的是 Helper::removePanel(3, 'X/Y.php'),而 removePanel 只在自己
+ * 那个菜单索引下找条目。面板被搬过家之后它找不到、只把 file 记录删了,
+ * 于是菜单里留下一条永远 404 的孤儿链接 —— 这里按 file 记录对账删掉;
+ * 2) 插件目录被直接删掉(没走停用流程),file 记录还在但文件没了,
+ * extending.php 会 require 一个不存在的文件 —— 一并清掉。
+ */
+ private static function prune(array $table, &$dirty)
+ {
+ if (empty($table['file']) || empty($table['child'])) {
+ return $table;
+ }
+
+ $known = array();
+
+ foreach ($table['file'] as $key => $file) {
+ $known[(string) $file] = $key;
+ }
+
+ foreach ($table['child'] as $index => $items) {
+ foreach ($items as $key => $item) {
+ $panel = self::panelFromUrl(isset($item[2]) ? $item[2] : '');
+
+ if ('' === $panel) {
+ continue;
+ }
+
+ $encoded = urlencode($panel);
+
+ if (!isset($known[$encoded])) {
+ unset($table['child'][$index][$key]);
+ $dirty = true;
+ continue;
+ }
+
+ if (!self::panelFileExists($panel)) {
+ unset($table['child'][$index][$key]);
+ unset($table['file'][$known[$encoded]]);
+ unset($known[$encoded]);
+ $dirty = true;
+ }
+ }
+
+ if (empty($table['child'][$index])) {
+ unset($table['child'][$index]);
+ $dirty = true;
+ }
+ }
+
+ return $table;
+ }
+
+ /**
+ * 从面板链接里取回面板路径
+ *
+ * 两种形式都要认:
+ * panelTable 里存的是 'extending.php?panel=EditHistory%2Fmanage-panel.php'
+ * Widget\Menu / NewAdmin 传出来的是 Common::url() 处理过的完整地址
+ */
+ private static function panelFromUrl($url)
+ {
+ if (!is_string($url) || '' === $url) {
+ return '';
+ }
+
+ $query = parse_url($url, PHP_URL_QUERY);
+
+ if (!is_string($query) || '' === $query) {
+ $query = ltrim($url, '?');
+ }
+
+ parse_str($query, $params);
+
+ return isset($params['panel']) && is_scalar($params['panel'])
+ ? (string) $params['panel']
+ : '';
+ }
+
+ /**
+ * 面板路径 => 配置项标识
+ */
+ private static function slug($panel)
+ {
+ $slug = preg_replace('/[^A-Za-z0-9]+/', '_', (string) $panel);
+
+ return trim((string) $slug, '_');
+ }
+
+ /**
+ * 读取排序值,没填就用默认值
+ *
+ * @param string $name 配置项
+ * @param float $default 默认值
+ * @param bool $custom 是否由用户指定(出参)
+ * @return float
+ */
+ private static function orderOf($name, $default, &$custom = null)
+ {
+ $value = trim((string) self::opt($name, ''));
+
+ if ('' === $value || !is_numeric($value)) {
+ $custom = false;
+
+ return (float) $default;
+ }
+
+ $custom = true;
+
+ return (float) $value;
+ }
+
+ /**
+ * 面板文件是否还在(插件被整个删掉时用来兜底)
+ */
+ private static function panelFileExists($panel)
+ {
+ $panel = trim((string) $panel, '/');
+
+ if (false === strpos($panel, '/')) {
+ return false;
+ }
+
+ list($pluginName, $file) = explode('/', $panel, 2);
+
+ try {
+ $path = Helper::options()->pluginDir($pluginName) . '/' . $file;
+ } catch (\Throwable $e) {
+ return true;
+ }
+
+ return is_file($path);
+ }
+
+ private static function countPanels(array $child)
+ {
+ $total = 0;
+
+ foreach ($child as $items) {
+ $total += is_array($items) ? count($items) : 0;
+ }
+
+ return $total;
+ }
+
+ /**
+ * 已保存的全部配置项(用来补隐藏域)
+ *
+ * @return array
+ */
+ private static function storedConfig()
+ {
+ try {
+ $config = Helper::options()->plugin('ExtMenu');
+ } catch (\Throwable $e) {
+ return array();
+ }
+
+ return is_object($config) ? $config->toArray() : (array) $config;
+ }
+
+ /**
+ * 读插件配置
+ *
+ * 不能用 isset($config->xxx):Typecho 的 Config 没有实现 __isset(),
+ * 返回恒为 false。
+ */
+ private static function opt($name, $default = null)
+ {
+ try {
+ // 插件配置行不存在时,取属性也会抛异常,所以整段都要包进来
+ $value = Helper::options()->plugin('ExtMenu')->{$name};
+ } catch (\Throwable $e) {
+ return $default;
+ }
+
+ return (null === $value || '' === $value) ? $default : $value;
+ }
+}
diff --git a/README.md b/README.md
index c4751db..d12cce4 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,48 @@
-# ExtMenu
+# ExtMenu(扩展管理)
+> 仓库:`ExtMenu` · 类型:Typecho 插件 · 版本:`1.4.0` · 作者:石头厝
+
+把所有插件的后台面板收进一个顶级菜单,并让后台的顶级、二级菜单都能改名、排序、显示隐藏;插件设置可一键备份与恢复。本仓库仅包含插件实现代码与必要文档,不包含备份目录与运行时数据。
+
+## 功能
+
+- **收纳**:各插件通过 `Helper::addPanel()` 注册的后台面板自动集中到顶级菜单「扩展管理」,不再散落在控制台、撰写、管理、设置之下。新启用的插件面板可随「自动收纳」开关自动归入。
+- **菜单定制**:顶级菜单(含美化后台写死的「概要」)及其二级菜单均可修改显示名称、调整排序、设置显示或隐藏;顶级菜单还可更换图标。默认值保持原名与原序,随时可改回。
+- **设置页**:树形卡片结构,顶级一行展示菜单、名称、排序、图标、显隐,点击菜单名展开二级项;支持「展开全部」与「清空全部自定义」。改过名的项显示「原名 → 新名」,隐藏项划线淡显;900px 以下两列堆叠,兼容深浅色后台。
+- **备份 / 恢复**:设置页顶部提供备份、恢复、历史备份。默认保留最近 5 份,历史备份列出时间、项数、大小与版本,可任选一份恢复。备份以 zlib 压缩后 base64 存储的 `.php` 文件保存,位于 `data/backup/`,带 `.htaccess` 禁止公网下载。
+- **兼容性**:支持原版后台与 NewAdmin 美化后台,两套后台的改名、排序、隐藏表现一致。
+
+## 环境要求
+
+- Typecho 1.3.0 及以上(1.2.x 缺少 `addMenu` 与父菜单映射机制)。
+- MySQL / PostgreSQL / SQLite 均可。
+- 「概要」顶级项由 NewAdmin 2.6.2 起交给菜单过滤器,本插件同时带兜底脚本;旧版 NewAdmin 也可改名、换图标、隐藏。原版后台中它属于「控制台」下的二级项,请在二级中修改。
+
+## 安装与升级
+
+1. 首次安装:将本仓库目录上传到 `usr/plugins/ExtMenu/`,在后台启用。启用时会把已有插件面板一次性搬进「扩展管理」。
+2. 从 1.2 / 1.3 升级:直接覆盖 `Plugin.php`,无需停用再启用(钩子未变);旧配置键会在下次进入后台时自动迁移。
+3. 停用:面板会自动放回「管理」,不会出现页面找不回的情况。
+
+## 配置项说明
+
+- 自动收纳:开启后,之后启用的新插件面板自动归入「扩展管理」;关闭则只保留本次收纳结果。
+- 名称 / 排序 / 图标 / 显隐:仅在渲染时套用,不写回面板表,因此清空自定义即可恢复默认,操作可逆。
+- 菜单标识使用指纹而非顺序:顶级菜单用核心序号或菜单名 md5,二级菜单用「父级 + 链接」的 md5,插件增删或菜单换序不会导致配置错位。
+
+## 权限与安全
+
+- 备份与恢复仅对管理员开放,操作链接带站点 secret 与用户 uid 计算的令牌;`data/backup/` 通过 `.htaccess` 拒绝公网访问。
+- 隐藏仅去除后台入口,页面地址本身仍可直接访问;需要时把显隐改回「显示」即可。若把「扩展管理」自身隐藏,可从「插件 → 设置」进入改回。
+
+## 开发与贡献
+
+详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
+
+## 授权
+
+授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
+
+## 变更记录
+
+详见 [CHANGELOG.md](CHANGELOG.md)。