Module:Wikidata link

From ArchivesWiki

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. This wiki
--  2. Wikipedia
--  3. Wikisource
--  4. Commons
--  5. Wikidata
function p.link( frame )
	-- Check input.
	if frame == nil or frame.args.wikidata == nil or frame.args.wikidata == '' then
		return "<span class='error'>Please specify 'wikidata' parameter.</span>"
	end
	local itemId = frame.args.wikidata
	local item = mw.ext.UnlinkedWikibase.getEntity( itemId )
	if not item then
		return "<span class='error'>" .. itemId .. "' could not be found.</span>"
	end
	
	-- Get label.
	local label = itemId
	local localTitle = mw.ext.UnlinkedWikibase.getLocalTitle( itemId )
	if frame.args.label ~= nil and frame.args.label ~= '' then
		label = frame.args.label
	elseif localTitle then
		label = localTitle.text
	elseif item.labels.en ~= nil then
		label = item.labels.en.value
	end

	if localTitle then
		return '<span class="mdl-wikidata-link">[[' .. localTitle.prefixedText .. '|' .. label .. ']]</span>';
	end

	-- Look through the site hierarchy for a matching sitelink, in this order.
	-- The first elements are sitelink IDs and the second are local interwiki prefixes.
	local sitelinks = {
		{ 'enwiki', 'wikipedia' },
		{ 'enwikisource', 'wikisource' },
		{ 'commonswiki', 'commons' },
	}
	for i,v in ipairs( sitelinks ) do
		local sitelink = sitelinks[i][1]
		local interwiki = sitelinks[i][2]
		if item.sitelinks[ sitelink ] ~= nil then
			return '<span class="mdl-wikidata-link">[[' .. interwiki .. ':' .. item.sitelinks[ sitelink ].title .. '|' .. label .. ']]</span>';
		end
	end

	-- Fall back on Wikidata if no sitelink found.
	return '<span class="mdl-wikidata-link">[[wikidata:' .. itemId .. '|' .. label .. ']]</span>'
end

return p