Documentation for this module may be created at Module:Wikipedia/doc

--[[

@author d:User:Legoktm

This template automatically adds the Wikipedia
link to the sidebar if it exists in Wikidata

@version 0.1en.voy
If this template is copied to other sites, please try
and copy all edits back to the main one on en.voy

]]--


local p = {}

function p.wplink(frame)
    local pframe = frame:getParent()
    local config = frame.args -- the arguments passed BY the template, in the wikitext of the template itself
    local args = pframe.args -- the arguments passed TO the template, in the wikitext that transcludes the template
    
    -- do some exemption checking...
    local text = mw.title.getCurrentTitle():getContent()
    if string.find(text, "{{noexternallinks}}") then
        return "" -- they dont want any wikidata stuff
    end
    
    -- this part is rather hacky, but it works... I think.
    -- note that this doesn't check links like nost or tenwiki
    text = string.lower(text);
    if string.find(text, "%[%[wikipedia:") then
        return ""
    end
    if string.find(text, "%[%[w:") then
        return ""
    end
    
    local entity = mw.wikibase.getEntityObject()
    if not entity then -- no Wikidata item
        return "" -- we could add a tracking category here if we wanted...
    end
    local sitelinks = entity.sitelinks -- this will always be populated since it's a connected item :P
    local langcode = mw.getContentLanguage():getCode();
    local dbname = langcode.gsub('-', '_') .. "wiki"
    local hasLink = sitelinks[dbname]
    if not hasLink then
        return "" -- no wikipedia link in that language
    end
    local link = hasLink.title
    return "[[wikipedia:" .. link .. "]]"
end

return p