跳转到内容

模組:WikidataDescription/sandbox

维基百科,自由的百科全书
-- Simple wrapper for mw.wikibase.description
local p = {}

function p._fromQID(qid, prefix)
	if qid == nil then
		return ''
	end
	local prefix = prefix or ''
	local result, lang = mw.wikibase.getDescriptionWithLang(qid)
	-- don't get english fallback results
	if result and string.sub(lang,0,2) == 'zh' then
		return prefix .. result
	else
		return ''
	end
end

function p.fromQID(frame)
	return p._fromQID(frame.args[1], frame.args[2])
end

-- 这个方法不计expensive function和PEIS,但会算作transclusion
local function testTitle(name)
	local title = mw.title.new(name)
	return title:getContent() ~= nil
end

-- {{#invoke:WikidataDescription|fromTitle|络丝蛋白}} => "人类大脑糖蛋白" 
-- {{#invoke:WikidataDescription|fromTitle|络丝蛋白|,}} => ",人类大脑糖蛋白"
function p.fromTitle(frame)
	local pageTitle = frame.args[1]
	-- 尝试尽量优化fast path
	local qid = mw.wikibase.getEntityIdForTitle(pageTitle)

	-- 假设繁简和重定向的情况是罕见的。避免这个slow path影响fast path的expensive function count
	if not qid then
		-- 先尝试寻找仅简繁不同的页面标题。需注意另一变体的标题也可能是重定向
		local lczh = require('Module:ZhLangconv').new('zh')
		local newt = lczh:resolveVariantBatch({mw.title.new(pageTitle)}, {['preferNonRedirect'] = true})[1]
		if newt == nil then
			-- 原标题及变体均不存在
			return ''
		end
		if newt.prefixedText ~= pageTitle then
			-- 目前mw.wikibase.getEntityIdForTitle不计expensive或者其他限制,所以就大方用了
			-- 尽管这样会令本函数的结构变得复杂、存在多个exit point。若有需要可以退回到版本88906727
			qid = mw.wikibase.getEntityIdForTitle(newt.prefixedText)
			if qid then
				return p._fromQID(qid, frame.args[2])
			end
		end

		-- 若另一变体确实存在则改用新标题,以继续检查其是否为重定向
		-- mw.title.newBatch查询结果已填入isRedirect属性,不额外计入expensive
		if newt.isRedirect then
			local redirect = require('Module:Redirect')
			pageTitle = redirect.getTarget(newt)
		else
			return '' -- 没有另一变体、也非重定向,则终止
		end
		qid = mw.wikibase.getEntityIdForTitle(pageTitle)
	end

	return p._fromQID(qid, frame.args[2])
end

return p