Moduuli:Cs:Wikidata

Wikipediasta
Siirry navigaatioon Siirry hakuun

require "Module:No globals"

local p = {}

local lib = require "Module:cs:Wikidata/lib"
local i18n = mw.loadData("Module:cs:Wikidata/i18n")

-- todo: local getArgs = require('Module:cs:Arguments').getArgs

local function getIdFromStatements(entity, prop)
	local prop = mw.ustring.upper(prop)
	local Statements = entity:getBestStatements(prop)
	for _, statement in ipairs(Statements) do
		if lib.IsSnakValue(statement.mainsnak) then
			if statement.mainsnak.datavalue.type ~= 'wikibase-entityid' then
				return error(lib.raiseInvalidDatatype('findEntity',
					statement.mainsnak.datatype, {'wikibase-item', 'wikibase-property'}))
			end
			local Formatters = require 'Module:cs:Wikidata/Formatters'
			return Formatters.getRawValue(statement.mainsnak)
		end
	end
	return nil
end

local function getIdFromTitle(titleString)
	local title = mw.title.new(titleString)
	while title do
		local id = mw.wikibase.getEntityIdForTitle(title.prefixedText)
		if id then
			return id
		end
		title = title.redirectTarget
	end
	return nil
end

local function findEntityId(options)
	local id, entity
	if options.entity and type(options.entity) == "table" then
		entity = options.entity
		id = entity.id
	end
	if not id and options.page then
		id = getIdFromTitle(options.page)
		if not id then
			return nil
		end
	end
	if not id then
		id = options.id or p.getCurrentId()
	end
	if options.of then
		if not entity then
			entity = mw.wikibase.getEntity(id)
		end
		if entity then
			return getIdFromStatements(entity, options.of)
		end
		return nil
	end
	return id
end

local function findEntity(options)
	local entity
	if options.entity and type(options.entity) == "table" then
		entity = options.entity
	end
	if not entity then
		if options.id then
			local id = options.id:upper()
			entity = mw.wikibase.getEntity(id)
			if entity and entity.id ~= id then
				mw.log(id .. ' je přesměrování na ' .. entity.id)
			end
		else
			if options.page then
				local id = getIdFromTitle(options.page)
				if id then
					entity = mw.wikibase.getEntity(id)
				end
			else
				entity = mw.wikibase.getEntity()
			end
		end
	end
	if options.of then
		if entity then
			local id = getIdFromStatements(entity, options.of)
			if id then
				return mw.wikibase.getEntity(id)
			end
		end
		return nil
	end
	return entity
end

local function getSitelink(options)
	local options = lib.common.cleanArgs(options)

	local id = findEntityId(options)
	if not id then
		return nil
	end

	local site = options.site or options[1]
	local sitelink
	if not site or site == 'cswiki' then
		sitelink = mw.wikibase.sitelink(id)
	else
		local entity = mw.wikibase.getEntity(id)
		if entity and entity.sitelinks then
			sitelink = entity:getSitelink(site)
		end
	end

	if not sitelink then
		return nil
	end

	if options.pattern then
		sitelink = lib.formatFromPattern(sitelink, options.pattern)
	end
	if lib.IsOptionTrue(options, 'addclass') then
		sitelink = lib.addWdClass(sitelink)
	end
	return sitelink
end

