Module:Wikidata : Tameẓla gar ileqman

Contenu supprimé Contenu ajouté
SalemB (mmeslay | attekki)
Asebtar amaynut: --script that retrieves basic data stored in Wikidata, for the datamodel, see https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua local p = {} local linguistic = requi...
 
SalemB (mmeslay | attekki)
Aucun résumé des modifications
Ajerriḍ 1:
-- vim: set noexpandtab ft=lua ts=4 sw=4:
--script that retrieves basic data stored in Wikidata, for the datamodel, see https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
require('Module:No globals')
 
 
local p = {}
local debug = false
local linguistic = require('Module:Linguistique')
local dates = require('Module:Wikidata/Dates')
local langmodule = require('Module:Langue')
lang = 'fr' -- peut-être écrasé par args.lang
 
 
local i18n = {
------------------------------------------------------------------------------
["errors"] = {
-- module local variables and functions
["property-param-not-provided"] = "property parameter missing",
 
["qualifier-param-not-provided"] = "qualifier parameter missing",
local wiki =
["entity-not-found"] = "entity not found",
{
["unknown-claim-type"] = "unknown claim type",
langcode = mw.language.getContentLanguage().code
["unknown-snak-typeg"] = "unknown snak type",
["unknown-datavalue-type"] = "unknown datavalue type.",
["unknown-entity-type"] = "unknown entity type",
["invalid-id"] = "invalid ID"
},
["no-label"] = "pas de libellé",
['no description'] = "pas description",
["novalue"] = "not applicable",
["somevalue"] = "inconnu",
["trackingcat"] = 'Page utilisant des données de Wikidata'
}
 
-- internationalisation
local function formatError( key )
local i18n =
return error(i18n.errors[key])
{
end
["errors"] =
{
["property-not-found"] = "Property not found.",
["entity-not-found"] = "Wikidata entity not found.",
["unknown-claim-type"] = "Unknown claim type.",
["unknown-entity-type"] = "Unknown entity type.",
["qualifier-not-found"] = "Qualifier not found.",
["site-not-found"] = "Wikimedia project not found.",
["unknown-datetime-format"] = "Unknown datetime format.",
["local-article-not-found"] = "Article is not yet available in this wiki."
},
["datetime"] =
{
-- $1 is a placeholder for the actual number
[0] = "$1 billion years", -- precision: billion years
[1] = "$100 million years", -- precision: hundred million years
[2] = "$10 million years", -- precision: ten million years
[3] = "$1 million years", -- precision: million years
[4] = "$100,000 years", -- precision: hundred thousand years
[5] = "$10,000 years", -- precision: ten thousand years
[6] = "$1 millennium", -- precision: millennium
[7] = "$1 century", -- precision: century
[8] = "$1s", -- precision: decade
-- the following use the format of #time parser function
[9] = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[11] = "F j, Y", -- precision: day
[12] = "F j, Y ga", -- precision: hour
[13] = "F j, Y g:ia", -- precision: minute
[14] = "F j, Y g:i:sa", -- precision: second
["beforenow"] = "$1 BCE", -- how to format negative numbers for precisions 0 to 5
["afternow"] = "$1 CE", -- how to format positive numbers for precisions 0 to 5
["bc"] = '$1 "BCE"', -- how print negative years
["ad"] = "$1", -- how print positive years
-- the following are for function getDateValue() and getQualifierDateValue()
["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
-- #4 (getQualifierDateValue) argument
["default-addon"] = "BC", -- default value of the #4 (getDateValue) or
-- #5 (getQualifierDateValue) argument
["prefix-addon"] = false, -- set to true for languages put "BC" in front of the
-- datetime string; or the addon will be suffixed
["addon-sep"] = " ", -- separator between datetime string and addon (or inverse)
["format"] = -- options of the 3rd argument
{
["mdy"] = "F j, Y",
["my"] = "F Y",
["y"] = "Y",
["dmy"] = "j F Y",
["ymd"] = "Y-m-d",
["ym"] = "Y-m"
}
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
["ordinal"] =
{
[1] = "st",
[2] = "nd",
[3] = "rd",
["default"] = "th"
}
}
 
-- Credit to http://stackoverflow.com/a/1283608/2644759
local function addtrackingcat(prop, cat)
-- cc-by-sa 3.0
if not prop and not cat then
local function tableMerge(t1, t2)
return error("no property provided")
for k,v in pairs(t2) do
end
if nottype(v) cat== "table" then
if type(t1[k] or false) == "table" then
cat = i18n.trackingcat .. '/' .. string.upper(prop)
tableMerge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return '[[Category:' .. cat .. ']]'t1
end
 
local function loadI18n()
function formatTheUnknown() -- voir si on peut accorder/adapter l'usage de "inconnu"
local exist, res = pcall(require, "Module:Wikidata/i18n")
return i18n.somevalue
if exist and next(res) ~= nil then
end
tableMerge(i18n, res.i18n)
 
local function samevalue(snak, target)
if snak.snaktype == 'value' and p.getRawvalue(snak) == target then
return true
end
end
 
loadI18n()
local function getEntity( val )
 
if type(val) == 'table' then
-- this function needs to be internationalised along with the above:
return val
-- takes cardinal numer as a numeric and returns the ordinal as a string
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
local function makeOrdinal (cardinal)
local ordsuffix = i18n.ordinal.default
if cardinal % 10 == 1 then
ordsuffix = i18n.ordinal[1]
elseif cardinal % 10 == 2 then
ordsuffix = i18n.ordinal[2]
elseif cardinal % 10 == 3 then
ordsuffix = i18n.ordinal[3]
end
-- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th'
-- similarly for 12 and 13, etc.
if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then
ordsuffix = i18n.ordinal.default
end
return tostring(cardinal) .. ordsuffix
return mw.wikibase.getEntityObject(val)
end
 
local function printError(code)
local function formattable(statements, params) -- transform a table of claims into a table of formatted values
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
for i, j in pairs(statements) do
j = p.formatStatement(j, params)
end
return statements
end
 
local function parseDateValue(timestamp, date_format, date_addon)
local function tableToText(values, params) -- takes a list of already formatted values and make them a text
local prefix_addon = i18n["datetime"]["prefix-addon"]
if not values then
local addon_sep = i18n["datetime"]["addon-sep"]
return nil
local addon = ""
end
 
return linguistic.quickconj( values, params.conjtype)--linguistic.conj( values, params.lang, params.conjtype )
-- check for negative date
if string.sub(timestamp, 1, 1) == '-' then
timestamp = '+' .. string.sub(timestamp, 2)
addon = date_addon
end
local function d(f)
local year_suffix
local tstr = ""
local lang_obj = mw.language.new(wiki.langcode)
local f_parts = mw.text.split(f, 'Y', true)
for idx, f_part in pairs(f_parts) do
year_suffix = ''
if string.match(f_part, "x[mijkot]$") then
-- for non-Gregorian year
f_part = f_part .. 'Y'
elseif idx < #f_parts then
-- supress leading zeros in year
year_suffix = lang_obj:formatDate('Y', timestamp)
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
end
if addon ~= "" and prefix_addon then
return addon .. addon_sep .. tstr
elseif addon ~= "" then
return tstr .. addon_sep .. addon
else
return tstr
end
end
local _date_format = i18n["datetime"]["format"][date_format]
if _date_format ~= nil then
return d(_date_format)
else
return printError("unknown-datetime-format")
end
end
 
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
function p.getDate(statement)
-- with the millennium/century/decade handling of formatDate()
--[[
local function parseDateFull(timestamp, precision, date_format, date_addon)
return a "timedata" object as used by the date modules with the date of an item from the p580, p582 and p585 qualifiers
local prefix_addon = i18n["datetime"]["prefix-addon"]
object format:
local addon_sep = i18n["datetime"]["addon-sep"]
* timestamp 28 char string value for the timepoint, or if non the beginning or if none, the end (for easy sorting)
local addon = ""
* timepoint: snak
 
* begin: snak
-- check for negative date
]]--
if string.sub(timestamp, 1, 1) == '-' then
local q = statement.qualifiers
timestamp = '+' .. string.sub(timestamp, 2)
if not q or not (q.P585 or q.P580 or q.P582) then
addon = date_addon
return nil
end
 
if q.P585 and q.P585[1].snaktype == 'value' then -- P585: punctual date
-- get the next four characters after the + (should be the year now in all cases)
return dates.dateobject(q.P585[1].datavalue.value)
-- ok, so this is dirty, but let's get it working first
local intyear = tonumber(string.sub(timestamp, 2, 5))
if intyear == 0 and precision <= 9 then
return ""
end
local begin, ending
 
-- precision is 10000 years or more
if q.P582 and q.P582[1].snaktype == 'value' then
if precision <= 5 then
ending = dates.dateobject(q.P582[1].datavalue.value)
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(intyear) / factor)
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if addon ~= "" then
-- negative date
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end
 
if q.P580 and q.P580[1].snaktype == 'value' then
-- precision is decades (8), centuries (7) and millennia (6)
begin = dates.dateobject(q.P580[1].datavalue.value)
local era, card
if precision == 6 then
card = math.floor((intyear - 1) / 1000) + 1
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
end
if precision == 7 then
card = math.floor((intyear - 1) / 100) + 1
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
end
if precision == 8 then
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
end
if era then
if addon ~= "" then
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
else
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
end
return era
end
return dates.daterange(begin, ending)
end
 
local _date_format = i18n["datetime"]["format"][date_format]
function p.getFormattedDate(statement, params)
if _date_format ~= nil then
local datetable = p.getDate(statement)
-- check for precision is year and override supplied date_format
if not datetable then
if precision == 9 then
return nil
_date_format = i18n["datetime"][9]
end
local year_suffix
local tstr = ""
local lang_obj = mw.language.new(wiki.langcode)
local f_parts = mw.text.split(_date_format, 'Y', true)
for idx, f_part in pairs(f_parts) do
year_suffix = ''
if string.match(f_part, "x[mijkot]$") then
-- for non-Gregorian year
f_part = f_part .. 'Y'
elseif idx < #f_parts then
-- supress leading zeros in year
year_suffix = lang_obj:formatDate('Y', timestamp)
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
end
local fdate
if addon ~= "" and prefix_addon then
fdate = addon .. addon_sep .. tstr
elseif addon ~= "" then
fdate = tstr .. addon_sep .. addon
else
fdate = tstr
end
 
return fdate
else
return printError("unknown-datetime-format")
end
return dates.objecttotext(datetable, params)
end
 
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local function withtargetvalue(claims, targetvalue)
-- use these as the second parameter and this function instead of the built-in "pairs" function
targetvalue = string.upper(targetvalue)
-- to iterate over all qualifiers and snaks in the intended order.
local oldclaims = claims
local function orderedpairs(array, order)
local claims = {}
if not order then for i, statement inreturn pairs(oldclaimsarray) doend
if samevalue(statement.mainsnak, targetvalue) then
table.insert(claims, statement)
end
end
return claims
end
 
-- return iterator function
local function validclaims(claims)
local oldclaimsi = claims0
return function()
local claims = {}
i = i + 1
for i, statement in pairs(oldclaims) do
if order[i] then
if statement.rank == 'preferred' or statement.rank == 'normal' then
return order[i], array[order[i]]
table.insert(claims, statement)
end
end
return claims
end
 
-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
local function withrank(claims, rank)
local function normalizeDate(date)
if rank == 'best' then
date = mw.text.trim(date, "+")
local preferred = withrank(claims, 'preferred')
-- extract year
if #preferred > 0 then
local yearstr = mw.ustring.match(date, "^\-?%d+")
return preferred
local year = tonumber(yearstr)
else
-- remove leading zeros of year
return withrank(claims, 'normal')
return year .. mw.ustring.sub(date, #yearstr + 1), year
end
end
if rank == 'valid' then
return validclaims(claims)
end
local oldclaims = claims
local claims = {}
for i, statement in pairs(oldclaims) do
if statement.rank == rank then
table.insert(claims, statement)
end
end
return claims
end
 
local function withqualifierformatDate(claimsdate, qualifierprecision, qualifiervaluetimezone)
precision = precision or 11
qualifier, qualifiervalue = string.upper(qualifier), string.upper(qualifiervalue or '')
local date, year = normalizeDate(date)
if year == 0 and precision <= 9 then return "" end
local oldclaims = claims
local claims = {}
for i, statement in pairs(oldclaims) do
if statement.qualifiers and statement.qualifiers then
if qualifiervalue ~= '' then
for j, qualif in pairs(statement.qualifiers[qualifier]) do
if p.getRawvalue(qualif) == qualifiervalue then
table.insert(claims, statement)
end
end
else
table.insert(claims, statement)
end
end
end
return claims
end
local function withsource(claims, source, sourceproperty)
local oldclaims = claims
local claims = {}
sourceproperty = string.upper(sourceproperty or 'P248')
local sourcevalue = string.upper(source or '')
for i, statement in pairs(oldclaims) do
local success
if statement.references then
for j, reference in pairs(statement.references) do
if success then break end -- sp that it does not return twice the same reference when the property is used twice
for prop, content in pairs(reference.snaks) do
if prop == sourceproperty then
if sourcevalue == '' then
table.insert(claims, statement)
success = true
else
for l, m in pairs(content) do
if p.getRawvalue(m) == source then
table.insert(claims, statement)
success = true
end
end
end
end
end
end
end
end
return claims
end
 
-- precision is 10000 years or more
local function isinlanguage(claims, lang) -- ne fonctionne que pour les monolingualtext / étendre aux autres types en utilisant les qualifiers ?
if precision <= 5 then
local newclaims = {}
local factor = 10 ^ ((5 - precision) + 4)
for i, j in pairs(claims) do
local y2 = math.ceil(math.abs(year) / factor)
if j.mainsnak.snaktype == 'value' and j.mainsnak.datavalue.type == 'monolingualtext' then
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if j.mainsnak.datavalue.value.language == lang then
if year < 0 then
table.insert(newclaims,j)
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
end
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end
return newclaims
end
 
-- precision is decades, centuries and millennia
local function excludespecial(claims)
local oldclaims = claimsera
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
local claims = {}
if precision == 7 then era = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(year) - 1) / 100) + 1)) end
for i, statement in pairs(oldclaims) do
if precision == 8 then era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(year) / 10) * 10)) end
if statement.mainsnak.snaktype == 'value' then
if era then
table.insert(claims, statement)
if year < 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
end
elseif year > 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era) end
end
return claimsera
end
 
