You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于页面最后修订日期为MediaWiki内部链接设置自定义样式?

实现MediaWiki内部链接按目标页面修订日期添加样式的方案

一、服务器端PHP实现(推荐,性能更优)

利用MediaWiki的钩子机制,在链接渲染阶段直接注入CSS类,无需前端额外请求。

关键钩子与核心代码

  1. 注册钩子:在LocalSettings.php中添加钩子注册(或封装成自定义扩展):
$wgHooks['LinkBegin'][] = 'addOutdatedLinkClass';
  1. 实现钩子函数:创建处理函数,获取页面修订时间并添加样式类:
function addOutdatedLinkClass( $skin, $target, &$text, &$customAttribs, &$query, &$options, &$ret ) {
    // 仅处理内部页面链接
    if ( !$target->isLocal() || $target->isSpecial() ) {
        return true;
    }

    try {
        // 获取页面对象
        $page = WikiPage::factory( $target );
        if ( !$page->exists() ) {
            return true;
        }

        // 获取最后修订时间(Unix时间戳)
        $lastRevTimestamp = wfTimestamp( TS_UNIX, $page->getTimestamp() );
        // 定义"过时"阈值,比如超过180天(60*60*24*180)
        $outdatedThreshold = time() - ( 60 * 60 * 24 * 180 );

        if ( $lastRevTimestamp < $outdatedThreshold ) {
            // 添加自定义CSS类
            $customAttribs['class'] = isset( $customAttribs['class'] ) ? $customAttribs['class'] . ' outdated-link' : 'outdated-link';
        }
    } catch ( Exception $e ) {
        // 出错时不中断链接渲染
        return true;
    }

    return true;
}
  1. 添加自定义CSS:在MediaWiki的公共CSS页面(如MediaWiki:Common.css)中定义样式:
.outdated-link {
    color: #d9534f;
    border-bottom: 1px dashed #d9534f;
}

参考资源

  • MediaWiki官方文档:Hook:LinkBegin(链接渲染开始时触发的钩子)
  • MediaWiki核心类:WikiPage(用于获取页面元数据与修订信息)

二、客户端JS+API实现(无需修改服务器代码)

通过MediaWiki Action API批量获取页面修订时间,前端动态添加样式。

核心代码示例

document.addEventListener('DOMContentLoaded', function() {
    // 获取所有内部页面链接(排除特殊页面、非wiki链接)
    const links = document.querySelectorAll('.mw-body-content a[href^="/wiki/"]:not([href*="Special:"])');
    if (links.length === 0) return;

    // 提取页面标题(处理URL解码与下划线转空格)
    const titles = Array.from(links).map(link => {
        const title = link.href.split('/wiki/')[1];
        return decodeURIComponent(title).replace(/_/g, ' ');
    });

    // 调用MediaWiki Action API批量获取修订时间
    fetch(`${mw.config.get('wgScriptPath')}/api.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'query',
            format: 'json',
            titles: titles.join('|'),
            prop: 'revisions',
            rvprop: 'timestamp',
            rvlimit: 1
        })
    })
    .then(res => res.json())
    .then(data => {
        const pages = data.query.pages;
        // 遍历页面数据,匹配链接并添加样式
        Array.from(links).forEach(link => {
            const title = decodeURIComponent(link.href.split('/wiki/')[1]).replace(/_/g, ' ');
            // 找到对应页面的修订时间
            const page = Object.values(pages).find(p => p.title === title);
            if (!page || !page.revisions) return;

            const lastRevTimestamp = new Date(page.revisions[0].timestamp).getTime() / 1000;
            const outdatedThreshold = Date.now() / 1000 - (60 * 60 * 24 * 180);

            if (lastRevTimestamp < outdatedThreshold) {
                link.classList.add('outdated-link');
            }
        });
    })
    .catch(err => console.error('获取修订时间失败:', err));
});

参考资源

  • MediaWiki Action API文档:query模块(prop=revisions参数用法)
  • MediaWiki前端全局变量:mw.config(用于获取站点路径等配置)

内容的提问来源于stack exchange,提问作者PAS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 02:13:18