local function formatStatement(statement, options)
	if not statement.type or statement.type ~= 'statement' then
		return error(lib.formatError('unknown-claim-type', statement.type or '[neznámý]'))
	end
	local Filterers = require 'Module:cs:Wikidata/Filterers'
	local Formatters = require 'Module:cs:Wikidata/Formatters'

	local mainsnak = Formatters.getFormattedValue(statement.mainsnak, options)
	if options.isQualifier == true then
		return mainsnak
	end
	local qualifiers, targetdata, references
	if statement.qualifiers and options.showqualifier then
		local PropList = lib.textToTable(options.showqualifier)
		local Snaks = {}
		for _, property in ipairs(PropList) do
			local Values = {}
			local property = mw.ustring.upper(property)
			local format_options = {
				autoformat = true,
				isQualifier = true,
				--label = 'short',
				precision = 9,
				property = property
			}
			if statement.qualifiers[property] then
				local Qualifiers = mw.clone(statement.qualifiers[property])
				Filterers.filterQualifiers(Qualifiers, options)
				for _, snak in ipairs(Qualifiers) do
					if lib.IsSnakValue(snak) then
						table.insert(Values, Formatters.getFormattedValue(snak, format_options))
					end
				end
			elseif property == "TIME" then
				local Data = {}
				-- todo: factor out
				for key, array in pairs(lib.props) do
					for _, prop in ipairs(array) do
						for _, snak in ipairs(statement.qualifiers[prop] or {}) do
							if lib.IsSnakValue(snak) then
								Data[key] = Formatters.getRawValue(snak)
								break
							end
						end
					end
				end
				-- todo: tohle tu už nechceme
				if Data.point then
					table.insert(Values, Formatters.formatRawValue(Data.point, 'time', format_options))
				elseif Data.begin or Data.ending then
					-- xxx: improve
					table.insert(Values, Formatters.Formatters.time.formatDateRange(Data, format_options))
				end
			end
			if #Values > 0 then
				table.insert(Snaks, mw.text.listToText(Values))
			end
		end
		if #Snaks > 0 then
			qualifiers = table.concat(Snaks, '; ')
		end
	end
	if not qualifiers and options.showtargetdata then
		local entity
		if lib.IsSnakValue(statement.mainsnak) then
			if statement.mainsnak.datavalue.type == 'wikibase-entityid' then
				entity = mw.wikibase.getEntity(Formatters.getRawValue(statement.mainsnak))
			else
				return error(lib.formatError('invalid-datatype', statement.mainsnak.property, statement.mainsnak.datatype, 'wikibase-item/wikibase-property'))
			end
		end
		if entity then
			local PropList = lib.textToTable(options.showtargetdata)
			local date
			local rank = 'best'
			if options.targetdate then
				if lib.isPropertyId(options.targetdate) then
					date = p.getRawValueFromLua{ entity = options.entity, property = options.targetdate }
				else
					date = options.targetdate
				end
				if date then
					rank = 'valid'
				end
			end
			local options = {
				autoformat = true,
				date = date,
				entity = entity,
				isQualifier = true,
				label = 'short',
				precision = 9,
				rank = rank,
				sort = {'date'},
			}
			local Snaks = {}
			for _, property in ipairs(PropList) do
				local result
				if mw.ustring.lower(property) == 'time' then
					local Data = {}
					for key, array in pairs(lib.props) do
						for _, prop in ipairs(array) do
							options.property = prop
							local Statements = Filterers.filterStatementsFromEntity(entity, options)
							for _, statement in ipairs(Statements) do
								Data[key] = Formatters.getRawValue(statement.mainsnak)
								break
							end
						end
					end
					if Data.point then
						result = Formatters.Formatters.time.formatTimevalue(Data.point, options)
					elseif Data.begin or Data.ending then
						result = Formatters.Formatters.time.formatDateRange(Data, options)
					end
				else
					options.property = property
					result = p.formatStatementsFromLua(options)
				end
				if result then
					table.insert(Snaks, result)
				end
			end
			if #Snaks > 0 then
				targetdata = table.concat(Snaks, '; ')
			end
		end
	end
	if statement.references and lib.IsOptionTrue(options, 'showsource') then
		local Module = require 'Module:Wikidata/cite'
		references = Module.formatReferences(statement.references, options)
	end

	if qualifiers or targetdata then
		if options.delimiter then
			mainsnak = mainsnak .. options.delimiter .. (qualifiers or targetdata)
		else
			mainsnak = mainsnak .. ' (' .. (qualifiers or targetdata) .. ')'
		end
	end
	if references then
		mainsnak = mainsnak .. references
	end
	return mainsnak
end

local function formatStatements(statements, options)
	local formattedStatements = {}
	for _, statement in ipairs(statements) do
		if not statement.type or statement.type ~= 'statement' then
			return error(lib.formatError('unknown-claim-type', statement.type or '[neznámý]')) -- fixme: i18n
		end
		local formatted = formatStatement(statement, options)
		local add = true
		for _, fmt in ipairs(formattedStatements) do
			if formatted == fmt then
				add = false
				break
			end
		end
		if add then -- not in_array
			table.insert(formattedStatements, formatted)
		end
	end
	return formattedStatements
end

local function getStatements(entity, options)
	local Filterers = require 'Module:cs:Wikidata/Filterers'
	return Filterers.filterStatementsFromEntity(entity, options)
end

