Mòdul:Wikidata: diferència entre les revisions

De Viquidites
Contingut suprimit Contingut afegit
actualització, correccions i millores menors
actualització de ca.wiki, millores menors
Línia 1: Línia 1:
-- version 20180809 from master @cawiki
-- version 20180819 from master @cawiki


local p = {}
local p = {}
Línia 64: Línia 64:


local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]

local wiki =
{
langcode = mw.language.getContentLanguage().code,
module_title = "Module:Wikidata"
}


----------------------------------------------------------------------------
----------------------------------------------------------------------------
Línia 86: Línia 92:


local function loadI18n()
local function loadI18n()
local exist, res = pcall(require, "Module:Wikidata/i18n")
local exist, res = pcall(require, wiki.module_title .. "/i18n")
if exist and next(res) ~= nil then
if exist and next(res) ~= nil then
tableMerge(i18n, res.i18n)
tableMerge(i18n, res.i18n)
Línia 95: Línia 101:
loadI18n()
loadI18n()


local function case(word, localcase, lang)
local wiki =
if word == nil or word == '' or cases[localcase] == nil then
{
return word
langcode = mw.language.getContentLanguage().code
end
}
return cases[localcase](word, lang)
end


local function findLang(langcode)
local function findLang(langcode)
Línia 107: Línia 116:
langcode = myframe:getParent().args.lang
langcode = myframe:getParent().args.lang
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
if not mw.title.new(myframe:getParent():getTitle()).isContentPage then
if not mw.title.getCurrentTitle().isContentPage then
langcode = myframe:preprocess( '{{int:lang}}' )
langcode = myframe:preprocess( '{{int:lang}}' )
end
end
Línia 119: Línia 128:
table.insert(languages, 1, langcode)
table.insert(languages, 1, langcode)
return languages
return languages
end

local function case(word, localcase, lang)
if word == nil or word == '' or cases[localcase] == nil then
return word
end
return cases[localcase](word, lang)
end
end


Línia 166: Línia 167:
if feminine_claims then
if feminine_claims then
for _, feminine_claim in ipairs(feminine_claims) do
for _, feminine_claim in ipairs(feminine_claims) do
local feminine_value = getValueOfClaim(feminine_claim, nil, {["formatting"]=lang, ["lang"]={lang}})
local feminine_value = getValueOfClaim(feminine_claim, nil, {["list"]="lang", ["lang"]={lang}})
if feminine_value then
if feminine_value then
return feminine_value
return feminine_value
Línia 172: Línia 173:
end
end
end
end
end

-- Fetch unit symbol
local function unitSymbol(id, lang)
local claims = findClaims(mw.wikibase.getEntityObject(id), 'P5061')
local langclaims = {}
if claims then
for _, snak in ipairs(claims) do
if snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value and
not langclaims[snak.mainsnak.datavalue.value.language] -- just the first one by language
then
langclaims[snak.mainsnak.datavalue.value.language] = snak.mainsnak.datavalue.value.text
end
end
for _, l in ipairs(lang) do
if langclaims[l] then
return langclaims[l]
end
end
end
return langclaims["mul"] -- last try
end
end


Línia 226: Línia 248:
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', escaped_data), parameters.formatting)
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', escaped_data), parameters.formatting)
elseif parameters.case then
elseif parameters.case then
return case(data, parameters.case, wiki.langcode)
return case(data, parameters.case, parameters.lang[1])
else
else
return data
return data
Línia 262: Línia 284:
amount = mw.ustring.gsub(amount, "%+", "")
amount = mw.ustring.gsub(amount, "%+", "")
local sortkey = string.format("%09d", amount)
local sortkey = string.format("%09d", amount)
amount = mw.language.new(wiki.langcode):formatNum(tonumber(amount))
amount = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
-- This is used to get the unit name for a numeric value
-- This is used to get the unit name for a numeric value
local suffix = ""
local suffix = ""
Línia 271: Línia 293:
unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)
unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)
if mw.ustring.sub(unitID, 1, 1) == "Q" then
if mw.ustring.sub(unitID, 1, 1) == "Q" then
local unit_label = mw.wikibase.label(unitID)
local unit_label, lang = getLabelByLangs(unitID, parameters.lang)
local unit_symbol
if pcall(require, "Module:Wikidata/Units") then
suffix = " " .. require("Module:Wikidata/Units").getUnit(amount, unit_label, unitID, parameters.formatting == "unitcode")
if parameters.formatting == "unitcode" then
unit_symbol = unitSymbol(unitID, parameters.lang)
end
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
suffix = " " .. require(wiki.module_title .. "/Units").getUnit(amount, unit_label, unitID, parameters.formatting == "unitcode", unit_symbol)
elseif parameters.formatting == "unitcode" then
suffix = " " .. unit_symbol or unit_label or unitID
else
else
suffix = " " .. unit_label or unitID
suffix = " " .. unit_label or unitID
Línia 289: Línia 317:
-- calendar model
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
local calendar_add = ""
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
local calendar_add = ""
if (timestamp < "+1582-10-15T00:00:00Z" and (calendar_id == "Q12138" or calendar_id == "Q1985727"))
or (timestamp > "+1582-10-04T00:00:00Z" and (calendar_id == "Q11184" or calendar_id == "Q1985786"))
if (timestamp < "+1582-10-15T00:00:00Z" and calendar_model[calendar_id] == "gregorian")
or (timestamp > "+1582-10-04T00:00:00Z" and calendar_model[calendar_id] == "julian")
then
then
calendar_add = " <sup>(" .. mw.message.new('Wikibase-time-calendar-' .. calendar_model[calendar_id]):inLanguage(parameters.lang[1]):plain() .. ")</sup>"
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
calendar_add = " <sup>(" .. mw.message.new('Wikibase-time-calendar-' .. calendar_model[calendar_id]):inLanguage(wiki.langcode):plain() .. ")</sup>"
end
end
Línia 307: Línia 335:
addon = addon .. calendar_add
addon = addon .. calendar_add
local function d(f, t)
local function d(f, t)
return mw.language.new(wiki.langcode):formatDate(f, t or timestamp) .. addon
return mw.language.new(parameters.lang[1]):formatDate(f, t or timestamp) .. addon
end
end
local precision = data.precision or 11
local precision = data.precision or 11
Línia 358: Línia 386:


local function printDatavalueEntity(data, parameters)
local function printDatavalueEntity(data, parameters)
local entityId = "Q" .. tostring(data['numeric-id'])
local entityId = data['id']
local entityIdPreffix = data['entity-type'] == 'property' and "Property:" .. entityId or entityId
if parameters.formatting == 'raw' then
if parameters.formatting == 'raw' then
return entityId, entityId
return entityId, entityId
end
end
local label, lang = mw.wikibase.getLabelWithLang(entityId)
local label, lang = getLabelByLangs(entityId, parameters.lang)
local sitelink = mw.wikibase.sitelink(entityId)
local sitelink = mw.wikibase.sitelink(entityId)
local parameter = parameters.formatting
local parameter = parameters.formatting
Línia 374: Línia 403:
local ret1, ret2
local ret1, ret2
if parameter == 'label' then
if parameter == 'label' then
ret1 = labelcase or entityId
ret1 = (labelcase or entityId)
ret2 = labelcase or entityId
ret2 = labelcase or entityId
elseif parameter == 'sitelink' then
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'wikidata:' .. entityId)
ret1 = (sitelink or 'wikidata:' .. entityIdPreffix)
ret2 = sitelink or entityId
ret2 = sitelink or entityId
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
Línia 401: Línia 430:
ret2 = labelcase
ret2 = labelcase
else
else
ret1 = '[[wikidata:' .. entityId .. '|' .. (labelcase or entityId) .. ']]'
ret1 = '[[wikidata:' .. entityIdPreffix .. '|' .. (labelcase or entityId) .. ']]'
ret2 = labelcase or entityId
ret2 = labelcase or entityId
end
end
end
end
return ret1 .. addEditIcon(entityIdPreffix, lang, parameters.lang[1], parameters.editicon), ret2
return ret1, ret2
end
end


