Jump to content

Module:Work interlanguage links

From Wikisource

Documentation for this module may be created at Module:Work interlanguage links/doc

local p = {}

local function processLocalLink(localLinks, lang, title)
	localLinks[lang] = localLinks[lang] or title
end

local function processEditionLink(editionLinks, lang, title)
	if not editionLinks[lang] then
		editionLinks[lang] = { title = title, conflict = false }
	else
		editionLinks[lang].conflict = true
	end
end

local function processSiteLinks(entity, outputTable, processLink)
	if entity.sitelinks then
		for _, v in pairs(entity.sitelinks) do
			if string.sub(v.site, -10) == 'wikisource' then
				local lang = string.sub(v.site, 1, -11)
				processLink(outputTable, lang, v.title)
			end
		end
	end
end

function p._wikisourceLangLinks(entity)
	if not entity then
		return {}
	end
	local localLinks = {}
	processSiteLinks(entity, localLinks, processLocalLink)
	local editionEntity
	local editionOf = entity:getBestStatements('P629')
	if #editionOf == 1 and editionOf[1].mainsnak.snaktype == 'value' then
		editionEntity = mw.wikibase.getEntity(editionOf[1].mainsnak.datavalue.value.id)
		processSiteLinks(editionEntity, localLinks, processLocalLink)
	end
	local editionLinks = {}
	local editions = entity:getBestStatements('P747')
	for _, editionStatement in ipairs(editions) do
		if editionStatement.mainsnak.snaktype == 'value' then
			processSiteLinks(mw.wikibase.getEntity(editionStatement.mainsnak.datavalue.value.id), editionLinks, processEditionLink)
		end
	end
	if editionEntity then
		editions = editionEntity:getBestStatements('P747')
		for _, editionStatement in ipairs(editions) do
			if editionStatement.mainsnak.snaktype == 'value' then
				processSiteLinks(mw.wikibase.getEntity(editionStatement.mainsnak.datavalue.value.id), editionLinks, processEditionLink)
			end
		end
	end
	for lang, v in pairs(editionLinks) do
		if not v.conflict and not localLinks[lang] then
			localLinks[lang] = v.title
		end
	end
	local finalLinks = {}
	for lang, title in pairs(localLinks) do
		if lang ~= 'mul' then -- skip this very wiki
			table.insert(finalLinks, {lang = lang:gsub('%_', '-'), title = title})
		end
	end
	table.sort(finalLinks, function (a, b) return a.lang < b.lang end)
	return finalLinks
end

function p.wikisourceLangLinks(frame)
	local args = require('Module:Arguments').getArgs(frame)
	local entity = args.entity
	if not entity then
		entity = mw.wikibase.getEntity(args.entityId or args[1])
	end
	local finalLinks = p._wikisourceLangLinks(entity)
	local ret = {}
	for _, v in ipairs(finalLinks) do
		table.insert(ret, string.format('[[%s:%s]]', v.lang, v.title))
	end
	return table.concat(ret, '\n')
end

return p