Modulu:Sandbox/Edgars2007

Documentation for this module may be created at Modulu:Sandbox/Edgars2007/dok

local p = {}

-- module local variables
local wiki = 
{
	langcode = mw.language.getContentLanguage().code
}

local i18n = {
    ["errors"] = {
        ["property-param-not-provided"] = "Propietatearen parametroa falta da.",
        ["qualifier-property-param-not-provided"] = "Kualifikadorearen proietatearen parametroa falta da.",
        ["entity-not-found"] = "Entitatea ez da aurkitu.",
        ["unknown-claim-type"] = "Afirmazio mota (claim) ezezaguna.",
        ["unknown-snak-type"] = "Konektore mota (snak) ezezaguna.",
        ["unknown-datavalue-type"] = "Balore mota (datavalue) ezezaguna.",
        ["unknown-entity-type"] = "Entitate mota ezezaguna.",
        ["unknown-value-module"] = "Value-module eta value-function parametroak jarri behar dituzu.",
        ["value-module-not-found"] = "Value-modulek dioen modulua ez da aurkitu.",
        ["value-function-not-found"] = "Value-functionek dioen funtzioa ez da aurkitu.."
    },
    ["somevalue"] = "''balio ezezaguna''",
    ["novalue"] = "''ezin da balorerik eman''",
    ["warnLabel"] = "[[Kategoria:Euskarazko etiketarik ez duten artikuluak]]",
    ["warnLabel2"] = "eman etiketa bat Wikidatan!",
    ["warnDump"] = "[[Kategoria:Wikidata moduluaren dump funtzioa]]",
    ["datetime"] =
	{
		-- $1 is a placeholder for the actual number
		[0] = "$1 mila milioi urte",	-- precision: billion years
		[1] = "$100 milioi urte",	-- precision: hundred million years
		[2] = "$10 milioi urte",	-- precision: ten million years
		[3] = "$1 milioi urte",	-- precision: million years
		[4] = "$100.000 urte",		-- precision: hundred thousand years
		[5] = "$10.000 urte",		-- precision: ten thousand years
		[6] = "$1 milurteko",	 	-- precision: millennium
		[7] = "$1 mende",			-- precision: century
		[8] = "$1(e)ko hamarkada",		-- precision: decade
		-- the following use the format of #time parser function
		[9]  = "Y",					-- precision: year, 
		[10] = "Y F",				-- precision: month
		[11] = "Y F j",			-- precision: day
		[12] = "Y F j, ga",			-- precision: hour
		[13] = "Y F j, g:ia",		-- precision: minute
		[14] = "Y F j, g:i:sa",		-- precision: second
		["beforenow"] = "K. a. $1",	-- how to format negative numbers for precisions 0 to 5
		["afternow"] = "$1 dC",		-- how to format positive numbers for precisions 0 to 5
		["bc"] = '$1 "K. a."',		-- how print negative years
		["ad"] = "$1"				-- how print positive years
	},
	["monolingualtext"] = '<span lang="%language">%text</span>'
}

function getClaims( args ) -- returns a table of the claims (TODO: matching some conditions given in args)
    if not args.property then
        return formatError( 'property-param-not-provided' )
    end
    --Get entity
    local entity = nil
    local property = string.upper(args.property)
    if args.entity and type( args.entity ) == "table" then
        entity = args.entity
    else
        entity = mw.wikibase.getEntityObject()
    end
 
    if not entity or not entity.claims or not entity.claims[property] then
        return nil
    end
	return entity.claims[property]
end

function numOfClaims( claims )
	if type(claims) ~= "table" then
		return 0
	elseif claims == {} then 
		return 0
	else
		return #claims
	end
end

