Hopp til innhold

Modul:Official links

Fra Wikipedia, den frie encyklopedi
Sideversjon per 23. des. 2015 kl. 04:57 av Jeblad (diskusjon | bidrag) (flytter funksjoner for å hente label)
Moduldokumentasjon

require('Module:No globals')

local labels = {}

local function getEntityLabel( id )
	local entity = mw.wikibase.getEntity( id )
	if entity then
		return entity:getLabel()
	end
end

local function findEntityLabel( id )
	if not labels[id] then
		local label = getEntityLabel( id )
		if label then
			labels[id] = contLang:ucfirst( label ) -- labels is an outer structure
		end
	end
	return labels[id]
end

local contLang = mw.language.getContentLanguage()

local mainFormatter = {}
mainFormatter['string'] = function( pid, datavalue )
		if datavalue['type'] ~= 'string' then
			return nil
		end
		return '[' .. datavalue.value .. ' ' .. labels[pid] .. ']'
	end

local main = {}
main.P856 = {
	types = {
		snaktype = 'value',
		datatype = 'url',
	},
	formatter = mainFormatter['string']
}

local p = {}

function p.findOfficialLinks(pid, qid)
	local links = {}
	local entity = mw.wikibase.getEntityObject( qid )
	if entity then
		local statements = entity:getBestStatements( pid )
		if statements then
			for _, claim in ipairs( statements ) do
				if claim then
					if claim['type'] ~= 'statement' then
						break
					end
					local mainsnak = claim.mainsnak
					if not mainsnak or not main[pid] then
						break
					end
					if (mainsnak.snaktype ~= main[pid].types.snaktype
						or mainsnak.datatype ~= main[pid].types.datatype)
					then
						break
					end
					links[1+#links] = main[pid].formatter(pid, mainsnak.datavalue)
				end
			end
		end
	end
	return links
end

function p.links( frame )
	local seq = {}
	for _,v in ipairs(frame.args) do
		local _, _, ch, num= v:find("([pP])(%d+)")
		if ch then
			local pid = ch:upper()..num
			local label = findEntityLabel( pid )
			if label then
				seq[1+#seq] = pid
			end
		end
	end
	local items = {}
	for _,v in ipairs(seq) do
		local links = p.findOfficialLinks(v)
		if links then
			for _,link in ipairs( links ) do
				items[1+#items] = (#items > 0 and '* ' or '') .. link
			end
		end
	end
	if #items > 0 then
		return table.concat(items, "\n") .. '[[Kategori:Artikler med offisielt nettsted fra Wikidata]]'
	end
	return "''Ikke noe offisielt nettsted tilgjengelig''" .. '[[Kategori:Artikler uten offisielt nettsted]]'
end

return p