Modulo:Wikidata: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Allineo a versione di it.wikipedia copiando da https://it.wikipedia.org/w/index.php?title=Modulo:Wikidata&oldid=109802505 e aggiunto checkStatements copiato da https://it.wikiquote.org/w/index.php?title=Modulo:Wikidata&oldid=1052196
Riga 1:
--[[
* Modulo per implementare le funzionalità dei template {{Wikidata}} e {{Wikidata Check}}.:
* {{Wikidata}}, {{WikidataQ}}, {{WikidataIdx}}, {{WikidataN}}, {{WikidataLabel}},
* {{WikidataLink}}, {{WikidataId}}, {{WikidataTipo}} e {{WikidataIstanza}}.
* Permette di accedere a Wikidata in modo più avanzato rispetto a {{#property}}.
 
* Per la maggior parte riscritto e ampliato a partire dalla versione iniziale a:
* Il modulo è stato importato inizialmente da:
* http://test2.wikipedia.org/w/index.php?title=Module:Wikidata&oldid=52322
]]
-- <nowiki>
 
-- =============================================================================
-- Messaggi di errore
-- Non utilizzare mai mw.wikibase.getEntity, per esempio un solo utilizzo di
-- mw.wikibase.getEntity('Q183') fa aumentare di 7 MB l'utilizzo di memoria
-- per Lua ed è molto lenta se ripetuta (unico utilizzo in getDatatype,
-- solo per proprietà, non essendoci alternative).
-- =============================================================================
 
require('Module:No globals')
 
local getArgs = require('Module:Arguments').getArgs
local mConvert = require('Module:Conversione')
local mLanguages = require('Module:Linguaggi')
 
-- Categoria per le pagine con errori
local errorCategory = '[[Categoria:Voci con errori del modulo Wikidata]]'
 
-- Messaggi
local i18n = {
["errors"] = {
["property'entityid-param-not-provided"'] = "Parametro ''propertyentityid'' non fornito.",
["qualifier'property-param-not-provided"'] = "Parametro ''qualifierproperty'' non fornito.",
["entity'qualifier-param-not-found"provided'] = "EntitàParametro ''qualifier'' non trovata.fornito",
['value-param-not-provided'] = "Parametro ''valore'' da ricercare non fornito",
["unknown-claim-type"] = "Tipo asserzione sconosciuta.",
["unknown'entity-snaknot-type"found'] = "Tipo'Entità dinon snak sconosciuto."trovata',
["'unknown-datavalueclaim-type"'] = "'Tipo diasserzione dato sconosciuto."sconosciuta',
["'unknown-entitysnak-type"'] = "'Tipo di entitàsnak sconosciuta."sconosciuto',
['unknown-datavalue-type'] = 'Tipo di dato sconosciuto',
["unknown-value-module"] = "Devi impostare entrambi i parametri: ''value-module'' e ''value-function''.",
['unknown-entity-type'] = 'Tipo di entità sconosciuta'
["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''",
datatypes = {
['commonsMedia'] = 'file multimediale su Commons',
['external-id'] = 'identificativo esterno',
['geo-shape'] = 'forma geografica',
['globe-coordinate'] = 'coordinate geografiche',
['math'] = 'espressione matematica',
['monolingualtext'] = 'testo monolingua',
['quantity'] = 'quantità',
['string'] = 'stringa',
['tabular-data'] = 'tabular data',
['time'] = 'data e ora',
['url'] = 'URL',
['wikibase-item'] = 'elemento',
['wikibase-property'] = 'proprietà'
}
}
 
local p = {}
 
-------------------------------------------------------------------------------
Line 30 ⟶ 63:
-------------------------------------------------------------------------------
 
local function formatErrorerrhandler(keymsg)
local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
return '<span class="error">' .. i18n.errors[key] .. '</span>'
return string.format('<span class="error">%s</span>%s', msg, cat)
end
 
Line 39 ⟶ 73:
end
 
local function formatEntityIdformatExtLink(entityId, options, formattingurl)
local protocols = { ftp = true, http = true, https = true }
if formatting == 'raw' then
 
return entityId
local success, uri = pcall(function() return mw.uri.new(url) end)
if success and uri.protocol and protocols[uri.protocol] then
local dest = tostring(uri)
return string.format('<span style="word-break: break-all;">[%s %s]</span>', dest, dest:gsub(uri.protocol .. '://', ''))
else
return url
end
end
 
local labelfunction = mw.wikibase.labelformatEntityId(entityId)
local linklabel = mw.wikibase.sitelinkgetLabel(entityId)
local siteLink = mw.wikibase.getSitelink(entityId)
if link and options.formatting ~= 'nolink' then
local ret
if label then
if entityId == mw.wikibase.getEntityIdForCurrentPage() then
return '[[' .. link .. '|' .. label .. ']]'
ret = siteLink
else
elseif siteLink and label then
return '[[' .. link .. ']]'
ret = mw.getContentLanguage():ucfirst(label) == siteLink and
end
string.format('[[%s]]', label) or
string.format('[[%s|%s]]', siteLink, label)
elseif siteLink then
ret = string.format('[[%s]]', siteLink)
elseif label then
ret = label
else
returnret label or= ''
end
return ret
end
 
local function formatTimeformatMonolingualtext(value, args)
local year, month, day
local ret = ''
if not args.includelang or args.includelang:match('%f[a-z]' .. value.language .. '%f[^a-z]') then
if not args.excludelang or not args.excludelang:match('%f[a-z]' .. value.language .. '%f[^a-z]') then
ret = value.text
if args.showlang then
ret = mLanguages.lingue({ value.language }) .. '&nbsp;' .. ret
end
end
end
return ret
end
 
local function formatTimeWithPrecision(time, precision)
local months = {
'gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno',
'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'
}
local ret, year, month, day
year, month, day = time:match('(%d+)%-(%d%d)%-(%d%d).+')
year, month, day = tonumber(year), tonumber(month), tonumber(day)
if precision == 9 then
ret = year
elseif precision == 10 then
ret = months[month] .. ' ' .. year
elseif precision == 11 then
ret = day .. ' ' .. months[month] .. ' ' .. year
ret = ret:gsub('^1%s', '1º ')
end
if precision >= 9 and precision <= 11 then
ret = ret .. (time:sub(1, 1) == '-' and ' a.C.' or '')
end
 
return ret
end
 
local function formatTime(value, args)
local ret
if args.time == 'precision' then
Line 66 ⟶ 150:
ret = value.calendarmodel
elseif args.time == 'year' and value.precision >= 9 then
ret = formatTimeWithPrecision(value.time, 9)
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
ret = tonumber(year)
elseif args.time == 'month' and value.precision >= 10 then
ret = formatTimeWithPrecision(value.time, 10)
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
ret = mw.getLanguage('it'):formatDate('F', tonumber(year) .. '-' .. month)
elseif args.time == 'day' and value.precision >= 11 then
ret = formatTimeWithPrecision(value.time, 11)
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
ret = tonumber(day)
elseif not args.time then
ret = formatTimeWithPrecision(value.time, value.precision)
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
if value.precision == 9 then
ret = tonumber(year)
elseif value.precision == 10 then
ret = mw.getLanguage('it'):formatDate('F Y', tonumber(year) .. '-' .. month)
elseif value.precision == 11 then
ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
ret = ret:gsub('^1%s', '1º ')
end
if value.precision >= 9 and value.precision <= 11 then
ret = ret .. (value.time:sub(1, 1) == '-' and ' a.C.' or '')
end
end
 
return ret or ''
end
 
local function formatGlobecoordinate(value, optionsargs)
local ret
if optionsargs.formattingcoord == 'latitude' then
ret = value.latitude
elseif optionsargs.formattingcoord == 'longitude' then
ret = value.longitude
elseif args.coord == 'globe' then
ret = value.globe
else
ret = valuestring.latitude .. format('%s, %s', value..latitude, value.longitude)
end
return ret
end
 
local function formatFromPattern(str, optionsargs)
local pattern = args.pattern
-- la parentesi () extra serve per non ritornare anche il gsub.count
returnpattern = (mw.ustring.gsub(options.pattern, '$1\\{', str)'{')
pattern = mw.ustring.gsub(pattern, '\\}', '}')
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
end
 
local function formatUserValue(value, args)
if args.extlink then
value = formatExtLink(value)
end
return args.pattern and formatFromPattern(value, args) or value
end
 
Line 116 ⟶ 197:
prefix = 'P'
else
return formatErrorerror(i18n.errors['unknown-entity-type'])
end
return prefix .. value['numeric-id']
end
 
local function formatDatavalueformatUnitSymbol(datavalueentityId, options, formattingargs)
local ret
for _, lang in ipairs({ 'mul', 'it', 'en' }) do
 
ret = p._getProperty({ 'P5061', includelang = lang, from = entityId })
--Use the customize handler if provided
if ret and ret ~= '' then
if options['value-module'] or options['value-function'] then
break
if not options['value-module'] or not options['value-function'] then
else
return formatError('unknown-value-module')
ret = nil
end
end
local formatter = require ('Modulo:' .. options['value-module'])
local space = ret == '°' and '' or ' '
if formatter == nil then
if ret and args.showunitlink then
return formatError('value-module-not-found')
local link = mw.wikibase.getSitelink(entityId)
if link then
ret = string.format('[[%s|%s]]', link, ret)
end
end
local funct = formatter[options['value-function']]
return ret and (space .. ret) or ''
if funct == nil then
end
return formatError('value-function-not-found')
 
-- http://lua-users.org/wiki/SimpleRound
local function round(num, idp)
local mult = 10 ^ (idp or 0)
return math.floor(num * mult + 0.5) / mult
end
 
 
local function formatQuantity(value, args)
local ret = tonumber(value.amount)
 
if (args.unit or args.showunit) and value.unit ~= '1' then
local unitId = mw.ustring.match(value.unit, 'Q%d+')
if args.unit then
local opts = {
showunit = args.showunit,
showunitlink = args.showunitlink,
formatnum = args.formatnum,
rounding = args.rounding
}
ret = mConvert._main(ret, unitId, args.unit, opts)
else
-- se è richiesto solo il simbolo dell'unità
-- senza la conversione lo ottiene da P5061
ret = args.rounding and round(ret, args.rounding) or ret
if args.formatnum then
ret = mw.language.getContentLanguage():formatNum(ret)
end
ret = ret .. formatUnitSymbol(unitId, args)
end
elseif args.formatnum then
return funct(datavalue.value, options)
ret = args.rounding and round(ret, args.rounding) or ret
ret = mw.language.getContentLanguage():formatNum(ret)
elseif args.formatduration and value.unit ~= '1' then
local unitId = mw.ustring.match(value.unit, 'Q%d+')
ret = mConvert._main(ret, unitId, 'second')
ret = ret and mw.language.getContentLanguage()
:formatDuration(tonumber(ret), { 'days', 'hours', 'minutes', 'seconds' })
end
 
return ret
--Default formatters
end
 
local function formatDatavalue(datavalue, snakdatatype, args)
local ret
 
if datavalue.type == 'wikibase-entityid' then
retlocal entityId = formatEntityId(getEntityIdFromValue(datavalue.value), options, formatting)
if args.showprop then
ret = p._getProperty({ args.showprop, n = 1, from = entityId }) or ''
else
ret = args.formatting == 'raw' and entityId or formatEntityId(entityId)
end
elseif datavalue.type == 'string' then
ret = datavalue.value
if args.extlink and snakdatatype == 'url' then
ret = formatExtLink(ret)
elseif args.urlencode then
ret = mw.uri.encode(ret)
end
elseif datavalue.type == 'monolingualtext' then
ret = formatMonolingualtext(datavalue.value.text, args)
elseif datavalue.type == 'time' then
if args.formatting == 'raw' then
ret = formatTime(datavalue.value, options)
ret = datavalue.value.time
else
ret = formatTime(datavalue.value, args)
end
elseif datavalue.type == 'globecoordinate' then
ret = formatGlobecoordinate(datavalue.value, optionsargs)
elseif datavalue.type == 'quantity' then
ret = tonumberformatQuantity(datavalue.value.amount, args)
else
ret = formatErrorerror(i18n.errors['unknown-datavalue-type'])
end
 
Line 160 ⟶ 300:
end
 
local function formatSnak(snak, options, formattingargs)
if snak.snaktype == 'somevalue' then
return i18n['somevalue']
Line 166 ⟶ 306:
return i18n['novalue']
elseif snak.snaktype == 'value' then
return formatDatavalue(snak.datavalue, optionssnak.datatype, formattingargs)
else
return formatErrorerror(i18n.errors['unknown-snak-type'])
end
end
 
-- È al plurale perché anche i qualifier possono avere più di un valore
local function formatStatement(statement, options)
-- (si ottiene inserendo due volte lo stesso qualifier)
local function formatQualifiers(claim, qualifierId, args, rawTable, retTable)
local formattedQualifiers = retTable or {}
 
if claim.qualifiers and claim.qualifiers[qualifierId] then
local qualifiers = claim.qualifiers[qualifierId]
-- con args.nq seleziona solo l'n-esimo qualifier
if args.nq then
local n = tonumber(args.nq)
qualifiers = (n and n <= #qualifiers) and { qualifiers[n] } or {}
end
-- qualifier filtrati per snaktype, default "value"
args.snaktype = args.snaktype or 'value'
for _, qualifier in ipairs(qualifiers) do
if qualifier.snaktype == args.snaktype or args.snaktype == 'all' then
local formattedQualifier = formatSnak(qualifier, args)
if formattedQualifier ~= '' then
if args.pattern then
formattedQualifier = formatFromPattern(formattedQualifier, args)
if formattedQualifier ~= '' then
table.insert(formattedQualifiers, formattedQualifier)
end
else
table.insert(formattedQualifiers, formattedQualifier)
end
end
end
end
end
 
if rawTable then
return formattedQualifiers
end
 
return #formattedQualifiers > 0 and
mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
 
local function appendQualifiers(statement, text, args)
local formattedQualifiers = {}
local qualifierIds = mw.text.split(args.showqualifiers, ',')
for _, qualifierId in ipairs(qualifierIds) do
if statement.qualifiers[qualifierId] then
local formattedQualifier = formatQualifiers(statement, qualifierId, args)
table.insert(formattedQualifiers, formattedQualifier)
end
end
if #formattedQualifiers > 0 then
text = string.format('%s (%s)', text, mw.text.listToText(formattedQualifiers, ', ', ', '))
end
return text
end
 
local function formatStatement(statement, args)
if not statement.type or statement.type ~= 'statement' then
return formatErrorerror(i18n.errors['unknown-claim-type'])
end
local ret = formatSnak(statement.mainsnak, args)
-- eventuale showqualifiers
if args.showqualifiers and statement.qualifiers then
ret = appendQualifiers(statement, ret, args)
end
 
return ret
return formatSnak(statement.mainsnak, options)
end
 
local function formatStatements(claims, optionsargs, rawTable)
local formattedStatements = {}
 
for _, claim in pairsipairs(claims) do
local formattedStatement = formatStatement(claim, optionsargs)
if formattedStatement ~= '' then
-- eventuale pattern
-- eventuale pattern
if options.pattern then
if args.pattern then
formattedStatement = formatFromPattern(formattedStatement, options)
formattedStatement = formatFromPattern(formattedStatement, args)
if formattedStatement ~= '' then
table.insert(formattedStatements, formattedStatement)
end
else
table.insert(formattedStatements, formattedStatement)
end
end
end
table.insert(formattedStatements, formattedStatement)
if rawTable then
return formattedStatements
end
 
return ((optionsargs.list or optionsargs.orderedlist) and #formattedStatements > 1) and
formatList(formattedStatements, optionsargs.orderedlist ~= nil) or
mw.text.listToText(formattedStatements, optionsargs.separator, optionsargs.conjunction)
end
 
Line 201 ⟶ 410:
-------------------------------------------------------------------------------
 
-- RitornaRestituisce true se lo statement contiene il qualifier richiesto con un dato valore
local function hasQualifierValue(statement, optionsqualifierId, qualifierValue)
local ret = false
for i_, qualifier in pairsipairs(statement.qualifiers[options.qualifierqualifierId]) do
local isItem = qualifier.snaktype == 'value' and
if formatSnak(qualifier, options, 'raw') == options.qualifiervalue then
qualifier.datavalue.type == 'wikibase-entityid'
-- per le proprietà di tipo item il confronto è eseguito sull'id
if formatSnak(qualifier, isItem and { formatting = 'raw' } or {}) == qualifierValue then
ret = true
break
Line 213 ⟶ 425:
end
 
-- RitornaRestituisce i claim con il rank richiesto
local function filterRankValue(claims, rank)
local ret = {}
for i_, claim in pairsipairs(claims) do
if claim.rank == rank then
table.insert(ret, claim)
Line 224 ⟶ 436:
end
 
-- RitornaRestituisce una tablesequence Lua contenente gli statement per la property richiesta.,
-- anche vuota se la proprietà non esiste, o non ci sono valori che soddisfano i criteri
-- Gli statement ritornati sono eventualmente filtrati in base ai parametri:
-- ("rank", "qualifier", "qualifiertype" e, "nnoqualifier", ...).
-- Restituisce nil solo se la pagina non è collegata a un elemento Wikidata e non è indicato il from.
local function getClaims(options)
local function getClaims(propertyId, args)
local entityId, entity, claims, filteredClaims
local entityId, claims, filteredClaims
 
-- get entity
entityId = optionsargs.entityIdfrom andor stringmw.upper(optionswikibase.entityIdgetEntityIdForCurrentPage()
entityif =not mw.wikibase.getEntity(entityId) then
return nil
if not entity then
error('') -- error(formatError('entity-not-found'))
end
 
-- il default rank è 'best'
-- get property
args.rank = args.rank or 'best'
if not options.property then
if args.rank == 'best' then
error(formatError('property-param-not-provided'))
claims = mw.wikibase.getBestStatements(entityId, propertyId)
end
 
if entity.claims and entity.claims[options.property] and
#entity.claims[options.property] > 0 then
claims = entity.claims[options.property]
else
-- statements filtrati per rank
error('') --TODO error?
claims = mw.wikibase.getAllStatements(entityId, propertyId)
claims = filterRankValue(claims, args.rank)
end
 
-- statements filtrati per ranksnaktype, default "value"
args.snaktype = args.snaktype or 'value'
if options.rank then
if optionsargs.ranksnaktype =and args.snaktype ~= 'bestall' then
filteredClaims = filterRankValue(claims, 'preferred'){}
for _, claim in ipairs(claims) do
if #filteredClaims == 0 then
if claim.mainsnak.snaktype == args.snaktype then
filteredClaims = filterRankValue(claims, 'normal')
table.insert(filteredClaims, claim)
end
else
filteredClaims = filterRankValue(claims, options.rank)
end
claims = filteredClaims
Line 263 ⟶ 471:
 
-- statements filtrati per qualifier
if optionsargs.qualifier then
filteredClaims = {}
for i_, claim in pairsipairs(claims) do
if claim.qualifiers and claim.qualifiers[optionsargs.qualifier] then
if optionsargs.qualifiervalue then
if hasQualifierValue(claim, optionsargs.qualifier, args.qualifiervalue) then
table.insert(filteredClaims, claim)
end
Line 279 ⟶ 487:
end
 
-- statements filtrati per essere senza un qualifier
-- con options.qualifiertype=latest ritorna solo il più recente
if args.noqualifier then
if options.qualifier and options.qualifiertype == 'latest' then
filteredClaims = {}
for _, claim in ipairs(claims) do
if not (claim.qualifiers and claim.qualifiers[args.noqualifier]) then
table.insert(filteredClaims, claim)
end
end
claims = filteredClaims
end
 
-- statements filtrati per non avere un certo valore a un certo qualifier opzionale
if args.qualifieroptnovalue and args.qualifiervalue then
filteredClaims = {}
for _, claim in ipairs(claims) do
if claim.qualifiers and claim.qualifiers[args.qualifieroptnovalue] then
if not hasQualifierValue(claim, args.qualifieroptnovalue, args.qualifiervalue) then
table.insert(filteredClaims, claim)
end
else
table.insert(filteredClaims, claim)
end
end
claims = filteredClaims
end
 
-- con args.qualifiertype=latest restituisce solo il più recente
if args.qualifier and args.qualifiertype == 'latest' then
local latest, latestTime
for i_, claim in pairsipairs(claims) do
if claim.qualifiers and claim.qualifiers[optionsargs.qualifier] then
for j_, qualifier in pairsipairs(claim.qualifiers[optionsargs.qualifier]) do
if qualifier.datavalue.type == 'time' then
if not latestTime or qualifier.datavalue.value.time > latestTime then
Line 294 ⟶ 528:
end
end
claims = latest and { latest } or {}
end
 
-- con optionsargs.n ritornarestituisce solo l'n-esimo elemento
if optionsargs.n then
local n = tonumber(optionsargs.n)
claims = (n and n <= #claims) and { claims[n] } or {}
end
 
Line 307 ⟶ 541:
 
-------------------------------------------------------------------------------
-- Funzioni esportate per altri APImoduli
-------------------------------------------------------------------------------
 
function p._getClaims(propertyId, args)
local p = {}
return getClaims(propertyId, args or {})
end
 
function p._formatStatement(statement, args)
-- Funzione di utilità, ritorna gli argomenti passati al modulo
return formatStatement(statement, args or {})
-- scartando quelli valorizzati a stringhe vuote
end
local function getArgs(frame)
 
local args = {}
function p._formatQualifiers(claim, qualifierId, args, rawTable, retTable)
return formatQualifiers(claim, qualifierId, args or {}, rawTable, retTable)
end
 
-- Restituisce il valore di una proprietà di Wikidata oppure nil se l'entity o
-- la proprietà non esistono, o se per parametri di selezione gli statement sono zero.
function p._getProperty(args, rawTable)
local propertyId, value, claims, ret
 
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
value = args[2]
-- fix uppercase
args.qualifier = args.qualifier and string.upper(args.qualifier)
 
if value then
ret = formatUserValue(value, args)
elseif args.wd ~= 'no' then
claims = getClaims(propertyId, args)
ret = (claims and #claims > 0) and formatStatements(claims, args, rawTable) or nil
end
 
return ret
end
 
-- Restituisce il valore di un qualifier di una proprietà di Wikidata,
-- o nil se l'entity o la proprietà non esistono, o se per parametri di selezione non ci sono risultati.
function p._getQualifier(args)
local propertyId, qualifierId, value, claims, ret
 
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
qualifierId = args[2] and string.upper(args[2])
if not qualifierId then
error(i18n.errors['qualifier-param-not-provided'], 2)
end
value = args[3]
 
if frame == mw.getCurrentFrame()value then
ret = formatUserValue(value, args)
-- argomenti passati indirettamente come parametri del template invocante
elseif args.wd ~= 'no' then
local parent = frame:getParent()
claims = getClaims(propertyId, args)
local parentArgs = parent and parent.args or {}
if claims and #claims > 0 then
for k, v in pairs(parentArgs) do
local formattedQualifiers = {}
if v ~= '' then
for _, claim in ipairs(claims) do
args[k] = v
formattedQualifiers = formatQualifiers(claim, qualifierId, args, true, formattedQualifiers)
end
ret = #formattedQualifiers > 0 and
mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
end
-- argomenti passati direttamente come parametri di #invoke
 
for k, v in pairs(frame.args) do
return ret
if v ~= '' then
end
args[k] = v
 
-- Restituisce l'indice dello statement con il valore richiesto, o nil se non trovato.
function p._indexOf(args)
local ret, propertyId, value, claims
 
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
value = args[2]
if not value then
error(i18n.errors['value-param-not-provided'], 2)
end
 
claims = getClaims(propertyId, args)
if claims and #claims > 0 then
args.formatting = 'raw'
for i, claim in ipairs(claims) do
if formatStatement(claim, args) == value then
ret = i
break
end
end
else
args = frame
end
 
return ret
-- trasforma i valori di property, qualifier e qualifiervalue in maiuscolo
end
local toUpper = {
 
property = true,
-- Restituisce il numero di statement di una proprietà di Wikidata.
qualifier = true,
function p._N(args)
qualifiervalue = true
local propertyId, claims
}
 
for k, v in pairs(args) do
-- parametri posizionali
if toUpper[k] then
propertyId = args[k1] =and string.upper(vargs[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
-- get claims
claims = getClaims(propertyId, args)
 
return claims and #claims or 0
end
 
-- Restituisce true se la propriertà specificata ha come valore
-- almeno uno tra gli entityId passati come argomento.
function p._propertyHasEntity(propertyId, args)
local statements = p._getProperty({ propertyId, from = args.from, formatting = 'raw' }, true)
if statements then
for _, statement in ipairs(statements) do
for _, entityId in ipairs(args) do
if statement == entityId then
return true
end
end
end
 
-- Se non è stato trovato alcun valore, controlla se questo sia ereditato
-- tramite la proprietà "sottoclasse di" (P279) scavando in profondità
-- fino all'esaurirsi del numero specificato in args.recursion.
--[[ TODO: Valutare se sia opportuna una ricerca ricorsiva potenzialmente infinita.
Per farlo si può aggiungere un parametro (opzionale) maxDepth
che svolga l'attuale funzione di recursion e cambiare quest'ultimo
in un parametro booleano.
]]
args.recursion = tonumber(args.recursion) or 0
if args.recursion > 0 then
local recursion = args.recursion
if type(args.loadedEntities) ~= 'table' then
args.loadedEntities = setmetatable({}, {
__newindex = function(t, k, v)
rawset(t, k, v)
rawset(t, #t+1, k)
end })
args.loadedEntities[args.from or mw.wikibase.getEntityIdForCurrentPage()] = true
end
for _, statement in ipairs(statements) do
if not args.loadedEntities[statement] then
args.loadedEntities[statement] = true
args.recursion = args.recursion - 1
args.from = statement
if p._propertyHasEntity('P279', args) then
return true, args.loadedEntities
end
args.recursion = recursion
end
end
end
end
 
return false, args.loadedEntities
-- rank impostato a best per default
end
args.rank = args.rank or 'best'
 
-- Restituisce true se la proprietà P31 (instance of) ha come valore almeno uno tra gli entityId specificati
return args
function p._instanceOf(args)
return p._propertyHasEntity('P31', args)
end
 
-- Restituisce true se la proprietà P279 (subclass of) ha come valore almeno uno tra gli entityId specificati
-- Entry-point per {{#invoke:Wikidata|formatStatements}}
function p.formatStatements_subclassOf(frameargs)
return p._propertyHasEntity('P279', args)
local args, ret, claims
end
 
-- Restituisce l'etichetta di un item o di una proprietà Wikidata.
args = getArgs(frame)
function p._getLabel(args)
 
local entityId = args[1] and string.upper(args[1])
-- if parameter value is already set, use it
local ret
if args.value then
if args[2] then
return not(args.novaluepattern) -- if parameter novaluepattern is not set
ret = mw.wikibase.getLabelByLang(entityId, args[2])
and args.pattern and formatFromPattern(args.value, args)
else
or args.value
ret = mw.wikibase.getLabel(entityId)
end
return ret
end
 
-- Restituisce il titolo della pagina collegata a un dato item Wikidata.
-- get claims
function p._getLink(args)
ret, claims = pcall(getClaims, args)
-- parametri posizionali
if not ret then
local entityId = args[1] and string.upper(args[1])
return claims:match('.+%d:%s(.+)$')
if not entityId then
error(i18n.errors['entityid-param-not-provided'], 2)
end
 
return entityId:sub(1, 1) == 'Q' and formatEntityId(entityId) or nil
return formatStatements(claims, args)
end
 
-- Restituisce il datatype di una proprietà Wikidata.
-- Entry-point per {{#invoke:Wikidata|getQualifier}}
function p.getQualifier_getDatatype(frameargs)
local propertyId, entity
local args, ret, claims, formattedQualifier, formattedQualifiers
 
args = getArgs(frame)
 
-- parametri posizionali
-- if parameter value is already set, use it
propertyId = args[1] and string.upper(args[1])
if args.value then
if not propertyId then
return not(args.novaluepattern) -- if parameter novaluepattern is not set
error(i18n.errors['property-param-not-provided'], 2)
and args.pattern and formatFromPattern(args.value, args)
or args.value
end
 
entity = mw.wikibase.getEntity(propertyId)
-- get qualifier name
if not args.qualifierentity then
error(i18n.errors['entity-not-found'], 2)
return formatError('qualifier-param-not-provided')
end
 
if not i18n.datatypes[entity.datatype] then
-- get claims
error(i18n.errors['unknown-datavalue-type'], 2)
ret, claims = pcall(getClaims, args)
if not ret then
return claims:match('.+%d:%s(.+)$')
end
 
return i18n.datatypes[entity.datatype]
-- get qualifiers and format them
end
formattedQualifiers = {}
 
for i, claim in pairs(claims) do
-- Restituisce l'ID dell'item Wikidata collegato alla pagina corrente o a una pagina specificata
if claim.qualifiers and claim.qualifiers[args.qualifier] then
-- (nota: segue i redirect fermandosi al primo redirect collegato a un elemento)
for j, qualifier in pairs(claim.qualifiers[args.qualifier]) do
function p._getId(args)
formattedQualifier = formatSnak(qualifier, args)
local ret
if args.pattern then
if args[1] then
formattedQualifier = formatFromPattern(formattedQualifier, args)
local title = mw.title.new(args[1])
end
while title do
table.insert(formattedQualifiers, formattedQualifier)
local id = mw.wikibase.getEntityIdForTitle(title.prefixedText)
if id then
ret = id
break
else
title = title.redirectTarget
end
end
else
ret = mw.wikibase.getEntityIdForCurrentPage()
end
return ret
end
 
-------------------------------------------------------------------------------
-- Funzioni esportate per i template
-------------------------------------------------------------------------------
 
-- Funzione per il template {{Wikidata}}
return mw.text.listToText(formattedQualifiers, args.separator, args.conjunction)
function p.getProperty(frame)
return select(2, xpcall(function()
return p._getProperty(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{#invoke:Wikidata|NWikidataQ}}
function p.getQualifier(frame)
return select(2, xpcall(function()
return p._getQualifier(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataIdx}}
function p.indexOf(frame)
return select(2, xpcall(function()
return p._indexOf(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataN}}
function p.N(frame)
return select(2, xpcall(function()
local property, count, entity, entityId
return p._N(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataLabel}}
property = frame.args[1] and string.upper(frame.args[1])
function p.getLabel(frame)
return select(2, xpcall(function()
return p._getLabel(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataLink}}
if not property then
function p.getLink(frame)
return formatError('property-param-not-provided')
return select(2, xpcall(function()
end
return p._getLink(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataIstanza}}
entityId = frame.args.entityId and string.upper(frame.args.entityId)
function p.instanceOf(frame)
entity = mw.wikibase.getEntity(entityId)
return select(2, xpcall(function()
if entity and entity.claims and entity.claims[property] then
return p._instanceOf(getArgs(frame, { parentOnly = true })) and 1 or ''
count = #entity.claims[property]
end, errhandler))
end
 
-- Funzione per il template {{WikidataTipo}}
function p.getDatatype(frame)
return select(2, xpcall(function()
return p._getDatatype(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataId}}
function p.getId(frame)
return select(2, xpcall(function()
return p._getId(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataValido}}
return count or 0
function p.checkProperty(frame)
return select(2, xpcall(function()
return p._N(getArgs(frame, { parentOnly = true })) > 0 and 1 or ''
end, errhandler))
end
 
-- Entry-point per {{#invoke:Wikidata|checkStatements}}
-- Modulo specifico per Wikiquote
function p.checkStatements(frame)
local property, value, checkvalue, entity, entityId
Line 475 ⟶ 895:
 
return p
 
-- </nowiki>