function getDatavalue(snak, formatting)
	if snak.snaktype ~= 'value' then 
		return nil
	end
	datatype = snak.datavalue.type
 
	if datatype == 'wikibase-entityid' then
		local entityId = "Q" .. tostring(snak.datavalue.value['numeric-id'])
		local label = mw.wikibase.label( entityId )
		local sitelink = mw.wikibase.sitelink( entityId )
		if formatting == 'raw' then 
			return entityId
		elseif formatting == 'normal' then
			return formatEntityId2( entityId )
		elseif formatting == 'label' then
			return ( label or entityId )
		elseif formatting == 'sitelink' then
			return ( sitelink or 'wikidata:' .. entityId )
		else
			return formatEntityId( entityId )
		end
 
	elseif datatype == 'string' then
		local astring = snak.datavalue.value
		if formatting == 'weblink' then 
			return '[' .. astring ..  ' ' ..  mw.text.split( astring, '//' )[2] .. ']'
		elseif mw.ustring.find( (formatting or ''), '$1', 1, true ) then -- formatting = a pattern
			return mw.ustring.gsub( formatting, '$1', astring ) .. '' --Hack to get only the first result of the function
		else
			return astring
		end
 
	elseif datatype == 'time' then
		-- Dates and times are stored in ISO 8601 format
		-- check for negative date
		local suffix = ""
		local timestamp = snak.datavalue.value.time
		if string.sub(timestamp, 1, 1) == '-' then
			timestamp = '+' .. string.sub(timestamp, 2)
			suffix = " aC"
		end
		local function d(f)
			return mw.language.new(wiki.langcode):formatDate(f, timestamp) .. suffix
		end
		if formatting == 'year' then
			-- suppress leading zeros in year
			local stryear = d("Y")
			while string.sub(stryear, 1, 1) == '0' do
				stryear = string.sub(stryear, 2)
			end
			return stryear
		else
			return d("j F Y")
		end
 
	elseif datatype == 'globecoordinate' then
		local coord = snak.datavalue.value
		local globetable = { Q2 = 'earth', Q111 = 'mars', Q405 = 'moon'}
		
		if formatting == 'latitude' then
			return coord.latitude
		elseif formatting == 'longitude' then
			return coord.longitude
		elseif formatting == 'dimension' then
			return coord.dimension
		else
			if coord.globe == '' or coord.globe == nil then
				return 'earth'
			else
				local globenum = mw.text.split( snak.datavalue.value.globe, 'entity/' )[2] -- http://www.wikidata.org/wiki/Q2
				if globetable[globenum] then 
					return globetable[globenum]
				else
					return globenum
				end
			end
		end
 
	else 
		return formatError( 'unknown-datavalue-type' )
	end
end

function getEntityIdFromValue( value )
    if value['entity-type'] == 'item' then
        return 'q' .. value['numeric-id']
    elseif value['entity-type'] == 'property' then
        return 'p' .. value['numeric-id']
    else
        return formatError( 'unknown-entity-type' )
    end
end
 
function formatError( key )
    return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
 
function formatStatement( statement, options )
    if not statement.type or statement.type ~= 'statement' then
        return formatError( 'unknown-claim-type' )
    end
 
    return formatSnak( statement.mainsnak, options )
    --TODO reference and qualifiers
end
 
function formatQualifier ( qualifiers, qualifierProperty, options )
	if not qualifiers[qualifierProperty] then
		return nil
	end
	
	return formatSnak( qualifiers[qualifierProperty][1], options )
end

function formatSnak( snak, options )
    if snak.snaktype == 'somevalue' then
        return i18n['somevalue']
    elseif snak.snaktype == 'novalue' then
        return i18n['novalue']
    elseif snak.snaktype == 'value' then
        return getDatavalue( snak, options.formatting )
    else
        return formatError( 'unknown-snak-type' )
    end
end

function nodis( text )
text2= mw.ustring.gsub(text, " [(][^()]*[)]$", "")
	return text2
end

function formatEntityId2( entityId )
	local entity = mw.wikibase.getEntity(entityId)
	local label = mw.wikibase.label( entityId )
	local link = mw.wikibase.sitelink( entityId )
	if link then
		if label then
			return '[[' .. link .. '|' .. nodis(label) .. ']]'
		else
			return '[[' .. link .. '|' .. nodis(link) .. ']]'
		end
	elseif label then
		return '[[' .. nodis(label) .. ']]'
	elseif entity.sitelinks['enwiki'] then
		return '[[' .. nodis(entity.sitelinks['enwiki'].title) .. '|' .. (nodis(entity.labels['en'].value) or i18n.warnLabel2) .. ']]' .. i18n.warnLabel
	elseif entity.sitelinks['eswiki'] then
		return '[[' .. nodis(entity.sitelinks['eswiki'].title) .. '|' .. (nodis(entity.labels['es'].value) or i18n.warnLabel2) .. ']]' .. i18n.warnLabel
	else
		return '[[:d:' .. entityId .. '|' .. entityId .. ']]'  .. i18n.warnLabel
	end
end

function formatEntityId( entityId )
	local label = mw.wikibase.label( entityId )
	local link = mw.wikibase.sitelink( entityId )
	if link then
		if label then
			return '[[' .. link .. '|' .. label .. ']]'
		else
			return '[[' .. link .. ']]'
		end
	else
		return '[[d:' ..  entityId .. '|' .. (label or entityId) .. ']]'
	end