-- precision is year
local function comparedate(a, b) -- returns true if a is earlier than B or if a has a date but not b
if aprecision and== b9 then
return a.timestamp < b.timestampyear
elseif a then
return true
end
end
 
-- precision is less than years
local function chronosort(claims, inverted)
if precision > 9 then
table.sort(claims, function(a,b)
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
local timeA = p.getDate(a)
timezone = tonumber(timezone)
local timeB = p.getDate(b)
if timezone and timezone ~= 0 then
if inverted then
timezone = -timezone
return comparedate(timeB, timeA)
timezone = string.format("%.2d%.2d", timezone / 60, timezone % 60)
else
if timezone[1] ~= '-' then timezone = "+" .. timezone end
return comparedate(timeA, timeB)
date = mw.text.trim(date, "Z") .. " " .. timezone
end
]]--
 
local formatstr = i18n.datetime[precision]
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
elseif year < 0 then
-- Mediawiki formatDate doesn't support negative years
date = mw.ustring.sub(date, 2)
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.bc, "$1", i18n.datetime[9]))
elseif year > 0 and i18n.datetime.ad ~= "$1" then
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.ad, "$1", i18n.datetime[9]))
end
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
)
end
return claims
end
 
local function p.sortclaimsprintDatavalueEntity(claimsdata, sorttypeparameter)
-- data fields: entity-type [string], numeric-id [int, Wikidata id]
if sorttype == 'chronological' then
local id
return chronosort(claims)
 
