Module:Urltowiki
Appearance
-- This module takes a URL from a Wikimedia project and returns the equivalent wikitext.
-- Any actions such as edit, history, etc., are stripped, and percent-encoded characters
-- are converted to normal text.
p = {}
local function _urlToWiki(args)
url = args[1] or error("No URL specified")
url = mw.ustring.match(url, "^%s*(.*%S)") or "" -- Trim whitespace.
url = mw.uri.new(url)
-- Get the page title.
local pagetitle
if mw.ustring.sub(url.path, 1, 6) == "/wiki/" then
pagetitle = mw.ustring.sub(url.path, 7, -1)
elseif url.path == "/w/index.php" then
pagetitle = url.query.title or error("Invalid URL detected")
else
error("Invalid URL detected")
end
-- Get the fragment and convert percent-encoded characters.
local fragment = url.fragment
if fragment then
fragment = mw.ustring.gsub(fragment, "%.([0-9A-F][0-9A-F])", "%%%1")
end
-- Assemble the wikilink
if fragment then
wikitext = pagetitle .. "#" .. fragment
else
wikitext = pagetitle
end
wikitext = mw.uri.decode(wikitext, "WIKI")
return wikitext
end
function p.urlToWiki(frame)
local args
if frame == mw.getCurrentFrame() then
-- We're being called via #invoke. If the invoking template passed any args, use
-- them. Otherwise, use the args that were passed into the template.
args = frame:getParent().args
for k, v in pairs(frame.args) do
args = frame.args
break
end
else
-- We're being called from another module or from the debug console, so assume
-- the args are passed in directly.
args = frame
end
return _urlToWiki(args)
end
return p