Jump to content

Module:Redirect/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 05:58, 16 May 2014 (add two more functions for calling from Lua, getTarget and getTargetString (was an edit conflict from earlier, overwriting for now)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- Given a single page name determines what page it redirects to and returns the target page name, or the
-- passed page name when not a redirect. The passed page name can be given as plain text or as a page link.
-- Returns page name as plain text, or when the bracket parameter is given, as a page link. Returns an
-- error message when page does not exist or the redirect target cannot be determined for some reason.

-- Thus these are roughly the same:
-- [[{{#invoke:redirect|main|redirect-page-name}}]] and {{#invoke:redirect|main|redirect-page-name|bracket=yes}}

local mArguments -- lazily initialise [[Module:Arguments]]

local p = {}

local function getTitle(...)
	local success, titleObj = pcall(mw.title.new, ...)
	if success then
		return titleObj
	else
		return nil
	end
end

function p.main(frame)
	mArguments = require('Module:Arguments')
	local args = mArguments.getArgs(frame)
	local rname, bracket = args[1], args.bracket
	return p._main(rname, bracket) or ''
end

function p._main(rname, bracket)
	if type(rname) ~= "string" or not rname:find("%S") then
		return nil
	end
	bracket = bracket and "[[%s]]" or "%s"
	rname = rname:match("%[%[(.+)%]%]") or rname
	local target = p.getTargetString(rname)
	if target then
		return bracket:format(target)
	else
		return bracket:format(rname)
	end
end

function p.getTarget(page)
	return getTitle(p.getTargetString)
end

function p.getTargetString(page)
	-- Get the title object. Both page names and title objects are allowed
	-- as input.
	local titleObj
	if type(page) == 'string' then
		titleObj = getTitle(page)
	elseif type(page) == 'table' and type(page.getContent) == 'function' then
		titleObj = page
	else
		local msg = 'invalid input to "getTarget":'
			.. 'the first parameter must be a string or a title object'
		error(msg, 2)
	end
	if not titleObj or not titleObj.isRedirect then
		return nil
	end
	
	-- Find the target by using string matching on the page content.
	local target = string.match(
		titleObj:getContent() or "",
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]]-)%]%]"
	)
	if target then
		-- Decode html entities and percent encodings.
		target = mw.text.decode(target, true)
		target = mw.uri.decode(target, 'WIKI')
		return target
	else
		-- The page is a redirect, but matching failed. This indicates a bug in
		-- the redirect matching pattern, so throw an error.
		local msg = 'could not parse redirect on page [[:'
			.. titleObj.prefixedText
			.. ']]'
		error(msg)
	end
end

return p