elseif sorttype == 'inverted' then
if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
return chronosort(claims, true)
elseif data["entity-type(sorttype)"] == 'function'"property" then id = "P" .. data["numeric-id"]
else return printError("unknown-entity-type")
table.sort(claims, sorttype)
end
return claims
 
if parameter then
if parameter == "link" then
local linkTarget = mw.wikibase.sitelink(id)
local linkName = mw.wikibase.label(id)
if linkTarget then
-- if there is a local Wikipedia article link to it using the label or the article title
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
else
-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
end
else
return data[parameter]
end
else
return mw.wikibase.label(id) or id
end
return claims
end
 
local function numvalprintDatavalueTime(claimsdata, numvalparameter)
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
local numval = tonumber(numval) or 0 -- raise a error if numval is not a positive integer ?
-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
local newclaims = {}
-- calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
for i, j in pairs(claims) do
if #newclaims == numvalparameter then
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
return newclaims
elseif parameter == "time" then data.time = normalizeDate(data.time) end
end
return data[parameter]
table.insert(newclaims,j)
else
end
return formatDate(data.time, data.precision, data.timezone)
return newclaims
end
end
 
local function printDatavalueMonolingualText(data, parameter)
function p.getRawvalue(snak)
-- data fields: language [string], text [string]
return p.getDatavalue(snak, {format = 'raw'})
if parameter then
return data[parameter]
else
local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
return result
end
end
 