local function getFormattedStatements(options)
	local value = options.value
	if value then
		if value == '' and lib.IsOptionTrue(options, 'over') then
			value = nil
		end
		if value and not lib.IsOptionTrue(options, 'compare') then
			return value
		end
	end

	--Get entity
	local options = lib.common.cleanArgs(options)

	options.limit = tonumber(options.limit) --TODO default?
	local add_more = false
	if not lib.IsOptionTrue(options, 'compare') then
		if options.limit and lib.IsOptionTrue(options, 'showmore') then
			options.limit = options.limit + 1
			add_more = true
		end
	end

	local entity = findEntity(options)
	local statements = getStatements(entity, options)

	options.property = mw.ustring.upper(options.property)
	if value then
		local compare = require 'Module:cs:Wikidata/compare'
		local marked, category = compare.compareValues(value, statements, {
			catbase = options.catbase,
			property = options.of or options.property
		})
		if lib.IsOptionTrue(options, 'addclass') and marked then
			value = marked
		end
		if lib.IsOptionTrue(options, 'addcat') and category then
			return value .. category
		end
		return value
	end

	if #statements == 0 then return nil end
	if add_more then
		if #statements == options.limit then
			table.remove(statements)
		else
			add_more = false
		end
	end

	options.entity = entity
	local formattedStatements = formatStatements(statements, options)
	if add_more then
		table.insert(formattedStatements, mw.ustring.format(i18n["more-on-Wikidata"], entity.id, options.property))
	end

	-- Format statements and concat them cleanly
	value = mw.text.listToText(formattedStatements, options.separator, options.conjunction)

	if lib.IsOptionTrue(options, 'addlink') then
		value = mw.ustring.format('%s <sup class="wd-link">([[d:%s#%s|e]])</sup>', value, entity.id, options.property)
	end
	if lib.IsOptionTrue(options, 'addcat') then
		value = value .. lib.category('used-property', options.catbase or 'Vlastnost ' .. options.property)
	end
	if lib.IsOptionTrue(options, 'addclass') then
		value = lib.addWdClass(value)
	end
	return value
end

function p.dumpWikidataEntity( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})

	return mw.dumpObject( mw.wikibase.getEntity( args.id or nil ) )
end

