跳转到内容

模組:Interwiki

维基百科,自由的百科全书
local familys = {}
local siteCfg
siteCfg = {
	lang = 'zh',
	family = 'wiki',
	familyToInterPrefix = {
		wiki = 'w',
		wiktionary = 'wikt',
		wikiquote = 'q',
		wikibooks = 'b', 
		wikinews = 'n',
		wikisource = 's',
		wikiversity = 'v',
		wikivoyage = 'voy',
	},
	getInterWikiFromWikiId = function (wikiId)
		if wikiId == 'mediawikiwiki' then
			return 'mw:'
		end
		local familyPrefix = ''
		local lang = wikiId
		for _, family in ipairs(familys) do
			if wikiId:sub(-#family) == family then
				lang = wikiId:sub(0, -#family-1)
				if family ~= siteCfg.family then
					familyPrefix = siteCfg.familyToInterPrefix[family] .. ':'
				end
				break
			end
		end
		if lang == siteCfg.lang then
			return familyPrefix
		end
		return familyPrefix .. lang .. ':'
	end
}

for family, _ in pairs(siteCfg.familyToInterPrefix) do
	table.insert(familys, family)
end

local function inArray(array, item)
	for _, this in ipairs(array) do
		if this == item then
			return true
		end
	end
	return false
end

local p = {}

local getArgs = require('Module:Arguments').getArgs

function p._main(args)
	local lang = args['lang'] or args['1'] or args[1]
	local family = args['family']
	local wikiId = args['wiki']
	if not wikiId then
		if not lang and not family then
			error('At least one of the parameters lang, family or wiki must be provided.')
		elseif family and not inArray(familys, family) then
			error('Unknown family:  "' .. family .. '".')
		end
		wikiId = (lang or siteCfg.lang) .. (family or siteCfg.family)
	end
	local overrideTitle = args['title']
	local entity = args['entity']
	if not entity then
		if overrideTitle then
			entity = mw.wikibase.getEntityIdForTitle(overrideTitle)
			if not entity then
				error('The title "' .. overrideTitle .. '" isn\'t valid or there are no wikidata entity for this title yet.')
			end
		else
			entity = mw.wikibase.getEntityIdForCurrentPage()
			if not entity then
				error('There are no wikidata entity for this page yet.')
			end
		end
	end
	local remotePage = mw.wikibase.getSitelink(entity, wikiId)
	if remotePage then
		return '[[:' .. siteCfg.getInterWikiFromWikiId(wikiId) .. remotePage .. ']]'
	end
	return args.fallback or error('Can\'t found interwiki for wikiId ' .. wikiId .. ' for entity ' .. entity .. '.')
end

function p.main(frame)
	return p._main(getArgs(frame, {
		trim = true,
		removeBlanks = true
	}))
end

return p