Module:Wikidata link

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

local p = {}

-- Get a link to the given Wikidata item's page on the first of the following places:
--  1. Wikiversity
--  2. Wikipedia
--  3. Wikisource
--  4. Commons
--  5. Wikidata
function p.link(frame)
	-- Check input.
	if frame.args.wikidata == nil or frame.args.wikidata == '' then
		return "<span class='error'>Please specify 'wikidata' parameter.</span>"
	end
	local itemId = frame.args.wikidata
	if not mw.wikibase.isValidEntityId(itemId) then
		return "<span class='error'>" .. itemId .. "' is not a valid Wikidata item.</span>"
	end
	if not mw.wikibase.entityExists(itemId) then
		return "<span class='error'>" .. itemId .. "' does not exist on Wikidata.</span>"
	end
	
	local label = mw.wikibase.getLabel(itemId)
	if frame.args.label ~= nil and frame.args.label ~= '' then
		label = frame.args.label
	end

	-- Look through the site hierarchy for a matching sitelink.
	-- These two variables are in the same order.
	local sitelinks = {'enwikiversity', 'enwiki', 'enwikisource', 'commonswiki'}
	local interwikis = {'', 'wikipedia', 'wikisource', 'commons'}
	for i = 1, #sitelinks do
		local sitelink = mw.wikibase.getSitelink(itemId, sitelinks[i])
		if sitelink then
			return '<span class="module-wikidata-link">[[' .. interwikis[i] .. ':' .. sitelink .. '|' .. label .. ']]</span>';
		end
	end

	-- Fall back on Wikidata if no sitelink found.
	return '<span class="plainlinks module-wikidata-link reasonator-link">[https://www.wikidata.org/wiki/' .. itemId .. ' ' .. label .. ']</span>'
end

return p