2642 lines
89 KiB
PHP
2642 lines
89 KiB
PHP
<?php
|
||
/**
|
||
* 扩展管理
|
||
*
|
||
* 后台菜单统一改名、排序、显示隐藏
|
||
* @package ExtMenu
|
||
* @version 1.4.0
|
||
* @author 石头厝
|
||
* @link https://www.shitoucuo.com/
|
||
*/
|
||
|
||
class ExtMenu_Plugin implements Typecho_Plugin_Interface
|
||
{
|
||
/** 顶级菜单名 */
|
||
const MENU_NAME = '扩展管理';
|
||
|
||
/** 停用插件时,面板回落到哪个菜单:1 控制台 / 2 撰写 / 3 管理 / 4 设置 */
|
||
const FALLBACK_INDEX = 3;
|
||
|
||
/** 设置备份的文件名前缀 */
|
||
const BACKUP_PREFIX = 'em-settings-';
|
||
|
||
/** 设置备份默认保留份数 */
|
||
const BACKUP_KEEP = 5;
|
||
|
||
/** 原版后台的四个顶级菜单(键 => 默认名称) */
|
||
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
|
||
? '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl) . '"'
|
||
. ' onclick="return confirm(\'恢复会用最新一份备份覆盖当前插件设置,确定继续?\');">恢复</a>'
|
||
: '<span class="cnot-btn cnot-btn-ghost is-disabled" aria-disabled="true" title="还没有备份">恢复</span>';
|
||
|
||
/* 历史备份:只有一份时「恢复」就是它,不必再展开列表 */
|
||
$historyBtn = '';
|
||
$historyBox = '';
|
||
if (count($list) > 1) {
|
||
$rows = '';
|
||
foreach ($list as $index => $item) {
|
||
$rows .= '<div class="cnot-backup-item">'
|
||
. '<div class="cnot-backup-main">'
|
||
. '<span class="cnot-backup-time">' . self::e(date('Y-m-d H:i:s', $item['created'])) . '</span>'
|
||
. ($index === 0 ? '<span class="cnot-backup-tag">最新</span>' : '')
|
||
. '<span class="cnot-backup-desc">' . intval($item['count']) . ' 项配置 · '
|
||
. self::e(self::formatBytes($item['size']))
|
||
. ($item['version'] !== '' ? ' · v' . self::e($item['version']) : '')
|
||
. '</span>'
|
||
. '</div>'
|
||
. '<a class="cnot-btn cnot-btn-ghost" href="' . self::e($restoreUrl . '&file=' . rawurlencode($item['file'])) . '"'
|
||
. ' onclick="return confirm(\'用 ' . self::e(date('Y-m-d H:i', $item['created'])) . ' 的这份备份覆盖当前插件设置?\');">恢复</a>'
|
||
. '</div>';
|
||
}
|
||
|
||
$historyBtn = '<a class="cnot-btn cnot-btn-ghost" id="cnot-backups-btn" href="#cnot-backups"'
|
||
. ' aria-expanded="false" aria-controls="cnot-backups">历史备份</a>';
|
||
|
||
$historyBox = '<div class="cnot-backups" id="cnot-backups" hidden>'
|
||
. '<div class="cnot-backups-head"><strong>历史备份</strong><span>从新到旧,点「恢复」就用那一份覆盖当前设置</span></div>'
|
||
. $rows
|
||
. '</div>'
|
||
. '<script>(function(){var box=document.getElementById("cnot-backups");'
|
||
. 'var btn=document.getElementById("cnot-backups-btn");'
|
||
. 'if(!box||!btn||!btn.addEventListener){return;}'
|
||
. 'btn.addEventListener("click",function(e){'
|
||
. 'if(e&&e.preventDefault){e.preventDefault();}'
|
||
. 'var open=box.hasAttribute("hidden");'
|
||
. 'if(open){box.removeAttribute("hidden");}else{box.setAttribute("hidden","hidden");}'
|
||
. 'btn.textContent=open?"收起备份":"历史备份";'
|
||
. 'btn.setAttribute("aria-expanded",open?"true":"false");'
|
||
. 'return false;});'
|
||
. '})();</script>';
|
||
}
|
||
|
||
return '<div class="cnot-hero">'
|
||
. '<div class="cnot-hero-icon">'
|
||
. '<svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="currentColor" stroke-width="1.8"'
|
||
. ' stroke-linecap="round" stroke-linejoin="round">'
|
||
. '<path d="M4 7h16M6 7v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7"/>'
|
||
. '<path d="M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>'
|
||
. '<path d="M10 11h4M10 15h4"/></svg>'
|
||
. '</div>'
|
||
. '<div class="cnot-hero-text">'
|
||
. '<div class="cnot-hero-title">'
|
||
. '<h2>' . self::e(self::MENU_NAME) . '</h2>'
|
||
. '</div>'
|
||
. '<p>后台菜单改名、排序、显示隐藏,以及插件面板的收纳设置,都可以存成一份文件;改乱了点「恢复」就能退回上一次。</p>'
|
||
. '<div class="cnot-hero-ops">'
|
||
. '<a class="cnot-btn" href="' . self::e($backupUrl) . '">备份</a>'
|
||
. $restoreBtn
|
||
. $historyBtn
|
||
. '<span class="cnot-hero-meta">' . $meta . '</span>'
|
||
. '</div>'
|
||
. '</div>'
|
||
. '</div>'
|
||
. $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 '<div class="cnot-note ' . ($ok ? 'cnot-note-ok' : 'cnot-note-fail') . '">' . self::e($text) . '</div>';
|
||
}
|
||
|
||
/**
|
||
* 备份文件目录
|
||
*/
|
||
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 = '<?php /* EM-SETTINGS-BACKUP '
|
||
. json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||
. ' */ exit; ?>' . "\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<script>(function(){var d=" . $json . ";"
|
||
. "function t(e){return (e.textContent||'').replace(/^\\s+|\\s+$/g,'');}"
|
||
. "function seq(a,b){return a.o-b.o||a.i-b.i;}"
|
||
. "function kids(li,list){var s=li.querySelector('menu');if(!s){return;}"
|
||
. "var m={},all=[],i,n;"
|
||
. "for(i=0;i<s.children.length;i++){n=s.children[i];"
|
||
. "if(n.tagName!=='LI'||!n.firstElementChild){continue;}all.push(n);m[t(n.firstElementChild)]=n;}"
|
||
. "var r=[],k=0;list.forEach(function(x){var node=m[x.f];if(!node){return;}delete m[x.f];"
|
||
. "if(x.h){s.removeChild(node);return;}"
|
||
. "if(x.t){node.firstElementChild.textContent=x.t;}r.push({o:x.o,i:k++,li:node});});"
|
||
. "all.forEach(function(node,j){if(node.parentNode!==s){return;}"
|
||
. "var used=false;r.forEach(function(x){if(x.li===node){used=true;}});"
|
||
. "if(!used){r.push({o:1e9,i:1e3+j,li:node});}});"
|
||
. "r.sort(seq);r.forEach(function(x){s.appendChild(x.li);});}"
|
||
. "function run(){var nav=document.querySelector('.typecho-head-nav > nav > menu');if(!nav){return;}"
|
||
. "var op=nav.querySelector('li.operate'),all=[],by={},i,li;"
|
||
. "for(i=0;i<nav.children.length;i++){li=nav.children[i];"
|
||
. "if(li.tagName!=='LI'||(li.className||'').indexOf('operate')>-1){continue;}"
|
||
. "if(!li.firstElementChild||li.firstElementChild.tagName!=='A'){continue;}all.push(li);by[t(li.firstElementChild)]=li;}"
|
||
. "if(!all.length){return;}"
|
||
. "var r=[],k=0;(d.p||[]).forEach(function(x){var node=by[x.f];if(!node){return;}delete by[x.f];"
|
||
. "if(x.h){nav.removeChild(node);return;}"
|
||
. "if(x.c&&x.c.length){kids(node,x.c);var sm=node.querySelector('menu');"
|
||
. "if(!sm||!sm.children.length){nav.removeChild(node);return;}}"
|
||
. "if(x.t){node.firstElementChild.textContent=x.t;}"
|
||
. "r.push({o:x.o,i:k++,li:node});});"
|
||
. "all.forEach(function(node,j){if(node.parentNode!==nav){return;}"
|
||
. "var used=false;r.forEach(function(x){if(x.li===node){used=true;}});"
|
||
. "if(!used){r.push({o:1e9,i:1e3+j,li:node});}});"
|
||
. "r.sort(seq);r.forEach(function(x){nav.insertBefore(x.li,op);});}"
|
||
. "if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',run);}else{run();}"
|
||
. "})();</script>";
|
||
}
|
||
|
||
/**
|
||
* 美化后台里「概要」这一项的兜底脚本
|
||
*
|
||
* 「概要」在 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<script>(function(){var d=" . $json . ";"
|
||
. "function plain(s){return (s||'').replace(/^\\s+|\\s+$/g,'');}"
|
||
. "function label(a){var i,n;"
|
||
. "for(i=a.childNodes.length-1;i>=0;i--){n=a.childNodes[i];"
|
||
. "if(n.nodeType===3&&plain(n.nodeValue)){return n;}}return null;}"
|
||
. "function run(){"
|
||
. "var box=document.querySelector('#newadmin .menu')||document.querySelector('.typecho-head-nav');"
|
||
. "if(!box){return;}"
|
||
. "var li=box.querySelector('li.menua');if(!li){return;}"
|
||
. "if(d.h){if(li.parentNode){li.parentNode.removeChild(li);}return;}"
|
||
. "var a=li.querySelector('a');if(!a){return;}"
|
||
. "if(d.t){var t=label(a);"
|
||
. "if(t){if(plain(t.nodeValue)!==d.t){t.nodeValue=d.t;}}"
|
||
. "else{a.appendChild(document.createTextNode(d.t));}}"
|
||
. "if(d.i){var u=a.querySelector('use');"
|
||
. "if(u){var h=u.getAttribute('xlink:href')||u.getAttribute('href')||'';"
|
||
. "u.setAttribute('xlink:href',h.replace(/#.*$/,'')+'#icon-'+d.i);}}}"
|
||
. "if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',run);}else{run();}"
|
||
. "})();</script>";
|
||
}
|
||
|
||
/**
|
||
* 美化后台(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'
|
||
<style>
|
||
/* 插件设置页:后台菜单树 */
|
||
.em-card{margin:0 0 20px;background:#fff;border:1px solid #e2e6ec;border-radius:8px}
|
||
.em-card-hd{display:flex;align-items:center;gap:12px;padding:12px 16px;background:#f7f9fb;border-bottom:1px solid #e6eaef;border-radius:8px 8px 0 0}
|
||
.em-card-hd h4{margin:0;font-size:14px;font-weight:600;color:#2b3440;white-space:nowrap}
|
||
.em-card-hd .em-tip{flex:1 1 auto;min-width:0;font-size:12px;color:#8b95a3;line-height:1.5}
|
||
.em-btn{flex:0 0 auto;padding:5px 12px;font-size:12px;color:#5b6675;background:#fff;border:1px solid #d5dbe3;border-radius:4px;cursor:pointer}
|
||
.em-btn:hover{color:#c0392b;border-color:#e3b0a8;background:#fdf5f4}
|
||
.em-btn.em-plain:hover{color:#1f6feb;border-color:#a8c7f0;background:#f4f8ff}
|
||
.em-grid{padding:4px 16px 14px}
|
||
.em-row{display:grid;grid-template-columns:minmax(118px,.95fr) minmax(108px,1.25fr) 62px minmax(84px,.85fr) 70px;gap:10px;align-items:center;padding:7px 0;border-bottom:1px solid #f1f3f6}
|
||
.em-head{font-size:12px;color:#8b95a3;padding-bottom:6px;border-bottom-color:#e6eaef}
|
||
.em-name-wrap{display:flex;align-items:center;gap:6px;min-width:0;cursor:default}
|
||
.em-node.has-kids > .em-row > .em-name-wrap{cursor:pointer}
|
||
.em-caret{flex:0 0 auto;width:0;height:0;border-left:5px solid #94a3b5;border-top:4px solid transparent;border-bottom:4px solid transparent;transition:transform .15s}
|
||
.em-node.open > .em-row > .em-name-wrap .em-caret{transform:rotate(90deg)}
|
||
.em-name{font-size:13px;color:#2b3440;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.em-sub{display:none}
|
||
.em-node.open > .em-sub{display:block}
|
||
.em-row-c{background:#fbfcfe}
|
||
.em-row-c .em-name-wrap{padding-left:16px}
|
||
.em-row-c .em-name{font-size:12.5px;color:#4a5666}
|
||
.em-row.is-off .em-name{color:#b2bbc7;text-decoration:line-through}
|
||
.em-cell{min-width:0}
|
||
.em-cell .typecho-option{margin:0;padding:0;border:0;background:none;list-style:none}
|
||
.em-cell .typecho-option .typecho-label,
|
||
.em-cell .typecho-option .description{display:none}
|
||
.em-cell .typecho-option input[type=text],
|
||
.em-cell .typecho-option select{width:100%;margin:0;box-sizing:border-box}
|
||
/* ------------------------------------------------------------------
|
||
* 顶部:设置备份卡片(结构与样式完整照搬 MailNotifier 的 cnot-hero)
|
||
* 注意 .cnot-hero-meta 放在 .cnot-hero-ops 内,flex-basis:100% 让它换行到按钮下一行
|
||
* ---------------------------------------------------------------- */
|
||
.cnot-hero,.cnot-note,.cnot-backups{box-sizing:border-box;width:100%;}
|
||
.cnot-hero{position:relative;display:flex;align-items:flex-start;gap:18px;flex-wrap:wrap;margin:6px 0 12px;padding:22px 24px;border:1px solid rgba(126,96,60,.15);border-radius:8px;background:linear-gradient(135deg,rgba(255,253,248,.98),rgba(246,236,223,.86));box-shadow:0 14px 34px rgba(75,56,35,.075);overflow:hidden;}
|
||
.cnot-hero:after{content:"";position:absolute;right:-44px;top:-50px;width:170px;height:170px;border-radius:50%;background:rgba(126,96,60,.065);}
|
||
.cnot-hero-icon{position:relative;z-index:1;width:54px;height:54px;display:grid;place-items:center;flex:0 0 54px;border-radius:8px;color:#7f603d;background:linear-gradient(145deg,rgba(255,253,248,.88),rgba(239,225,207,.72));border:1px solid rgba(126,96,60,.18);font-size:25px;box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 12px 24px rgba(93,68,43,.08);}
|
||
.cnot-hero-text{position:relative;z-index:1;min-width:0;flex:1 1 300px;}
|
||
.cnot-hero h2{position:relative;z-index:1;margin:0;color:#2d2824;font-size:14px;line-height:1.5;font-weight:600;}
|
||
.cnot-hero p{position:relative;z-index:1;margin:6px 0 0;color:#6f6153;font-size:12px;line-height:1.6;}
|
||
.cnot-hero-title{position:relative;z-index:1;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
|
||
.cnot-hero-ops{position:relative;z-index:1;display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:12px;}
|
||
.cnot-hero-meta{flex-basis:100%;margin-top:2px;color:#8d7b6a;font-size:12px;line-height:1.5;}
|
||
.cnot-btn{height:32px;padding:0 12px;display:inline-flex;align-items:center;justify-content:center;border-radius:4px;text-decoration:none!important;color:#fff!important;background:linear-gradient(135deg,#8b633b,#a77b4c);box-shadow:0 4px 12px rgba(125,90,50,.16);font-size:12px;font-weight:600;white-space:nowrap;}
|
||
.cnot-btn:hover{transform:translateY(-1px);}
|
||
.cnot-hero .cnot-btn{height:30px;padding:0 12px;font-size:12px;}
|
||
.cnot-btn-ghost{color:#6d4a2b!important;background:rgba(255,255,255,.92)!important;border:1px solid rgba(126,96,60,.22);box-shadow:none;}
|
||
.cnot-btn-ghost.is-disabled{opacity:.42;cursor:not-allowed;box-shadow:none;}
|
||
.cnot-btn-ghost.is-disabled:hover{transform:none;}
|
||
.cnot-note{margin:-2px 0 16px;padding:9px 14px;border-radius:8px;font-size:12px;line-height:1.6;}
|
||
.cnot-note-ok{color:#2f8a57;background:rgba(47,138,87,.10);border:1px solid rgba(47,138,87,.18);}
|
||
.cnot-note-fail{color:#b4503f;background:rgba(180,80,63,.10);border:1px solid rgba(180,80,63,.18);}
|
||
.cnot-backups{margin:-6px 0 18px;padding:4px 6px 6px;border:1px solid rgba(126,96,60,.14);border-radius:8px;background:rgba(255,255,255,.86);box-shadow:0 4px 16px rgba(75,56,35,.045);}
|
||
.cnot-backups[hidden]{display:none;}
|
||
.cnot-backups-head{display:flex;align-items:baseline;gap:9px;flex-wrap:wrap;padding:10px 11px 8px;}
|
||
.cnot-backups-head strong{color:#342b24;font-size:13px;}
|
||
.cnot-backups-head span{color:#8d7b6a;font-size:12px;line-height:1.5;}
|
||
.cnot-backup-item{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 11px;border-radius:4px;}
|
||
.cnot-backup-item+.cnot-backup-item{border-top:1px solid rgba(126,96,60,.10);}
|
||
.cnot-backup-main{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;min-width:0;}
|
||
.cnot-backup-time{color:#3f342a;font-size:12.5px;font-weight:600;font-variant-numeric:tabular-nums;}
|
||
.cnot-backup-tag{padding:1px 7px;border-radius:4px;background:#8b633b;color:#fff;font-size:11px;font-weight:600;line-height:1.7;}
|
||
.cnot-backup-desc{color:#8d7b6a;font-size:12px;}
|
||
.cnot-backup-item .cnot-btn{flex:0 0 auto;height:28px;padding:0 12px;font-size:12px;}
|
||
@media(max-width:680px){.cnot-hero{padding:16px 14px;align-items:flex-start}.cnot-hero-icon{width:44px;height:44px;flex-basis:44px;border-radius:8px}.cnot-hero h2{font-size:14px}.cnot-hero p{font-size:12px;line-height:1.6}.cnot-hero-title{gap:10px}.cnot-hero-ops{margin-top:10px;gap:8px}.cnot-hero-ops .cnot-btn{box-sizing:border-box;flex:1 1 0;min-width:0;height:32px;padding:0 8px;font-size:12px}.cnot-hero-meta{flex-basis:100%}.cnot-backups{padding:2px 4px 4px}.cnot-backups-head{padding:10px 9px 8px;gap:5px}.cnot-backup-item{padding:9px;gap:9px}.cnot-backup-item .cnot-btn{flex:0 0 auto;height:30px;padding:0 12px;font-size:12px}}
|
||
@media(max-width:900px){
|
||
.em-row{grid-template-columns:1fr 1fr;gap:6px 10px}
|
||
.em-head{display:none}
|
||
.em-row > .em-name-wrap{grid-column:1/-1;padding-top:4px}
|
||
.em-spacer{display:none}
|
||
.em-row-c .em-name-wrap{padding-left:14px}
|
||
}
|
||
#newadmin.dark .em-card{background:#17212f;border-color:#23303f}
|
||
#newadmin.dark .em-card-hd{background:#1f2937;border-bottom-color:#23303f}
|
||
#newadmin.dark .em-card-hd h4{color:#e6edf3}
|
||
#newadmin.dark .em-card-hd .em-tip{color:#9cb0c6}
|
||
#newadmin.dark .em-btn{color:#c3d1de;background:#1f2937;border-color:#2b3a4d}
|
||
#newadmin.dark .em-btn:hover{color:#f0a49a;border-color:#5b3b3b;background:#241f26}
|
||
#newadmin.dark .em-btn.em-plain:hover{color:#8bbcf5;border-color:#2b4a72;background:#1b2b3f}
|
||
#newadmin.dark .em-row{border-bottom-color:#23303f}
|
||
#newadmin.dark .em-head{color:#9cb0c6;border-bottom-color:#23303f}
|
||
#newadmin.dark .em-name{color:#e6edf3}
|
||
#newadmin.dark .em-row-c{background:#1b2534}
|
||
#newadmin.dark .em-row-c .em-name{color:#b7c6d6}
|
||
#newadmin.dark .em-row.is-off .em-name{color:#64748b}
|
||
/* 深色:备份卡片,照搬 MailNotifier 用 .dark 前缀(body 与 #newadmin 同时命中) */
|
||
.dark .cnot-hero{background:linear-gradient(135deg,#1b2635,#18212f);border-color:rgba(255,255,255,.10);box-shadow:0 14px 34px rgba(0,0,0,.28);}
|
||
.dark .cnot-hero:after{background:rgba(208,168,119,.07);}
|
||
.dark .cnot-hero-icon{color:#d0a877;background:linear-gradient(145deg,#202c3d,#1a2434);border-color:rgba(255,255,255,.10);box-shadow:inset 0 1px 0 rgba(255,255,255,.06),0 12px 24px rgba(0,0,0,.30);}
|
||
.dark .cnot-hero h2{color:#e8eef7;}
|
||
.dark .cnot-hero p{color:#9aa8bb;}
|
||
.dark .cnot-btn{background:linear-gradient(135deg,#9d7247,#bb8c57);box-shadow:0 4px 12px rgba(0,0,0,.24);}
|
||
.dark .cnot-hero-meta{color:#93a2b8;}
|
||
.dark .cnot-btn-ghost{color:#e8d0ad!important;background:rgba(255,255,255,.06)!important;border-color:rgba(255,255,255,.14);box-shadow:none;}
|
||
.dark .cnot-note-ok{color:#4ade80;background:rgba(74,222,128,.10);border-color:rgba(74,222,128,.20);}
|
||
.dark .cnot-note-fail{color:#f87171;background:rgba(248,113,113,.10);border-color:rgba(248,113,113,.20);}
|
||
.dark .cnot-backups{background:#1b2635;border-color:rgba(255,255,255,.10);box-shadow:0 12px 30px rgba(0,0,0,.22);}
|
||
.dark .cnot-backups-head strong{color:#e8eef7;}
|
||
.dark .cnot-backups-head span{color:#93a2b8;}
|
||
.dark .cnot-backup-item+.cnot-backup-item{border-top-color:rgba(255,255,255,.08);}
|
||
.dark .cnot-backup-time{color:#e8eef7;}
|
||
.dark .cnot-backup-tag{background:#d0a877;color:#18212f;}
|
||
.dark .cnot-backup-desc{color:#93a2b8;}
|
||
</style>
|
||
CSS;
|
||
|
||
$js = <<<'JS'
|
||
<script>
|
||
(function () {
|
||
var M = __META__;
|
||
var groups = {};
|
||
var known = {};
|
||
|
||
(M.t || []).forEach(function (p) {
|
||
known['m_' + p.k] = p.n;
|
||
groups['m_' + p.k] = { cells: {} };
|
||
|
||
(p.c || []).forEach(function (k) {
|
||
known['c_' + k.k] = k.n;
|
||
groups['c_' + k.k] = { cells: {} };
|
||
});
|
||
});
|
||
|
||
function el(tag, cls, text) {
|
||
var e = document.createElement(tag);
|
||
if (cls) { e.className = cls; }
|
||
if (text != null) { e.textContent = text; }
|
||
return e;
|
||
}
|
||
|
||
function input(key, f) {
|
||
var g = groups[key];
|
||
var ul = g && g.cells[f];
|
||
return ul ? ul.querySelector('input, select') : null;
|
||
}
|
||
|
||
function cell(key, f) {
|
||
var wrap = el('div', 'em-cell');
|
||
var ul = groups[key] && groups[key].cells[f];
|
||
|
||
if (!ul) { return wrap; }
|
||
|
||
var lab = ul.querySelector('label.typecho-label');
|
||
if (lab) { lab.style.display = 'none'; }
|
||
|
||
var desc = ul.querySelector('.description');
|
||
if (desc) { desc.style.display = 'none'; }
|
||
|
||
wrap.appendChild(ul);
|
||
return wrap;
|
||
}
|
||
|
||
function nameCell(key) {
|
||
var span = el('span', 'em-name', known[key]);
|
||
var node = input(key, 'n');
|
||
|
||
function sync() {
|
||
var v = node ? (node.value || '') : '';
|
||
span.textContent = v && v !== known[key] ? known[key] + ' → ' + v : known[key];
|
||
span.title = span.textContent;
|
||
}
|
||
|
||
if (node) {
|
||
node.addEventListener('input', sync);
|
||
sync();
|
||
}
|
||
|
||
return span;
|
||
}
|
||
|
||
function watchOff(row, key) {
|
||
var sel = input(key, 'v');
|
||
|
||
function sync() {
|
||
row.classList.toggle('is-off', !!sel && sel.value === '0');
|
||
}
|
||
|
||
if (sel) { sel.addEventListener('change', sync); }
|
||
sync();
|
||
}
|
||
|
||
function trigger(node, type) {
|
||
try {
|
||
node.dispatchEvent(new Event(type));
|
||
} catch (e) {
|
||
}
|
||
}
|
||
|
||
function reset() {
|
||
if (!confirm('清空所有改名、排序、图标和显示/隐藏设置?\n清空后请点底部的「保存设置」才会生效。')) {
|
||
return;
|
||
}
|
||
|
||
var all = document.querySelectorAll('form[action*="plugins-edit"] [name]');
|
||
var i, node, name;
|
||
|
||
for (i = 0; i < all.length; i++) {
|
||
node = all[i];
|
||
name = node.name;
|
||
|
||
if (!/^[mcp][novi]_/.test(name)) {
|
||
continue;
|
||
}
|
||
|
||
if (node.tagName === 'SELECT') {
|
||
node.value = /^[mcp]v_/.test(name) ? '1' : '';
|
||
trigger(node, 'change');
|
||
} else {
|
||
node.value = '';
|
||
trigger(node, 'input');
|
||
}
|
||
}
|
||
}
|
||
|
||
function parentNode(p) {
|
||
var key = 'm_' + p.k;
|
||
var kids = p.c || [];
|
||
var node = el('div', 'em-node' + (kids.length ? ' has-kids' : ''));
|
||
var row = el('div', 'em-row em-row-p');
|
||
var wrap = el('div', 'em-name-wrap');
|
||
|
||
if (kids.length) {
|
||
wrap.appendChild(el('span', 'em-caret'));
|
||
}
|
||
|
||
wrap.appendChild(nameCell(key));
|
||
|
||
row.appendChild(wrap);
|
||
row.appendChild(cell(key, 'n'));
|
||
row.appendChild(cell(key, 'o'));
|
||
row.appendChild(cell(key, 'i'));
|
||
row.appendChild(cell(key, 'v'));
|
||
|
||
node.appendChild(row);
|
||
watchOff(row, key);
|
||
|
||
if (kids.length) {
|
||
var sub = el('div', 'em-sub');
|
||
|
||
kids.forEach(function (k) {
|
||
var ck = 'c_' + k.k;
|
||
var crow = el('div', 'em-row em-row-c');
|
||
var cwrap = el('div', 'em-name-wrap');
|
||
|
||
cwrap.appendChild(nameCell(ck));
|
||
crow.appendChild(cwrap);
|
||
crow.appendChild(cell(ck, 'n'));
|
||
crow.appendChild(cell(ck, 'o'));
|
||
crow.appendChild(el('div', 'em-spacer'));
|
||
crow.appendChild(cell(ck, 'v'));
|
||
|
||
sub.appendChild(crow);
|
||
watchOff(crow, ck);
|
||
});
|
||
|
||
node.appendChild(sub);
|
||
|
||
row.addEventListener('click', function (e) {
|
||
var t = e.target;
|
||
|
||
// 点输入框、下拉框不触发收起,免得填一半菜单塌了
|
||
if (t && t.closest && t.closest('.em-cell')) {
|
||
return;
|
||
}
|
||
|
||
node.classList.toggle('open');
|
||
});
|
||
}
|
||
|
||
return node;
|
||
}
|
||
|
||
function run() {
|
||
var form = document.querySelector('form[action*="plugins-edit"]');
|
||
|
||
if (!form || !form.children) {
|
||
return;
|
||
}
|
||
|
||
var i, node, field, match, key, items = [];
|
||
|
||
for (i = 0; i < form.children.length; i++) {
|
||
node = form.children[i];
|
||
|
||
if (node.tagName === 'UL' && (' ' + node.className + ' ').indexOf(' typecho-option ') > -1) {
|
||
items.push(node);
|
||
}
|
||
}
|
||
|
||
// 卡片插入位置要在搬走字段之前定下来,否则参照点可能已经被搬进卡片
|
||
var anchor = items.length ? items[0] : (form.firstChild || null);
|
||
|
||
items.forEach(function (ul) {
|
||
field = ul.querySelector('[name]');
|
||
match = field ? /^([mc])([novi])_(.+)$/.exec(field.name) : null;
|
||
|
||
if (!match) {
|
||
return;
|
||
}
|
||
|
||
key = match[1] + '_' + match[3];
|
||
|
||
// 历史遗留字段(插件已删、菜单已没)不参与重排,保持原样
|
||
if (!groups[key]) {
|
||
return;
|
||
}
|
||
|
||
groups[key].cells[match[2]] = ul;
|
||
});
|
||
|
||
var total = 0;
|
||
|
||
Object.keys(groups).forEach(function (k) {
|
||
total += Object.keys(groups[k].cells).length;
|
||
});
|
||
|
||
if (!total) {
|
||
return;
|
||
}
|
||
|
||
// 5 列在默认的 8/12 宽容器里太挤,撑满整行
|
||
var box = form.parentNode;
|
||
|
||
if (box && /\bcol-tb-8\b/.test(box.className || '')) {
|
||
box.className = box.className
|
||
.replace(/\bcol-tb-8\b/, 'col-tb-12')
|
||
.replace(/\bcol-tb-offset-2\b/, '');
|
||
}
|
||
|
||
var card = el('div', 'em-card em-card-menu');
|
||
var head = el('div', 'em-card-hd');
|
||
|
||
head.appendChild(el('h4', '', '后台菜单'));
|
||
head.appendChild(el('span', 'em-tip',
|
||
'点击菜单名展开二级菜单。排序值越小越靠前,留空按默认顺序;'
|
||
+ '隐藏只去掉菜单入口,页面本身仍可直接访问。'));
|
||
|
||
var expand = el('button', 'em-btn em-plain', '展开全部');
|
||
expand.type = 'button';
|
||
expand.addEventListener('click', function () {
|
||
var open = expand.textContent === '展开全部';
|
||
var all = card.querySelectorAll('.em-node');
|
||
var i;
|
||
|
||
for (i = 0; i < all.length; i++) {
|
||
all[i].classList.toggle('open', open);
|
||
}
|
||
|
||
expand.textContent = open ? '收起全部' : '展开全部';
|
||
});
|
||
|
||
var clear = el('button', 'em-btn', '清空全部自定义');
|
||
clear.type = 'button';
|
||
clear.addEventListener('click', reset);
|
||
|
||
head.appendChild(expand);
|
||
head.appendChild(clear);
|
||
card.appendChild(head);
|
||
|
||
var grid = el('div', 'em-grid');
|
||
var header = el('div', 'em-row em-head');
|
||
|
||
['菜单', '名称', '排序', '图标', '显隐'].forEach(function (t) {
|
||
header.appendChild(el('span', '', t));
|
||
});
|
||
|
||
grid.appendChild(header);
|
||
|
||
(M.t || []).forEach(function (p) {
|
||
grid.appendChild(parentNode(p));
|
||
});
|
||
|
||
card.appendChild(grid);
|
||
|
||
if (anchor) {
|
||
form.insertBefore(card, anchor);
|
||
} else {
|
||
form.appendChild(card);
|
||
}
|
||
}
|
||
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', run);
|
||
} else {
|
||
run();
|
||
}
|
||
})();
|
||
</script>
|
||
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;
|
||
}
|
||
}
|