local function printDatavalueMonolingualText(data, parameters)
local function printDatavalueMonolingualText(data, parameters)
-- data fields: language [string], text [string]
-- data fields: language [string], text [string]
local result = nil
-- temporary track for migration to list=lang
if parameters.formatting == "language" or parameters.formatting == "text" then
result = data[parameters.formatting]
local oldformatting = parameters.formatting and
elseif parameters.formatting then
not (parameters.formatting == "language" or parameters.formatting == "text") and
not mw.ustring.find(parameters.formatting, '$', 1, true)
if data["language"] == wiki.langcode then
if oldformatting then
result = data["text"]
require('Mòdul:utilitats').rastreig("Wikidata/monolingualtext")
end
end
else
if (parameters.list == "lang" or oldformatting) and data["language"] ~= parameters.lang[1] then
return
elseif parameters.formatting == "language" or parameters.formatting == "text" then
return data[parameters.formatting]
end
local result = data["text"]
if data["language"] ~= wiki.langcode then
result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
end
if mw.ustring.find((parameters.formatting or ''), '$', 1, true) then
-- output format defined with $text, $language
result = mw.ustring.gsub(parameters.formatting, '$text', result)
result = mw.ustring.gsub(result, '$language', data["language"])
end
end
return result
return result
Línia 478: Línia 520:
return printDatavalueMonolingualText(snak.datavalue.value, parameters)
return printDatavalueMonolingualText(snak.datavalue.value, parameters)
end
end
elseif snak.snaktype == 'novalue' then
return mw.message.new('Wikibase-snakview-snaktypeselector-novalue'):inLanguage(parameters.lang[1]):plain()
elseif snak.snaktype == 'somevalue' then
return mw.message.new('Wikibase-snakview-snaktypeselector-somevalue'):inLanguage(parameters.lang[1]):plain()
end
end
return mw.wikibase.renderSnak(snak)
return mw.wikibase.renderSnak(snak)
Línia 491: Línia 537:
local qualifier = claim.qualifiers[qualifierId]
local qualifier = claim.qualifiers[qualifierId]
if qualifier then
if qualifier then
-- iterate over monolingualtext qualifiers to get local language
if qualifier[1].datatype == "monolingualtext" then
-- iterate over monolingualtext qualifiers to get local language
for idx in pairs(qualifier) do
for idx in pairs(qualifier) do
if qualifier[idx].datavalue and qualifier[idx].datavalue.value and qualifier[idx].datavalue.value.language then
if qualifier[idx].datavalue.value.language == wiki.langcode then
if qualifier[idx].datavalue.value and qualifier[idx].datavalue.value.language == parameters.lang[1] then
return qualifier[idx]
return qualifier[idx]
end
end
Línia 562: Línia 608:
for snakidx = 1, #snakval do
for snakidx = 1, #snakval do
if snakidx > 1 then refparts = refparts .. ", " end
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {})
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang="wiki.langcode"})
end
end
refs[snakkey] = refparts
refs[snakkey] = refparts
Línia 639: Línia 685:
-- arguments
-- arguments
local id = args["item"] or (pargs and pargs["item"]); if id == "" then id = nil end
local id = args.item or (pargs and pargs.item); if id == "" then id = nil end
local languages = findLang(args.lang)
local idgender = args["itemgender"]
local idgender = args["itemgender"]
if idgender and not string.match(idgender, "^Q%d+$") then -- id malformed, maybe "unknown value"
if idgender and not string.match(idgender, "^Q%d+$") then -- id malformed, maybe "unknown value"
Línia 654: Línia 701:
local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
local case = args.case
local case = args.case
local list = args["list"] or true; if list == "false" then list = false end
local list = args["list"] or true; if (list == "false" or list == "no") then list = false end
local sorting_col = args.tablesort
local sorting_col = args.tablesort
local sorting_up = (args.sorting or "") ~= "-1"
local sorting_up = (args.sorting or "") ~= "-1"
Línia 663: Línia 710:
local showerrors = args["showerrors"]
local showerrors = args["showerrors"]
local default = args["default"]
local default = args["default"]
local editicon = not (args.editicon == "false" or args.editicon == "no")
local parameters = {["formatting"] = parameter, ["list"] = list, ["case"] = case,
local parameters = {["formatting"] = parameter, ["list"] = list, ["case"] = case, ["lang"] = languages, ["editicon"] = editicon,
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
local preformat = ""
local preformat = ""
Línia 738: Línia 786:
parameters.separator = parameters.separator == "LF" and "\010" or parameters.separator
parameters.separator = parameters.separator == "LF" and "\010" or parameters.separator
parameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction
parameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction
-- i18n separators
parameters.separator = parameters.separator or mw.message.new('Comma-separator'):inLanguage(parameters.lang[1]):plain()
parameters.conjunction = parameters.conjunction or (mw.message.new('And'):inLanguage(parameters.lang[1]):plain() .. mw.message.new('Word-separator'):inLanguage(parameters.lang[1]):plain())
-- iterate over all elements and return their value (if existing)
-- iterate over all elements and return their value (if existing)
local value, valueq
local value, valueq
Línia 955: Línia 1.006:
end
end


local function getPropertyValue(id, property, parameter)
local function getPropertyValue(id, property, parameter, langs, editicon)
local entity = mw.wikibase.getEntityObject(id)
local entity = mw.wikibase.getEntityObject(id)
if not (entity and entity.claims) then return end
if not (entity and entity.claims) then return end
Línia 981: Línia 1.032:
if snak.datavalue then
if snak.datavalue then
entityId = "Q" .. tostring(snak.datavalue.value['numeric-id'])
entityId = "Q" .. tostring(snak.datavalue.value['numeric-id'])
result, _ = getSnakValue(snak, {formatting=parameter})
result, _ = getSnakValue(snak, {formatting=parameter, lang=langs, editicon=editicon})
end
end
Línia 989: Línia 1.040:
function p.getParentValues(frame)
function p.getParentValues(frame)
local args = frame.args
local args = frame.args
local id = args["item"] or frame:getParent().args["item"]; if id == "" then id = nil end
local id = args.item or frame:getParent().args.item; if id == "" then id = nil end
local languages = findLang()
local propertySup = args["property"]; if (propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entity
local propertySup = args["property"]; if (propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entity
local propertyLabel = args["label"]; if (propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instance
local propertyLabel = args["label"]; if (propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instance
Línia 998: Línia 1.050:
local separator = args["separator"]; if (separator == nil or separator == "") then separator = "<br />" end
local separator = args["separator"]; if (separator == nil or separator == "") then separator = "<br />" end
local sorting = args["sorting"]; if sorting == "" then sorting = nil end
local sorting = args["sorting"]; if sorting == "" then sorting = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local lastlabel = uc_first(upto or '')
local lastlabel = uc_first(upto or '')
Línia 1.014: Línia 1.067:
for iter = 1, maxloop do
for iter = 1, maxloop do
local label, link
local label, link
id, link = getPropertyValue(id, propertySup, "internallink")
id, link = getPropertyValue(id, propertySup, "internallink", languages, editicon)
if id then
if id then
_, label = getPropertyValue(id, propertyLabel, "label")
_, label = getPropertyValue(id, propertyLabel, "label", languages)
if label and link then
if label and link then
if propertyLink then
if propertyLink then
_, linktext = getPropertyValue(id, propertyLink, "label")
_, linktext = getPropertyValue(id, propertyLink, "label", languages)
if linktext then
if linktext then
link = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")
link = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")
end
end
end
end
label = case(label, "infoboxlabel")
label = case(label, "infoboxlabel", languages[1])
if labelShow == nil or labelFilter[label] then
if labelShow == nil or labelFilter[label] then
result[#result + 1] = {label, link}
result[#result + 1] = {label, link}
Línia 1.099: Línia 1.152:
local comparator = function(a, b)
local comparator = function(a, b)
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
return ranka < rankb
return ranka < rankb
end
end
Línia 1.189: Línia 1.242:
local editicon = not (args.editicon == "false" or args.editicon == "no")
local editicon = not (args.editicon == "false" or args.editicon == "no")
local languages = findLang()
local languages = findLang()
local label, lang
if languages[1] == wiki.langcode and args.fixed then
label = require("Module:Wikidata/labels").infoboxLabelsFromId[id] -- exceptions or labels fixed
end
local pencil = ''
local pencil = ''
if label == nil then
local label, lang
if args.label then
label, lang = getLabelByLangs(id, languages)
if label then
label = args.label
else
if args.itemgender and feminineGender(args.itemgender) then
local languages = findLang()
label = feminineForm(id, lang) or label
if languages[1] == wiki.langcode then
-- exceptions or labels fixed
local exist, labels = pcall(require, wiki.module_title .. "/labels")
if exist and next(labels.infoboxLabelsFromId) ~= nil then
label = labels.infoboxLabelsFromId[id]
end
end
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
end
pencil = addEditIcon(id, lang, languages[1], editicon)
if label == nil then
label, lang = getLabelByLangs(id, languages)
if label then
if args.itemgender and feminineGender(args.itemgender) then
label = feminineForm(id, lang) or label
end
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
pencil = addEditIcon(id, lang, languages[1], editicon)
end
end
end
Línia 1.214: Línia 1.276:
return (label or id) .. pencil
return (label or id) .. pencil
end
end
end

-- Return default language used
function p.lang(frame)
return findLang(frame.args[1])[1]
end
end



Revisió del 14:18, 23 maig 2019

Aquest mòdul extrau dades formatades de Wikidata. Funciona en la llengua local del wiki, o en una llengua específica per a proves, i té opcions de configuració.

Funcions

Funció bàsica:

  • claim: Retorna el valor (o els valors) d'una declaració o d'un qualificador formatat amb paràmetres o amb un format per defecte segons el tipus de dada.

Altres funcions:

  • getLabel: retorna una etiqueta en la llengua especificada, o la llengua per defecte.
  • getParentValues: retorna etiquetes i valors superiors d'una propietat de forma recursiva.
  • linkWithParentLabel: crea un enllaç amb l'etiqueta d'una propietat superior. Per exemple per enllaçar autor taxonòmic (P405) amb l'etiqueta abreviatura d'autor en zoologia (P835) definida en el corresponent ítem superior.
  • yearsOld: retorna l'edat d'una persona: diferència entre data de naixement (P569) i data de defunció (P570), quan estan les dues propietats; o diferència entre data de naixement (P569) i la data d'avui, si no hi ha P570. Retorna una (nn) o dues xifres (nn/mm) segons la precisió de les dates. No retorna res quan alguna de les dues està expressada en segles.
  • getTAValue: retorna els valors de TA98 (Terminologia Anatomica primera edició 1998) de la propietat P1323. No pren paràmetres i retorna una llista amb cada valor enllaçat a la font externa.

Altres utilitats: getSiteLink, lang, numStatements.

Funció claim

Retorna el valor (o els valors) d'una declaració o d'un qualificador formatat amb paràmetres o amb un format per defecte segons el tipus de dada. Per defecte està referit a l'ítem de Wikidata (Qid) associat a la pàgina actual.

Sintaxi completa:

{{#invoke:Wikidata|claim|item= |lang= |property= |qualifier= |value= |list= |tablesort= |formatting= |separator= |conjunction= |editicon= |showerrors= |default= }}

Sintaxi addicional pel format de taula:

{{#invoke:Wikidata|claim|item= |lang= |property= |qualifier= |qualifier2= |...|qualifierx= |formatting=table |tablesort= |sorting= |rowformat= |rowsubformat1= |...|rowsubformatx= |colformat0= |...|colformatx= |case0= |...|casex= |separator= |conjunction= |editicon= |showerrors= |default= |references= }}

Paràmetres generals

  • item= (opcional) Permet indicar un ítem (Qid) diferent a l'ítem associat a la pàgina actual. Cal fer-lo servir amb moderació pel seu alt consum de recursos. Es pot usar també com a paràmetre de l'entorn superior de la plantilla. Té com a àlies from.
  • lang= (opcional) Permet indicar el codi d'una llengua determinada. Es pot usar també com a paràmetre de l'entorn superior de la plantilla. Per defecte usa la llengua local del wiki per a l'espai principal d'articles o la llengua d'usuari definida en les preferències per a altres espais de noms. Si no troba el valor en aquesta llengua ho intenta en les llengües alternatives definides en el MediaWiki. Per exemple per català les llengües alternatives són occità i anglès. En cas que el valor no s'hagi trobat en la llengua demanada, hi afegeix el codi de llengua i una icona d'etiqueta per a traduir-ho a Wikidata. Aquesta icona es pot eliminar amb el paràmetre editicon.
  • property= (obligatori) Identificador de la propietat de la declaració (Pid). Es poden definir diferents propietats alternatives amb qualsevol separador, per exemple "P17 o P131", i obtindrà la primera que trobi. Accepta també una p minúscula, però no és recomanat. Igualment accepta l'etiqueta de la propietat, per exemple property=estat equival a property=P17 per la propietat estat (P17).
  • qualifier= (opcional) Qualificador (Pid) del valor de la propietat.
  • value= (opcional) Valor preferent al de Wikidata. Pot ser un paràmetre opcional en una plantilla amb el format {{{paràmetre|}}}, així si existeix pren el valor del paràmetre i si està buit llavors obté el valor de Wikidata.
    • value=NONE Amb aquest valor no treu res de Wikidata. Permet configurar un paràmetre per a que no tregui cap valor de Wikidata, o bé treure només valors informats en la plantilla amb {{{paràmetre|NONE}}}. És equivalent a la sintaxi wiki: {{#ifeq:{{{paràmetre|}}}|NONE|<!-- no res -->}}.
  • list= (opcional):
    • list=true (per defecte) Mostra una llista de tots els valors (vegeu separator i conjuction més avall).
    • list=false o list=no Mostra només un valor, el de rang més alt segons l'ordre preferent/normal/obsolet, o el més antic dels que tenen el rang més alt.
    • list=firstrank Mostra una llista dels valors amb el rang més alt. És equivalent a list=true si tots tenen el mateix rang. És equivalent a list=false si només hi ha un valor amb el rang més alt.
    • list=lang En cas de valors monolingües només treu els corresponents a la llengua del paràmetre lang. Vegeu el paràmetre lang i el formatting pel tipus de valor monolingüe (monolingualtext).
    • tablesort=0 (opcional) ordenació ascendent de la llista. Per defecte l'ordenació és pel rang (preferent, normal, obsolet) i per l'antiguitat de definició a Wikidata.
  • separator= (opcional) Separador a usar en llistes o taules. En cas de llistes, per defecte és MediaWiki:Comma-separator, en català una coma i un espai en blanc ', '. En cas de taules per defecte és un salt de línia <br />. En algun cas, si s'inclou en etiquetes que usen strip markers, pot ser que un <br /> no funcioni. L'alternativa és usar separator=LF per a un caràcter de control line feed.
  • conjunction= (opcional) Conjunció a usar com a separador diferent entre els dos últims elements de la llista. Per defecte és igual a separator si està definit i si no és MediaWiki:And més MediaWiki:Word-separator, en català ' i '. En el cas de taules per defecte és un salt de línia <br />.
  • itemgender= (opcional) Element on es comprova sexe o gènere (P21) per aplicar la forma femenina si fos necessari, per defecte item. S'usa en combinació amb case=gender o case=infoboxlabel.
  • editicon= (opcional) Defineix si es posa alguna icona. Per defecte és true. Amb valors editicon=false o editicon=no és false. Les icones poden ser: una icona d'etiqueta Tradueix en cas que l'etiqueta no s'hagi trobat en la llengua demanada, i un petit llapis Modifica com a icona per mostrar i poder editar la declaració a Wikitada (en el futur gestionat per mw:Wikidata Bridge). La icona del llapis es mostrarà si està definida en la configuració pel wiki a Module:Wikidata/i18n amb el valor ["addpencil"] = true.
  • showerrors= (opcional) Amb qualsevol valor mostra el missatge d'error, si n'hi ha cap. Si no està definit mostrarà el paràmetre default en cas d'error.
  • default= (opcional) Text a mostrar en cas d'error. No té cap efecte si està definit el paràmetre showerrors. Si no està definit, i tampoc el paràmetre showerrors, retornarà un valor buit en cas d'error.
  • sandbox= (opcional) Amb qualsevol valor desvia les crides al Module:Wikidata/proves. El títol de la subpàgina l'obté de MediaWiki:Sandboxlink-subpage-name, en català "proves". El paràmetre es pot usar en l'entorn de plantilla. Com a paràmetre d'invoke o de require no té sentit per les proves. A usar només provisionalment o en previsualització, el mòdul de proves no hauria de tenir cap enllaç permanent.

Paràmetres de formatació

formatting= (opcional) Format desitjat. Valors possibles, per a cada tipus de dada:

Dada amb valor d'element (entity):

  • formatting=raw Número identificador de l'element.
  • formatting=label Etiqueta de l'element en la llengua demanada, alguna de les llengües alternatives o bé com a raw.
  • formatting=sitelink Títol de la pàgina de la Viquipèdia de l'element, sense enllaç. Si no existeix retorna el format raw amb el prefix d:.
  • formatting=internallink Enllaç intern sempre que sigui possible, bé a la pàgina de la Viquipèdia (sitelink) o bé a l'etiqueta (possiblement un enllaç vermell). Com a darrera opció enllaça a Wikidata.
  • formatting=pattern Format segons un patró usant $1 com a paràmetre a substituir. Pot incloure plantilles o funcions parser amb el format: {{((}}nom-de-la-plantilla{{!}}$1{{))}} o bé {{((}}nom-de-la-plantilla{{!}}nom_paràmetre{{=}}$1{{))}}, o similar.
El format per defecte és un enllaç conduït, bé a sitelink o bé a wikitada:raw, usant label com a etiqueta de l'enllaç.
  • formatting=ucfirst Variant del format per defecte amb majúscula inicial en l'etiqueta. En una llista només posa majúscula en el primer valor.
  • formatting=ucinternallink Combinació del format "ucfirst" i "internallink".

Dada amb valor de text (string):

General:
  • formatting=pattern Format segons un patró usant $1 com a paràmetre a substituir. Exemple: formatting=[http://whc.unesco.org/en/list/$1 $1]. Per a propietats d'identificador que tenen un enllaç autogenerat per Wikidata, el patró es troba a la pàgina de discussió de la propietat. Pot incloure plantilles i funcions parser (vegeu més amunt per entity).
Tipus URL:
  • formatting=weblink Format d'enllaç extern, posant com a etiqueta el lloc web sense prefixos i amb punts suspensius si enllaça a una pàgina web: [http://www.example.com example.com], [http://example.com/en/page example.com…].
Tipus identificador extern (external-id):
  • formatting=externalid Format d'enllaç extern amb el patró de l'URL definit a format d'URL (P1630) en l'entitat Pid de property.
Tipus fórmula matemàtica (math):
El contingut s'engloba amb l'etiqueta <math> que genera una imatge de la fórmula. Vegeu mw:Extension:Math i exemples a fórmula (P2534).
Tipus notació musical (musical-notation):
El contingut s'engloba amb l'etiqueta <score> que genera una imatge de la partitura. Vegeu mw:Extension:Score i exemples a motiu musical (P6686). Opcions de format:
  • formatting=sound Afegeix l'atribut sound="1" a l'etiqueta generant un fitxer d'àudio que s'incrusta sota la imatge.

Dada amb valor numèric (quantity):

Per defecte mostra només el número.
  • formatting=unit Format numèric incloent la unitat. Si és diferent a 1 ho posa en plural segons Module:Wikidata/Units.
  • formatting=unitcode Format numèric incloent el codi o l'abreviatura de la unitat definit a símbol de la unitat (P5061). Es pot canviar a Module:Wikidata/Units. Si no el troba usa el nom de la unitat.
  • convert=Qid Fa una conversió a la unitat indicada pel seu indicador d'element Qid. Les conversions es fan segons els factors indicats en la unitat obtinguda per la unitat Qid en les propietats conversió a unitats del SI (P2370) o conversió a unitats estàndard (P2442), excepte per a temperatures on s'usen fórmules de conversió entre ºC, ºF i ºK. Per exemple, un valor de "74 polzades" amb convert=Q174728 (centímetre (Q174728)) dóna "188 centímetres" segons la conversió "2,54 centímetre" indicada a polzada (Q218593). L'arrodoniment de la conversió es fa mantenint la precisió per defecte del valor original segons el nombre de xifres significatives. Es pot combinar amb formatting=unitcode. Es pot usar també amb formatting=table, vegeu més avall.
  • convert=default Fa una conversió de les unitats indicades en la taula convert_default de Module:Wikidata/Units.
  • convert=default2 Variant que mostra els dos valors: amb la quantitat convertida i entre parèntesis la quantitat original.
  • convert=M Fa una conversió a milions, arrodonint sense decimals, si la quantitat és major que 100 milions. Afegeix M davant de la unitat o el codi, per exemple Meuro, M$.

Dada amb valor monolingüe (monolingualtext):

  • formatting=language Retorna el codi de llengua corresponent al valor monolingüe, per exemple en el cas de nom oficial (P1448).
  • formatting=text Recupera el text amb la marca de llengua, si és diferent a la llengua local del wiki: <span lang="en">United...</span>.
  • formatting=pattern Format segons un patró usant $language i $text com a variables a substituir. Per exemple, "formatting=($language) $text" per treure el text amb el codi de llengua al davant entre parèntesis.
  • list=lang Sols treu els valors corresponents a la llengua definida o la llengua per defecte. Vegeu el paràmetre lang més amunt.

Dada amb valor de coordenades (globecoordinate):

  • formatting=latitude Valor de latitud en una declaració de coordenades, en format decimal
  • formatting=longitude Valor de longitud en una declaració de coordenades, en format decimal
  • formatting=globe (per defecte) Valor del paràmetre globe amb el format usat en la plantilla {{coord}}, necessari per coordenades fora de la Terra.
  • formatting=$lat...$lon...$globe Format lliure amb paràmetres $lat i $lon, i opcionalment $globe, a substituir pels valors de latitud i longitud, en format decimal, més globe. Admet la inclusió de plantilles en format no expandit, p. ex. {{((}}coord{{!}}$lat{{!}}$lon{{))}}.
  • formatting=dimension Valor de dimensió en una declaració de coordenades, en metres, equivalent al paràmetre dim de GeoHack.

Dada amb valor de data (time):

Per defecte usa el format definit a Module:Wikidata/i18n en la taula datetime segons la precisió de la data. Opcionalment, per precisió de dies:
  • formatting= sintaxi #time Accepta qualsevol format vàlid de la funció d'analitzador #time. Per exemple: formatting=d-m-Y (23-04-2024), formatting=[[j xg]] (23 d'abril), formatting=Y (2024). Per defecte, està definit a Module:Wikidata/i18n com "j F Y" (23 abril 2024), però amb una funció que permet modificar el dia 1r de cada mes.
Hi afegeix el calendari quan pot ser ambigu: si la data és anterior al 15-10-1582 i està definida en gregorià o si és posterior al 4-10-1582 i està definida en julià. Vegeu calendari gregorià per a més informació.

Paràmetres de taula de propietat i qualificadors

propietat qualificador1 qualificador2 etc.
valors 1a declaració $0 $1 $2, etc.
2a, etc. $0 $1 $2, etc.

formatting=table Una declaració amb qualificadors es considera com una taula de valors mostrada a la dreta. Es pot indicar el format de les files i de cada columna de la taula. Els separadors per a cada fila són per defecte salts de línia (vegeu separator i conjunction més amunt). Si realment voleu el resultat en una taula wiki podeu usar separator=</tr><tr> amb les corresponents etiquetes d'apertura i tancament abans i desprès de l'invoke. Paràmetres específics per a aquest format:

Columnes:

  • qualifier1 ... qualifierx= Qualificadors amb un número consecutiu i il·limitat. El paràmetre general qualifier és un àlies per qualifier1.
    • qualifierx = Pid1 OR Pid2 Definició alternativa d'un qualificador quan el primer no existeix. Un cas d'ús típic és data (P585) OR data d'inici (P580). No hi ha límit per successius OR. Els espais en blanc d'abans i després són opcionals.
    • qualifierx = Pid1/Pid2 De l'element corresponent a Pid1 (un qualificador o una propietat) obté la propietat superior Pid2. Permet obtenir dades addicionals en la taula encara que definides en l'element superior. Per exemple, per obtenir les línies de metro amb la seva icona: qualifier=P81/P154. Es pot combinar amb l'opció OR prenent prioritat l'OR.
    • qualifierx = /Pid Equivalent a l'anterior però sense Pid1, obté una segona propietat del mateix element. Permet obtenir dades definides bé en un qualificador o bé en una propietat.
  • colformat0 ... colformatx= Format opcional a aplicar a les columnes, usant 0 per la propietat i 1-x pels qualificadors. Accepta la mateixa sintaxi que formatting per a cada tipus de dada. Vegeu més amunt #Paràmetres de formatació.
  • case0 ... casex= Cas gramatical a aplicar a cada columna. El paràmetre case, sense numeració, s'aplica a tots els valors. Vegeu més amunt #Paràmetres generals.
  • convert0 ... convertx= Conversió d'unitats a aplicar a cada columna. Vegeu més amunt #Paràmetres de formatació per format numèric.
  • whitelist0 ... whitelistx= Llista dels ítems a mostrar per a una columna, usant qualsevol separador.
  • blacklist0 ... blacklistx= Llista dels ítems que no es mostraran per a una columna, usant qualsevol separador. En cas d'usar whitelist per a una columna i blacklist per a una altra els resultats poden ser inesperats (vegeu un comentari al respecte)

Files:

  • rowformat= Format de les files de propietat més qualificadors. La propietat s'indica amb $0 i els qualificadors $1 a $x. Per defecte és rowformat=$0 ($1, ... $x). Pot incloure marques de llistes * o # i també plantilles o funcions parser amb el format: {{((}}plantilla{{!}}paràmetre{{!}}nom{{=}}paràmetre{{))}}. En cas d'usar el paràmetre "references" (vegeu més amunt) cal indicar on han d'aparèixer les referències amb $R0.
  • rowsubformat1 ... rowsubformatx= Format previ a aplicar a $1-$x definits en rowformat, només si existeix el valor. Per exemple, "rowformat=$0 $1" i "rowsubformat1=($1)" resulta "$0 ($1)" o bé "$0" si $1 està buit, evitant uns parèntesis buits. Un rowsubformat pot contenir diferents variables $1-$x. Cal tenir en compte que les substitucions en fan de forma seqüencial per ordre numèric, per tant pot incloure un $x posterior però no un d'anterior ja que haurà estat tractat.
  • tablesort= amb valors de 0 a x, permet ordenar la taula per la propietat (0) o els qualificadors (1 a x). L'ordenació és ascendent alfabèticament, numèricament o per dates, segons el tipus de dada. Accepta múltiples claus usant qualsevol separador, p. ex. tablesort=0/2/1. Per defecte l'ordenació és pel rang de la propietat (preferent, normal, obsolet) i per l'antiguitat de definició a Wikidata.
  • sorting=-1 inverteix l'ordenació fent-la descendent. Amb qualsevol altre valor, o en el seu defecte, l'ordenació és ascendent. En cas de tablesort amb múltiples claus, el criteri de sorting s'aplicarà a totes per igual.
  • list=false Treu només la primera fila de la taula, segons l'ordre indicat o l'ordre per defecte.

Funció getLabel

Retorna l'etiqueta d'un element.

  • 1= (primer paràmetre posicional, requerit) Identificador de l'ítem de Wikidata (Qid o Pid). Àlies: item, from.
  • lang= (opcional) Codi de llengua, com en la funció claim. Vegeu més amunt #Paràmetres generals.
  • itemgender= (opcional) Identificador de l'ítem que determina el gènere a usar, com en la funció claim. Vegeu més amunt #Paràmetres generals.
  • linked= (opcional) Amb qualsevol valor, excepte 'no', retorna l'etiqueta enllaçada a l'article local o bé a Wikidata.
  • label= (opcional) Treu l'etiqueta indicada. Només té sentit amb linked= per generar un enllaç amb l'etiqueta de label=.
  • editicon= (opcional) permet eliminar la icona del llapis, com en la funció claim. Vegeu més amunt #Paràmetres generals.

Funció getParentValues

Retorna de forma recursiva valors d'una propietat usant com a etiqueta un valor superior. Per exemple pot estraure l'estructura administativa o la classificació de tàxons.

  • item= (opcional) Permet indicar un item (Qid) diferent a l'article actiu. Aquest accés arbitrari a Wikidata està limitat pel seu alt consum de recursos.
  • property= (opcional) Propietat de la declaració (Pid). Per defecte és localitzat a l'entitat territorial administrativa (P131). Admet una llista de valors alternatius usant qualsevol separador.
  • label= (opcional) Propietat superior a usar com a etiqueta. Per defecte és instància de (P31).
  • upto= (opcional) Darrera iteració a extraure, si abans no ha trobat cap propietat no existent. Tipus de valors:
    • upto=etiqueta: darrera etiqueta a consultar, per exemple "upto=estat".
    • upto=valor numèric: nombre màxim d'iteracions. Per defecte és 10 com a protecció, normalment un valor més alt del que serà necessari.
  • uptolabelid= (opcional) Alternatiu a upto=etiqueta usant el Qid.
  • uptovalueid= (opcional) Alternatiu a uptolabelid usant el Qid del valor en lloc de l'etiqueta. Admet valors múltiples usant qualsevol separador. Àlies uptolinkid mantingut provisionalment per compatibilitat.
  • labelshow= (opcional) Filtre d'etiquetes a mostrar, separades per una barra / si són més d'una. Per exemple "labelshow=municipi/comarca". Mostra el primer valor trobat per a cada etiqueta, sense repeticions posteriors de la mateixa etiqueta.
  • showlabelid= (opcional) Alternatiu a labelshow usant Qid i qualsevol separador.
  • include_self=true (opcional) Inclou l'etiqueta de la pròpia pàgina en la llista generada.
  • sorting=-1 (opcional) Ordenació descendent de la llista.
  • last_only=true (opcional) Només mostra el darrer valor obtingut. Per exemple amb uptolinkid=Qid només mostrarà el valor corresponent a Qid.
  • formatting= (opcional) Format del valor de la propietat. Per defecte és un enllaç conduït local o a Wikidata (vegeu més amunt formatting de la funció claim per valors entity).
  • valuetext= (opcional) Propietat a usar com a text de l'enllaç amb el valor 'property' com a enllaç conduït.
  • labelformat= (opcional) Format de l'etiqueta. Per defecte és "label" (vegeu més amunt formatting de la funció claim per valors entity).
  • rowformat= (opcional) Format de sortida per a cada parell de valors obtingut, indicant $0 per l'etiqueta i $1 pel valor. Per defecte és "rowformat=$0 = $1" mostrant per exemple "comarca = [[Maresme]]"
  • separator= (opcional) Separador per a cada parell de valors obtingut, per defecte és <br />.
  • cascade=true (opcional) opció de presentació amb sagnat. Pot ser útil quan només s'utilitza $1 a rowformat.

Nota: les etiquetes es modifiquen amb un format adequat a les necessitats d'una infotaula segons les definicions a Module:Wikidata/labels. Per exemple, "municipi del Brasil" es presenta com a "Municipi".

Funció linkWithParentLabel

Crea un enllaç amb l'etiqueta d'una propietat superior.

Accepta la majoria de paràmetres de la funció claim, excepte "formatting" que usa el valor per defecte "internallink". Addicionalment:

  • parent= és la propietat a usar en l'etiqueta corresponent a l'ítem superior del valor obtingut per "property/qualifier". Accepta valors alternatius amb qualsevol separador, igual que el paràmetre "property" de la funció claim.

Funció yearsOld

Retorna l'edat avaluant la data de naixement i la data de defunció o en el seu defecte la data actual. Si les dues dates no tenen precisió de dia mostra el rang amb un marge d'1 o de 10 anys.

La seva sintaxi és: {{#invoke:Wikidata|yearsOld|formatting= |item= }}. Els paràmetres item i formatting són opcionals. Per defecte retorna la quantitat.

  • formatting=unit (opcional) Obté la unitat de la taula i18n["years-old"] de Module:Wikidata/i18n pel singular o el plural, a més de paucal usat en llengües eslaves com el rus. Vegeu la funció parser PLURAL a mw:Help:Magic words#Localization.
  • formatting=pattern (opcional) Format amb un patró usant $1 com a variable per la quantitat. Un exemple típic és " ($1 anys)". En aquest cas no avalua l'expressió en singular, plural o paucal i obté la unitat de anys (Q24564698). Una alternativa és usar un patró uniforme definit en la taula i18n["years-old"] que admet el paràmetre $1.

Utilitats

  • getSiteLink Retorna el títol de pàgina local per un element donat. Sintaxi:
    {{#invoke:Wikidata|getSiteLink|<Qid>|<wiki>}}
    Sense cap paràmetre retorna la pròpia pàgina. Proporcionant l'id retornarà la pàgina local enllaçada en l'element corresponent. En cas de no existir o ser erroni no retorna res. Amb un segon paràmetre amb un codi de wiki obté la pàgina en el wiki especificat (enwiki, frwiki,... cawiktionary, etc.)
  • lang Retorna el codi de llengua tal com el gestiona la funció claim. Vegeu #Paràmetres generals més amunt. Sintaxi:
    {{#invoke:Wikidata|lang|{{{lang|}}}}}
    El paràmetre lang és el codi de la llengua aportat explícitament.
  • numStatements Retorna el nombre d'instàncies que té una propietat multi-valor. Permet decidir el tractament a donar a llistes llargues. Sintaxi:
    {{#invoke:Wikidata|numStatements|<Pid>|item={{{item|}}}
    Exemple: {{#invoke:Wikidata|numStatements|P47|item=Q1861}} → Error de l'script: la funció "numStatements" no existeix.
  • validProperty Retorna "null" si la propietat no existeix, o només té valors amb marcador "sense valor" o "valor desconegut" o obsolet. Sintaxi:
    {{#invoke:<nowiki>{{ROOTPAGENAME}}<nowiki>|validProperty|<Pid>|item={{{item|}}}
    Es pot usar com a alternativa a #property. Per compatibilitat amb aquesta funció parser, el paràmetre from és un àlies de item.

Redireccions a Wikidata

Un element de Wikidata pot ser una redirecció a un altre element, sovint com a resultat d'una fusió. Els valors d'una propietat poden ser provisionalment una redirecció, normalment corregit per bot al cap d'una setmana. El tractament de les redireccions és el següent:

  • Funció claim
    • Amb formatting=raw no retorna el Qid redirigit sinó el Qid final de la redirecció.
    • Amb paràmetres whitelist o blacklist, si la llista de valors inclou alguna redirecció, considera tant el Qid redirigit com el nou Qid final.
  • Funció getLabel
    • Si es demana l'etiqueta d'un Qid redirigit, la buscarà en el Qid final.

En tots els casos afegeix un rastreig per poder corregir en les plantilles els Qid redirigits. Es poden trobar a Special:WhatLinksHere/Template:Track/wikidata/redirect.

La resolució de redireccions a Wikidata està pendent de phab:T157868. La solució tècnica adoptada provisionalment pot provocar un alt consum de recursos si un element no té cap etiqueta en la llengua local ni en les llengües alternatives. Es recomana comprovar el rastreig Special:WhatLinksHere/Template:Track/wikidata/label per afegir les etiquetes que manquen.

Crides des d'un altre mòdul

Totes les funcions (claim, getLabel, getParentValues, linkWithParentLabel, yearsOld, lang) es poden cridar des d'altres mòduls via require amb els mateixos paràmetres proporcionats en una taula, per exemple:

require("Module:Wikidata").claim{item="Q...", property="P...", ...}
require("Module:Wikidata").getLabel({"Q...", ['lang']="ca"})

Les funcions claim i getLabel retornen com a segon valor la variable untranslated (nil o true) per a tractament específic en mòduls d'infotaules.

Exemples

Els exemples a continuació són mostres provades en les pàgines corresponents. Es poden fer proves a w:Viquipèdia:Proves de Wikidata, comprovacions en previsualització d'una pàgina o usar el paràmetre item per un element de Wikidata diferent de la pàgina actual.

  • Ús simple:
{{#invoke:Wikidata | claim |property=P20}} a l'article Jean-François Champollion (Q260) dóna: París
és la propietat lloc de defunció (P20), per defecte amb el valor enllaçat.
  • Sense enllaç:
{{#invoke:Wikidata | claim | property=P20 | formatting=label}} dóna: París
  • Valor preferent:
{{#invoke:Wikidata | claim | property=P20 | value={{{lloc_mort|}}} }} en la infotaula de l'article donarà
el valor de {{{lloc_mort|}}} si està definit en l'article, en cas contrari París
  • Valor tipus data:
{{#invoke:Wikidata | claim | property=P569}} dóna la data de naixement amb el format per defecte:
Error de Lua: bad argument #1 to 'formatDate' (string expected, got function).
  • Formatat amb un patró:
{{#invoke:Wikidata | claim | property=P214 | formatting=[http://viaf.org/viaf/$1 $1]}} dóna:
34454460
  • Un únic valor:
Imatge de mostra
{{#invoke:Wikidata | claim | property=P18 | list=false | formatting=[[File:$1|thumb|upright=.5|Imatge de mostra]]}}
Treu només la primera de les imatges definides.
  • Format d'enllaç extern:
{{#invoke:Wikidata | claim | property=P856 | formatting=weblink}} a Berlín dóna:
www.berlin.de/politik-verwaltung-buerger/
  • Llista de valors:
{{#invoke:Wikidata | claim | property=P47}} a l'Alcoià (Q746061) dóna:
l'Alacantí, l'Alt Vinalopó, el Comtat, la Marina Baixa, la Vall d'Albaida i el Vinalopó Mitjà
Cal notar l'enllaç conduït [[Comtat (País Valencià)|Comtat]]
  • Llista formatada:
{{#invoke:Wikidata | claim | property=P150 | separator=<br /> | conjunction=<br />}} dóna
Alcoi
Banyeres de Mariola
Benifallim
Castalla
Ibi
Onil
Penàguila
Tibi
  • Coordenades:
{{#invoke:Wikidata | claim | property=P625 | formatting=latitude}} dóna: 38.701944444444
{{#invoke:Wikidata | claim | property=P625 | formatting=longitude}} dóna: -0.47722222222222

Dependències

Vegeu també


-- version 20180819 from master @cawiki

local p = {}

-----------------------------------------------------------------------------
-- internationalisation at [[Module:Wikidata/i18n]]
local i18n = {
	["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.",
		['not-from-content-page'] = "Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing ."
	},
	["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
		["bc-addon"] = " BC",		-- suffix for negative dates
		["ad-addon"] = ""			-- suffix for 1st century AD dates
	},
	["monolingualtext"] = '<span lang="%language">%text</span>',
	["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
	
	["cite"] = {					-- Cite web parameters
		["url"]          = "url",
		["title"]        = "title",
		["website"]      = "website",
		["access-date"]  = "access-date",
		["archive-url"]  = "archive-url",
		["archive-date"] = "archive-date",
		["author"]       = "author",
		["publisher"]    = "publisher",
		["quote"]        = "quote",
		["language"]     = "language",
		["date"]         = "date",
		["pages"]        = "pages"
	}
}

local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]

local wiki = 
{
	langcode = mw.language.getContentLanguage().code,
	module_title = "Module:Wikidata"
}

----------------------------------------------------------------------------
-- module local functions

-- Credit to http://stackoverflow.com/a/1283608/2644759
-- cc-by-sa 3.0
local function tableMerge(t1, t2)
	for k,v in pairs(t2) do
		if type(v) == "table" then
			if type(t1[k] or false) == "table" then
				tableMerge(t1[k] or {}, t2[k] or {})
			else
				t1[k] = v
			end
		else
			t1[k] = v
		end
	end
	return t1
end

local function loadI18n()
	local exist, res = pcall(require, wiki.module_title .. "/i18n")
	if exist and next(res) ~= nil then
		tableMerge(i18n, res.i18n)
		cases = res.cases
	end
end

loadI18n()

local function case(word, localcase, lang)
	if word == nil or word == '' or cases[localcase] == nil then
		return word
	end
	
	return cases[localcase](word, lang)
end

local function findLang(langcode)
	if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
		local myframe = mw.getCurrentFrame()
		langcode = myframe.args.lang
		if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
			langcode = myframe:getParent().args.lang
			if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
				if not mw.title.getCurrentTitle().isContentPage then
					langcode = myframe:preprocess( '{{int:lang}}' )
				end
				if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
					langcode = wiki.langcode
				end
			end
		end
	end
	local languages = mw.language.getFallbacksFor(langcode)
	table.insert(languages, 1, langcode)
	return languages
end

-- mw.wikibase.getLabelWithLang or getLabelByLang with a table of languages
local function getLabelByLangs(id, languages)
	local label
	local lang = languages[1]
	if lang == wiki.langcode then
		-- using getLabelWithLang when possible instead of getLabelByLang
		label, lang = mw.wikibase.getLabelWithLang(id)
	else
		for _, l in ipairs(languages) do
			label = mw.wikibase.getLabelByLang(id, l)
			lang = l
			if label then
				break
			end
		end
	end
	return label, lang
end

-- Is gender femenine? true or false
local function feminineGender(id)
	local entity = mw.wikibase.getEntityObject(id)
	local genderClaims = entity.claims["P21"] -- sex or gender
	if genderClaims then
		local genderId = getValueOfClaim(genderClaims[1], nil, {["formatting"]="raw"})
		if genderId == "Q6581072" or genderId == "Q1052281" or genderId == "Q43445" then -- female, transgender female, female organism
			return true
		end
	end
	return false
end

-- Fetch female form of label
local function feminineForm(id, lang)
	local feminine_claims = findClaims(mw.wikibase.getEntityObject(id), 'P2521') -- female form of label
	if feminine_claims then
		for _, feminine_claim in ipairs(feminine_claims) do
			local feminine_value = getValueOfClaim(feminine_claim, nil, {["list"]="lang", ["lang"]={lang}})
			if feminine_value then
				return feminine_value
			end
		end
	end
end

-- Fetch unit symbol
local function unitSymbol(id, lang)
	local claims = findClaims(mw.wikibase.getEntityObject(id), 'P5061')
	local langclaims = {}
	if claims then
		for _, snak in ipairs(claims) do
			if snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value and
				not langclaims[snak.mainsnak.datavalue.value.language] -- just the first one by language
				then
					langclaims[snak.mainsnak.datavalue.value.language] = snak.mainsnak.datavalue.value.text
			end
		end
		for _, l in ipairs(lang) do
			if langclaims[l] then
				return langclaims[l]
			end
		end
	end
	return langclaims["mul"] -- last try
end

-- Add a small pencil as icon for edit on Wikidata
local function addEditIcon(id, lang, uselang, icon)
	if icon and lang ~= uselang then
		return " [[File:Arbcom ru editing.svg|12px|" .. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain() .. "|link=d:" .. id .. "]]"
	end
	return ''
end

local function expandBraces(text, formatting)
	if text == nil or formatting == nil then return text end
	-- only expand braces if provided in argument, not included in value as in Q1164668
	if mw.ustring.find(formatting, '{{', 1, true) == nil then return text end
	if type(text) ~= "string" then
		text = tostring(text)
	end
	
	for braces in mw.ustring.gmatch(text, "{{(.-)}}") do
		local parts = mw.text.split(braces, "|")
		local title_part = parts[1]
		local parameters = {}
		for i = 2, #parts do
			if mw.ustring.find(parts[i], "=") then
				local subparts = mw.text.split(parts[i], "=")
				parameters[subparts[1]] = subparts[2]
			else
				table.insert(parameters, parts[i])
			end
		end
		
		local braces_expanded
		if mw.ustring.find(title_part, ":")
			and mw.text.split(title_part, ":")[1] ~= mw.site.namespaces[10].name -- not a prefix Template:
			then
			braces_expanded = mw.getCurrentFrame():callParserFunction{name=title_part, args=parameters}
		else
			braces_expanded = mw.getCurrentFrame():expandTemplate{title=title_part, args=parameters}
		end
		braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
		braces_expanded = mw.ustring.gsub(braces_expanded, "(%%[0-9])", "%%%1") -- no captures in replacement string, i.e. url %-coded
		text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
	end
	
	return text
end

local function printDatavalueString(data, parameters)
	if parameters.formatting == 'weblink' then 
		return '[' .. data ..  ' ' ..  mw.text.split(data, '//' )[2] .. ']'
	elseif mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
		local escaped_data = mw.ustring.gsub(data, "%%", "%%%") -- escape % character, normally used in url, avoiding invalid capture in gsub
		return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', escaped_data), parameters.formatting)
	elseif parameters.case then
		return case(data, parameters.case, parameters.lang[1])
	else
		return data
	end
end

local function printDatavalueCoordinate(data, parameter)
	if parameter == 'latitude' then
		return data.latitude
	elseif parameter == 'longitude' then
		return data.longitude
	elseif parameter == 'dimension' then
		return data.dimension
	else --default formatting='globe'
		if data.globe == '' or data.globe == nil or data.globe == 'http://www.wikidata.org/entity/Q2' then
			return 'earth'
		else
			local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
			if pcall(require, "Module:Mapa cos celeste/dades") then
				local globetable = mw.loadData('Module:Mapa cos celeste/dades')
				for _, globe in pairs(globetable.maps) do
					if globe.wikidata == globenum then
						return globe.coord_globe
					end
				end
			end
			return globenum
		end
	end
end

local function printDatavalueQuantity(data, parameters)
	-- exemples: 277±1 Centímetre, 1,94 metre
	local amount = data.amount
	amount = mw.ustring.gsub(amount, "%+", "")
	local sortkey = string.format("%09d", amount)
	amount = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
	-- This is used to get the unit name for a numeric value
	local suffix = ""
	if parameters.formatting == "unit" or parameters.formatting == "unitcode" then
		-- get the url for the unit entry on Wikidata:
		local unitID = data.unit
		-- and just return the last bit from "Q" to the end (which is the QID):
		unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)
		if mw.ustring.sub(unitID, 1, 1) == "Q" then
			local unit_label, lang = getLabelByLangs(unitID, parameters.lang)
			local unit_symbol
			if parameters.formatting == "unitcode" then
				unit_symbol = unitSymbol(unitID, parameters.lang)
			end
			if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
				suffix = " " .. require(wiki.module_title .. "/Units").getUnit(amount, unit_label, unitID, parameters.formatting == "unitcode", unit_symbol)
			elseif parameters.formatting == "unitcode" then
				suffix = " " .. unit_symbol or unit_label or unitID
			else
				suffix = " " .. unit_label or unitID
			end
		end
	end
	return amount .. suffix, sortkey
end

local function printDatavalueTime(data, parameters)
	-- Dates and times are stored in ISO 8601 format
	local timestamp = data.time
	local sortkey = timestamp
	local addon = ""
	
	-- calendar model
	local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
	local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
	local calendar_add = ""
	if (timestamp < "+1582-10-15T00:00:00Z" and calendar_model[calendar_id] == "gregorian")
		or (timestamp > "+1582-10-04T00:00:00Z" and calendar_model[calendar_id] == "julian")
		then
		calendar_add = " <sup>(" .. mw.message.new('Wikibase-time-calendar-' .. calendar_model[calendar_id]):inLanguage(parameters.lang[1]):plain() .. ")</sup>"
	end
	
	-- check for negative date, ex. "-0027-01-16T00:00:00Z"
	if string.sub(timestamp, 1, 1) == '-' then
		timestamp = '+' .. string.sub(timestamp, 2)
		addon = i18n.datetime["bc-addon"]
	elseif string.sub(timestamp, 2, 3) == '00' then
		addon = i18n.datetime["ad-addon"]
	end
	addon = addon .. calendar_add
	local function d(f, t)
		return mw.language.new(parameters.lang[1]):formatDate(f, t or timestamp) .. addon
	end
	local precision = data.precision or 11
	local intyear = tonumber(mw.ustring.match(timestamp, "^\+?%d+"))
	local ret = ""
	
	-- precision is 10000 years or more
	if precision <= 5 then
		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 == i18n.datetime["bc-addon"] then
			-- negative date
			ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
		else
			ret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
		end
	-- precision is millennia, centuries or decades
	elseif precision == 6 then
		local card = math.floor((intyear - 1) / 1000) + 1
		if mw.ustring.find(i18n.datetime[6], "$1") then
			ret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(card)) .. addon
		else
			ret = d(i18n.datetime[6], string.format("%04d", tostring(card)))
		end
	elseif precision == 7 then
		local card = math.floor((math.abs(intyear) - 1) / 100) + 1
		if mw.ustring.find(i18n.datetime[7], "$1") then
			ret = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(card)) .. addon
		else
			ret = d(i18n.datetime[7], string.format("%04d", tostring(card)))
		end
	elseif precision == 8 then
		local card = math.floor(math.abs(intyear) / 10) * 10
		ret = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(card)) .. addon
	-- precision is year
	elseif parameters.formatting == 'Y' or precision == 9 then
		ret = tostring(intyear) .. addon
	-- precision is month
	elseif precision == 10 then
		timestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous month
		ret, _ = string.gsub(d(i18n.datetime[10]), " 0+", " ") -- supress leading zeros in year
	elseif parameters.formatting then
		ret, _ = string.gsub(d(parameters.formatting), "([ %[])0+", "%1") -- supress leading zeros in year optionally linked
	else
		ret, _ = string.gsub(d(i18n.datetime[11]), " 0+", " ")
	end
	return ret, sortkey
end

local function printDatavalueEntity(data, parameters)
	local entityId = data['id']
	local entityIdPreffix = data['entity-type'] == 'property' and "Property:" .. entityId or entityId
	if parameters.formatting == 'raw' then
		return entityId, entityId
	end
	local label, lang = getLabelByLangs(entityId, parameters.lang)
	local sitelink = mw.wikibase.sitelink(entityId)
	local parameter = parameters.formatting
	local labelcase = label or sitelink
	if parameters.case == 'feminineform' and lang ~= nil then -- case gender and item is female
		labelcase = feminineForm(entityId, lang) or labelcase
	end
	if parameters.case then
		labelcase = case(labelcase, parameters.case, lang)
	end
	local ret1, ret2
	if parameter == 'label' then
		ret1 = (labelcase or entityId)
		ret2 = labelcase or entityId
	elseif parameter == 'sitelink' then
		ret1 = (sitelink or 'wikidata:' .. entityIdPreffix)
		ret2 = sitelink or entityId
	elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
		ret1 = mw.ustring.gsub(parameter, '$1', labelcase or entityId)
		ret1 = expandBraces(ret1, parameter)
		ret2 = labelcase or entityId
	else
		if parameter == "ucfirst" or parameter == "ucinternallink" then
			labelcase = labelcase and mw.language.new(lang):ucfirst(labelcase)
			-- only first of a list, reset formatting for next ones
			if parameter == "ucinterlanllink" then
				parameters.formatting = 'internallink'
			else
				parameters.formatting = nil -- default format
			end
		end
		
		if sitelink then
			ret1 = '[[' .. sitelink .. '|' .. labelcase .. ']]'
			ret2 = labelcase
		elseif label and (parameter == 'internallink' or parameter == 'ucinternallink') then
			ret1 = '[[' .. label .. '|' .. labelcase .. ']]'
			ret2 = labelcase
		else
			ret1 = '[[wikidata:' .. entityIdPreffix .. '|' .. (labelcase or entityId) .. ']]'
			ret2 = labelcase or entityId
		end
	end
	
	return ret1 .. addEditIcon(entityIdPreffix, lang, parameters.lang[1], parameters.editicon), ret2
end

local function printDatavalueMonolingualText(data, parameters)
	-- data fields: language [string], text [string]
	
	-- temporary track for migration to list=lang
	local oldformatting = parameters.formatting and
		not (parameters.formatting == "language" or parameters.formatting == "text") and
		not mw.ustring.find(parameters.formatting, '$', 1, true)
	if oldformatting then
		require('Mòdul:utilitats').rastreig("Wikidata/monolingualtext")
	end
	
	if (parameters.list == "lang" or oldformatting) and data["language"] ~= parameters.lang[1] then
		return
	elseif parameters.formatting == "language" or parameters.formatting == "text" then
		return data[parameters.formatting]
	end
	local result = data["text"]
	if data["language"] ~= wiki.langcode then
		result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
	end
	if mw.ustring.find((parameters.formatting or ''), '$', 1, true) then
		-- output format defined with $text, $language
		result = mw.ustring.gsub(parameters.formatting, '$text', result)
		result = mw.ustring.gsub(result, '$language', data["language"])
	end
	return result
end

local function printDatatypeMath(data)
	return mw.getCurrentFrame():callParserFunction('#tag:math', data)
end

local function printError(key)
    return '<span class="error">' .. i18n.errors[key] .. '</span>'
end

-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- use these as the second parameter and this function instead of the built-in "pairs" function
-- to iterate over all qualifiers and snaks in the intended order.
local function orderedpairs(array, order)
	if not order then return pairs(array) end

	-- return iterator function
	local i = 0
	return function()
		i = i + 1
		if order[i] then
			return order[i], array[order[i]]
		end
	end
end

function findClaims(entity, property)
	if not property or not entity or not entity.claims then return end
	
	if not mw.ustring.match(property, "^P%d+$") then
		-- get property id for the given label
		property = mw.wikibase.resolvePropertyId(property)
		if not property then return end
	end
	
	return entity.claims[property]
end

local function getSnakValue(snak, parameters)
	if snak.snaktype == 'value' then
		-- call the respective snak parser
		if snak.datatype == 'math' then
			return printDatatypeMath(snak.datavalue.value)
		elseif snak.datavalue.type == "string" then
			return printDatavalueString(snak.datavalue.value, parameters)
		elseif snak.datavalue.type == "globecoordinate" then
			return printDatavalueCoordinate(snak.datavalue.value, parameters.formatting)
		elseif snak.datavalue.type == "quantity" then
			return printDatavalueQuantity(snak.datavalue.value, parameters)
		elseif snak.datavalue.type == "time" then
			return printDatavalueTime(snak.datavalue.value, parameters)
		elseif snak.datavalue.type == 'wikibase-entityid' then
			return printDatavalueEntity(snak.datavalue.value, parameters)
		elseif snak.datavalue.type == 'monolingualtext' then
			return printDatavalueMonolingualText(snak.datavalue.value, parameters)
		end
	elseif snak.snaktype == 'novalue' then
		return mw.message.new('Wikibase-snakview-snaktypeselector-novalue'):inLanguage(parameters.lang[1]):plain()
	elseif snak.snaktype == 'somevalue' then
		return mw.message.new('Wikibase-snakview-snaktypeselector-somevalue'):inLanguage(parameters.lang[1]):plain()
	end
	return mw.wikibase.renderSnak(snak)
end

local function getQualifierSnak(claim, qualifierId, parameters)
	-- a "snak" is Wikidata terminology for a typed key/value pair
	-- a claim consists of a main snak holding the main information of this claim,
	-- as well as a list of attribute snaks and a list of references snaks
	if qualifierId then
		-- search the attribute snak with the given qualifier as key
		if claim.qualifiers then
			local qualifier = claim.qualifiers[qualifierId]
			if qualifier then
				if qualifier[1].datatype == "monolingualtext" then
					-- iterate over monolingualtext qualifiers to get local language
					for idx in pairs(qualifier) do
						if qualifier[idx].datavalue.value and qualifier[idx].datavalue.value.language == parameters.lang[1] then
							return qualifier[idx]
						end
					end
				end
				if parameters.list then
					return qualifier
				else
					return qualifier[1]
				end
			end
		end
		return nil, printError("qualifier-not-found")
	else
		-- otherwise return the main snak
		return claim.mainsnak
	end
end

function getValueOfClaim(claim, qualifierId, parameters)
	local error
	local snak
	snak, error = getQualifierSnak(claim, qualifierId, parameters)
	if not snak then
		return nil, nil, error
	elseif snak[1] then -- a multi qualifier
		local result = {}
		local sortkey = {}
		for idx in pairs(snak) do
			result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
		end
		return mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]
	else -- a property or a qualifier
		return getSnakValue(snak, parameters)
	end
end

local function getReferences(claim)
	local refaliases = {
		citeWeb         = "Q5637226",
		author          = "P50",
		publisher       = "P123",
		importedFrom    = "P143",
		statedIn        = "P248",
		pages           = "P304",
		publicationDate = "P577",
		startTime       = "P580",
		endTime         = "P582",
		chapter         = "P792",
		retrieved       = "P813",
		referenceURL    = "P854",
		archiveURL      = "P1065",
		title           = "P1476",
		quote           = "P1683",
		shortName       = "P1813",
		language        = "P2439",
		archiveDate     = "P2960"
	}
	local result = ""
	-- traverse through all references
	for ref in pairs(claim.references or {}) do
		local refparts
		local refs = {}
		-- traverse through all parts of the current reference
		for snakkey, snakval in pairs(claim.references[ref].snaks or {}) do
			if snakkey ~= refaliases.importedFrom then -- "imported from" is not a proper reference
				for snakidx = 1, #snakval do
					if snakidx > 1 then refparts = refparts .. ", " end
					refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang="wiki.langcode"})
				end
				refs[snakkey] = refparts
				refparts = nil
			end
		end
		
		-- get title of general template for citing web references
		local template = mw.wikibase.sitelink(refaliases.citeWeb) or ""
		template = mw.text.split(template, ":")[2]  -- split off namespace from front
		
		-- (1) if both "reference URL" and "title" are present, then use the general template for citing web references
		if refs[refaliases.referenceURL] and (refs[refaliases.title] or refs[refaliases.statedIn]) and template then
			local citeParams = {}
			citeParams[i18n['cite']['url']] = refs[refaliases.referenceURL]
			citeParams[i18n['cite']['title']] = refs[refaliases.title] or refs[refaliases.statedIn]:match("^%[%[.-|(.-)%]%]")
			citeParams[i18n['cite']['website']] = refs[refaliases.statedIn]
			citeParams[i18n['cite']['language']] = refs[refaliases.language]
			citeParams[i18n['cite']['date']] = refs[refaliases.publicationDate]
			citeParams[i18n['cite']['access-date']] = refs[refaliases.retrieved]
			citeParams[i18n['cite']['archive-url']] = refs[refaliases.archiveURL]
			citeParams[i18n['cite']['archive-date']] = refs[refaliases.archiveDate]
			citeParams[i18n['cite']['publisher']] = refs[refaliases.publisher]
			citeParams[i18n['cite']['quote']] = refs[refaliases.quote]
			citeParams[i18n['cite']['pages']] = refs[refaliases.pages]
			citeParams[i18n['cite']['author']] = refs[refaliases.author]
			refparts = mw.getCurrentFrame():expandTemplate{title=template, args=citeParams}
		else
			-- raw ouput
			for k, v in orderedpairs(refs or {}, claim.references[ref]["snaks-order"]) do
				if k and v then
					if refparts then refparts = refparts .. ", " else refparts = "" end
					refparts = refparts .. tostring(mw.wikibase.label(k)) .. ": "
					refparts = refparts .. v
				end
			end
		end
		if refparts then result = result .. mw.getCurrentFrame():extensionTag("ref", refparts) end
	end
	return result
end

-- Return the site link (for the current site) for a given data item.
function p.getSiteLink(frame)
    if frame.args[1] == nil then
        entity = mw.wikibase.getEntityObject()
        if not entity then
        	return nil
        end
        id = entity.id
    else
        id = frame.args[1]
    end
 
    return mw.wikibase.sitelink(id)
end

function p.claim(frame)
	if mw.title.new(frame:getParent():getTitle()).isContentPage then
		if not mw.title.new(frame:getTitle()).isSubpage then
			-- invoked from a content page and not invoking a module subpage
			return printError("not-from-content-page")
		end
	end
	return p._main(frame.args, frame:getParent().args)
end

-- Entry point from other modules or debugging, with a list of arguments.
-- From other modules use: require("Module:Wikidata")._main({item="Q...", property="P...", ...})
-- On debug console use: =p._main({item="Q...", property="P...", ...})
function p._main(args, pargs)
	--If a value is already set, use it
	if args.value and args.value ~= '' then
		return args.value
	end
	
	-- arguments
	local id = args.item or (pargs and pargs.item); if id == "" then id = nil end
	local languages = findLang(args.lang)
	local idgender = args["itemgender"]
	if idgender and not string.match(idgender, "^Q%d+$") then -- id malformed, maybe "unknown value"
		idgender = nil
	end
	local property = string.upper(args["property"] or "")
	local qualifierId = {}
	qualifierId[1] = args["qualifier"] and string.upper(args["qualifier"]) or nil
	local i = 2
	while args["qualifier" .. i] do
		qualifierId[i] = string.upper(args["qualifier" .. i])
		i = i + 1
	end
	local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
	local case = args.case
	local list = args["list"] or true; if (list == "false" or list == "no") then list = false end
	local sorting_col = args.tablesort
	local sorting_up = (args.sorting or "") ~= "-1"
	local separator = args.separator
	local conjunction = args.conjunction or args.separator
	local rowformat = args.rowformat
	local references = args["references"]
	local showerrors = args["showerrors"]
	local default = args["default"]
	local editicon = not (args.editicon == "false" or args.editicon == "no")
	
	local parameters = {["formatting"] = parameter, ["list"] = list, ["case"] = case, ["lang"] = languages, ["editicon"] = editicon,
		["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
	local preformat = ""
	local postformat = ""
	if parameters.formatting == "table" then
		parameters.separator = parameters.separator or "<br />"
		parameters.conjunction = parameters.conjunction or "<br />"
		parameters.qseparator = ", "
		parameters.qconjunction = ", "
		if not rowformat then
			rowformat = "$0 ($1"
			i = 2
			while qualifierId[i] do
				rowformat = rowformat .. ", $" .. i
				i = i + 1
			end
			rowformat = rowformat .. ")"
		elseif mw.ustring.find(rowformat, "^[*#]") then
			parameters.separator = "</li><li>"
			parameters.conjunction = "</li><li>"
			if mw.ustring.match(rowformat, "^[*#]") == "*" then
				preformat = "<ul><li>"
				postformat = "</li></ul>"
			else
				preformat = "<ol><li>"
				postformat = "</li></ol>"
			end
			rowformat = mw.ustring.gsub(rowformat, "^[*#] ?", "")
		end
	end
	if default then showerrors = nil end
	
	-- get wikidata entity
	local entity = mw.wikibase.getEntityObject(id)
	if not entity then
		if showerrors then return printError("entity-not-found") else return default end
	end
	-- fetch the first claim of satisfying the given property
	local claims = findClaims(entity, property)
	if not claims or not claims[1] then
		if showerrors then return printError("property-not-found") else return default end
	end
	
	-- find feminine case if gender is requested
	local genderCase
	if parameters.case == "gender" or idgender or parameters.formatting == "table" then
		if feminineGender(idgender or id) then
			genderCase = "feminineform"
			if parameters.case == "gender" or idgender then
				parameters.case = genderCase
			end
		end
	end
	
	-- get initial sort indices
	local sortindices = {}
	for idx in pairs(claims) do
		sortindices[#sortindices + 1] = idx
	end
	-- sort by claim rank
	local comparator = function(a, b)
		local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
		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 result
	local error
	if parameters.list or parameters.formatting == "table" then
		-- convert LF to line feed, <br /> may not work on some cases
		parameters.separator = parameters.separator == "LF" and "\010" or parameters.separator
		parameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction
		-- i18n separators
		parameters.separator = parameters.separator or mw.message.new('Comma-separator'):inLanguage(parameters.lang[1]):plain()
		parameters.conjunction = parameters.conjunction or (mw.message.new('And'):inLanguage(parameters.lang[1]):plain() .. mw.message.new('Word-separator'):inLanguage(parameters.lang[1]):plain())
		-- iterate over all elements and return their value (if existing)
		local value, valueq
		local sortkey, sortkeyq
		local values = {}
		local sortkeys = {}
		local firstrank = parameters.list == "firstrank" and claims[sortindices[1]].rank or ''
		for idx in pairs(claims) do
			local claim = claims[sortindices[idx]]
			if firstrank ~= '' and firstrank ~= claim.rank then
				break
			end
			if parameters.formatting == "table" then
				local params = mw.clone(parameters)
				params.formatting = args["colformat0"]
				if args["case0"] then
					params.case = args["case0"] == "gender" and genderCase or args["case0"]
				end
				value, sortkey, error =  getValueOfClaim(claim, nil, params)
				if value then
					values[#values + 1] = {}
					sortkeys[#sortkeys + 1] = {}
					for i, qual in ipairs(qualifierId) do
						params.formatting = args["colformat" .. i]
						if args["case" .. i] then
							params.case = args["case" .. i] == "gender" and genderCase or args["case" .. i]
						else
							params.case = parameters.case
						end
						if qual == property then qual = nil end -- hack for getting the property with another formatting, i.e. colformat1=raw
						valueq, sortkeyq, _ =  getValueOfClaim(claim, qual, params)
						values[#values]["col" .. i] = valueq
						sortkeys[#sortkeys]["col" .. i] = sortkeyq or valueq
					end
				end
			else
				value, sortkey, error =  getValueOfClaim(claim, qualifierId[1], parameters)
				values[#values + 1] = {}
				sortkeys[#sortkeys + 1] = {}
			end
			if not value and showerrors then value = error end
			if value then
				if references then value = value .. getReferences(claim) end
				values[#values]["col0"] = value
				sortkeys[#sortkeys]["col0"] = sortkey or value
			end
		end
		-- sort and format results
		sortindices = {}
		for idx in pairs(values) do
			sortindices[#sortindices + 1] = idx
		end
		if sorting_col then
			local comparator = function(a, b)
				local valuea = sortkeys[a]["col" .. sorting_col] or ''
				local valueb = sortkeys[b]["col" .. sorting_col] or ''
				if sorting_up then
					return valuea < valueb
				end
				return valuea > valueb
			end
			table.sort(sortindices, comparator)
		end
		result = {}
		for idx in pairs(values) do
			local valuerow = values[sortindices[idx]]
			value = valuerow["col0"]
			if parameters.formatting == "table" then
				value = mw.ustring.gsub(rowformat .. "$", "$0", value) -- fake end character added for easy gsub
				for i, _ in ipairs(qualifierId) do
					valueq = valuerow["col" .. i]
					if args["rowsubformat" .. i] and valueq then
						-- add fake end character $
						-- gsub $i not followed by a number so $1 doesn't match $10, $11...
						-- remove fake end character
						valueq = mw.ustring.gsub(args["rowsubformat" .. i] .. "$", "$" .. i .. "(%D)", valueq .. "%1")
						valueq = string.sub(valueq, 1, -2)
					end
					value = mw.ustring.gsub(value, "$" .. i .. "(%D)", (valueq or '') .. "%1")
				end
				value = string.sub(value, 1, -2) -- remove fake end character
				value = expandBraces(value, rowformat)
			else
				value = expandBraces(value, parameters.formatting)
			end
			result[#result + 1] = value
			if not parameters.list then
				break
			end
		end
		result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
	else
		-- return first element
		local claim = claims[sortindices[1]]
		result, _, error = getValueOfClaim(claim, qualifierId[1], parameters)
		if result and references then result = result .. getReferences(claim) end
	end
	
	if result then return result else
		if showerrors then return error else return default end
	end
end

-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
-- 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
-- uses the newer mw.wikibase calls instead of directly using the snaks
-- 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
p.getTAValue = function(frame)
    local ent = mw.wikibase.getEntityObject()
    local props = ent:formatPropertyValues('P1323')
    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
end

-- look into entity object
function p.ViewSomething(frame)
	local f = (frame.args[1] or frame.args.item) and frame or frame:getParent()
	local id = f.args.item
	if id and (#id == 0) then
		id = nil
	end
	local data = mw.wikibase.getEntityObject(id)
	if not data then
		return nil
	end

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			if type(data) == "table" then
				return frame:extensionTag('syntaxhighlight', mw.text.jsonEncode(data, mw.text.JSON_PRETTY), {lang = 'json'})
			else
				return tostring(data)
			end
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		
		i = i + 1
	end
end

-- Dump data tree structure
-- From pl:Module:Wikidane, by User:Paweł Ziemian
-- Funció pensada com a eina d'ajuda en previsualització.
function p.Dump(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return i18n.warnDump
	end
	
	local f = frame.args[1] and frame or frame:getParent()

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return frame:extensionTag('syntaxhighlight', mw.dumpObject(data), {lang = 'json'}) .. i18n.warnDump
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return i18n.warnDump
		end
		
		i = i + 1
	end
end

-- Look into entity object
-- From pl:Module:Wikidane, function V, by User:Paweł Ziemian
function p.getEntityFromTree(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return nil
	end
	
	local f = frame.args[1] and frame or frame:getParent()
	
	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return tostring(data)
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		
		i = i + 1
	end
end

-- getParentValues: returns a property value with its instance label fetching a recursive tree

local function uc_first(word)
	return mw.ustring.upper(mw.ustring.sub(word, 1, 1)) .. mw.ustring.sub(word, 2)
end

local function getPropertyValue(id, property, parameter, langs, editicon)
	local entity = mw.wikibase.getEntityObject(id)
	if not (entity and entity.claims) then return end
	
	local claims = entity.claims[property]
	if not claims then return end
	-- get initial sort indices
	local sortindices = {}
	for idx in pairs(claims) do
		sortindices[#sortindices + 1] = idx
	end
	-- sort by claim rank
	local comparator = function(a, b)
		local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
		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 snak = claims[sortindices[1]].mainsnak
	
	local entityId
	local result = '-' -- default for 'no value'
	if snak.datavalue then
		entityId = "Q" .. tostring(snak.datavalue.value['numeric-id'])
		result, _ = getSnakValue(snak, {formatting=parameter, lang=langs, editicon=editicon})
	end
	
	return entityId, result
end

function p.getParentValues(frame)
	local args = frame.args
	local id = args.item or frame:getParent().args.item; if id == "" then id = nil end
	local languages = findLang()
	local propertySup = args["property"]; if (propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entity
	local propertyLabel = args["label"]; if (propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instance
	local propertyLink = args["valuetext"]; if propertyLink == "" then propertyLink = nil end --internallink
	local upto = args["upto"]; if upto == "" then upto = nil end
	local labelShow = args["labelshow"]; if labelShow == "" then labelShow = nil end
	local rowformat = args["rowformat"]; if (rowformat == nil or rowformat == "") then rowformat = "$0 = $1" end
	local separator = args["separator"]; if (separator == nil or separator == "") then separator = "<br />" end
	local sorting = args["sorting"]; if sorting == "" then sorting = nil end
	local editicon = not (args.editicon == "false" or args.editicon == "no")
	
	local lastlabel = uc_first(upto or '')
	local maxloop = tonumber(upto) or (lastlabel == '' and 10 or 50)
	
	local labelFilter = {}
	if labelShow then
		for i, v in ipairs(mw.text.split(labelShow, "/")) do
			labelFilter[uc_first(v)] = true
		end
	end
	
	local result = {}
	local label, link, linktext
	
	for iter = 1, maxloop do
		local label, link
		id, link = getPropertyValue(id, propertySup, "internallink", languages, editicon)
		if id then
			_, label = getPropertyValue(id, propertyLabel, "label", languages)
			if label and link then
				if propertyLink then
					_, linktext = getPropertyValue(id, propertyLink, "label", languages)
					if linktext then
						link = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")
					end
				end
				label = case(label, "infoboxlabel", languages[1])
				if labelShow == nil or labelFilter[label] then
					result[#result + 1] = {label, link}
					labelFilter[label] = nil -- only first label found
				end
				if label == lastlabel then
					break
				end
			else
				break
			end
		else
			break
		end
	end
	
	local ret = {}
	local first = 1
	local last = #result
	local iter = 1
	if sorting == "-1" then first = #result; last = 1; iter = -1 end

	for i = first, last, iter do
		local rowtext = mw.ustring.gsub(rowformat, "$[01]", {["$0"] = result[i][1], ["$1"] = result[i][2]})
		ret[#ret +1] = expandBraces(rowtext, rowformat)
	end
	return mw.text.listToText(ret, separator, separator)
end

function p.linkWithParentLabel(frame)
	local args = {}
	for k, v in pairs(frame.args) do -- metatable
		args[k] = v
	end
	args.list = "true"
	args.formatting = "internallink"
	args.separator = "/·/"
	local pargs = frame:getParent().args
	local link_list = p._main(args, pargs) -- get internal link of property/qualifier
	if link_list == nil then
		return
	end
	local link_table = mw.text.split(link_list, "/·/", true)
	args.formatting = "raw"
	local items_list = p._main(args, pargs) -- get item of property/qualifier
	local items_table = mw.text.split(items_list, "/·/", true)
	args.property = args.parent
	args.qualifier = nil
	args.formatting = "label"
	args.list = "false"
	for i, v in ipairs(items_table) do
		args.item = v
		local link_label = p._main(args, pargs) -- get label of parent property
		if link_label then
			link_table[i] = mw.ustring.gsub(link_table[1] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
		end
	end
	
	return mw.text.listToText(link_table)
end

function p.years_old(frame)
	local args = frame.args
	local id = args.item; if id == '' then id = nil end
	local lang = mw.language.new('en')
	
	local function bestclaim(claims)
		-- get initial sort indices
		local sortindices = {}
		for idx in pairs(claims) do
			sortindices[#sortindices + 1] = idx
		end
		-- sort by claim rank
		local comparator = function(a, b)
			local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
			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)
		return claims[sortindices[1]]
	end
	
	local function fetchsnak(id, snak)
		local ret = mw.wikibase.getEntityObject(id)
		for i, v in ipairs(snak) do
			if ret == nil then break end
			if v == 1 then
				ret = bestclaim(ret)
			else
				ret = ret[v]
			end
		end
		return ret
	end
	
	local birth = fetchsnak(id, {'claims', 'P569', 1, 'mainsnak', 'datavalue', 'value'})
	if type(birth) ~= 'table' or birth.time == nil or birth.precision == nil or birth.precision < 8 then
		return
	end
	local death = fetchsnak(id, {'claims', 'P570', 1, 'mainsnak', 'datavalue', 'value'})
	if type(death) ~= 'table' or death.time == nil or death.precision == nil then
		death = {['time'] = lang:formatDate('c'), ['precision'] = 11} -- current date
	elseif death.precision < 8 then
		return
	end
	
	local dates = {}
	dates[1] = {['min'] = {}, ['max'] = {}, ['precision'] = birth.precision}
	dates[1].min.year = tonumber(mw.ustring.match(birth.time, "^[+-]?%d+"))
	dates[1].min.month = tonumber(mw.ustring.match(birth.time, "\-(%d%d)\-"))
	dates[1].min.day = tonumber(mw.ustring.match(birth.time, "\-(%d%d)T"))
	dates[1].max = mw.clone(dates[1].min)
	dates[2] = {['min'] = {}, ['max'] = {}, ['precision'] = death.precision}
	dates[2].min.year = tonumber(mw.ustring.match(death.time, "^[+-]?%d+"))
	dates[2].min.month = tonumber(mw.ustring.match(death.time, "\-(%d%d)\-"))
	dates[2].min.day = tonumber(mw.ustring.match(death.time, "\-(%d%d)T"))
	dates[2].max = mw.clone(dates[2].min)
	
	for i, d in ipairs(dates) do
		if d.precision == 10 then -- month
			d.min.day = 1
			local timestamp = string.format("%04d", tostring(math.abs(d.max.year)))
				.. string.format("%02d", tostring(d.max.month))
				.. "01"
			d.max.day = tonumber(lang:formatDate("j", timestamp .. " + 1 month - 1 day"))
		elseif d.precision < 10 then -- year or decade
			d.min.day = 1
			d.min.month = 1
			d.max.day = 31
			d.max.month = 12
			if d.precision == 8 then -- decade
				d.max.year = d.max.year + 9
			end
		end
	end
	
	local function age(d1, d2)
		local years = d2.year - d1.year
		if d2.month < d1.month or (d2.month == d1.month and d2.day < d1.day) then
			years = years - 1
		end
		if d2.year > 0 and d1.year < 0 then
			years = years - 1 -- no year 0
		end
		return years
	end
	
	local old_min = age(dates[1].max, dates[2].min)
	local old_max = age(dates[1].min, dates[2].max)
	local old = old_min == old_max and old_min or old_min .. "/" .. old_max
	if args.formatting then
		old = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
	end
	
	return old
end

-- Gets a label in a given language (content language by default) or its fallbacks, optionnally linked.
function p.getLabel(frame)
	local args = frame.args
	local id = mw.text.trim(args[1] or "")
	if id == "" then return end
	local editicon = not (args.editicon == "false" or args.editicon == "no")
	local languages = findLang()
	
	local pencil = ''
	local label, lang
	if args.label then
		label = args.label
	else
		local languages = findLang()
		if languages[1] == wiki.langcode then
			-- exceptions or labels fixed
			local exist, labels = pcall(require, wiki.module_title .. "/labels")
			if exist and next(labels.infoboxLabelsFromId) ~= nil then
				label = labels.infoboxLabelsFromId[id]
			end
		end
		
		if label == nil then
			label, lang = getLabelByLangs(id, languages)
			if label then
				if args.itemgender and feminineGender(args.itemgender) then
					label = feminineForm(id, lang) or label
				end
				label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
			end
			pencil = addEditIcon(id, lang, languages[1], editicon)
		end
	end
	
	local linked = args.linked
	if linked and linked ~= "" and linked ~= "no" then
		local article = mw.wikibase.getSitelink(id) or ("d:" .. id)
		return "[[" .. article .. "|" .. (label or id) .. "]]" .. pencil
	else
		return (label or id) .. pencil
	end
end

-- Return default language used
function p.lang(frame)
	return findLang(frame.args[1])[1]
end

return p