Modulo:Wikidata/sandbox: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
aggiunta funzione getId
Nessun oggetto della modifica
Etichetta: Ripristino manuale
 
(113 versioni intermedie di 7 utenti non mostrate)
Riga 1:
--[[
* Modulo per implementare le funzionalità dei template:
* {{Wikidata}}, {{WikidataQ}}, {{WikidataIdx}}, {{WikidataN}}, {{WikidataLabel}}, {{WikidataDescription}}
* {{WikidataLabelWikidataLink}}, {{WikidataLinkWikidataId}}, {{WikidataTipo}} e {{WikidataIdWikidataIstanza}}.
* 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
]]
 
-- =============================================================================
require('Module:No globals')
-- 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('strict')
 
local getArgs = require('Module:Arguments').getArgs
local mConvert = require('Module:Conversione')
local mLanguages = require('Module:LinguaggiLingue')
local mCitation = require('Module:Citazione')
 
-- Categoria per le pagine con errori
local errorCategory = '[[Categoria:Voci con errori del modulo Wikidata]]'
 
-- Messaggi
local p = {}
 
-- Messaggi di errore
local i18n = {
["errors"] = {
["'entityid-param-not-provided"'] = "Parametro ''entityid'' non fornito",
["'property-param-not-provided"'] = "Parametro ''property'' non fornito",
["'qualifier-param-not-provided"'] = "Parametro ''qualifier'' non fornito",
["'value-param-not-provided"'] = "Parametro ''valore'' da ricercare 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"'
},
["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 = {}
 
-------------------------------------------------------------------------------
Riga 44 ⟶ 67:
local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
return string.format('<span class="error">%s</span>%s', msg, cat)
end
 
local function formatList(values, ordered)
local fmt = ordered and '<ol><li>%s</li></ol>' or '<ul><li>%s</li></ul>'
return #values > 0 and string.format(fmt, mw.text.listToText(values, '</li><li>', '</li><li>')) or ''
end
 
Riga 52 ⟶ 80:
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
Riga 59 ⟶ 87:
 
local function formatEntityId(entityId)
local label = mw.wikibase.labelgetLabel(entityId)
local linksiteLink = mw.wikibase.sitelinkgetSitelink(entityId)
local ret
if link then
if entityId == mw.wikibase.getEntityIdForCurrentPage() then
if label and label ~= link then
ret = siteLink
return '[[' .. link .. '|' .. label .. ']]'
elseif siteLink and label then
else
ret = mw.getContentLanguage():ucfirst(label) == siteLink and
return '[[' .. link .. ']]'
string.format('[[%s]]', label) or
end
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 formatMonolingualtext(value, args)
local ret = ''
if not (args.langitincludelang ==or args.includelang:match('no%f[a-z]' and.. value.language ==.. 'it%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
ret = value.text
if args.showlang then
if args.showlang then
ret = mLanguages.lingue( { value.language } ) .. '&nbsp;' .. ret
ret = mLanguages.lingue({ value.language }) .. '&nbsp;' .. ret
end
end
end
Riga 83 ⟶ 119:
end
 
local function formatTimeformatTimeWithPrecision(valuetime, argsprecision)
local year,months month,= day{
'gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno',
local ret = ''
'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'
}
local ret, year, month, day
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
year, month, day = tonumber(year), tonumber(month), tonumber(day)
if value.precision == 9 then
if precision == 9 then
ret = tonumber(year)
ret = year
elseif value.precision == 10 then
elseif precision == 10 then
ret = mw.getLanguage('it'):formatDate('F Y', tonumber(year) .. '-' .. month)
ret = months[month] .. ' ' .. year
elseif value.precision == 11 then
elseif precision == 11 then
ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
ret = day .. ' ' .. months[month] .. ' ' .. year
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
 
return ret
end
 
local function formatTime(value, args)
local ret
if args.time == 'precision' then
ret = value.precision
elseif args.time == 'calendarmodel' then
ret = value.calendarmodel
elseif args.time == 'year' and value.precision >= 9 then
ret = formatTimeWithPrecision(value.time, 9)
elseif args.time == 'month' and value.precision >= 10 then
ret = formatTimeWithPrecision(value.time, 10)
elseif args.time == 'day' and value.precision >= 11 then
ret = formatTimeWithPrecision(value.time, 11)
elseif not args.time then
ret = formatTimeWithPrecision(value.time, value.precision)
end
 
return ret or ''
end
 
Riga 109 ⟶ 169:
elseif args.coord == '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, args, refs)
local pattern = args.pattern
pattern = mw.ustring.gsub(pattern, '\\{', '{')
pattern = mw.ustring.gsub(pattern, '\\}', '}')
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str, refs or ''):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
 
Riga 135 ⟶ 204:
 
local function formatUnitSymbol(entityId, args)
local ret
local ret = p._getProperty( { 'P558', n = 1, from = entityId } )
for _, lang in ipairs({ 'mul', 'it', 'en' }) do
ret = p._getProperty({ 'P5061', includelang = lang, from = entityId })
if ret and ret ~= '' then
break
else
ret = nil
end
end
local space = ret == '°' and '' or ' '
if ret and args.showunitlink then
local link = mw.wikibase.sitelinkgetSitelink(entityId)
if link then
ret = string.format('[[%s|%s]]', link, ret)
end
end
return ret and (' 'space .. ret) or ''
end
 
-- 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)
Riga 154 ⟶ 239:
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 P558P5061
ret = args.rounding and round(ret, args.rounding) or ret
if args.formatnum then
ret = mw.language.getContentLanguage():formatNum(ret)
Riga 166 ⟶ 253:
end
elseif args.formatnum then
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
 
Riga 178 ⟶ 271:
local entityId = getEntityIdFromValue(datavalue.value)
if args.showprop then
ret = p._getProperty( { args.showprop, n = 1, from = entityId } ) or ''
else
ret = args.formatting == 'raw' and entityId or formatEntityId(entityId)
Riga 186 ⟶ 279:
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
Riga 220 ⟶ 315:
-- È al plurale perché anche i qualifier possono avere più di un valore
-- (si ottiene inserendo due volte lo stesso qualifier)
local function formatQualifiers(claim, qualifierqualifierId, args, rawTable, retTable)
local formattedQualifiers = retTable or {}
 
if claim.qualifiers and claim.qualifiers[qualifierqualifierId] then
forlocal _,qualifiers q= in pairs(claim.qualifiers[qualifierqualifierId]) do
-- con args.nq seleziona solo l'n-esimo qualifier
local formattedQualifier = formatSnak(q, args)
if formattedQualifier ~= ''args.nq then
iflocal n = tonumber(args.pattern thennq)
qualifiers = (n and n <= #qualifiers) and { qualifiers[n] } or {}
formattedQualifier = formatFromPattern(formattedQualifier, args)
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
table.insert(formattedQualifiers, formattedQualifier)
end
end
Riga 245 ⟶ 354:
local function appendQualifiers(statement, text, args)
local formattedQualifiers = {}
local qualifiersqualifierIds = mw.text.split(args.showqualifiers, ',')
for _, qualifierqualifierId in ipairs(qualifiersqualifierIds) do
if statement.qualifiers[qualifierqualifierId] then
local formattedQualifier = formatQualifiers(statement, qualifierqualifierId, args)
table.insert(formattedQualifiers, formattedQualifier)
end
Riga 256 ⟶ 365:
end
return text
end
 
local function formatReferences(references, args)
local formattedReferences = {}
local refArgs = {}
local parameters = {
titolo = 'P1476', data = 'P577', url = 'P854', dataaccesso = 'P813',
editore = 'P123', urlarchivio = 'P1065', dataarchivio = 'P2960'
}
if references[1].snaks.P854 then
local snaks = references[1].snaks
for parameter, property in pairs(parameters) do
if snaks[property] then
refArgs[parameter] = formatSnak(snaks[property][1], args)
end
end
refArgs.titolo = refArgs.titolo or refArgs.url
if snaks.P407 then
local langs = {}
for _, value in ipairs(snaks.P407) do
local lang = formatSnak(value, { formatting = 'raw' })
table.insert(langs, mw.wikibase.getLabel(lang) or lang)
end
refArgs.lingua = table.concat(langs, ',')
end
if refArgs.urlarchivio then refArgs.urlmorto = 'sì' end
local formattedReference = mw.getCurrentFrame():extensionTag{
name = 'ref',
content = mCitation.cita_da_modulo('web', refArgs),
args = { name = references[1].hash }
}
table.insert(formattedReferences, formattedReference)
end
return table.concat(formattedReferences)
end
 
Riga 275 ⟶ 418:
local formattedStatements = {}
 
for i_, claim in pairsipairs(claims) do
local formattedStatement = formatStatement(claim, args)
if formattedStatement ~= '' then
local formattedReferences
if args.showreferences and claim.references then
formattedReferences = formatReferences(claim.references, args)
end
-- eventuale pattern
if args.pattern then
formattedStatement = formatFromPattern(formattedStatement, args, formattedReferences)
elseif formattedReferences then
formattedStatement = formattedStatement .. formattedReferences
end
if formattedStatement ~= '' then
table.insert(formattedStatements, formattedStatement)
end
table.insert(formattedStatements, formattedStatement)
end
end
Riga 289 ⟶ 440:
end
 
ifreturn ((args.list or args.orderedlist) thenand #formattedStatements > 1) and
table.insert formatList(formattedStatements, 1, args.listorderedlist and~= '<ul><li>'nil) or '<ol><li>');
table mw.text.insertlistToText(formattedStatements, args.list andseparator, '</li></ul>' or '</li></ol>'args.conjunction);
args.separator = '</li><li>'
args.conjunction = args.separator
end
 
return mw.text.listToText(formattedStatements, args.separator, args.conjunction)
end
 
Riga 303 ⟶ 449:
-------------------------------------------------------------------------------
 
-- RitornaRestituisce true se lo statement contiene il qualifier richiesto con un dato valore (o uno tra più valori separati da virgola)
local function hasQualifierValue(statement, argsqualifierId, qualifierValue)
local ret = false
for i_, qualifier in pairsipairs(statement.qualifiers[args.qualifierqualifierId]) do
local isItem = qualifier.snaktype == 'value' and
qualifier.datavalue.type == 'wikibase-entityid'
local qualifierValues = mw.text.split(qualifierValue, ',')
-- per le proprietà di tipo item il confronto è eseguito sull'id
for _, qualifierHas in ipairs(qualifierValues) do
if formatSnak(qualifier, isItem and { formatting = 'raw' } or {} ) == args.qualifiervalue then
-- per le proprietà di tipo item il confronto è eseguito sull'id
ret = true
if formatSnak(qualifier, isItem and { formatting = 'raw' } or {}) == qualifierHas then
break
ret = true
break
end
end
end
Riga 318 ⟶ 467:
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)
Riga 329 ⟶ 478:
end
 
-- RitornaRestituisce una tablesequence Lua contenente gli statement per la property richiesta,
-- oppureanche nilvuota se l'entity o la proprietà non esistono.esiste, o non ci sono valori che soddisfano i criteri
-- ("rank", "qualifier", "qualifiertype", "noqualifier", ...).
-- Gli statement ritornati sono eventualmente filtrati in base ai parametri:
-- Restituisce nil solo se la pagina non è collegata a un elemento Wikidata e non è indicato il from.
-- "rank", "qualifier", "qualifiertype" e "n"
local function getClaims(propertypropertyId, args)
local entityentityId, claims, filteredClaims
entityId = args.from or mw.wikibase.getEntityIdForCurrentPage()
-- get entity
if not entityId then
entity = mw.wikibase.getEntityObject(args.from)
if not entity then
return nil
end
 
-- il default rank è 'best'
if property and entity.claims and entity.claims[property] and
args.rank = args.rank or 'best'
#entity.claims[property] > 0 then
if args.rank == 'best' then
claims = entity.claims[property]
claims = mw.wikibase.getBestStatements(entityId, propertyId)
else
-- statements filtrati per rank
return nil
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 args.rank then
if args.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, args.rank)
end
claims = filteredClaims
Riga 365 ⟶ 515:
if args.qualifier then
filteredClaims = {}
for i_, claim in pairsipairs(claims) do
if claim.qualifiers and claim.qualifiers[args.qualifier] then
if args.qualifiervalue then
if hasQualifierValue(claim, args.qualifier, args.qualifiervalue) then
table.insert(filteredClaims, claim)
end
Riga 379 ⟶ 529:
end
 
-- statements filtrati per essere senza un qualifier
-- con args.qualifiertype=latest ritorna solo il più recente
if args.noqualifier 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[args.qualifier] then
for j_, qualifier in pairsipairs(claim.qualifiers[args.qualifier]) do
if qualifier.datavalue.type == 'time' then
if not latestTime or qualifier.datavalue.value.time > latestTime then
Riga 394 ⟶ 570:
end
end
claims = latest and { latest } or {}
end
 
-- con args.n ritornarestituisce solo l'n-esimo elemento
if args.n then
local n = tonumber(args.n)
claims = (n and n <= #claims) and { claims[n] } or {}
end
 
Riga 407 ⟶ 583:
 
-------------------------------------------------------------------------------
-- Funzioni esportate per altri APImoduli
-------------------------------------------------------------------------------
 
function p._getClaims(propertypropertyId, args)
return getClaims(propertypropertyId, args or {})
end
 
Riga 418 ⟶ 594:
end
 
function p._formatQualifiers(claim, qualifierqualifierId, args, rawTable, retTable)
return formatQualifiers(claim, qualifierqualifierId, args or {}, rawTable, retTable)
end
 
-- RitornaRestituisce 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 propertypropertyId, value, claims, ret
 
-- parametri posizionali
propertypropertyId = args[1] and string.upper(args[1]) or nil
if not propertypropertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
value = args[2]
-- fix uppercase
args.qualifier = args.qualifier and string.upper(args.qualifier) or nil
 
-- if parameter value is already set, use it
if value then
ret = formatUserValue(value, args)
if args.extlink then
elseif args.wd ~= 'no' then
value = formatExtLink(value)
claims = getClaims(propertyId, args)
end
returnret args.pattern= (claims and formatFromPattern#claims > 0) and formatStatements(valueclaims, args, rawTable) or value nil
end
-- default rank
args.rank = args.rank or 'best'
 
return ret
-- get claims
claims = getClaims(property, args)
 
return (claims and #claims > 0) and formatStatements(claims, args, rawTable) or nil
end
 
-- RitornaRestituisce 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 propertypropertyId, qualifierqualifierId, value, claims, ret
 
-- parametri posizionali
propertypropertyId = args[1] and string.upper(args[1]) or nil
if not propertypropertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
qualifierqualifierId = args[2] and string.upper(args[2]) or nil
if not qualifierqualifierId then
error(i18n.errors['qualifier-param-not-provided'], 2)
end
value = args[3]
 
-- if parameter value is already set, use it
if value then
returnret args.pattern= and formatFromPatternformatUserValue(value, args) or value
elseif args.wd ~= 'no' then
claims = getClaims(propertyId, args)
if claims and #claims > 0 then
local formattedQualifiers = {}
for _, claim in ipairs(claims) do
formattedQualifiers = formatQualifiers(claim, qualifierId, args, true, formattedQualifiers)
end
ret = #formattedQualifiers > 0 and
mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
end
 
return ret
-- default rank
args.rank = args.rank or 'best'
 
-- get claims
claims = getClaims(property, args)
if not claims or #claims == 0 then
return nil
end
 
local formattedQualifiers = {}
for _, claim in pairs(claims) do
formattedQualifiers = formatQualifiers(claim, qualifier, args, true, formattedQualifiers)
end
 
return #formattedQualifiers > 0 and
mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
 
-- RitornaRestituisce l'indice dello statement con il valore richiesto, o -1nil se non trovato.
function p._indexOf(args)
local ret, propertypropertyId, value, claims
 
-- parametri posizionali
propertypropertyId = args[1] and string.upper(args[1]) or nil
if not propertypropertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
Riga 506 ⟶ 669:
end
 
claims = getClaims(propertyId, args)
-- default rank
if claims and #claims > 0 then
args.rank = args.rank or 'best'
args.formatting = 'raw'
 
-- for geti, claim in ipairs(claims) do
if formatStatement(claim, args) == value then
claims = getClaims(property, args)
ret = i
if not claims or #claims == 0 then
break
return -1
end
 
args.formatting = 'raw'
for i, claim in pairs(claims) do
if formatStatement(claim, args) == value then
ret = i
break
end
end
 
return ret or -1
end
 
-- RitornaRestituisce il numero di statement di una proprietà di Wikidata.
function p._N(args)
local entitypropertyId, property, countclaims
 
-- parametri posizionali
propertypropertyId = args[1] and string.upper(args[1]) or nil
if not propertypropertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
-- get claims
claims = getClaims(propertyId, args)
 
return claims and #claims or 0
entity = mw.wikibase.getEntityObject(args.from)
if entity and entity.claims and entity.claims[property] then
count = #entity.claims[property]
end
 
return count or 0
end
 
-- RitornaRestituisce true se la proprietàpropriertà P31 (instance of)specificata ha come valore almeno uno tra gli entityId specificati
-- almeno uno tra gli entityId passati come argomento.
function p._instanceOf(args)
function p._propertyHasEntity(propertyId, args)
local statements = p._getProperty( { 'P31', from = args.from, formatting = 'raw' }, true)
local statements = p._getProperty({ propertyId, from = args.from, formatting = 'raw' }, true)
if statements then
for _, statement in ipairs(statements) do
Riga 552 ⟶ 707:
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
Riga 557 ⟶ 744:
end
 
return false, args.loadedEntities
end
 
-- Restituisce true se la proprietà P31 (instance of) ha come valore almeno uno tra gli entityId specificati
-- Ritorna l'etichetta di un item o di una proprietà Wikidata.
function p._getLabel_instanceOf(args)
return p._propertyHasEntity('P31', args)
-- parametri posizionali
end
local entityId = args[1] and string.upper(args[1]) or nil
 
if not entityId then
-- Restituisce true se la proprietà P279 (subclass of) ha come valore almeno uno tra gli entityId specificati
error(i18n.errors['entityid-param-not-provided'], 2)
function p._subclassOf(args)
return p._propertyHasEntity('P279', args)
end
 
-- Restituisce l'etichetta di un item o di una proprietà Wikidata.
function p._getLabel(args)
local entityId = args[1] and string.upper(args[1])
local ret
if args[2] then
ret = mw.wikibase.getLabelByLang(entityId, args[2])
else
ret = mw.wikibase.getLabel(entityId)
end
return ret
end
 
-- Restituisce la descrizione di un item o di una proprietà Wikidata.
return mw.wikibase.label(entityId)
function p._getDescription(args)
local entityId = args[1] and string.upper(args[1])
local ret = mw.wikibase.getDescription(entityId)
return ret
end
 
-- RitornaRestituisce il titolo della pagina collegata a un dato item Wikidata.
function p._getLink(args)
-- parametri posizionali
local entityId = args[1] and string.upper(args[1]) or nil
if not entityId then
error(i18n.errors['entityid-param-not-provided'], 2)
Riga 582 ⟶ 787:
end
 
-- RitornaRestituisce il datatype di una proprietà Wikidata.
function p._getDatatype(args)
local ret, propertypropertyId, entity, datatype
 
-- parametri posizionali
propertypropertyId = args[1] and string.upper(args[1]) or nil
if not propertypropertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
 
entity = mw.wikibase.getEntityObjectgetEntity(propertypropertyId)
if not entity then
error(i18n.errors['entity-not-found'], 2)
end
 
datatypeif =not i18n.datatypes[entity.datatype] then
if datatype == 'commonsMedia' then
ret = 'file multimediale su Commons'
elseif datatype == 'globe-coordinate' then
ret = 'coordinate geografiche'
elseif datatype == 'monolingualtext' then
ret = 'testo monolingua'
elseif datatype == 'quantity' then
ret = 'quantità'
elseif datatype == 'string' then
ret = 'stringa'
elseif datatype == 'time' then
ret = 'data e ora'
elseif datatype == 'url' then
ret = 'URL'
elseif datatype == 'external-id' then
ret = 'identificatore esterno'
elseif datatype == 'wikibase-item' then
ret = 'elemento'
elseif datatype == 'wikibase-property' then
ret = 'proprietà'
elseif datatype == 'math' then
ret = 'espressione matematica'
else
error(i18n.errors['unknown-datavalue-type'], 2)
end
 
return reti18n.datatypes[entity.datatype]
end
 
-- RitornaRestituisce l'ID dell'item Wikidata collegato alla pagina corrente. o a una pagina specificata
-- (nota: segue i redirect fermandosi al primo redirect collegato a un elemento)
function p._getId()
function p._getId(args)
local entity = mw.wikibase.getEntityObject()
local ret
return entity and entity.id or nil
if args[1] then
local title = mw.title.new(args[1])
while title do
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
 
-------------------------------------------------------------------------------
-- Entry-point per {{Wikidata}}
-- Funzioni esportate per i template
-------------------------------------------------------------------------------
 
-- Funzione per il template {{Wikidata}}
function p.getProperty(frame)
return select(2, xpcall(function()
return p._getProperty(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataQ}}
function p.getQualifier(frame)
return select(2, xpcall(function()
return p._getQualifier(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataIdx}}
function p.indexOf(frame)
return select(2, xpcall(function()
return p._indexOf(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataN}}
function p.N(frame)
return select(2, xpcall(function()
return p._N(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataLabel}}
function p.getLabel(frame)
return select(2, xpcall(function()
return p._getLabel(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataLinkWikidataDescription}}
function p.getDescription(frame)
return select(2, xpcall(function()
return p._getDescription(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Funzione per il template {{WikidataLink}}
function p.getLink(frame)
return select(2, xpcall(function()
return p._getLink(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataIstanza}}
function p.instanceOf(frame)
return select(2, xpcall(function()
return p._instanceOf(getArgs(frame, { parentOnly = true })) and 1 or 0''
end, errhandler))
end
 
-- Entry-pointFunzione per il template {{WikidataTipo}}
function p.getDatatype(frame)
return select(2, xpcall(function()
return p._getDatatype(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
 
-- Entry-pointFunzione 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}}
function p.checkProperty(frame)
return select(2, xpcall(function()
return p._N(getArgs(frame, { parentOnly = true })) > 0 and 1 or ''
end, errhandler))
end
 
-- Funzione per il template {{WikidataClasse}}
function p.propertyHasEntity(frame)
local args = getArgs(frame, { parentOnly = true })
local propertyId = args[1]
args.recursion = tonumber(args.prof) or 8
return select(2, xpcall(function()
return p._propertyHasEntity(propertyId, args) and 1 or ''
end, errhandler))
end