end

-- Return the site link (for the current site) for a given data item.
function p.getSiteLink( frame )
    if frame.args[1] == nil then
        entity = mw.wikibase.getEntityObject()
        if not entity then
        	return nil
        end
        id = entity.id
    else
        id = frame.args[1]
    end
 
    return mw.wikibase.sitelink( id )
end

-- Return the statements with a format
function p.formatStatements( frame ) -- Format statement and concat them cleanly
	local args = frame.args
 
	--If a value is already set, use it
	if args.value and args.value ~= '' then
		return args.value
	end

	local rawStatements = getClaims( args )
	if not rawStatements or numOfClaims(rawStatements) == 0 then
		return nil
	end

	--Format statement and concat them cleanly
	local formattedStatements = {}
	for i, statement in pairs( rawStatements ) do
		if args.rank == 'one' then
			return formatStatement( statement, args ) --Output only one value
		elseif args.rank == 'preferred' then --This should be set as the default case
			if #rawStatements == 1 then
				return formatStatement( statement, args ) --Output the only value
			else
				if statement.rank == 'preferred' then
					table.insert( formattedStatements, formatStatement( statement, args ) ) --Output only the preferred values
				end
			end
		else
			table.insert( formattedStatements, formatStatement( statement, args ) )
		end
	end
 
	return mw.text.listToText( formattedStatements, args.separator, args.conjunction )
end

--Return the qualifiers wth a format
function p.formatQualifiers( frame )
	local args = frame.args
	--If a value is already set, use it
	if args.value and args.value ~= '' then
		return args.value
	end
	--Required parameters
	local property = string.upper(args.property)
	local qualifierProperty = string.upper(args.qualifierProperty)
	if not property then
		return formatError( 'property-param-not-provided' )
	end
	if not qualifierProperty then
		return formatError( 'qualifier-property-param-not-provided' )
	end
	
	--Get statements
	local rawStatements = getClaims( args )
	if not rawStatements or numOfClaims(rawStatements) == 0 then
		return nil
	end
	
	--Format statement and concat them cleanly
	local formattedQualifiers = {}
	for i, statement in pairs( rawStatements ) do
		if not statement.qualifiers then
			return nil
		end
		if args.rank == 'one' then
			return formatQualifier( statement.qualifiers, qualifierProperty, args )
		elseif args.rank == 'preferred' then --This should be set as the default case
			if #rawStatements == 1 then
				return formatQualifier( statement.qualifiers, qualifierProperty, args ) --Output the only value
			else
				if statement.rank == 'preferred' then
					table.insert( formattedQualifiers, formatQualifier( statement.qualifiers, qualifierProperty, args ) ) --Output only the preferred values
				end
			end
		else
			table.insert( formattedQualifiers, formatQualifier( statement.qualifiers, qualifierProperty, args ) )
		end
	end
	
	return mw.text.listToText( formattedQualifiers, args.separator, args.conjunction )
end

-- Dump data tree structure
-- From pl:Module:Wikidane, by User:Paweł Ziemian
-- Funció pensada com a eina d'ajuda en previsualització.
function p.Dump(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return i18n.warnDump
	end
	
	local f = frame.args[1] and frame or frame:getParent()

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return "<pre>" .. mw.dumpObject(data) .. "</pre>" .. i18n.warnDump
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return i18n.warnDump
		end
		
		i = i + 1
	end
end

-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
-- uses the newer mw.wikibase calls instead of directly using the snaks
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
p.getTAValue = function(frame)
	local ent = mw.wikibase.getEntityObject()
	local props = ent:formatPropertyValues('P1323')
	local out = {}
	local t = {}
	for k, v in pairs(props) do
		if k == 'value' then
			t = mw.text.split( v, ", ")
			for k2, v2 in pairs(t) do
				out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
			end
		end
	end
	local ret = table.concat(out, "<br> ")
	if #ret == 0 then
		ret = "Invalid TA"
	end
	return ret
end

-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.pageId(frame)
	local entity = mw.wikibase.getEntityObject()
	if not entity then return nil else return entity.id end
end

-- Look into entity object
-- From pl:Module:Wikidane, function V, by User:Paweł Ziemian
function p.getEntityFromTree(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return nil
	end
	
	local f = frame.args[1] and frame or frame:getParent()
	
	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return tostring(data)
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		
		i = i + 1
	end
end

return p