function p.getBadges( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local site = args.site
	if not site then
		return error(lib.formatError('param-not-provided', 'site'))
	end
	local entity = findEntity( args )
	local Badges = {}
	if entity and entity.sitelinks and entity.sitelinks[site] then
		local Formatters = require 'Module:cs:Wikidata/Formatters'
		for _, badge in ipairs(entity.sitelinks[site].badges) do
			table.insert(Badges, Formatters.formatRawValue(badge, 'wikibase-entityid'))
		end
	end
	return table.concat( Badges, ', ' )
end

function p.getLabel( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local id = findEntityId(args)
	if not id then
		return nil
	end
	local lang = args.lang
	local code = mw.language.getContentLanguage():getCode()
	if not lang or lang == code then
		local label, _ = lib.getLabelInLanguage(id, { code })
		if label and lib.IsOptionTrue(args, 'addclass') then
			label = lib.addWdClass(label)
		end
		return label
	end
	local entity = mw.wikibase.getEntity(id)
	if entity and entity.labels and entity.labels[lang] then
		local label = entity.labels[lang].value
		if label and lib.IsOptionTrue(args, 'addclass') then
			label = lib.addWdClass(label)
		end
		return label
	end
	return nil
end

function p.getDescription( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local id = findEntityId(args)
	if not id then
		return nil
	end
	local lang = args.lang
	if not lang or lang == mw.language.getContentLanguage():getCode() then
		local description = mw.wikibase.description(id)
		if description and lib.IsOptionTrue(args, 'addclass') then
			description = lib.addWdClass(description)
		end
		return description 
	end
	local entity = mw.wikibase.getEntity(id)
	if entity and entity.descriptions and entity.descriptions[lang] then
		local description = entity.descriptions[lang].value
		if description and lib.IsOptionTrue(args, 'addclass') then
			description = lib.addWdClass(description)
		end
		return description 
	end
	return nil
end

function p.getAliases( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local lang = args.lang
	local entity = findEntity( args )
	if not lang then
		lang = mw.language.getContentLanguage():getCode()
	end
	if not entity or not entity.aliases or not entity.aliases[lang] then
		return nil
	end

	local limit = tonumber(args.limit)

	local Aliases = {}
	for i, alias in ipairs( entity.aliases[lang] ) do
		if not limit or (limit and i <= limit) then
			table.insert( Aliases, alias.value )
		else break end
	end
	local list = mw.text.listToText(Aliases, args.separator, args.conjunction)
	if lib.IsOptionTrue(args, 'addclass') then
		list = lib.addWdClass(list)
	end
	return list
end

function p.getCount( frame )
	local args = lib.common.cleanArgs(frame and frame.args or {})
	args.limit = nil
	local entity = findEntity(args)
	return #getStatements(entity, args)
end

p.getCurrentId = mw.wikibase.getEntityIdForCurrentPage

function p.getId( frame )
	local args = (frame.args[1] and frame.args) or (frame:getParent() and frame:getParent().args) or {}
	
	if not args[1] then
		return mw.wikibase.getEntityIdForCurrentPage()
	end
	
	for _, titleString in ipairs(args) do
		local id = getIdFromTitle(titleString)
		if id then
			return id
		end
	end
	return nil
end

function p.getSitelink( frame )
	return getSitelink( frame and frame.args or {} )
end

function p.getSitelinkFromLua( options )
	return getSitelink( options or {} )
end

p.filterStatementsFromLua = getStatements

function p.formatStatements(frame)
	local args = frame and frame.args or {}
	return getFormattedStatements(args)
end

function p.formatStatementsFromLua(options)
	return getFormattedStatements(options)
end

local function getRawValue(options)
	if options.showspecial == nil then -- may be false
		options.showspecial = true
	end
	if options.rank ~= 'best' and options.rank ~= 'preferred' then
		local byRank = mw.ustring.match(options.sort or '', 'rank') and true
		options.sort = lib.textToTable(options.sort or '')
		if not byRank then
			table.insert(options.sort, 1, 'rank')
		end
	end

	local entity = findEntity(options)
	for _, statement in ipairs(getStatements(entity, options)) do
		local Formatters = require 'Module:cs:Wikidata/Formatters'
		return Formatters.getRawValue(statement.mainsnak, options)
	end
	return nil
end

function p.getRawValue(frame)
	return getRawValue(lib.common.cleanArgs(frame and frame.args or {}))
end

function p.getRawValueFromLua(options)
	return getRawValue(options)
end

local function getQualifiers(args)
	if not args.qualifier then
		return error(lib.formatError('param-not-provided', 'qualifier'))
	end
	local entity = findEntity(args)
	for _, statement in ipairs(getStatements(entity, args)) do
		if statement.qualifiers then
			local qualifiers = mw.clone(statement.qualifiers[mw.ustring.upper(args.qualifier)] or {})
			local Filterers = require 'Module:cs:Wikidata/Filterers'
			Filterers.filterQualifiers(qualifiers, args)
			return qualifiers
		end
		return {}
	end
	return {}
end

function p.getQualifier(frame)
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local limit = args.limit and tonumber(args.limit)
	args.limit = 1
	args.isQualifier = true
	if not args['qualifiers limit'] then
		args['qualifiers limit'] = limit
	end
	local qualifiers = getQualifiers(args)
	if #qualifiers == 0 then
		return nil
	end

	local Formatters = require 'Module:cs:Wikidata/Formatters'
	local formattedQualifiers = {}
	for _, qualifier in ipairs(qualifiers) do
		table.insert(formattedQualifiers, Formatters.getFormattedValue(qualifier, args))
	end

	local value = mw.text.listToText(formattedQualifiers, args.separator, args.conjunction)
	if lib.IsOptionTrue(args, 'addclass') then
		value = lib.addWdClass(value)
	end
	return value
end

function p.getRawQualifier(frame)
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local limit = args.limit and tonumber(args.limit)
	args.limit = 1
	for _, qualifier in ipairs(getQualifiers(args)) do
		local Formatters = require 'Module:cs:Wikidata/Formatters'
		return Formatters.getRawValue(qualifier)
	end
	return nil
end

function p.formatEntity(frame)
	local args = lib.common.cleanArgs(frame and frame.args or {})
	local id = args.id or p.getCurrentId()
	args.id = nil
	if id then
		local Formatters = require 'Module:cs:Wikidata/Formatters'
		return Formatters.formatRawValue(id, 'wikibase-entityid', args)
	end
	return nil
end

return p