Jump to content

Module:RedirectChecker

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Stjn (talk | contribs) at 19:54, 10 November 2024 (fix). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
--
-- Checks redirects to sections for their target
-- Also checks if a page is a redirect page
--
-- Adds tracking categories in both cases
--
require( 'strict' )
local p = {}

local getArgs = require( 'Module:Arguments' ).getArgs
local delink

-- [[Module:RedirectChecker/config.json]]
local config = mw.loadJsonData( 'Module:RedirectChecker/config.json' )

local function getError( str )
	return string.format( '<strong class="error">%s</span>[[Category:%s]]', str, errorCat )
end

-- Returns the anchor in the first link on a page
local function getRedirectAnchor( content )
	if content == nil then return nil end
	
	local link = mw.ustring.match( content, '%[%[.+%]%]' )
	if link == nil then
		return nil
	end
	
	link = mw.text.trim( link, ' %[%]' )
	local parts = mw.text.split( link, '#' )
	if parts[ 2 ] == nil then
		return nil
	end
	
	return parts[ 2 ]
end

function p._main( page, frame )
	local mwTitle = mw.title.new( page )
	if mwTitle == nil or not mwTitle.exists then
		return false, getError( string.format( config.errorMissing, page ) )
	end
	
	local target = mwTitle.redirectTarget
	if target == false then
		return false, getError( string.format( config.notRedirect, page ) )
	end
	
	local anchor = getRedirectAnchor( mwTitle:getContent() )
	if anchor == nil then
		return false, getError( string.format( config.errorNoSection, page ) )
	end
	
	local content = target:getContent()
	
	-- Find a heading of any level matching anchor
	local headingPattern = '=%s*' .. anchor .. '%s*='
	local heading = mw.ustring.match( content, headingPattern )
	if heading ~= nil then
		return true
	end
	
	-- Remove all wikilinks with [[Module:Delink]] and try again
	delink = require( 'Module:Delink' )._delink
	content = delink( { content } )
	heading = mw.ustring.match( content, headingPattern )
	if heading ~= nil then
		return true
	end
	
	-- Preprocess and try to find an ID
	content = ( frame or mw.getCurrentFrame() ):preprocess( content )
	content = mw.text.killMarkers( content )
	
	local id = mw.ustring.match( content, ' id="?' .. anchor .. '"?' )
	if id ~= nil then
		return true
	end
	
	return false
end

function p.main( frame )
	local args = getArgs( frame )
	
	local result, err = p._main( args.page or mw.title.getCurrentTitle().fullText )
	if result == true then
		return ''
	end
	
	return string.format( '%s[[Category:%s]]', err or '', config.brokenRedirectCat )
end

return p