Modulo:Wikidata

Questo è un modulo scritto in Lua. Le istruzioni che seguono sono contenute nella sottopagina Modulo:Wikidata/man (modifica · cronologia)
Sandbox: Modulo:Wikidata/sandbox (modifica · cronologia) · Sottopagine: lista · Test: Modulo:Wikidata/test (modifica · cronologia · esegui)
Il modulo Wikidata implementa le funzionalità dei template {{Wikidata}}, {{WikidataQ}}, {{WikidataIdx}}, {{WikidataN}}, {{WikidataLabel}}, {{WikidataDescription}}, {{WikidataLink}}, {{WikidataId}}, {{WikidataTipo}} e {{WikidataIstanza}}.
Utilizzo da un altro modulo
Il modulo può essere usato anche da un altro modulo tramite "require". È sufficiente inserire all'inizio del modulo:
local mWikidata = require('Modulo:Wikidata')
Le funzioni hanno gli stessi nomi di quelle utilizzate dai template ma con un underscore iniziale e ricevono come argomento, invece del frame, una table con cui specificare gli argomenti.
_getProperty(args, rawTable)
: per l'utilizzo della tabella args vedere il manuale del template {{Wikidata}}. Il parametro aggiuntivo rawTable, se valorizzato a true, fa sì che le dichiarazioni non vengano unite in un'unica stringa come per il template (separate dalla virgola e con la "e" prima dell'ultima), ma venga invece restituita una sequence, contenente le stringhe separate per ciascuna dichiarazione._getQualifier(args)
: vedere {{WikidataQ}}_indexOf(args)
: vedere {{WikidataIdx}}_N(args)
: vedere {{WikidataN}}_getLabel(args)
: vedere {{WikidataLabel}}_getDescription(args)
: vedere {{WikidataDescription}}_getLink(args)
: vedere {{WikidataLink}}_getDatatype(args)
: vedere {{WikidataTipo}}_getId(args)
: vedere {{WikidataId}}_instanceOf(args)
: vedere {{WikidataIstanza}}_subClassOf(args)
: analogamente, vedere {{WikidataIstanza}}
A queste si aggiungono tre funzioni specifiche del modulo, che permettono di iterare sulle dichiarazioni di una proprietà:
_getClaims(property, args)
: restituisce una sequence con le dichiarazioni di una proprietà, come _getProperty, ma senza formattarle. Per gli argomenti utilizzabili nella tabella args vedere i parametri di selezione nel manuale del template {{Wikidata}}. Può restituirenil
nel caso in cui la pagina non sia collegata a Wikidata._formatStatement(statement, args)
: formatta una dichiarazione (parametro statement) ottenuta tramite getClaims. Per l'utilizzo della tabella args vedere i parametri di formattazione nel manuale del template {{Wikidata}}._formatQualifiers(claim, qualifier, args, rawTable, retTable)
: formatta un qualificatore (parametro qualifier) di una dichiarazione (parametro claim) ottenuta tramite getClaims. Per l'utilizzo della tabella args vedere i parametri di formattazione nel manuale del template {{Wikidata}}. Il parametro rawTable, se valorizzato a true, fa sì che eventuali valori multipli di un qualificatore vengano restituiti come sequence invece che come unica stringa (con retTable è possibile specificare una sequence già esistente).
- Esempio
local mWikidata = require('Modulo:Wikidata')
local p = {}
function p.main(frame)
local capitale, data, stati, italia, onu
-- utilizzo della funzione getProperty
capitale = mWikidata._getProperty( { 'P36', from = 'Q183' } )
-- utilizzo della funzione getQualifier
data = mWikidata._getQualifier( { 'P36', 'P580', from = 'Q183' } )
-- utilizzo della funzione N
stati = mWikidata._N( { 'P47', from = 'Q183' } )
-- utilizzo della funzione indexOf
italia = mWikidata._indexOf( { 'P47', 'Q38', from = 'Q183' } )
-- utilizzo della funzione instanceOf
onu = mWikidata._instanceOf( { 'Q160016', from = 'Q183' } )
return string.format('La capitale della Germania è %s, dal %s. ' ..
'Confina con %s Stati, con l\'Italia: %s. ' ..
'Membro delle Nazioni Unite: %s.',
capitale, data, stati, italia and 'si' or 'no', onu and 'sì' or 'no')
end
return p
- Esempio con getClaims, formatStatement e formatQualifiers
local mWikidata = require('Modulo:Wikidata')
local p = {}
function p.main(frame)
local scuole = {}
local claims
claims = mWikidata._getClaims('P69', { from = 'Q42' })
for _, claim in ipairs(claims) do
local scuola = mWikidata._formatStatement(claim)
local inizio = mWikidata._formatQualifiers(claim, 'P580')
local fine = mWikidata._formatQualifiers(claim, 'P582')
table.insert(scuole, string.format('%s dal %s al %s', scuola, inizio, fine))
end
return 'Douglas Adams ha frequentato: ' .. table.concat(scuole, ', ')
end
return p
local i18n = {
["errors"] = {
["property-param-not-provided"] = "Parametro ''property'' non fornito.",
["entity-not-found"] = "Entità non trovata.",
["unknown-claim-type"] = "Tipo asserzione sconosciuta.",
["unknown-snak-type"] = "Tipo di snak sconosciuto.",
["unknown-datavalue-type"] = "Tipo di dato sconosciuto.",
["unknown-entity-type"] = "Tipo di entità sconosciuta.",
["unknown-value-module"] = "Devi impostare entrambi i parametri: ''value-module'' e ''value-function''.",
["value-module-not-found"] = "Modulo indicato da ''value-module'' non trovato.",
["value-function-not-found"] = "Funzione indicata da ''value-function'' non trovata."
},
["somevalue"] = "''valore sconosciuto''",
["novalue"] = "''nessun valore''"
}
function getEntityFromId( id )
if id then
return mw.wikibase.getEntity( id )
end
return mw.wikibase.getEntity()
end
function getEntityIdFromValue( value )
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'q'
elseif value['entity-type'] == 'property' then
prefix = 'p'
else
return formatError( 'unknown-entity-type' )
end
return prefix .. value['numeric-id']
end
function formatError( key )
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
function formatStatements( options )
if not options.property then
return formatError( 'property-param-not-provided' )
end
--Get entity
local entity = getEntityFromId( options.entityId )
if not entity then
return -- formatError( 'entity-not-found' )
end
if (entity.claims == nil) or (not entity.claims[string.lower(options.property)]) then
return '' --TODO error?
end
--Format statement and concat them cleanly
local formattedStatements = {}
local list_end
if options.list or options.orderedlist then
if options.list then
formattedStatements[1] = '<ul><li>'
list_end = '</li></ul>'
else
formattedStatements[1] = '<ol><li>'
list_end = '</li></ol>'
end
options.separator = '</li><li>'
options.conjunction = options.separator
end
if options.n then
local n = tonumber(options.n)
if n then
local statement = entity.claims[string.lower(options.property)][n - 1]
if statement then
table.insert( formattedStatements, formatStatement( statement, options ) )
end
end
else
for i, statement in pairs( entity.claims[string.lower(options.property)] ) do
table.insert( formattedStatements, formatStatement( statement, options ) )
end
end
if list_end then table.insert(formattedStatements, list_end) end
return mw.text.listToText( formattedStatements, options.separator, options.conjunction )
end
function formatStatement( statement, options )
if not statement.type or statement.type ~= 'statement' then
return formatError( 'unknown-claim-type' )
end
if options.qualifier then
return (statement.qualifiers and statement.qualifiers[options.qualifier]) and
formatDatavalue( statement.qualifiers[options.qualifier][0].datavalue, options ) or ''
else
return formatSnak( statement.mainsnak, options )
end
--TODO reference
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 formatDatavalue( snak.datavalue, options )
else
return formatError( 'unknown-snak-type' )
end
end
function formatDatavalue( datavalue, options )
local ret
--Use the customize handler if provided
if options['value-module'] or options['value-function'] then
if not options['value-module'] or not options['value-function'] then
return formatError( 'unknown-value-module' )
end
local formatter = require ('Module:' .. options['value-module'])
if formatter == nil then
return formatError( 'value-module-not-found' )
end
local fun = formatter[options['value-function']]
if fun == nil then
return formatError( 'value-function-not-found' )
end
return fun( datavalue.value, options )
end
--Default formatters
if datavalue.type == 'wikibase-entityid' then
ret = formatEntityId( getEntityIdFromValue( datavalue.value ), options )
elseif datavalue.type == 'string' then
ret = datavalue.value
elseif datavalue.type == 'time' then
ret = formatTime( datavalue.value, options )
elseif datavalue.type == 'globecoordinate' then
ret = formatGlobecoordinate( datavalue.value, options )
end
-- Optional pattern
if ret then
return options.pattern and formatFromPattern( ret, options ) or ret
else
return formatError( 'unknown-datavalue-type' )
end
end
function formatEntityId( entityId, options )
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 label --TODO what if no links and label + fallback language?
end
end
function formatTime( value, options )
local year, month, day
local ret = ''
year, month, day = value.time:match('.+(%d%d%d%d%d)%-(%d%d)%-(%d%d).+')
if value.precision == 9 then
ret = tonumber(year)
elseif value.precision == 11 then
ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
end
if value.precision == 9 or value.precision == 11 then
ret = ret .. (value.time:sub(1, 1) == '-' and ' a.C.' or '')
end
return ret
end
function formatGlobecoordinate( value, options )
return value.globe == 'http://www.wikidata.org/entity/Q2' and
(value.latitude .. ', ' .. value.longitude) or ''
end
function formatFromPattern( str, options )
-- la parentesi () extra serve per non ritornare anche il gsub.count
return ( mw.ustring.gsub( options.pattern, '$1', str ) )
end
-- Ritorna gli argomenti passati al modulo, scartando quelli valorizzati a stringhe vuote
local function getArgs(frame)
local args = {}
for k, v in pairs(frame.args) do
if v ~= '' then
args[k] = v
end
end
return args
end
local p = {}
function p.formatStatements( frame )
local args, value
--value è l'unico parametro che può anche essere una stringa vuota
value = frame.args.value
args = getArgs(frame)
--If a value is already set, use it
if value and value ~= '' then
return args.pattern and formatFromPattern( value, args ) or value
end
return formatStatements( args )
end
function p.N(frame)
local count = 0
property = string.lower(frame.args[1])
entity = mw.wikibase.getEntity()
if entity and entity.claims and entity.claims[property] then
for _ in pairs(entity.claims[property]) do count = count + 1 end
end
return count
end
return p