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 03:18, 16 May 2014 (split this into two functions, and convert spaces to tabs). 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 = {}

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

	-- Get the title object, passing the function through pcall  in case we are
	-- over the expensive function count limit, etc.
	local success, rpage = pcall(mw.title.new, rname)
	if not success or not rpage then
		-- mw.title.new failed, so use the passed page name.
		return bracket:format(rname)
	elseif not rpage.isRedirect then
		-- the page is not a redirect, so use the normalized name of the page we
		-- were given.
		return bracket:format(rpage.prefixedText)
	end

	-- Match the redirect target text from the page content.
	local redirect = string.match(
		rpage:getContent() or "",
		"^%s*#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]]-)%]%]"
	)
	if redirect then
		-- Decode html entities and percent encodings.
		redirect = mw.text.decode(redirect, true)
		redirect = mw.uri.decode(redirect, 'WIKI')
		return bracket:format(redirect)
	else
		-- The page is a redirect, but matching failed. This indicates a bug in
		-- the redirect matching pattern, so throw an error.
		error('could not parse redirect on page [[:' .. rname .. ']]')
	end
end

return p