Jump to content

Module:Urltowiki

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 06:33, 8 April 2013 (create). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

-- 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]", "%%")
    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