local function p.getDatavaluefindClaims(snakentity, paramsproperty)
if not paramsproperty or not entity or not entity.claims then return end
 
params = {}
if mw.ustring.match(property, "^P%d+$") then
-- if the property is given by an id (P..) access the claim list by this id
return entity.claims[property]
else
-- otherwise, iterate over all properties, fetch their labels and compare this to the given property name
for k, v in pairs(entity.claims) do
if mw.wikibase.label(k) == property then return v end
end
return
end
end
local formatting = params.formatting
if snak.snaktype ~= 'value' then
return nil
end
local datatype = snak.datavalue.type
local value = snak.datavalue.value
local displayformat = params.format
if datatype == 'wikibase-entityid' then
if displayformat == 'raw' then
return "Q" .. tostring(value['numeric-id'])
else
return p.formatEntity('Q' .. value['numeric-id'], params)
end
elseif datatype == 'string' then
if params.displayformat == 'weblink' then
return require('Module:Weblink').makelink(value)
elseif params.urlpattern then
value = '[' .. mw.ustring.gsub(params.urlpattern, '$1', value) .. ' ' .. value .. ']'
end
return value
 
local function getSnakValue(snak, parameter)
elseif datatype == 'time' then -- format example: +00000001809-02-12T00:00:00Z
if snak.snaktype == "value" then
local precision = params.precision -- degré de précision à afficher ('day', 'month', 'year'), inférieur ou égal à value.precision
-- call the respective snak parser
if formatting == 'raw' then
if snak.datavalue.type == "string" then return snak.datavalue.value
return value.time
elseif snak.datavalue.type == "globecoordinate" then return printDatavalueCoordinate(snak.datavalue.value, parameter)
else
elseif snak.datavalue.type == "quantity" then return printDatavalueQuantity(snak.datavalue.value, parameter)
return dates.objecttotext(dates.dateobject(value))
elseif snak.datavalue.type == "time" then return printDatavalueTime(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "wikibase-entityid" then return printDatavalueEntity(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "monolingualtext" then return printDatavalueMonolingualText(snak.datavalue.value, parameter)
end
end
return mw.wikibase.renderSnak(snak)
end
 
local function getQualifierSnak(claim, qualifierId)
elseif datatype == 'globecoordinate' then
-- a "snak" is Wikidata terminology for a typed key/value pair
-- retourne une table avec clés latitude, longitude, précision et globe à formater par un autre module (à changer ?)
-- a claim consists of a main snak holding the main information of this claim,
value.globe = require('Module:Wikidata/Globes')[value.globe] -- transforme l'ID du globe en nom anglais utilisable par geohack
-- as well as a list of attribute snaks and a list of references snaks
if formatting == 'latitude' then
if qualifierId then
return value.latitude
-- search the attribute snak with the given qualifier as key
elseif formatting == 'longitude' then
if claim.qualifiers then
return value.longitude
local qualifier = claim.qualifiers[qualifierId]
else
if qualifier then return qualifier[1] end
return value -- note : les coordonnées Wikidata peuvent être utilisée depuis Module:Coordinates. Faut-il aussi autoriser à appeler Module:Coordiantes ici ?
end
return nil, printError("qualifier-not-found")
else
-- otherwise return the main snak
return claim.mainsnak
end
end
 
local function getValueOfClaim(claim, qualifierId, parameter)
elseif datatype == 'quantity' then
local error
if displayformat == 'raw' then
local snak
return value.amount
snak, error = getQualifierSnak(claim, qualifierId)
else
if snak then
local str = string.sub(value.amount,2) --
return getSnakValue(snak, parameter)
return str
else
end
return nil, error
elseif datatype == 'monolingualtext' then
end
return langmodule.langue({value.language, value.text})
else
return formatError('unknown-datavalue-type' )
end
end
 
local function getMultipleClaimsgetReferences(argsframe, claim)
local newargsresult = args""
-- traverse through all references
local claims = {}
for i, jref in pairs(argsclaim.propertyreferences or {}) do
local refparts
newargs.property = j
-- traverse through all parts of the current reference
local newclaims = p.getClaims(args)
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
for k, l in pairs(newclaims) do
if refparts then refparts = refparts .. ", " else refparts = "" end
table.insert(claims, l)
-- output the label of the property of the reference part, e.g. "imported from" for P143
refparts = refparts .. tostring(mw.wikibase.label(snakkey)) .. ": "
-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
for snakidx = 1, #snakval do
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts .. getSnakValue(snakval[snakidx])
end
end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
end
return claimsresult
end
function p.getClaims( args ) -- returns a table of the claims matching some conditions given in 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 args.entity = args.item end -- synonyms
local entity = args.entity
if type(entity) ~= 'table' then
entity = getEntity( args.entity )
end
if (not entity) or (not entity.claims) then
return nil
end
local property = string.upper(args.property)
local claims = entity.claims[property]
if not claims then return nil end
-- mettre ~= '' pour le cas ou le paramètre est écrit mais laissé blanc ({{#invoke:formatStatements|property=pXX|targetvalue = xx}})
if args.targetvalue and args.targetvalue ~= '' then
claims = withtargetvalue(claims, args.targetvalue)
end
 
if args.qualifier and args.qualifier ~= '' then
claims = withqualifier(claims, args.qualifier, args.qualifiervalue)
end
if (args.source and args.source ~= '') or (args.sourceproperty and args.sourceproperty ~= '') then
claims = withsource(claims, args.source, args.sourceproperty)
end
if (args.isinlanguage and args.isinlanguage ~= '') then
claims = isinlanguage(claims, args.inlanguage)
end
if args.excludespecial and args.excludespecial ~= '' then
claims = excludespecial(claims)
end
 
------------------------------------------------------------------------------
if args.rank ~= 'all' then
-- module global functions
if not args.rank or args.rank == '' then
 
args.rank = 'best'
if debug then
end
function p.inspectI18n(frame)
claims = withrank(claims, args.rank)
local val = i18n
end
for _, key in pairs(frame.args) do
key = mw.text.trim(key)
if args.sorttype then
val = val[key]
claims = p.sortclaims(claims, args.sorttype)
end
return val
if args.numval and args.numval ~= '' then --keep at the end, after other filters have been implmented
claims = numval(claims, args.numval)
end
if #claims > 0 then
return claims
end
end
 
function p.formatClaimListdescriptionIn(claims, argsframe)
local langcode = frame.args[1]
if not claims then
local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
return nil
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
end
return mw.wikibase.getEntityObject(id).descriptions[langcode or wiki.langcode].value
for i, j in pairs(claims) do
claims[i] = p.formatStatement(j, args)
end
return claims
end
 
function p.labelIn(frame)
function p.stringTable(args) -- like getClaims, but get a list of string rather than a list of snaks, for easier manipulation
local claimslangcode = pframe.getClaims(args)[1]
local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
return p.formatClaimList(claims, args)
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
return mw.wikibase.getEntityObject(id).labels[langcode or wiki.langcode].value
end
 
-- This is used to get a value, or a comma separated list of them if multiple values exist
p.getValue = function(frame)
local propertyID = mw.text.trim(frame.args[1] or "")
local input_parm = mw.text.trim(frame.args[2] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
local claims
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
-- if wiki-linked value output as link if possible
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
local out = {}
for k, v in pairs(claims) do
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
local label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"])
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
if sitelink then
local function getQualifiers(statement, qualifs, params)
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
if not statement.qualifiers then
else
return nil
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return table.concat(out, ", ")
else
-- just return best values
return entity:formatPropertyValues(propertyID).value
end
else
return ""
end
else
return input_parm
end
end
local vals = {}
 
for i, j in pairs(qualifs) do
-- Same as above, but uses the short name property for label if available.
if statement.qualifiers[j] then
p.getValueShortName = function(frame)
for k, l in pairs(statement.qualifiers[j]) do
local propertyID = mw.text.trim(frame.args[1] or "")
table.insert(vals, l)
local input_parm = mw.text.trim(frame.args[2] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
local claims
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
-- if wiki-linked value output as link if possible
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
local out = {}
for k, v in pairs(claims) do
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
local label
local claimEntity = mw.wikibase.getEntity("Q" .. v.mainsnak.datavalue.value["numeric-id"])
if claimEntity ~= nil then
if claimEntity.claims.P1813 then
for k2, v2 in pairs(claimEntity.claims.P1813) do
if v2.mainsnak.datavalue.value.language == "en" then
label = v2.mainsnak.datavalue.value.text
end
end
end
end
if label == nil or label == "" then label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"]) end
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
if sitelink then
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
else
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return table.concat(out, ", ")
else
-- just return best vakues
return entity:formatPropertyValues(propertyID).value
end
else
return ""
end
else
return input_parm
end
end
if #vals == 0 then
 
return nil
-- This is used to get a value, or a comma separated list of them if multiple values exist
-- from an arbitrary entry by using its QID.
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
-- Please use sparingly - this is an *expensive call*.
p.getValueFromID = function(frame)
local itemID = mw.text.trim(frame.args[1] or "")
local propertyID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity(itemID)
local claims = entity.claims[propertyID]
if claims then
-- if wiki-linked value output as link if possible
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
local out = {}
for k, v in pairs(claims) do
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
local label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"])
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
if sitelink then
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
else
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return table.concat(out, ", ")
else
return entity:formatPropertyValues(propertyID).value
end
else
return ""
end
else
return input_parm
end
end
return vals
end
 
p.getQualifierValue = function(frame)
function p.getFormattedQualifiers(statement, qualifs, params)
local propertyID = mw.text.trim(frame.args[1] or "")
if not params then params = {} end
local qualiftablequalifierID = getQualifiersmw.text.trim(statement,frame.args[2] qualifsor "")
local input_parm = mw.text.trim(frame.args[3] or "")
if not qualiftable then
if input_parm == "FETCH_WIKIDATA" then
return nil
local entity = mw.wikibase.getEntityObject()
if entity.claims[propertyID] ~= nil then
local out = {}
for k, v in pairs(entity.claims[propertyID]) do
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
if v2.snaktype == 'value' then
if (mw.wikibase.sitelink("Q" .. v2.datavalue.value["numeric-id"])) then
out[#out + 1] = "[[" .. mw.wikibase.sitelink("Q" .. v2.datavalue.value["numeric-id"]) .. "]]"
else
out[#out + 1] = "[[:d:Q" .. v2.datavalue.value["numeric-id"] .. "|" .. mw.wikibase.label("Q" .. v2.datavalue.value["numeric-id"]) .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
end
end
return table.concat(out, ", ")
else
return ""
end
else
return input_parm
end
end
for i, j in pairs(qualiftable) do
 
qualiftable[i] = p.formatSnak(j, params)
-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
p.getRawValue = function(frame)
local propertyID = mw.text.trim(frame.args[1] or "")
local input_parm = mw.text.trim(frame.args[2] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
local claims
if entity and entity.claims then claims = entity.claims[propertyID] end
if claims then
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
 
-- if number type: remove thousand separators, bounds and units
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
result = mw.ustring.gsub(result, "(%d)±.*", "%1")
end
return result
else
return ""
end
else
return input_parm
end
return linguistic.conj(qualiftable, params)
end
 
-- This is used to get the unit name for the numeric value returned by getRawValue
function p.formatStatement( statement, args )
p.getUnits = function(frame)
if not statement.type or statement.type ~= 'statement' then
local propertyID = mw.text.trim(frame.args[1] or "")
return formatError( 'unknown-claim-type' )
local input_parm = mw.text.trim(frame.args[2] or "")
end
if input_parm == "FETCH_WIKIDATA" then
local str = p.formatSnak( statement.mainsnak, args )
local entity = mw.wikibase.getEntityObject()
if args.showqualifiers then
local claims
local qualifs = args.showqualifiers
if entity and entity.claims then claims = entity.claims[propertyID] end
if type(qualifs) == 'string' then
if claims then
qualifs = mw.text.split(qualifs, ',')
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
end
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
local foundvalues = p.getFormattedQualifiers(statement, qualifs, args)
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
if foundvalues then
end
str = str .. linguistic.inparentheses(foundvalues, lang)
return result
else
return ""
end
else
return input_parm
end
end
if args.showdate then -- when "withdate and chronosort are both set, date retrieval is performed twice
local timedata = p.getDate(statement)
if timedata then
local formatteddate = dates.objecttotext(timedata, args)
formattteddate = linguistic.inparentheses(formatteddate, lang)
str = str .. '<small>' .. formattteddate ..'</small>'
end
end
 
-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
if args.showsource and statement.references then --[[needs abritrary access
p.getUnitID = function(frame)
local sourcestring = ''
local propertyID = mw.text.trim(frame.args[1] or "")
for i, ref in pairs(statement.references) do
local input_parm = mw.text.trim(frame.args[2] or "")
if ref.snaks.P248 then
if input_parm == "FETCH_WIKIDATA" then
for j, source in pairs(ref.snaks.P248) do
local entity = mw.wikibase.getEntityObject()
if source.snaktype == 'value' then
local pageclaims
if entity and entity.claims then claims = entity.claims[propertyID] end
if ref.snaks.P304 and ref.snaks.P304[1].snaktype == 'value' then
if claims then
page = ref.snaks.P304[1].datavalue.value
local result
end
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
local s = require('Module:Cite/sandbox').citeitem('Q' .. source.datavalue.value['numeric-id'], lang, page)
-- get the url for the unit entry on Wikidata:
s = mw.getCurrentFrame():extensionTag( 'ref', s )
result = claims[1].mainsnak.datavalue.value.unit
sourcestring = sourcestring .. s
-- and just reurn the last bit from "Q" to the end (which is the QID):
end
result = mw.ustring.sub(result, mw.ustring.find(result, "Q"), -1)
end
end
elseif ref.snaks.P854 and ref.snaks.P854[1].snaktype == 'value' then
return result
s = mw.getCurrentFrame():extensionTag( 'ref', formatLink(ref.snaks.P854[1].datavalue.value))
else
sourcestring = sourcestring .. s
return ""
end
end
else
str = str .. sourcestring ]]--
return input_parm
end
end
return str
end
 
p.getRawQualifierValue = function(frame)
function p.formatSnak( snak, params )
local propertyID = mw.text.trim(frame.args[1] or "")
if not args then args = {} end -- pour faciliter l'appel depuis d'autres modules
local qualifierID = mw.text.trim(frame.args[2] or "")
if snak.snaktype == 'somevalue' then
local input_parm = mw.text.trim(frame.args[3] or "")
return formatTheUnknown()
if input_parm == "FETCH_WIKIDATA" then
elseif snak.snaktype == 'novalue' then
local entity = mw.wikibase.getEntityObject()
return i18n['novalue'] --todo
if entity.claims[propertyID] ~= nil then
elseif snak.snaktype == 'value' then
local out = {}
return p.getDatavalue( snak, params)
for k, v in pairs(entity.claims[propertyID]) do
else
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
return formatError( 'unknown-snak-type' )
if v2.snaktype == 'value' then
end
if v2.datavalue.value["numeric-id"] then
out[#out + 1] = mw.wikibase.label("Q" .. v2.datavalue.value["numeric-id"])
else
out[#out + 1] = v2.datavalue.value
end
end
end
end
local ret = table.concat(out, ", ")
return string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
else
return ""
end
else
return input_parm
end
end
 
-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
function p._getLabel(entity, default, inlanguage)
-- Dates and times are stored in ISO 8601 format (sort of).
local label
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
if not entity then
-- So I'll just supply "Z" in the call to formatDate below:
return nil
p.getDateValue = function(frame)
end
local propertyID = mw.text.trim(frame.args[1] or "")
if inlanguage then -- cherche dans l'élément complet s'il est déjà chargé, ou s'il faut une libellé non-français, inacessible par mw.wikibase.label
local input_parm = mw.text.trim(frame.args[2] or "")
entity = getEntity(entity)
local date_format = mw.text.trim(frame.args[3] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[4] or i18n["datetime"]["default-addon"])
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
if entity.claims[propertyID] ~= nil then
local out = {}
for k, v in pairs(entity.claims[propertyID]) do
if v.mainsnak.datavalue.type == 'time' then
local timestamp = v.mainsnak.datavalue.value.time
local dateprecision = v.mainsnak.datavalue.value.precision
out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
end
end
return table.concat(out, ", ")
else
return ""
end
else
return input_parm
end
end
if type(entity) == 'table' then
 
if entity and entity.labels and entity.labels[lang] then
p.getQualifierDateValue = function(frame)
label = entity.labels[lang].value
local propertyID = mw.text.trim(frame.args[1] or "")
local qualifierID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
if entity.claims[propertyID] ~= nil then
local out = {}
for k, v in pairs(entity.claims[propertyID]) do
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
if v2.snaktype == 'value' then
local timestamp = v2.datavalue.value.time
out[#out + 1] = parseDateValue(timestamp, date_format, date_addon)
end
end
end
return table.concat(out, ", ")
else
return ""
end
else
return input_parm
label = mw.wikibase.label(entity)
end
if label then
return label
end
if default == 'nolabel' then
return i18n['no-label']
end
return entity.id
end
 
-- This is used to fetch all of the images with a particular property, e.g. image (P18), Gene Atlas Image (P692), etc.
function p._getDescription(entity, lang)
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
if type(entity) ~= 'table' then
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
entity = getEntity(entity)
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
p.getImages = function(frame)
local propertyID = mw.text.trim(frame.args[1] or "")
local input_parm = mw.text.trim(frame.args[2] or "")
local sep = mw.text.trim(frame.args[3] or " ")
local imgsize = mw.text.trim(frame.args[4] or "frameless")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntityObject()
local claims
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
if (claims[1] and claims[1].mainsnak.datatype == "commonsMedia") then
local out = {}
for k, v in pairs(claims) do
local filename = v.mainsnak.datavalue.value
out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
end
return table.concat(out, sep)
else
return ""
end
else
return ""
end
else
return input_parm
end
if not entity.descriptions then
return i18n['no description']
end
local descriptions = entity.descriptions
if not descriptions then
return nil
end
if descriptions[lang] then
return descriptions[lang].value
end
local fblist = require('Module:Fallback').fblist(lang) -- list of fallback languages in no label in the desired language
for i, j in pairs (mw.language.getFallbacksFor(lang)) do
if descriptions.lang then
return descriptions[lang].value
end
end
if default == 'nolabel' then
return i18n['no-label']
end
return entity.id
end
 
-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
local function formattedLabel(label, entity, args)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
if args.link== '-' then
-- uses the newer mw.wikibase calls instead of directly using the snaks
return label
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
end
p.getTAValue = function(frame)
local link = mw.wikibase.sitelink( entity )
local ent = mw.wikibase.getEntityObject()
if not link then
local props = ent:formatPropertyValues('P1323')
link = 'd:' .. entity
local out = {}
local t = {}
for k, v in pairs(props) do
if k == 'value' then
t = mw.text.split( v, ", ")
for k2, v2 in pairs(t) do
out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
end
end
end
local ret = table.concat(out, "<br> ")
if #ret == 0 then
ret = "Invalid TA"
end
return ret
return '[[' .. link .. '|' .. label .. ']]'
end
 
--[[
This is used to return an image legend from Wikidata
image is property P18
image legend is property P2096
 
Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
function p.getmainid(claim)
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
if claim and claim.mainsnak.snaktype == 'value' then
If QID is omitted or blank, the current article is used (not an expensive call)
return 'Q' .. claim.mainsnak.datavalue.value['numeric-id']
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447
 
Ranks are: 'preferred' > 'normal'
This returns the label from the first image with 'preferred' rank
Or the label from the first image with 'normal' rank if preferred returns nothing
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
]]
 
p.getImageLegend = function(frame)
-- look for named parameter id; if it's blank make it nil
local id = frame.args.id
if id and (#id == 0) then
id = nil
end
 
-- look for named parameter lang
-- it should contain a two-character ISO-639 language code
-- if it's blank fetch the language of the local wiki
local lang = frame.args.lang
if (not lang) or (#lang < 2) then
lang = mw.language.getContentLanguage().code
end
 
-- first unnamed parameter is the local parameter, if supplied
local input_parm = mw.text.trim(frame.args[1] or "")
if input_parm == "FETCH_WIKIDATA" then
local ent = mw.wikibase.getEntityObject(id)
local imgs
if ent and ent.claims then
imgs = ent.claims.P18
end
local imglbl
if imgs then
-- look for an image with 'preferred' rank
for k1, v1 in pairs(imgs) do
if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
-- if we don't find one, look for an image with 'normal' rank
if (not imglbl) then
for k1, v1 in pairs(imgs) do
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
end
end
return imglbl
else
return input_parm
end
end
 
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.formatEntity( entity, args )
function p.pageId(frame)
local label = p._getLabel(entity, lang)
local entity = mw.wikibase.getEntityObject()
if not label then
if not entity then labelreturn =nil else return entity.id end
end
return formattedLabel(label, entity, args)
end
 
function p.claim(frame)
local property = frame.args[1] or ""
local id = frame.args["id"] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
local qualifierId = frame.args["qualifier"]
local parameter = frame.args["parameter"]
local list = frame.args["list"]
local references = frame.args["references"]
local showerrors = frame.args["showerrors"]
local default = frame.args["default"]
if default then showerrors = nil end
 
-- get wikidata entity
function p.getLabel(frame) -- simple for simple templates like {{Q|}}}
local argsentity = framemw.argswikibase.getEntityObject(id)
if localnot entity = args.entitythen
if showerrors then return printError("entity-not-found") else return default end
local lang = lang
end
if args.lang and args.lang ~= '' then
-- fetch the first claim of satisfying the given property
lang = args.lang
local claims = findClaims(entity, property)
end
if not claims or not claims[1] then
if string.sub(entity, 1, 10) == 'Property:P' then
if showerrors then return printError("property-not-found") else return default end
entity = string.sub(entity, 10)
end
elseif (string.sub(entity, 1, 1) ~= 'P' and string.sub(entity, 1, 1) ~= 'Q') or (not tonumber(string.sub(entity, 2))) then
return i18n.errors['invalid-id']
end
if not args.link or args.link == '' then -- by default: no link
args.link = '-'
end
if args.link == '-' then
return p._getLabel(entity, lang) or i18n.errors['invalid-id']
else
lang = lang
return p.formatEntity(entity, args)
end
end
 
-- get initial sort indices
function p._formatStatements( args )--Format statement and concat them cleanly
local sortindices = {}
if args.value == '-' then
for idx in pairs(claims) do
return nil
sortindices[#sortindices + 1] = idx
end
-- sort by claim rank
--If a value is already set, use it
local comparator = function(a, b)
if args.value and args.value ~= '' then
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
return args.value
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
return ranka < rankb
end
table.sort(sortindices, comparator)
local valuetable = p.stringTable(args)
return tableToText(valuetable, args)
end
 
local result
function p._formatAndCat(args)
local error
local val = p._formatStatements( args )
if vallist then
local value
return val .. addtrackingcat(args.property)
-- iterate over all elements and return their value (if existing)
result = {}
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
value, error = getValueOfClaim(claim, qualifierId, parameter)
if not value and showerrors then value = error end
if value and references then value = value .. getReferences(frame, claim) end
result[#result + 1] = value
end
result = table.concat(result, list)
else
-- return first element
local claim = claims[sortindices[1]]
result, error = getValueOfClaim(claim, qualifierId, parameter)
if result and references then result = result .. getReferences(frame, claim) end
end
 
if result then return result else
if showerrors then return error else return default end
end
end
 
-- look into entity object
function p.getTheDate(args)
function p.ViewSomething(frame)
local claims = p.getClaims(args)
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
if not claims then
local id = f.args.id
if id and (#id == 0) then
id = nil
end
local data = mw.wikibase.getEntityObject(id)
if not data then
return nil
end
 
local formattedvalues = {}
local i = 1
for i, j in pairs(claims) do
while true do
table.insert(formattedvalues, p.getFormattedDate(j))
local index = f.args[i]
if not index then
if type(data) == "table" then
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
else
return tostring(data)
end
end
 
data = data[index] or data[tonumber(index)]
if not data then
return
end
 
i = i + 1
end
return linguistic.conj(formattedvalues)
end
---FONCTIONS depuis le FRAME
function p.getaDate(frame)
return p.getTheDate(frame.args)
end
 
-- getting sitelink of a given wiki
 
function p.getQualifiergetSiteLink( frame )
local claimsf = p.getClaims(frame.args)[1]
local strentity = ''mw.wikibase.getEntity()
if not entity then
local qualifs = frame.args.qualifiers or frame.args.qualifier
return
if not qualifs then
return formatError( 'property-param-not-provided' )
end
local link = entity:getSitelink( f )
qualifs = mw.text.split(qualifs, ',')
if not link then
for i, j in pairs(claims) do
return
local new = p.getFormattedQualifiers(j, qualifs) or ''
str = str .. new
end
return strlink
end
 
function p.getDescriptionDump(frame) -- simple for simple templates like {{Q|}}}
local entityf = (frame.args[1] or frame.entityargs.id) and frame or frame:getParent()
local data = mw.wikibase.getEntityObject(f.args.id)
if frame.args.lang then
if not data then
lang = frame.args.lang
return i18n.warnDump
end
end
if (string.sub(entity, 1, 1) ~= 'P' and string.sub(entity, 1, 1) ~= 'Q') or (not tonumber(string.sub(entity, 2))) then
return i18n.errors['invalid-id']
end
return p._getDescription(entity, lang) or i18n.errors['invalid-id']
end
 
local i = 1
function p.numOfClaims(frame)
while true do
local claims = p.getClaims(frame.args)
local index = f.args[i]
if claims then
if not index then
return #claims
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
else
end
return 0
end
end
 
data = data[index] or data[tonumber(index)]
function p.formatStatements( frame )
if not data then
local args = {}
return i18n.warnDump
if frame == mw.getCurrentFrame() then
args = frame:getParent().args -- paramètres du modèle appelant (est-ce vraiment une bonne idée ?)
for k, v in pairs(frame.args) do
args[k] = v
end
 
else
argsi = framei + 1
end
return p._formatStatements( args )
end