Modulo:Wikidata: differenze tra le versioni

Vai alla navigazione Vai alla ricerca
p.isRedirect
(funzione per chiamata diretta a propertyHasEntity)
(p.isRedirect)
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}}.


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


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


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


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


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


-- Messaggi
local function addTrackingCat(prop, cat)
local i18n = {
if not prop and not cat then
errors = {
return error("no property provided")
['entityid-param-not-provided'] = "Parametro ''entityid'' non fornito",
end
['property-param-not-provided'] = "Parametro ''property'' non fornito",
if not cat then
['qualifier-param-not-provided'] = "Parametro ''qualifier'' non fornito",
cat = i18nmessages.trackingcat .. '/' .. string.upper(prop)
['value-param-not-provided'] = "Parametro ''valore'' da ricercare non fornito",
end
['entity-not-found'] = 'Entità non trovata',
return '[[Category:' .. cat .. ']]'
['unknown-claim-type'] = 'Tipo asserzione sconosciuta',
end
['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 = {}
local function removeBlanks(args)
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"
--                            Formatters
return i18n('somevalue')
-------------------------------------------------------------------------------
end


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


local function formatList(values, ordered)
local function sameValue(snak, target)
local fmt = ordered and '<ol><li>%s</li></ol>' or '<ul><li>%s</li></ul>'
return not isSpecial(snak) and p.getRawvalue(snak) == target
return #values > 0 and string.format(fmt, mw.text.listToText(values, '</li><li>', '</li><li>')) or ''
end
end


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


local success, uri = pcall(function() return mw.uri.new(url) end)
local langlist = {}
if success and uri.protocol and protocols[uri.protocol] then
if mainsnak.datavalue.type == 'monolingualtext' then
local dest = tostring(uri)
langlist = {mainsnak.datavalue.value.language}
return string.format('<span style="word-break: break-all;">[%s %s]</span>', dest, dest:gsub(uri.protocol .. '://', ''))
elseif statement.qualifiers and statement.qualifiers.P407 then
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 url
return '(' .. table.concat(langlist) .. ')' .. str
end
end
end
end


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


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


local function formatTimeWithPrecision(time, precision)
local function rangeObject(begin, ending)
local months = {
local timestamp
'gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno',
if begin then
'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'
timestamp = begin.timestamp
}
elseif ending then
local ret, year, month, day
timestamp = ending.timestamp
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
if precision >= 9 and precision <= 11 then
return {begin = begin, ending = ending, timestamp = timestamp, type = 'rangeobject'}
ret = ret .. (time:sub(1, 1) == '-' and ' a.C.' or '')
end
 
local function dateObject(orig, params) -- transforme un snak en un nouvel objet utilisable par Module:Date complexe
if not params then
params = {}
end
end


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


local function formatTime(value, args)
local function formatDatepoint(obj, params) -- TO IMPROVE
local ret
if not obj then
return nil
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 formatDate = require('Module:Complex date')
local lang = params.lang or defaultlang
local precision = math.min(obj.precision, params.precision or 15) -- if we don't want to show the value to its full detail
if precision >= 11 then
return formatDate.complex_date{args={date1 = obj.year .. '-' .. obj.month .. '-' .. obj.day, lang= lang}}
elseif precision == 10 then
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
return nil
end


return ret or ''
local function formatDaterange(obj, params) --TODO
local begin = formatDatepoint(obj.begin, params) or ''
local ending = formatDatepoint(obj.ending, params) or ''
return begin .. '-' .. ending
end
end


local function formatGlobecoordinate(value, args)
local function objectToText(obj, params)
local ret
if obj.type == 'dateobject' then
if args.coord == 'latitude' then
return formatDatepoint(obj, params)
ret = value.latitude
elseif obj.type == 'rangeobject' then
elseif args.coord == 'longitude' then
return formatDaterange(obj, params)
ret = value.longitude
elseif args.coord == 'globe' then
ret = value.globe
else
ret = string.format('%s, %s', value.latitude, value.longitude)
end
end
return ret
return nil
end
end


local function formatFromPattern(str, args)
local function tableToText(values, params) -- takes a list of already formatted values and make them a text
local pattern = args.pattern
if not values or #values == 0 then
pattern = mw.ustring.gsub(pattern, '\\{', '{')
return nil
pattern = mw.ustring.gsub(pattern, '\\}', '}')
end
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
return linguistic.conj(values, params.lang or defaultlang, params.conjtype)--linguistic.conj( values, params.lang, params.conjtype )
end
end


local function formatUserValue(value, args)
function p.getDate(obj)
if args.extlink then
--[[
value = formatExtLink(value)
returns an object containing a timestamp for easy sorting, and other data
possible types of object:
dateobject
{timestamp = string, year = number, month = number, day = number, calendar = string}
rangeobject
{timestamp = string, begin = dateobject, ending = dateobject}
]]--
if not obj then
return nil
end
if type(obj) == 'string' then
obj = p.getEntity(obj)
end
 
-- if obj is a statement with date, get it
if obj.mainsnak and not isSpecial(obj.mainsnak) and obj.mainsnak.datatype == 'time' then
return dateObject(obj.mainsnak.datavalue.value)
end
end
return args.pattern and formatFromPattern(value, args) or value
end


local function getEntityIdFromValue(value)
-- else preload relevant data
local prefix = ''
local qualifs = obj.qualifiers -- when obj is a statement, look in qualifiers
if value['entity-type'] == 'item' then
local claims = obj.claims -- when obj is an item, look in claims
prefix = 'Q'
 
elseif value['entity-type'] == 'property' then
local pointprop = {'P585', 'P571'} -- dates corresponding to a punctual fact
prefix = 'P'
local beginprop = {'P580', 'P569'} -- start date, birth date == start of a date range
else
local endingprop = {'P582', 'P570'}
error(i18n.errors['unknown-entity-type'])
 
local function getval(prop)
local val
if claims and claims[prop] and not isSpecial(claims[prop][1].mainsnak) then
val = claims[prop][1].mainsnak.datavalue.value
elseif qualifs and qualifs[prop] and not isSpecial(qualifs[prop][1]) then
val = qualifs[prop][1].datavalue.value
end
if val then
return dateObject(val)
end
return nil
end
end
return prefix .. value['numeric-id']
end


local function formatUnitSymbol(entityId, args)
for i, prop in pairs(pointprop) do
local ret
local val = getval(prop)
for _, lang in ipairs({ 'mul', 'it', 'en' }) do
if val then return val end
ret = p._getProperty({ 'P5061', includelang = lang, from = entityId })
end
if ret and ret ~= '' then
--if no date has not been found, look for startdate or enddate
local begin, ending
for i, prop in pairs(beginprop) do
begin = getval(prop)
if begin then
break
break
else
ret = nil
end
end
end
end
local space = ret == '°' and '' or ' '
for i, prop in pairs(endingprop) do
if ret and args.showunitlink then
ending = getval(prop)
local link = mw.wikibase.getSitelink(entityId)
if ending then
if link then
break
ret = string.format('[[%s|%s]]', link, ret)
end
end
end
end
return ret and (space .. ret) or ''
if begin or ending then
return rangeObject(begin, ending)
end
return nil
end
end


-- http://lua-users.org/wiki/SimpleRound
function p.getFormattedDate(statement, params)
local function round(num, idp)
local datetable = p.getDate(statement)
local mult = 10 ^ (idp or 0)
if not datetable then
return math.floor(num * mult + 0.5) / mult
return nil
end
return objectToText(datetable, params)
end
end


local function hasTargetValue(claim, target)
if target == nil then
return true
end
return sameValue(claim.mainsnak, target)
end


local function formatQuantity(value, args)
local function hasRank(claim, target)
local ret = tonumber(value.amount)
if target == 'valid' then
return hasRank(claim, 'preferred') or hasRank(claim, 'normal')
else
return claim.rank == target
end
end


if (args.unit or args.showunit) and value.unit ~= '1' then
local function bestRanked(claims)
local unitId = mw.ustring.match(value.unit, 'Q%d+')
if not claims then
if args.unit then
return nil
local opts = {
end
showunit = args.showunit,
local preferred, normal = {}, {}
showunitlink = args.showunitlink,
for _, j in ipairs(claims) do
formatnum = args.formatnum,
if j.rank == 'preferred' then
rounding = args.rounding
table.insert(preferred, j)
}
elseif j.rank == 'normal' then
ret = mConvert._main(ret, unitId, args.unit, opts)
table.insert(normal, j)
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
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 #preferred > 0 then
return ret
return preferred
else
return normal
end
end
end


local function formatDatavalue(datavalue, snakdatatype, args)
local function hasQualifier(claim, qualifier, qualifiervalues)
local ret
if not qualifier then -- si aucun qualificatif est demandé, ça passe
return true
end


if datavalue.type == 'wikibase-entityid' then
qualifier = string.upper(qualifier)
local entityId = getEntityIdFromValue(datavalue.value)
if not claim.qualifiers or not claim.qualifiers[qualifier] then
if args.showprop then
return false
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
error(i18n.errors['unknown-datavalue-type'])
end
end


return ret
if type(qualifiervalues) == 'string' then
end
qualifiervalues = mw.text.split(qualifiervalues, ',')
end


local function formatSnak(snak, args)
if (not qualifiervalues) or (qualifiervalues == {}) then
if snak.snaktype == 'somevalue' then
return true -- si aucune valeur spécifique n'est exigée
return i18n['somevalue']
elseif snak.snaktype == 'novalue' then
return i18n['novalue']
elseif snak.snaktype == 'value' then
return formatDatavalue(snak.datavalue, snak.datatype, args)
else
error(i18n.errors['unknown-snak-type'])
end
end
end


-- È al plurale perché anche i qualifier possono avere più di un valore
for _, j in ipairs(claim.qualifiers[qualifier]) do
-- (si ottiene inserendo due volte lo stesso qualifier)
for _, l in ipairs(qualifiervalues) do
local function formatQualifiers(claim, qualifierId, args, rawTable, retTable)
if p.sameValue(j, l) then
local formattedQualifiers = retTable or {}
return true
end
end
end
return false
end


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


if rawTable then
local function hasDate(statement)
return formattedQualifiers
if not statement.qualifiers then
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


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


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


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


local function formatStatements(claims, args, rawTable)
local function getLink(entity, typelink, lang)
local formattedStatements = {}
if typelink == 'wikidata' then
 
if type(entity) == 'table' then
for _, claim in ipairs(claims) do
if entity.type == 'property' then
local formattedStatement = formatStatement(claim, args)
return 'd:P:' .. entity.id
if formattedStatement ~= '' then
elseif entity.type == 'lexeme' then
-- eventuale pattern
return 'd:L:' .. entity.id
if args.pattern then
else
formattedStatement = formatFromPattern(formattedStatement, args)
return 'd:' .. entity.id
if formattedStatement ~= '' then
end
table.insert(formattedStatements, formattedStatement)
else
end
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
else
table.insert(formattedStatements, formattedStatement)
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
--                      Lettura e selezione statement
return wikipediaLink(entity, lang or defaultlang)
-------------------------------------------------------------------------------


-- Restituisce true se lo statement contiene il qualifier richiesto con un dato valore (o uno tra più valori separati da virgola)
elseif typelink == 'anywikipedia' then
local function hasQualifierValue(statement, qualifierId, qualifierValue)
for _, lg in ipairs(fb.fblist(lang or defaultlang, true)) do
local ret = false
local link = wikipediaLink(entity, lg)
for _, qualifier in ipairs(statement.qualifiers[qualifierId]) do
if link then
local isItem = qualifier.snaktype == 'value' and
return link
  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 ret
return nil
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


-- Restituisce i claim con il rank richiesto
function p.chronosort(objs, inverted)
local function filterRankValue(claims, rank)
table.sort(objs, function(a, b)
local ret = {}
local timeA = p.getDate(a)
for _, claim in ipairs(claims) do
local timeB = p.getDate(b)
if claim.rank == rank then
if inverted then
table.insert(ret, claim)
return p.comparedate(timeB, timeA)
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 ret
return claims
end
end


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


-- statements filtrati per snaktype, default "value"
elseif valuetype == 'string' then
args.snaktype = args.snaktype or 'value'
local showntext = params.showntext
if args.snaktype and args.snaktype ~= 'all' then
if displayformat == 'weblink' then
filteredClaims = {}
if showntext then
for _, claim in ipairs(claims) do
return '[' .. value .. ' ' .. showntext .. ']'
if claim.mainsnak.snaktype == args.snaktype then
else
table.insert(filteredClaims, claim)
return value
end
end
end
end
claims = filteredClaims
if ({['math'] = 1, ['musical-notation'] = 1})[snak.datatype] == 1 and displayformat ~= 'raw' then
end
value = mw.wikibase.formatValue(snak)
 
else
-- statements filtrati per qualifier
if params.urlpattern then
if args.qualifier then
showntext = mw.text.nowiki(showntext or value)
filteredClaims = {}
value = mw.ustring.gsub(value, '%%', '%%%%') -- escape '%'
for _, claim in ipairs(claims) do
value = '[' .. mw.ustring.gsub(mw.ustring.gsub(params.urlpattern, '$1', value), ' ', '%%20') .. ' ' .. showntext .. ']'
if claim.qualifiers and claim.qualifiers[args.qualifier] then
elseif params.pattern then
if args.qualifiervalue then
local pattern = mw.ustring.gsub(params.pattern, '%%', '%%%%')
if hasQualifierValue(claim, args.qualifier, args.qualifiervalue) then
value = mw.ustring.gsub(value, '%%', '%%%%')
table.insert(filteredClaims, claim)
value = mw.ustring.gsub(pattern, '$1', value)
end
else
else
if displayformat ~= 'raw' then
table.insert(filteredClaims, claim)
value = mw.text.nowiki(value)
end
end
end
end
end
end
claims = filteredClaims
return value
end
 
elseif valuetype == 'time' then -- format example: +00000001809-02-12T00:00:00Z
if displayformat == 'raw' then
return value.time
else
return objectToText(dateObject(value), params)
end
 
elseif valuetype == 'globecoordinate' then
-- retourne une table avec clés latitude, longitude, précision et globe à formater par un autre module (à changer ?)
if displayformat == 'latitude' then
return value.latitude
elseif displayformat == 'longitude' then
return value.longitude
elseif displayformat == 'qualifier' then
local coord = require 'Module:Coordinates'
value.globe = mw.loadData('Module:Wikidata/Globes')[value.globe]
value.precision = nil
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


-- statements filtrati per essere senza un qualifier
elseif valuetype == 'quantity' then -- todo : gérer les paramètre précision
if args.noqualifier then
if displayformat == 'raw' then
filteredClaims = {}
return tonumber(value.amount)
for _, claim in ipairs(claims) do
else
if not (claim.qualifiers and claim.qualifiers[args.noqualifier]) then
local formatNum = require 'Module:Formatnum'
table.insert(filteredClaims, claim)
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
claims = filteredClaims
elseif valuetype == 'monolingualtext' then
return '<span lang="' .. value.language .. '">' .. value.text .. '</span>'
else
return formatError( 'unknown-datavalue-type', valuetype )
end
end
end


-- statements filtrati per non avere un certo valore a un certo qualifier opzionale
local function getMultipleClaims(args)
if args.qualifieroptnovalue and args.qualifiervalue then
local newargs = args
filteredClaims = {}
local claims = {}
for _, claim in ipairs(claims) do
for i, j in pairs(args.property) do
if claim.qualifiers and claim.qualifiers[args.qualifieroptnovalue] then
newargs.property = j
if not hasQualifierValue(claim, args.qualifieroptnovalue, args.qualifiervalue) then
local newclaims = p.getClaims(args)
table.insert(filteredClaims, claim)
if newclaims then
end
for k, l in pairs(newclaims) do
else
table.insert(claims, l)
table.insert(filteredClaims, claim)
end
end
end
end
claims = filteredClaims
end
end
return claims
end


-- con args.qualifiertype=latest restituisce solo il più recente
function p.getClaims( args ) -- returns a table of the claims matching some conditions given in args
if args.qualifier and args.qualifiertype == 'latest' then
args = removeBlanks(args)
local latest, latestTime
if not args.property then
for _, claim in ipairs(claims) do
return formatError( 'property-param-not-provided' )
if claim.qualifiers and claim.qualifiers[args.qualifier] then
end
for _, qualifier in ipairs(claim.qualifiers[args.qualifier]) do
if type(args.property) == 'table' then
if qualifier.datavalue.type == 'time' then
return getMultipleClaims(args)
if not latestTime or qualifier.datavalue.value.time > latestTime then
end
latest = claim
--Get entity
latestTime = qualifier.datavalue.value.time
if args.item then -- synonyms
end
args.entity = args.item
end
end
end
local property = string.upper(args.property)
end
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
 
if not args.rank then
args.rank = 'best'
end
local claims = {}
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
claims = latest and { latest } or {}
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


-- con args.n restituisce solo l'n-esimo elemento
if args.numval then
if args.n then
return numval(claims, args.numval)
local n = tonumber(args.n)
claims = (n and n <= #claims) and { claims[n] } or {}
end
end
return claims
return claims
end
end


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


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


function p._formatQualifiers(claim, qualifierId, args, rawTable, retTable)
local function getQualifiers(statement, qualifs, params)
return formatQualifiers(claim, qualifierId, args or {}, rawTable, retTable)
if not statement.qualifiers then
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


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


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


if value then
local qualifs = args.showqualifiers
ret = formatUserValue(value, args)
if qualifs then
elseif args.wd ~= 'no' then
if type(qualifs) == 'string' then
claims = getClaims(propertyId, args)
qualifs = mw.text.split(qualifs, ',')
if claims and #claims > 0 then
end
local formattedQualifiers = {}
local foundvalues = p.getFormattedQualifiers(statement, qualifs, args)
for _, claim in ipairs(claims) do
if foundvalues then
formattedQualifiers = formatQualifiers(claim, qualifierId, args, true, formattedQualifiers)
if args.delimiter then
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


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


claims = getClaims(propertyId, args)
if args.showsource and statement.references then
if claims and #claims > 0 then
local cite = require 'Module:Cite'
args.formatting = 'raw'
local frame = mw.getCurrentFrame()
for i, claim in ipairs(claims) do
local sourcestring = ''
if formatStatement(claim, args) == value then
local s
ret = i
for _, ref in ipairs(statement.references) do
break
if ref.snaks.P248 then
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
end


return ret
function p.getmainid(claim)
if claim and not isSpecial(claim.mainsnak) then
return claim.mainsnak.datavalue.value.id
end
return nil
end
end


-- Restituisce il numero di statement di una proprietà di Wikidata.
function p.formatSnak(snak, params)
function p._N(args)
--local params = params or {} pour faciliter l'appel depuis d'autres modules
local propertyId, claims
if snak.snaktype == 'value' then
return p.getDatavalue(snak, params)
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


-- parametri posizionali
local function defaultLabel(entity, displayformat) -- label when no label is available
propertyId = args[1] and string.upper(args[1])
if displayformat == 'id' then
if not propertyId then
if type(entity) ~= 'table' then
error(i18n.errors['property-param-not-provided'], 2)
return entity
else
return entity.id
end
end
end
-- get claims
return i18n('no-label')
claims = getClaims(propertyId, args)
 
return claims and #claims or 0
end
end


-- Restituisce true se la propriertà specificata ha come valore
function p._getLabel(entity, lang, default, fallback)
-- almeno uno tra gli entityId passati come argomento.
if not entity then
function p._propertyHasEntity(propertyId, args)
return nil
local statements = p._getProperty({ propertyId, from = args.from, formatting = 'raw' }, true)
end
if statements then
if not lang then
for _, statement in ipairs(statements) do
lang = defaultlang
for _, entityId in ipairs(args) do
end
if statement == entityId then
if type(entity) ~= 'table' and lang == defaultlang then
return true
local label, lg = mw.wikibase.getLabelWithLang(entity)
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


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


-- Restituisce true se la proprietà P31 (instance of) ha come valore almeno uno tra gli entityId specificati
local function formattedLabel(label, entity, args)
function p._instanceOf(args)
local link = getLink(entity, args.link, args.lang)
return p._propertyHasEntity('P31', args)
if not link then
end
link = getLink(entity, defaultlink, args.lang)
 
end
-- Restituisce true se la proprietà P279 (subclass of) ha come valore almeno uno tra gli entityId specificati
if not link then
function p._subclassOf(args)
return label
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
else
ret = mw.wikibase.getLabel(entityId)
return '[[' .. link .. '|' .. label .. ']]'
end
end
return ret
end
end


-- Restituisce la descrizione di un item o di una proprietà Wikidata.
function p.formatEntity( entity, args )
function p._getDescription(args)
if not entity then
local entityId = args[1] and string.upper(args[1])
return nil
local ret = mw.wikibase.getDescription(entityId)
end
return ret
if not args then
end
args = {}
 
-- Restituisce 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])
if not entityId then
error(i18n.errors['entityid-param-not-provided'], 2)
end
end
local label = p._getLabel(entity, args.lang, 'id', args.fallback)
return entityId:sub(1, 1) == 'Q' and formatEntityId(entityId) or nil
return formattedLabel(label, entity, args)
end
end


-- Restituisce il datatype di una proprietà Wikidata.
function p.getLabel(frame) -- simple for simple templates like {{Q|}}}
function p._getDatatype(args)  
local args = frame.args
local propertyId, entity
local entity = args.entity
 
local lang = args.lang
-- parametri posizionali
propertyId = args[1] and string.upper(args[1])
if not propertyId then
error(i18n.errors['property-param-not-provided'], 2)
end
 
entity = mw.wikibase.getEntity(propertyId)
if not entity then
if not entity then
error(i18n.errors['entity-not-found'], 2)
return i18n('invalid-id')
end
end


if not i18n.datatypes[entity.datatype] then
if string.sub(entity, 1, 10) == 'Property:P' then
error(i18n.errors['unknown-datavalue-type'], 2)
entity = string.sub(entity, 10)
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


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


-------------------------------------------------------------------------------
function p._formatStatements( args )--Format statements and concat them cleanly
--                  Funzioni esportate per i template
if args.value == '-' then
-------------------------------------------------------------------------------
return nil
end
--If a value is already set, use it
if args.value and args.value ~= '' then
return args.value
end
local valuetable = p.stringTable(args)
return tableToText(valuetable, args)
end


-- Funzione per il template {{Wikidata}}
function p.showQualifier( args )
function p.getProperty(frame)
local qualifs = args.qualifiers or args.qualifier
return select(2, xpcall(function()
if type(qualifs) == 'string' then
return p._getProperty(getArgs(frame, { parentOnly = true }))
qualifs = mw.text.split(qualifs, ',')
end, errhandler))
end
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


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


-- Funzione per il template {{WikidataIdx}}
function p.getTheDate(args)
function p.indexOf(frame)
local claims = p.getClaims(args)
return select(2, xpcall(function()
if not claims then
return p._indexOf(getArgs(frame, { parentOnly = true }))
return nil
end, errhandler))
end
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
-- Funzione per il template {{WikidataN}}
function p.getaDate(frame)
function p.N(frame)
return p.getTheDate(frame.args)
return select(2, xpcall(function()
return p._N(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
end


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


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


-- Funzione per il template {{WikidataLink}}
return p._getDescription(entity, lang, fallback)
function p.getLink(frame)
return select(2, xpcall(function()
return p._getLink(getArgs(frame, { parentOnly = true }))
end, errhandler))
end
end


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


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


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


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


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

Menu di navigazione