Modulo:Wikidata: differenze tra le versioni

m
una versione importata
(p.isRedirect)
m (una versione importata)
Riga 1: Riga 1:
--script that retrieves basic data stored in Wikidata, for the datamodel, see https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
--[[
* Modulo per implementare le funzionalità dei template:
* {{Wikidata}}, {{WikidataQ}}, {{WikidataIdx}}, {{WikidataN}}, {{WikidataLabel}}, {{WikidataDescription}}
* {{WikidataLink}}, {{WikidataId}}, {{WikidataTipo}} e {{WikidataIstanza}}.
* Permette di accedere a Wikidata in modo più avanzato rispetto a {{#property}}.


local p = {}
* Per la maggior parte riscritto e ampliato a partire dalla versione iniziale a:
* http://test2.wikipedia.org/w/index.php?title=Module:Wikidata&oldid=52322
]]


local linguistic = require('Module:Linguistic')
-- =============================================================================
--local formatDate = require('Module:Complex date') only loaded when needed to save memory in large pages like Wikidata:List of properties/all
-- Non utilizzare mai mw.wikibase.getEntity, per esempio un solo utilizzo di
local fb = require('Module:Fallback')
-- mw.wikibase.getEntity('Q183') fa aumentare di 7 MB l'utilizzo di memoria
local i18nmessages = mw.loadData('Module:i18n/wikidata')
-- per Lua ed è molto lenta se ripetuta (unico utilizzo in getDatatype,
-- solo per proprietà, non essendoci alternative).
-- =============================================================================


-- Wiki-specific parameters
require('Module:No globals')
local defaultlang = mw.getCurrentFrame():preprocess("{{int:lang}}")
local defaultlink = 'wikidata'


local function i18n(str)
local getArgs = require('Module:Arguments').getArgs
local message = i18nmessages[str]
local mConvert = require('Module:Conversione')
if type(message) == 'string' then
local mLanguages = require('Module:Linguaggi')
return message
end
return fb._langSwitch(message, defaultlang) .. ''
end


local function formatError( key, text )
-- Categoria per le pagine con errori
return error(i18n(key) .. (text or ''))
local errorCategory = '[[Categoria:Voci con errori del modulo Wikidata]]'
end


local function addTrackingCat(prop, cat)
-- Messaggi
if not prop and not cat then
local i18n = {
return error("no property provided")
errors = {
end
['entityid-param-not-provided'] = "Parametro ''entityid'' non fornito",
if not cat then
['property-param-not-provided'] = "Parametro ''property'' non fornito",
cat = i18nmessages.trackingcat .. '/' .. string.upper(prop)
['qualifier-param-not-provided'] = "Parametro ''qualifier'' non fornito",
end
['value-param-not-provided'] = "Parametro ''valore'' da ricercare non fornito",
return '[[Category:' .. cat .. ']]'
['entity-not-found'] = 'Entità non trovata',
end
['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 function removeBlanks(args)
local p = {}
for i, j in pairs(args) do -- does not work ??
if (j == '') or (j == '-') then args[i] = nil end
end
return args
end


local function formatTheUnknown() -- voir si on peut accorder/adapter l'usage de "inconnu"
-------------------------------------------------------------------------------
return i18n('somevalue')
--                            Formatters
end
-------------------------------------------------------------------------------


local function isSpecial(snak)
local function errhandler(msg)
return snak.snaktype ~= 'value'
local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
return string.format('<span class="error">%s</span>%s', msg, cat)
end
end


local function sameValue(snak, target)
local function formatList(values, ordered)
return not isSpecial(snak) and p.getRawvalue(snak) == target
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
end


local function showLang(statement, str) -- TODO (not yet in proper format)
local function formatExtLink(url)
--adds a lang indication at the start of the string, based on data in statement
local protocols = { ftp = true, http = true, https = true }
local mainsnak = statement.mainsnak
if isSpecial(mainsnak) then
return str
end


local langlist = {}
local success, uri = pcall(function() return mw.uri.new(url) end)
if mainsnak.datavalue.type == 'monolingualtext' then
if success and uri.protocol and protocols[uri.protocol] then
langlist = {mainsnak.datavalue.value.language}
local dest = tostring(uri)
elseif statement.qualifiers and statement.qualifiers.P407 then
return string.format('<span style="word-break: break-all;">[%s %s]</span>', dest, dest:gsub(uri.protocol .. '://', ''))
local convertlangcode = mw.loadData('Module:Dictionary/lang codes')
for i, j in pairs( statement.qualifiers.P407 ) do
if not isSpecial(j) then
local val = convertlangcode[j.datavalue.value['numeric-id']]
table.insert(langlist, val)
end
end
end
if #langlist == 0 then
return str
else
else
return '(' .. table.concat(langlist) .. ')' .. str
return url
end
end
end
end


function p.getEntity( val )
local function formatEntityId(entityId)
if type(val) == 'table' then
local label = mw.wikibase.getLabel(entityId)
return val
local siteLink = mw.wikibase.getSitelink(entityId)
local ret
if entityId == mw.wikibase.getEntityIdForCurrentPage() then
ret = siteLink
elseif siteLink and label then
ret = mw.getContentLanguage():ucfirst(label) == siteLink and
  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
ret = ''
end
end
return mw.wikibase.getEntityObject(val)
return ret
end
end


-- DATE FUNCTIONS
local function formatMonolingualtext(value, args)
local function splitTimestamp(timestamp, calendar)
local ret = ''
local pattern = "(%W)(%d+)%-(%d+)%-(%d+)"
if not args.includelang or args.includelang:match('%f[a-z]' .. value.language .. '%f[^a-z]') then
local era, year, month, day = timestamp:match(pattern)
if not args.excludelang or not args.excludelang:match('%f[a-z]' .. value.language .. '%f[^a-z]') then
 
ret = value.text
if calendar == 'julian' then
if args.showlang then
--todo  year, month, day = formatdate.gregorianToJulian( era .. year, month, day )
ret = mLanguages.lingue({ value.language }) .. '&nbsp;' .. ret
end
end
end
end
 
return ret
return {day = day, month = month, year = year, era = era, timestamp = timestamp, type = 'dateobject'}
end
end


local function rangeObject(begin, ending)
local function formatTimeWithPrecision(time, precision)
local timestamp
local months = {
if begin then
'gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno',
timestamp = begin.timestamp
'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'
elseif ending then
}
timestamp = ending.timestamp
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
end
return {begin = begin, ending = ending, timestamp = timestamp, type = 'rangeobject'}
if precision >= 9 and precision <= 11 then
ret = ret .. (time:sub(1, 1) == '-' and ' a.C.' or '')
end
 
return ret
end
end


local function dateObject(orig, params) -- transforme un snak en un nouvel objet utilisable par Module:Date complexe
local function formatTime(value, args)
if not params then
local ret
params = {}
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
end


local newobj = splitTimestamp(orig.time, orig.calendar) -- initalise l'object en mettant la valeur des dates
return ret or ''
 
newobj.precision = params.precision or orig.precision
newobj.type = 'dateobject'
return newobj
end
end


local function formatDatepoint(obj, params) -- TO IMPROVE
local function formatGlobecoordinate(value, args)
if not obj then
local ret
return nil
if args.coord == 'latitude' then
end
ret = value.latitude
local formatDate = require('Module:Complex date')
elseif args.coord == 'longitude' then
local lang = params.lang or defaultlang
ret = value.longitude
local precision = math.min(obj.precision, params.precision or 15) -- if we don't want to show the value to its full detail
elseif args.coord == 'globe' then
if precision >= 11 then
ret = value.globe
return formatDate.complex_date{args={date1 = obj.year .. '-' .. obj.month .. '-' .. obj.day, lang= lang}}
else
elseif precision == 10 then
ret = string.format('%s, %s', value.latitude, value.longitude)
return formatDate.complex_date{args={date1 = obj.year .. '-' .. obj.month, lang= lang}}
elseif precision == 9 then
return formatDate.complex_date{args={date1 = tostring(obj.year), lang= lang}}
elseif precision == 8 then
return formatDate.complex_date{args={date1 = string.sub(tostring(obj.year), 1, 3) .. '0', lang = lang, precision = 'decade'}}
elseif precision == 7 then
return formatDate.complex_date{args={date1 = string.sub(tostring(obj.year + 100), 1, 2), lang = lang, precision = 'century'}}
end
end
return nil
return ret
end
end


local function formatDaterange(obj, params) --TODO
local function formatFromPattern(str, args)
local begin = formatDatepoint(obj.begin, params) or ''
local pattern = args.pattern
local ending = formatDatepoint(obj.ending, params) or ''
pattern = mw.ustring.gsub(pattern, '\\{', '{')
return begin .. '-' .. ending
pattern = mw.ustring.gsub(pattern, '\\}', '}')
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
end
end


local function objectToText(obj, params)
local function formatUserValue(value, args)
if obj.type == 'dateobject' then
if args.extlink then
return formatDatepoint(obj, params)
value = formatExtLink(value)
elseif obj.type == 'rangeobject' then
return formatDaterange(obj, params)
end
end
return nil
return args.pattern and formatFromPattern(value, args) or value
end
end


local function tableToText(values, params) -- takes a list of already formatted values and make them a text
local function getEntityIdFromValue(value)
if not values or #values == 0 then
local prefix = ''
return nil
if value['entity-type'] == 'item' then
prefix = 'Q'
elseif value['entity-type'] == 'property' then
prefix = 'P'
else
error(i18n.errors['unknown-entity-type'])
end
end
return linguistic.conj(values, params.lang or defaultlang, params.conjtype)--linguistic.conj( values, params.lang, params.conjtype )
return prefix .. value['numeric-id']
end
end


function p.getDate(obj)
local function formatUnitSymbol(entityId, args)
--[[
local ret
returns an object containing a timestamp for easy sorting, and other data
for _, lang in ipairs({ 'mul', 'it', 'en' }) do
possible types of object:
ret = p._getProperty({ 'P5061', includelang = lang, from = entityId })
dateobject
if ret and ret ~= '' then
{timestamp = string, year = number, month = number, day = number, calendar = string}
break
rangeobject
else
{timestamp = string, begin = dateobject, ending = dateobject}
ret = nil
]]--
end
if not obj then
return nil
end
end
if type(obj) == 'string' then
local space = ret == '°' and '' or ' '
obj = p.getEntity(obj)
if ret and args.showunitlink then
local link = mw.wikibase.getSitelink(entityId)
if link then
ret = string.format('[[%s|%s]]', link, ret)
end
end
end
return ret and (space .. ret) or ''
end


-- if obj is a statement with date, get it
-- http://lua-users.org/wiki/SimpleRound
if obj.mainsnak and not isSpecial(obj.mainsnak) and obj.mainsnak.datatype == 'time' then
local function round(num, idp)
return dateObject(obj.mainsnak.datavalue.value)
local mult = 10 ^ (idp or 0)
end
return math.floor(num * mult + 0.5) / mult
end


-- else preload relevant data
local qualifs = obj.qualifiers -- when obj is a statement, look in qualifiers
local claims = obj.claims -- when obj is an item, look in claims


local pointprop = {'P585', 'P571'} -- dates corresponding to a punctual fact
local function formatQuantity(value, args)
local beginprop = {'P580', 'P569'} -- start date, birth date == start of a date range
local ret = tonumber(value.amount)
local endingprop = {'P582', 'P570'}


local function getval(prop)
if (args.unit or args.showunit) and value.unit ~= '1' then
local val
local unitId = mw.ustring.match(value.unit, 'Q%d+')
if claims and claims[prop] and not isSpecial(claims[prop][1].mainsnak) then
if args.unit then
val = claims[prop][1].mainsnak.datavalue.value
local opts = {
elseif qualifs and qualifs[prop] and not isSpecial(qualifs[prop][1]) then
showunit = args.showunit,
val = qualifs[prop][1].datavalue.value
showunitlink = args.showunitlink,
end
formatnum = args.formatnum,
if val then
rounding = args.rounding
return dateObject(val)
}
end
ret = mConvert._main(ret, unitId, args.unit, opts)
return nil
else
end
-- se è richiesto solo il simbolo dell'unità
 
-- senza la conversione lo ottiene da P5061
for i, prop in pairs(pointprop) do
ret = args.rounding and round(ret, args.rounding) or ret
local val = getval(prop)
if args.formatnum then
if val then return val end
ret = mw.language.getContentLanguage():formatNum(ret)
end
end
--if no date has not been found, look for startdate or enddate
ret = ret .. formatUnitSymbol(unitId, args)
local begin, ending
for i, prop in pairs(beginprop) do
begin = getval(prop)
if begin then
break
end
end
for i, prop in pairs(endingprop) do
ending = getval(prop)
if ending then
break
end
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
end
if begin or ending then
return rangeObject(begin, ending)
end
return nil
end


function p.getFormattedDate(statement, params)
return ret
local datetable = p.getDate(statement)
if not datetable then
return nil
end
return objectToText(datetable, params)
end
end


local function hasTargetValue(claim, target)
local function formatDatavalue(datavalue, snakdatatype, args)
if target == nil then
local ret
return true
end
return sameValue(claim.mainsnak, target)
end


local function hasRank(claim, target)
if datavalue.type == 'wikibase-entityid' then
if target == 'valid' then
local entityId = getEntityIdFromValue(datavalue.value)
return hasRank(claim, 'preferred') or hasRank(claim, 'normal')
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, args)
elseif datavalue.type == 'time' then
if args.formatting == 'raw' then
ret = datavalue.value.time
else
ret = formatTime(datavalue.value, args)
end
elseif datavalue.type == 'globecoordinate' then
ret = formatGlobecoordinate(datavalue.value, args)
elseif datavalue.type == 'quantity' then
ret = formatQuantity(datavalue.value, args)
else
else
return claim.rank == target
error(i18n.errors['unknown-datavalue-type'])
end
end
return ret
end
end


local function bestRanked(claims)
local function formatSnak(snak, args)
if not claims then
if snak.snaktype == 'somevalue' then
return nil
return i18n['somevalue']
end
elseif snak.snaktype == 'novalue' then
local preferred, normal = {}, {}
return i18n['novalue']
for _, j in ipairs(claims) do
elseif snak.snaktype == 'value' then
if j.rank == 'preferred' then
return formatDatavalue(snak.datavalue, snak.datatype, args)
table.insert(preferred, j)
elseif j.rank == 'normal' then
table.insert(normal, j)
end
end
if #preferred > 0 then
return preferred
else
else
return normal
error(i18n.errors['unknown-snak-type'])
end
end
end
end


local function hasQualifier(claim, qualifier, qualifiervalues)
-- È al plurale perché anche i qualifier possono avere più di un valore
if not qualifier then -- si aucun qualificatif est demandé, ça passe
-- (si ottiene inserendo due volte lo stesso qualifier)
return true
local function formatQualifiers(claim, qualifierId, args, rawTable, retTable)
end
local formattedQualifiers = retTable or {}


qualifier = string.upper(qualifier)
if claim.qualifiers and claim.qualifiers[qualifierId] then
if not claim.qualifiers or not claim.qualifiers[qualifier] then
local qualifiers = claim.qualifiers[qualifierId]
return false
-- con args.nq seleziona solo l'n-esimo qualifier
end
if args.nq then
 
local n = tonumber(args.nq)
if type(qualifiervalues) == 'string' then
qualifiers = (n and n <= #qualifiers) and { qualifiers[n] } or {}
qualifiervalues = mw.text.split(qualifiervalues, ',')
end
 
if (not qualifiervalues) or (qualifiervalues == {}) then
return true -- si aucune valeur spécifique n'est exigée
end
 
for _, j in ipairs(claim.qualifiers[qualifier]) do
for _, l in ipairs(qualifiervalues) do
if p.sameValue(j, l) then
return true
end
end
end
end
-- qualifier filtrati per snaktype, default "value"
return false
args.snaktype = args.snaktype or 'value'
end
for _, qualifier in ipairs(qualifiers) do
 
if qualifier.snaktype == args.snaktype or args.snaktype == 'all' then
local function hasSource(statement, source, sourceproperty)
local formattedQualifier = formatSnak(qualifier, args)
if not statement.references then
if formattedQualifier ~= '' then
return false
if args.pattern then
end
formattedQualifier = formatFromPattern(formattedQualifier, args)
sourceproperty = string.upper(sourceproperty or 'P248')
if formattedQualifier ~= '' then
local sourcevalue = string.upper(source or '')
table.insert(formattedQualifiers, formattedQualifier)
for _, ref in ipairs(statement.references) do
for prop, content in pairs(ref.snaks) do
if prop == sourceproperty then
if sourcevalue == '' then
return true
else
for _, k in ipairs(content) do
if sameValue(k, source) then
return true
end
end
else
table.insert(formattedQualifiers, formattedQualifier)
end
end
end
end
Riga 320: Riga 342:
end
end
end
end
return false
end


local function hasDate(statement)
if rawTable then
if not statement.qualifiers then
return formattedQualifiers
return false
end
local dateprops = {'P580', 'P585', 'P582'}
for i, prop in pairs(dateprops) do
if statement.qualifiers[prop] then
return true
end
end
end
return false
end


local function isInLanguage(snak, lang) -- ne fonctionne que pour les monolingualtext / étendre aux autres types en utilisant les qualifiers ?
return #formattedQualifiers > 0 and
return not isSpecial(snak) and snak.datavalue.type == 'monolingualtext' and snak.datavalue.value.language == lang
  mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
end


local function numval(claims, numval) -- retourn les numval premières valeurs de la table claims
local function appendQualifiers(statement, text, args)
local numval = tonumber(numval) or 0 -- raise an error if numval is not a positive integer ?
local formattedQualifiers = {}
if #claims <= numval then
local qualifierIds = mw.text.split(args.showqualifiers, ',')
return claims
for _, qualifierId in ipairs(qualifierIds) do
if statement.qualifiers[qualifierId] then
local formattedQualifier = formatQualifiers(statement, qualifierId, args)
table.insert(formattedQualifiers, formattedQualifier)
end
end
end
local newclaims = {}
if #formattedQualifiers > 0 then
while #newclaims < numval do
text = string.format('%s (%s)', text, mw.text.listToText(formattedQualifiers, ', ', ', '))
table.insert(newclaims, claims[#newclaims + 1])
end
end
return newclaims
return text
end
end


local function wikipediaLink(entity, lang)
local function formatStatement(statement, args)
local link
if not statement.type or statement.type ~= 'statement' then
if type(entity) == 'table' then
error(i18n.errors['unknown-claim-type'])
link = entity:getSitelink(lang .. 'wiki')
else
link = mw.wikibase.getSitelink(entity, lang .. 'wiki')
end
end
if link then
return ':' .. lang .. ':' .. link
local ret = formatSnak(statement.mainsnak, args)
-- eventuale showqualifiers
if args.showqualifiers and statement.qualifiers then
ret = appendQualifiers(statement, ret, args)
end
end
return nil
 
return ret
end
end


local function getLink(entity, typelink, lang)
local function formatStatements(claims, args, rawTable)
if typelink == 'wikidata' then
local formattedStatements = {}
if type(entity) == 'table' then
 
if entity.type == 'property' then
for _, claim in ipairs(claims) do
return 'd:P:' .. entity.id
local formattedStatement = formatStatement(claim, args)
elseif entity.type == 'lexeme' then
if formattedStatement ~= '' then
return 'd:L:' .. entity.id
-- eventuale pattern
if args.pattern then
formattedStatement = formatFromPattern(formattedStatement, args)
if formattedStatement ~= '' then
table.insert(formattedStatements, formattedStatement)
end
else
else
return 'd:' .. entity.id
table.insert(formattedStatements, formattedStatement)
end
else
if string.sub(entity, 1, 1) == 'P' then
return 'd:P:' .. entity
elseif string.sub(entity, 1, 1) == 'L' then
return 'd:L:' .. entity
else
return 'd:' .. entity
end
end
end
end
end
if rawTable then
return formattedStatements
end
return ((args.list or args.orderedlist) and #formattedStatements > 1) and
  formatList(formattedStatements, args.orderedlist ~= nil) or
  mw.text.listToText(formattedStatements, args.separator, args.conjunction)
end


elseif typelink == 'wikipedia' then
-------------------------------------------------------------------------------
return wikipediaLink(entity, lang or defaultlang)
--                      Lettura e selezione statement
-------------------------------------------------------------------------------


elseif typelink == 'anywikipedia' then
-- Restituisce true se lo statement contiene il qualifier richiesto con un dato valore (o uno tra più valori separati da virgola)
for _, lg in ipairs(fb.fblist(lang or defaultlang, true)) do
local function hasQualifierValue(statement, qualifierId, qualifierValue)
local link = wikipediaLink(entity, lg)
local ret = false
if link then
for _, qualifier in ipairs(statement.qualifiers[qualifierId]) do
return link
local isItem = qualifier.snaktype == 'value' and
  qualifier.datavalue.type == 'wikibase-entityid'
local qualifierValues = mw.text.split(qualifierValue, ',')
for _, qualifierHas in ipairs(qualifierValues) do
-- per le proprietà di tipo item il confronto è eseguito sull'id
if formatSnak(qualifier, isItem and { formatting = 'raw' } or {}) == qualifierHas then
ret = true
break
end
end
end
end
end
end
return nil
return ret
end
 
function p.comparedate(a, b) -- returns true if a is earlier than B or if a has a date but not b
if a and b then
return a.timestamp < b.timestamp
elseif a then
return true
end
return false
end
end


function p.chronosort(objs, inverted)
-- Restituisce i claim con il rank richiesto
table.sort(objs, function(a, b)
local function filterRankValue(claims, rank)
local timeA = p.getDate(a)
local ret = {}
local timeB = p.getDate(b)
for _, claim in ipairs(claims) do
if inverted then
if claim.rank == rank then
return p.comparedate(timeB, timeA)
table.insert(ret, claim)
else
return p.comparedate(timeA, timeB)
end
end
end)
return objs
end
function p.sortclaims(claims, sorttype)
if type(sorttype) == 'function' then
table.sort(claims, sorttype)
elseif sorttype == 'chronological' then
return p.chronosort(claims)
elseif sorttype == 'inverted' then
return p.chronosort(claims, true)
end
end
return claims
return ret
end
end


function p.getRawvalue(snak)
-- Restituisce una sequence Lua contenente gli statement per la property richiesta,
return p.getDatavalue(snak, { displayformat = 'raw' })
-- anche vuota se la proprietà non esiste, o non ci sono valori che soddisfano i criteri
end
-- ("rank", "qualifier", "qualifiertype", "noqualifier", ...).
 
-- Restituisce nil solo se la pagina non è collegata a un elemento Wikidata e non è indicato il from.
function p.showentity(entity, lang)
local function getClaims(propertyId, args)
if not entity then
local entityId, claims, filteredClaims
entityId = args.from or mw.wikibase.getEntityIdForCurrentPage()
if not entityId then
return nil
return nil
end
end
local label, link, id = p._getLabel(entity, lang), getLink(entity, 'wikidata')
if type(entity) == 'table' then
-- il default rank è 'best'
id = entity.id
args.rank = args.rank or 'best'
if args.rank == 'best' then
claims = mw.wikibase.getBestStatements(entityId, propertyId)
else
else
id = entity
-- statements filtrati per rank
claims = mw.wikibase.getAllStatements(entityId, propertyId)
claims = filterRankValue(claims, args.rank)
end
end
return '[[' .. link .. '|' .. label .. ']] <small>(' .. id .. ')</small>'
end


function p.getDatavalue(snak, params)
-- statements filtrati per snaktype, default "value"
if isSpecial(snak) then
args.snaktype = args.snaktype or 'value'
return nil
if args.snaktype and args.snaktype ~= 'all' then
filteredClaims = {}
for _, claim in ipairs(claims) do
if claim.mainsnak.snaktype == args.snaktype then
table.insert(filteredClaims, claim)
end
end
claims = filteredClaims
end
end


if not params then
-- statements filtrati per qualifier
params = {}
if args.qualifier then
end
filteredClaims = {}
 
for _, claim in ipairs(claims) do
local displayformat = params.displayformat
if claim.qualifiers and claim.qualifiers[args.qualifier] then
local valuetype = snak.datavalue.type
if args.qualifiervalue then
local value = snak.datavalue.value
if hasQualifierValue(claim, args.qualifier, args.qualifiervalue) then
 
table.insert(filteredClaims, claim)
if valuetype == 'wikibase-entityid' then
end
if type(displayformat) == 'function' then
else
return displayformat(snak, params)
table.insert(filteredClaims, claim)
end
local id = snak.datavalue.value.id
if displayformat == 'raw' then
return id
elseif displayformat == 'wikidatastyle' then
return p.showentity(id, params.lang)
else
return p.formatEntity(id, params)
end
 
elseif valuetype == 'string' then
local showntext = params.showntext
if displayformat == 'weblink' then
if showntext then
return '[' .. value .. ' ' .. showntext .. ']'
else
return value
end
end
if ({['math'] = 1, ['musical-notation'] = 1})[snak.datatype] == 1 and displayformat ~= 'raw' then
value = mw.wikibase.formatValue(snak)
else
if params.urlpattern then
showntext = mw.text.nowiki(showntext or value)
value = mw.ustring.gsub(value, '%%', '%%%%') -- escape '%'
value = '[' .. mw.ustring.gsub(mw.ustring.gsub(params.urlpattern, '$1', value), ' ', '%%20') .. ' ' .. showntext .. ']'
elseif params.pattern then
local pattern = mw.ustring.gsub(params.pattern, '%%', '%%%%')
value = mw.ustring.gsub(value, '%%', '%%%%')
value = mw.ustring.gsub(pattern, '$1', value)
else
if displayformat ~= 'raw' then
value = mw.text.nowiki(value)
end
end
end
end
end
end
return value
claims = filteredClaims
end


elseif valuetype == 'time' then -- format example: +00000001809-02-12T00:00:00Z
-- statements filtrati per essere senza un qualifier
if displayformat == 'raw' then
if args.noqualifier then
return value.time
filteredClaims = {}
else
for _, claim in ipairs(claims) do
return objectToText(dateObject(value), params)
if not (claim.qualifiers and claim.qualifiers[args.noqualifier]) then
table.insert(filteredClaims, claim)
end
end
end
claims = filteredClaims
end


elseif valuetype == 'globecoordinate' then
-- statements filtrati per non avere un certo valore a un certo qualifier opzionale
-- retourne une table avec clés latitude, longitude, précision et globe à formater par un autre module (à changer ?)
if args.qualifieroptnovalue and args.qualifiervalue then
if displayformat == 'latitude' then
filteredClaims = {}
return value.latitude
for _, claim in ipairs(claims) do
elseif displayformat == 'longitude' then
if claim.qualifiers and claim.qualifiers[args.qualifieroptnovalue] then
return value.longitude
if not hasQualifierValue(claim, args.qualifieroptnovalue, args.qualifiervalue) then
elseif displayformat == 'qualifier' then
table.insert(filteredClaims, claim)
local coord = require 'Module:Coordinates'
end
value.globe = mw.loadData('Module:Wikidata/Globes')[value.globe]
else
value.precision = nil
table.insert(filteredClaims, claim)
return coord._coord(value)
else
value.globe = mw.loadData('Module:Wikidata/Globes')[value.globe] -- transforme l'ID du globe en nom anglais utilisable par geohack
return value -- note : les coordonnées Wikidata peuvent être utilisée depuis Module:Coordinates. Faut-il aussi autoriser à appeler Module:Coordiantes ici ?
end
 
elseif valuetype == 'quantity' then -- todo : gérer les paramètre précision
if displayformat == 'raw' then
return tonumber(value.amount)
else
local formatNum = require 'Module:Formatnum'
local number = formatNum.formatNum(value.amount, params.lang)
local unit = mw.ustring.match(value.unit, '(Q%d+)')
if unit then
number = number .. '&nbsp;' .. p.formatEntity(unit, params)
end
end
return number
end
end
elseif valuetype == 'monolingualtext' then
claims = filteredClaims
return '<span lang="' .. value.language .. '">' .. value.text .. '</span>'
else
return formatError( 'unknown-datavalue-type', valuetype )
end
end
end


local function getMultipleClaims(args)
-- con args.qualifiertype=latest restituisce solo il più recente
local newargs = args
if args.qualifier and args.qualifiertype == 'latest' then
local claims = {}
local latest, latestTime
for i, j in pairs(args.property) do
for _, claim in ipairs(claims) do
newargs.property = j
if claim.qualifiers and claim.qualifiers[args.qualifier] then
local newclaims = p.getClaims(args)
for _, qualifier in ipairs(claim.qualifiers[args.qualifier]) do
if newclaims then
if qualifier.datavalue.type == 'time' then
for k, l in pairs(newclaims) do
if not latestTime or qualifier.datavalue.value.time > latestTime then
table.insert(claims, l)
latest = claim
latestTime = qualifier.datavalue.value.time
end
end
end
end
end
end
end
end
claims = latest and { latest } or {}
return claims
end
 
function p.getClaims( args ) -- returns a table of the claims matching some conditions given in args
args = removeBlanks(args)
if not args.property then
return formatError( 'property-param-not-provided' )
end
if type(args.property) == 'table' then
return getMultipleClaims(args)
end
--Get entity
if args.item then -- synonyms
args.entity = args.item
end
local property = string.upper(args.property)
local allClaims
local entity = args.entity
if type(entity) == 'table' then
allClaims = (entity and entity.claims and entity.claims[property]) or {}
else
allClaims = mw.wikibase.getAllStatements(entity, property)
end
if #allClaims == 0 then
return nil
end
end


if not args.rank then
-- con args.n restituisce solo l'n-esimo elemento
args.rank = 'best'
if args.n then
end
local n = tonumber(args.n)
local claims = {}
claims = (n and n <= #claims) and { claims[n] } or {}
for _, statement in ipairs(allClaims) do
if
(
not args.excludespecial
or
not (isSpecial(statement.mainsnak))
)
and
(
not args.targetvalue
or
hasTargetValue(statement, args.targetvalue)
)
and
(
not args.qualifier
or
hasQualifier(statement, args.qualifier, args.qualifiervalues or args.qualifiervalue)
)
and
(
not args.withsource or args.withsource == '-'
or
hasSource(statement, args.withsource, args.sourceproperty)
)
and
(
not args.isinlanguage
or
isInLanguage(statement.mainsnak, args.isinlanguage)
)
and
(
args.rank == 'best' -- rank == best est traité à a fin
or
hasRank(statement, args.rank)
)
then
table.insert(claims, statement)
end
end
if #claims == 0 then
return nil
end
if args.rank == 'best' then
claims = bestRanked(claims)
end
if args.sorttype then
claims = p.sortclaims(claims, args.sorttype)
end
end


if args.numval then
return numval(claims, args.numval)
end
return claims
return claims
end
end


function p.formatClaimList(claims, args)
-------------------------------------------------------------------------------
if not claims then
--                  Funzioni esportate per altri moduli
return nil
-------------------------------------------------------------------------------
end
 
for i, j in pairs(claims) do
function p._getClaims(propertyId, args)
claims[i] = p.formatStatement(j, args)
return getClaims(propertyId, args or {})
end
return claims
end
end


function p.stringTable(args) -- like getClaims, but get a list of string rather than a list of snaks, for easier manipulation
function p._formatStatement(statement, args)
local claims = p.getClaims(args)
return formatStatement(statement, args or {})
return p.formatClaimList(claims, args)
end
end


local function getQualifiers(statement, qualifs, params)
function p._formatQualifiers(claim, qualifierId, args, rawTable, retTable)
if not statement.qualifiers then
return formatQualifiers(claim, qualifierId, args or {}, rawTable, retTable)
return nil
end
local vals = {}
for i, j in pairs(qualifs) do
j = string.upper(j)
if statement.qualifiers[j] then
local inserted = false
if statement.qualifiers[j][1].datatype == 'monolingualtext' then
local in_preferred_lang
for _, language in ipairs(fb.fblist(params.lang or defaultlang, true)) do
for _, snak in ipairs(statement.qualifiers[j]) do
if isInLanguage(snak, language) then
in_preferred_lang = snak
break
end
end
if in_preferred_lang then
break
end
end
if in_preferred_lang then
table.insert(vals, in_preferred_lang)
inserted = true
end
end
if not inserted then
for _, snak in pairs(statement.qualifiers[j]) do
table.insert(vals, snak)
end
end
end
end
if #vals == 0 then
return nil
end
return vals
end
end


function p.getFormattedQualifiers(statement, qualifs, params)
-- Restituisce il valore di una proprietà di Wikidata oppure nil se l'entity o
if not params then params = {} end
-- la proprietà non esistono, o se per parametri di selezione gli statement sono zero.
local qualiftable = getQualifiers(statement, qualifs, params)
function p._getProperty(args, rawTable)
if not qualiftable then
local propertyId, value, claims, ret
return nil
 
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
end
for i, j in pairs(qualiftable) do
value = args[2]
local params = params
-- fix uppercase
if j.datatype == 'globe-coordinate' then
args.qualifier = args.qualifier and string.upper(args.qualifier)
params.displayformat = 'qualifier'
 
end
if value then
qualiftable[i] = p.formatSnak(j, params)
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
end
return linguistic.conj(qualiftable, params.lang or defaultlang, params.conjtype)
 
return ret
end
end


function p.formatStatement( statement, args )
-- Restituisce il valore di un qualifier di una proprietà di Wikidata,
if not statement.type or statement.type ~= 'statement' then
-- o nil se l'entity o la proprietà non esistono, o se per parametri di selezione non ci sono risultati.
return formatError( 'unknown-claim-type', statement.type )
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
end
if not args then args = {} end
qualifierId = args[2] and string.upper(args[2])
local lang = args.lang or defaultlang
if not qualifierId then
local str = p.formatSnak( statement.mainsnak, args )
error(i18n.errors['qualifier-param-not-provided'], 2)
if args.showlang == true then
str = showLang(statement, str)
end
end
value = args[3]


local qualifs = args.showqualifiers
if value then
if qualifs then
ret = formatUserValue(value, args)
if type(qualifs) == 'string' then
elseif args.wd ~= 'no' then
qualifs = mw.text.split(qualifs, ',')
claims = getClaims(propertyId, args)
end
if claims and #claims > 0 then
local foundvalues = p.getFormattedQualifiers(statement, qualifs, args)
local formattedQualifiers = {}
if foundvalues then
for _, claim in ipairs(claims) do
if args.delimiter then
formattedQualifiers = formatQualifiers(claim, qualifierId, args, true, formattedQualifiers)
str = str .. args.delimiter .. foundvalues
else
str = str .. linguistic.inparentheses(foundvalues, lang)
end
end
ret = #formattedQualifiers > 0 and
  mw.text.listToText(formattedQualifiers, args.separator, args.conjunction) or nil
end
end
end
end


if args.showdate then -- when "showdate and p.chronosort are both set, date retrieval is performed twice
return ret
local timedata = p.getDate(statement)
end
if timedata then
 
local formatteddate = objectToText(timedata, args)
-- Restituisce l'indice dello statement con il valore richiesto, o nil se non trovato.
formatteddate = linguistic.inparentheses(formatteddate, lang)
function p._indexOf(args)
str = str .. '<small>' .. formatteddate ..'</small>'
local ret, propertyId, value, claims
end
 
-- 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
end


if args.showsource and statement.references then
claims = getClaims(propertyId, args)
local cite = require 'Module:Cite'
if claims and #claims > 0 then
local frame = mw.getCurrentFrame()
args.formatting = 'raw'
local sourcestring = ''
for i, claim in ipairs(claims) do
local s
if formatStatement(claim, args) == value then
for _, ref in ipairs(statement.references) do
ret = i
if ref.snaks.P248 then
break
for j, source in pairs(ref.snaks.P248) do
if not isSpecial(source) then
local page
if ref.snaks.P304 and not isSpecial(ref.snaks.P304[1]) then
page = ref.snaks.P304[1].datavalue.value
end
s = cite.citeitem(source.datavalue.value.id, lang, page)
s = frame:extensionTag( 'ref', s )
sourcestring = sourcestring .. s
end
end
elseif ref.snaks.P854 and not isSpecial(ref.snaks.P854[1]) then
s = frame:extensionTag( 'ref', p.getDatavalue(ref.snaks.P854[1]) )
sourcestring = sourcestring .. s
end
end
end
end
str = str .. sourcestring
end
end
return str
 
return ret
end
end


function p.getmainid(claim)
-- Restituisce il numero di statement di una proprietà di Wikidata.
if claim and not isSpecial(claim.mainsnak) then
function p._N(args)
return claim.mainsnak.datavalue.value.id
local propertyId, claims
end
return nil
end


function p.formatSnak(snak, params)
-- parametri posizionali
--local params = params or {} pour faciliter l'appel depuis d'autres modules
propertyId = args[1] and string.upper(args[1])
if snak.snaktype == 'value' then
if not propertyId then
return p.getDatavalue(snak, params)
error(i18n.errors['property-param-not-provided'], 2)
elseif snak.snaktype == 'somevalue' then
return formatTheUnknown()
elseif snak.snaktype == 'novalue' then
return i18n('novalue') --todo
else
return formatError( 'unknown-snak-type', snak.snaktype )
end
end
end
-- get claims
claims = getClaims(propertyId, args)


local function defaultLabel(entity, displayformat) -- label when no label is available
return claims and #claims or 0
if displayformat == 'id' then
if type(entity) ~= 'table' then
return entity
else
return entity.id
end
end
return i18n('no-label')
end
end


function p._getLabel(entity, lang, default, fallback)
-- Restituisce true se la propriertà specificata ha come valore
if not entity then
-- almeno uno tra gli entityId passati come argomento.
return nil
function p._propertyHasEntity(propertyId, args)
end
local statements = p._getProperty({ propertyId, from = args.from, formatting = 'raw' }, true)
if not lang then
if statements then
lang = defaultlang
for _, statement in ipairs(statements) do
end
for _, entityId in ipairs(args) do
if type(entity) ~= 'table' and lang == defaultlang then
if statement == entityId then
local label, lg = mw.wikibase.getLabelWithLang(entity)
return true
if label and (fallback ~= '-' or lg == lang) then
return label
end
else
entity = p.getEntity(entity)
if entity and entity.labels then
if fallback ~= '-' then
for _, lg in ipairs(fb.fblist(lang, true)) do
if entity.labels[lg] then
return entity.labels[lg].value
end
end
else
if entity.labels[lang] then
return entity.labels[lang].value
end
end
end
end
end
end
end
return defaultLabel(entity, default)
end


function p._getDescription(entity, lang, fallback)
-- Se non è stato trovato alcun valore, controlla se questo sia ereditato
if not entity then
-- tramite la proprietà "sottoclasse di" (P279) scavando in profondità
return i18n('no description')
-- fino all'esaurirsi del numero specificato in args.recursion.
end
--[[ TODO: Valutare se sia opportuna una ricerca ricorsiva potenzialmente infinita.
if not lang then
Per farlo si può aggiungere un parametro (opzionale) maxDepth
lang = defaultlang
che svolga l'attuale funzione di recursion e cambiare quest'ultimo
end
in un parametro booleano.
if type(entity) ~= 'table' and lang == defaultlang then
]]
local description, lg = mw.wikibase.getDescriptionWithLang(entity)
args.recursion = tonumber(args.recursion) or 0
if description and (fallback ~= '-' or lg == lang) then
if args.recursion > 0 then
return description
local recursion = args.recursion
end
if type(args.loadedEntities) ~= 'table' then
else
args.loadedEntities = setmetatable({}, {
entity = p.getEntity(entity)
__newindex = function(t, k, v)
if entity and entity.descriptions then
rawset(t, k, v)
if fallback ~= '-' then
rawset(t, #t+1, k)
for _, lg in ipairs(fb.fblist(lang, true)) do
end })
if entity.descriptions[lg] then
args.loadedEntities[args.from or mw.wikibase.getEntityIdForCurrentPage()] = true
return entity.descriptions[lg].value
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
end
end
args.recursion = recursion
else
if entity.descriptions[lang] then
return entity.descriptions[lang].value
end
end
end
end
end
end
end
end
return i18n('no description')
 
return false, args.loadedEntities
end
 
-- Restituisce true se la proprietà P31 (instance of) ha come valore almeno uno tra gli entityId specificati
function p._instanceOf(args)
return p._propertyHasEntity('P31', args)
end
end


local function formattedLabel(label, entity, args)
-- Restituisce true se la proprietà P279 (subclass of) ha come valore almeno uno tra gli entityId specificati
local link = getLink(entity, args.link, args.lang)
function p._subclassOf(args)
if not link then
return p._propertyHasEntity('P279', args)
link = getLink(entity, defaultlink, args.lang)
end
end
 
if not link then
-- Restituisce l'etichetta di un item o di una proprietà Wikidata.
return label
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
else
return '[[' .. link .. '|' .. label .. ']]'
ret = mw.wikibase.getLabel(entityId)
end
end
return ret
end
-- Restituisce la descrizione di un item o di una proprietà Wikidata.
function p._getDescription(args)
local entityId = args[1] and string.upper(args[1])
local ret = mw.wikibase.getDescription(entityId)
return ret
end
end


function p.formatEntity( entity, args )
-- Restituisce il titolo della pagina collegata a un dato item Wikidata.
if not entity then
function p._getLink(args)
return nil
-- parametri posizionali
local entityId = args[1] and string.upper(args[1])
if not entityId then
error(i18n.errors['entityid-param-not-provided'], 2)
end
end
if not args then
args = {}
return entityId:sub(1, 1) == 'Q' and formatEntityId(entityId) or nil
end
 
-- Restituisce il datatype di una proprietà Wikidata.
function p._getDatatype(args)
local propertyId, entity
 
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
end
local label = p._getLabel(entity, args.lang, 'id', args.fallback)
return formattedLabel(label, entity, args)
end


function p.getLabel(frame) -- simple for simple templates like {{Q|}}}
entity = mw.wikibase.getEntity(propertyId)
local args = frame.args
local entity = args.entity
local lang = args.lang
if not entity then
if not entity then
return i18n('invalid-id')
error(i18n.errors['entity-not-found'], 2)
end
end


if string.sub(entity, 1, 10) == 'Property:P' then
if not i18n.datatypes[entity.datatype] then
entity = string.sub(entity, 10)
error(i18n.errors['unknown-datavalue-type'], 2)
elseif string.sub(entity, 1, 8) == 'Lexeme:L' then
entity = string.sub(entity, 8)
elseif not ({L = 1, P = 1, Q = 1})[string.sub(entity, 1, 1)] or not tonumber(string.sub(entity, 2)) then
return i18n('invalid-id')
end
end


if not args.link or args.link == '' or args.link == '-' then -- by default: no link
return i18n.datatypes[entity.datatype]
if lang == '' then
end
lang = defaultlang
 
-- Restituisce 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(args)
local ret
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
end
return p._getLabel(entity, lang, args.default, args.fallback)
else
else
return p.formatEntity(entity, args)
ret = mw.wikibase.getEntityIdForCurrentPage()
end
end
return ret
end
end


function p._formatStatements( args )--Format statements and concat them cleanly
-------------------------------------------------------------------------------
if args.value == '-' then
--                  Funzioni esportate per i template
return nil
-------------------------------------------------------------------------------
end
 
--If a value is already set, use it
-- Funzione per il template {{Wikidata}}
if args.value and args.value ~= '' then
function p.getProperty(frame)
return args.value
return select(2, xpcall(function()
end
return p._getProperty(getArgs(frame, { parentOnly = true }))
local valuetable = p.stringTable(args)
end, errhandler))
return tableToText(valuetable, args)
end
end


function p.showQualifier( args )
-- Funzione per il template {{WikidataQ}}
local qualifs = args.qualifiers or args.qualifier
function p.getQualifier(frame)
if type(qualifs) == 'string' then
return select(2, xpcall(function()
qualifs = mw.text.split(qualifs, ',')
return p._getQualifier(getArgs(frame, { parentOnly = true }))
end
end, errhandler))
if not qualifs then
return formatError( 'property-param-not-provided' )
end
local claims = p.getClaims(args)
if not claims then
return nil
end
local str = ''
local new
for _, cl in ipairs(claims) do
new = p.getFormattedQualifiers(cl, qualifs, args) or ''
str = str .. new
end
return str
end
end


function p._formatAndCat(args)
-- Funzione per il template {{WikidataIdx}}
local val = p._formatStatements(args)
function p.indexOf(frame)
if val then
return select(2, xpcall(function()
return val .. addTrackingCat(args.property)
return p._indexOf(getArgs(frame, { parentOnly = true }))
end
end, errhandler))
return nil
end
end


function p.getTheDate(args)
-- Funzione per il template {{WikidataN}}
local claims = p.getClaims(args)
function p.N(frame)
if not claims then
return select(2, xpcall(function()
return nil
return p._N(getArgs(frame, { parentOnly = true }))
end
end, errhandler))
local formattedvalues = {}
for _, cl in ipairs(claims) do
table.insert(formattedvalues, p.getFormattedDate(cl))
end
local val = linguistic.conj(formattedvalues)
if val and args.addcat == true then
return val .. addTrackingCat(args.property)
else
return val
end
end
end
---FONCTIONS depuis le FRAME
 
function p.getaDate(frame)
-- Funzione per il template {{WikidataLabel}}
return p.getTheDate(frame.args)
function p.getLabel(frame)
return select(2, xpcall(function()
return p._getLabel(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
end


function p.getQualifier(frame)
-- Funzione per il template {{WikidataDescription}}
return p.showQualifier(frame.args)
function p.getDescription(frame)
return select(2, xpcall(function()
return p._getDescription(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
end


function p.getDescription(frame) -- simple for simple templates like {{Q|}}}
-- Funzione per il template {{WikidataLink}}
local entity = frame.args.entity
function p.getLink(frame)
if not entity then
return select(2, xpcall(function()
return i18n('invalid-id')
return p._getLink(getArgs(frame, { parentOnly = true }))
end
end, errhandler))
local lang = frame.args.lang
local fallback = frame.args.fallback
 
return p._getDescription(entity, lang, fallback)
end
end


function p.formatStatements( args )
-- Funzione per il template {{WikidataIstanza}}
return p._formatStatements( args )
function p.instanceOf(frame)
return select(2, xpcall(function()
return p._instanceOf(getArgs(frame, { parentOnly = true })) and 1 or ''
end, errhandler))
end
end


function p.formatStatementsE(frame)
-- Funzione per il template {{WikidataTipo}}
local args = {}
function p.getDatatype(frame)
if frame == mw.getCurrentFrame() then
return select(2, xpcall(function()
args = frame:getParent().args -- paramètres du modèle appelant (est-ce vraiment une bonne idée ?)
return p._getDatatype(getArgs(frame, { parentOnly = true }))
for k, v in pairs(frame.args) do
end, errhandler))
args[k] = v
end
else
args = frame
end
return p._formatStatements( args )
end
end


function p.formatAndCat(frame)
-- Funzione per il template {{WikidataId}}
local args = {}
function p.getId(frame)
if frame == mw.getCurrentFrame() then
return select(2, xpcall(function()
args = frame:getParent().args -- paramètres du modèle appelant (est-ce vraiment une bonne idée ?)
return p._getId(getArgs(frame, { parentOnly = true }))
for k, v in pairs(frame.args) do
end, errhandler))
args[k] = v
end
else
args = frame
end
return p._formatAndCat( args )
end
end


function p.getEntityFromId(id)
-- Funzione per il template {{WikidataValido}}
return p.getEntity(id)
function p.checkProperty(frame)
return select(2, xpcall(function()
return p._N(getArgs(frame, { parentOnly = true })) > 0 and 1 or ''
end, errhandler))
end
end


-- https://www.wikidata.org/w/index.php?title=Wikidata:Project_chat&oldid=1439583623#Check_if_redirect
-- Funzione per il template {{WikidataClasse}}
-- Not applicable outside Wikidata
function p.propertyHasEntity(frame)
function p.isRedirect(frame)
local args = getArgs(frame, { parentOnly = true })
return mw.title.new(frame.args[1]).isRedirect
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
end


return p
return p