Módulo:Wikidata nisqapaq musuqchasqapura wakin kaynin

Contenido eliminado Contenido añadido
Elwinlhq-pa 644806 hukchasqanta kutichisqa (rimay)
Unanchacha: Deshacer
Sin resumen de edición
Siq'i 1:
-- version 20200615 from master @cawiki
--[[*********************************************************************************
* Nombre: Módulo:Wikidata
*
* Descripción: Este módulo devuelve el valor o valores con o sin formato
* específico a una propiedad de Wikidata.
*
* Fecha última revisión: 2 de mayo de 2019.
*
* Estado: En uso.
*
*********************************************************************************`-- ]]
 
local p = {}
local datequalifiers = {'P585', 'P571', 'P580', 'P582'}
local es = mw.language.new('es')
local primera = true
--local marco Ojo. marco no debe definirse como local pues si se hace así puede fallar.
--[[ =========================================================================
Mensajes de error
========================================================================= `-- ]]
 
-- Initialization of variables --------------------
local avisos = {
 
["errores"] = {
local i18n = { -- internationalisation at [[Module:Wikidata/i18n]]
["property-param-not-provided"] = "Parámetro de la propiedad no proporcionado.",
["errors"] = {
["entity-not-found"] = "Entrada no encontrada.",
["unknownproperty-claimnot-typefound"] = "TipoProperty denot notificación desconocidafound.",
["unknownqualifier-snaknot-typefound"] = "TipoQualifier denot dato desconocidofound.",
["unknown-datavalue-type"] = "Formato de dato desconocido.",
["unknown-entity-type"] = "Tipo de entrada desconocido.",
["unknown-value-module"] = "Debe ajustar ambos parámetros de valor y el valor del módulo de funciones.",
["value-module-not-found"] = "No se ha encontrado el módulo apuntado por valor-módulo.",
["value-function-not-found"] = "No se ha encontrado la función apuntada por valor-función.",
["other entity"] = "Enlaces a elementos diferentes desactivado."
},
["somevalue"] = "''valor desconocido''",
["novaluedatetime"] = ""{
-- $1 is a placeholder for the actual number
["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 1st century AD dates
[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] = "$100000 years", -- precision: hundred thousand years; thousand separators added afterwards
[5] = "$10000 years", -- precision: ten thousand years; thousand separators added afterwards
[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
["hms"] = {["hours"] = "h", ["minutes"] = "m", ["seconds"] = "s"}, -- duration: xh xm xs
},
["years-old"] = {
["singular"] = "", -- year old, as in {{PLURAL:$1|singular|plural}}
["plural"] = "", -- years old
["paucal"] = "", -- for languages with 3 plural forms as in {{PLURAL:$1|singular|paucal|plural}}
},
["cite"] = { -- cite parameters
["title"] = "title",
["author"] = "author",
["date"] = "date",
["pages"] = "pages",
["language"] = "language",
-- cite web parameters
["url"] = "url",
["website"] = "website",
["access-date"] = "access-date",
["archive-url"] = "archive-url",
["archive-date"] = "archive-date",
["publisher"] = "publisher",
["quote"] = "quote",
-- cite journal parameters
["work"] = "work",
["issue"] = "issue",
["issn"] = "issn",
["doi"] = "doi"
},
-- local wiki settings
["addpencil"] = false, -- adds a pencil icon linked to Wikidata statement, planned to overwrite by Wikidata Bridge
["categorylabels"] = "", -- Category:Pages with Wikidata labels not translated (void for no local category)
["addfallback"] = {} -- additional fallback language codes
}
 
local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
-- Módulos y funciones utilizadas
local elementoTabla = require('Módulo:Tablas').elemento
--
-- Módulos en los que están definidos los tipos de datos más habituales si son
-- diferentes de Wikidata/Formatos
--
local modulosTipos = {
['altura'] = 'Módulo:Wikidata/Formato magnitud',
['área'] = 'Módulo:Wikidata/Formato magnitud',
['bandera'] = 'Módulo:Wikidata/Formatos país',
['educado en'] = 'Módulo:Wikidata/Formatos educación',
['imagen'] = 'Módulo:Wikidata/Formato imagen',
['lugar'] = 'Módulo:Wikidata/Formato lugar',
['formatoLugar']= 'Módulo:Wikidata/Formato lugar',
['magnitud'] = 'Módulo:Wikidata/Formato magnitud',
['movimiento'] = 'Módulo:Wikidata/Formato movimiento',
['periodicidad']= 'Módulo:Wikidata/Formato magnitud',
['premio'] = 'Módulo:Wikidata/Formato premio',
}
 
local required = ... -- variadic arguments from require function
local modulosTiposComplejos = {
local wiki =
['nacionalidad'] = 'Módulo:Wikidata/Formatos país',
{
langcode = mw.language.getContentLanguage().code,
module_title = required or mw.getCurrentFrame():getTitle()
}
 
local untranslated -- used in infobox modules: nil or true
--[[ =========================================================================
local _ -- variable for unused returned values, avoiding globals
Función para pasar el frame cuando se usa en otros módulos.
========================================================================= `-- ]]
function p:setFrame(frame)
marco = frame
end
--[[ =========================================================================
Función para identificar el ítem correspondiente a la página o otro dado.
Esto último aún no funciona.
========================================================================= `-- ]]
 
-- Module local functions --------------------------------------------
function SelecionEntidadPorId( id )
 
-- Credit to http://stackoverflow.com/a/1283608/2644759, cc-by-sa 3.0
if id and id ~= '' then
local function tableMerge(t1, t2)
return mw.wikibase.getEntityObject( id )
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
return mw.wikibase.getEntityObject()
end
end
return t1
end
 
local function loadI18n(lang)
local exist, res = pcall(require, wiki.module_title .. "/i18n")
if exist and next(res) ~= nil then
tableMerge(i18n, res.i18n)
cases = res.cases
end
if lang ~= wiki.langcode then
exist, res = pcall(require, wiki.module_title .. "/i18n/" .. lang)
if exist and next(res) ~= nil then
tableMerge(i18n, res.i18n)
tableMerge(cases, res.cases)
end
end
end
 
-- Table of language codes: requested or default and its fallbacks
--[[ =========================================================================
local function findLang(langcode)
Función que identifica si el valor devuelto es un ítem o una propiedad
if mw.language.isKnownLanguageTag(langcode or '') == false then
y en función de eso añade el prefijo correspondiente
local cframe = mw.getCurrentFrame()
========================================================================= `-- ]]
local pframe = cframe:getParent()
 
langcode = pframe and pframe.args.lang
function SelecionEntidadPorValor( valor )
if mw.language.isKnownLanguageTag(langcode or '') == false then
local prefijo = ''
if not mw.title.getCurrentTitle().isContentPage then
if valor['entity-type'] == 'item' then
langcode = cframe:preprocess('{{int:lang}}')
prefijo = 'q' -- Prefijo de ítem
end
elseif valor['entity-type'] == 'property' then
if mw.language.isKnownLanguageTag(langcode or '') == false then
prefijo = 'p' -- Prefijo de propiedad
langcode = wiki.langcode
else
end
return formatoError( 'unknown-entity-type' )
end
end
return prefijo .. valor['numeric-id'] -- Se concatena el prefijo y el código numérico
loadI18n(langcode)
local languages = mw.language.getFallbacksFor(langcode)
table.insert(languages, 1, langcode)
if langcode == wiki.langcode then
for _, l in ipairs(i18n.addfallback) do
table.insert(languages, l)
end
end
return languages
end
 
-- Argument is 'set' when it exists (not nil) or when it is not an empty string.
--[[ =========================================================================
local function isSet(var)
Función auxiliar para dar formato a los mensajes de error
return not (var == nil or var == '')
========================================================================= `-- ]]
 
function formatoError( clave )
return '<span class="error">' .. avisos.errores[clave] .. '</span>'
end
--[[ =========================================================================
Función para determinar el rango
========================================================================= `-- ]]
function getRango(tablaDeclaraciones)
 
-- Set local rankcase to =a 'deprecated'label
local function case(localcase, label, ...)
 
if not isSet(label) then return label end
for indice, declaracion in pairs(tablaDeclaraciones) do
if declaracion.rank == 'preferred' then
if localcase == "smallcaps" then
return 'preferred'
return '<span style="font-variant: small-caps;">' .. label .. '</span>'
elseif declaracion.rank == 'normal' then
elseif cases[localcase] then
rank = 'normal'
return cases[localcase](label, ...)
end
end
 
return ranklabel
end
 
-- get safely a serialized snak
--[[ =========================================================================
local function getSnak(statement, snaks)
Función para determinar la declaracion o declaraciones de mayor rango
local ret = statement
========================================================================= `-- ]]
for i, v in ipairs(snaks) do
function p.filtrarDeclaracionPorRango(tablaDeclaraciones)
if not ret then return end
local rango = getRango(tablaDeclaraciones)
ret = ret[v]
local tablaAuxiliar = tablaDeclaraciones
tablaDeclaraciones = {}
 
for indice, declaracion in pairs(tablaAuxiliar) do
if declaracion.rank == rango then
table.insert(tablaDeclaraciones, declaracion)
end
end
return tablaDeclaracionesret
end
 
-- mw.wikibase.getLabelWithLang or getLabelByLang with a table of languages
--[[ =========================================================================
local function getLabelByLangs(id, languages)
Función para seleccionar el tipo de declaración: Referencia, valor principal
local label
o calificador
local lang
========================================================================= `-- ]]
for _, l in ipairs(languages) do
 
if l == wiki.langcode then
function seleccionDeclaracion(declaracion, opciones)
-- using getLabelWithLang when possible instead of getLabelByLang, do not solve redirects pending phab:T157868
local fuente = {}
label, l = mw.wikibase.getLabelWithLang(id)
local propiedadFuente = {}
local calificador = opciones.formatoCalificador ~= '()' and opciones.calificador
 
if calificador ~= '' and calificador and declaracion['qualifiers'] then
if declaracion['qualifiers'][mw.ustring.upper(calificador)] then
return declaracion.qualifiers[mw.ustring.upper(calificador)][1] -- devuelve el calificador (solo devolverá el primer valor)
else
label = mw.wikibase.getLabelByLang(id, l)
return "" --Para que no lance excepción si no existe el calificador
end
if label then
elseif opciones.dato == 'fuente' and declaracion['references'] then
lang = l
fuente = declaracion.references[1]['snaks']
break
for k,v in pairs(fuente) do
propiedadFuente = k
end
end
return declaracion.references[1]['snaks'][propiedadFuente][1] -- devuelve la fuente (queda que se itinere la tabla)
return label, lang
elseif (calificador == '' or not calificador) and (opciones.dato ~= 'fuente') then
end
return declaracion.mainsnak -- devuelve el valor principal
 
-- getBestStatements if bestrank=true, else getAllStatements with no deprecated
local function getStatements(entityId, property, bestrank)
local claims = {}
if not (entityId and mw.ustring.match(property, "^P%d+$")) then return claims end
if bestrank then
claims = mw.wikibase.getBestStatements(entityId, property)
else
local allclaims = mw.wikibase.getAllStatements(entityId, property)
return ''
for _, c in ipairs(allclaims) do
if c.rank ~= "deprecated" then
table.insert(claims, c)
end
end
end
return claims
end
 
-- Is gender femenine? true or false
--[[ =========================================================================
local function feminineGender(id)
Función para recopilar las declaraciones
local claims = mw.wikibase.getBestStatements(id or mw.wikibase.getEntityIdForCurrentPage(),'P21')
========================================================================= `-- ]]
if getSnak(claims, {1, "mainsnak", "datavalue"}) == nil then -- no claim, novalue or somevalue
 
function p.getDeclaraciones(entityId)
 
 
-- == Comprobamos que existe un ítem enlazado a la página en Wikidata ==
if not pcall (SelecionEntidadPorId, entityId ) then
return false
else
local genderId = claims[1].mainsnak.datavalue.value.id
if genderId == "Q6581072" or genderId == "Q1052281" or genderId == "Q43445" then -- female, transgender female, female organism
return true
end
end
return false
local entidad = SelecionEntidadPorId(entityId)
end
 
-- Fetch female form of label
if not entidad then
local function feminineForm(id, lang)
return '' -- Si la página no está enlazada a un ítem no devuelve nada
local feminine_claims = getStatements(id, 'P2521')
for _, feminine_claim in ipairs(feminine_claims) do
if getSnak(feminine_claim, {'mainsnak', 'datavalue', 'value', 'language'}) == lang then
return feminine_claim.mainsnak.datavalue.value.text
end
end
end
 
-- Add an icon for no label in requested language
-- == Comprobamos que el ítem tiene declaraciones (claims) ==
local function addLabelIcon(label_id, lang, uselang, icon)
 
local ret_lang, ret_icon = '', ''
if not entidad.claims then
if icon then
return '' -- Si el ítem no tiene declaraciones no devuelve nada
if lang and lang ~= uselang then
ret_lang = " <sup>(" .. lang .. ")</sup>"
end
if label_id and (lang == nil or lang ~= uselang) then
ret_icon = " [[File:Noun Project label icon 1116097 cc mirror.svg|10px|baseline|"
.. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain()
.. "|link=https://www.wikidata.org/wiki/Special:EntityPage/" .. label_id .. "?uselang=" .. uselang .. "]]"
untranslated = true
end
if isSet(i18n.categorylabels) and lang ~= uselang and uselang == wiki.langcode then
ret_icon = ret_icon .. '[[' .. i18n.categorylabels .. (lang and ']]' or '/Q]]')
end
end
return ret_lang .. ret_icon
-- == Declaración de formato y concatenado limpio ==
 
return entidad.claims
end
 
-- Add an icon for editing a statement with requirements for Wikidata Bridge
--[[ =========================================================================
local function addEditIcon(parameters)
Función para crear la cadena que devolverá la declaración
local ret = ''
========================================================================= `-- ]]
if i18n.addpencil and parameters.editicon and parameters.id and parameters.property then
ret = ' <span data-bridge-edit-flow="single-best-value">'
local function valinQualif(claim, qualifs)
.. "[[File:Arbcom ru editing.svg|10px|baseline|"
local claimqualifs = claim.qualifiers
.. mw.message.new('Editlink'):inLanguage(parameters.lang[1]):plain()
local i,qualif
.. "|link=https://www.wikidata.org/wiki/" .. parameters.id .. "?uselang=" .. parameters.lang[1] .. "#" .. parameters.property .. "]]"
local vals, vals1, datavalue, value
.. "</span>"
if not claimqualifs then
return nil
end
return ret
for i, qualif in pairs(qualifs) do
end
vals = claimqualifs[qualif]
-- add edit icon to the last element of a table
if vals then
local function addEditIconTable(thetable, parameters)
vals1 = vals[1]
if #thetable == 0 or not i18n.addpencil then
if vals1 then
return thetable
datavalue=vals1.datavalue
end
local last_element = thetable[#thetable]
if datavalue then
local the_icon = addEditIcon(parameters)
value = datavalue.value
-- add it before last html closing tags
local tags = ''
if value then
local rev_element = string.reverse(last_element)
return value.time
for tag in string.gmatch(rev_element, '(>%l+/<)') do
end
if string.match(rev_element, '^' .. tags .. tag) then
end
tags = tags .. tag
end
else
break
end
end
local last_tags = string.reverse(tags)
end
local offset = string.find(last_element, last_tags .. '$')
 
if offset then
function p.getPropiedad(opciones, declaracion)
thetable[#thetable] = string.sub(last_element, 1, offset - 1) .. the_icon .. last_tags
local propiedad = {}
local tablaOrdenada = {}
 
if opciones.propiedad == 'precisión' or opciones.propiedad == 'latitud' or opciones.propiedad == 'longitud' then
propiedad = 'P625' -- Si damos el valor latitud, longitud o precisión equivaldrá a dar p625
else
thetable[#thetable] = last_element .. the_icon
propiedad = opciones.propiedad -- En el resto de casos se lee lo dado
end
return thetable
end
 
-- Escape Lua captures
if not propiedad then -- Comprobamos si existe la propiedad dada y en caso contrario se devuelve un error
local function captureEscapes(text)
return formatoError( 'property-param-not-provided' )
return mw.ustring.gsub(text, "(%%%d)", "%%%1")
end
end
 
-- expandTemplate or callParserFunction
if declaracion then
local function expandBraces(text, formatting)
tablaOrdenada = declaracion
if text == nil or formatting == nil then return text end
elseif not p.getDeclaraciones(opciones.entityId) then
-- only expand braces if provided in argument, not included in value as in Q1164668
return formatoError( 'other entity' )
if mw.ustring.find(formatting, '{{', 1, true) == nil then return text end
elseif p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)] then
if type(text) ~= "string" then
tablaOrdenada = p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)]
text = tostring(text)
else
return ''
end
for braces in mw.ustring.gmatch(text, "{{(.-)}}") do
local modulo, funcion
local parts = mw.text.split(braces, "|")
local title_part = parts[1]
funcion = opciones['valor-función'] or opciones['value-function'] or opciones['funcion']
local parameters = {}
for i = 2, #parts do
if funcion then
local subparts = mw.ustring.find(parts[i], "=")
modulo = modulosTiposComplejos[funcion]
if subparts then
parameters[mw.ustring.sub(parts[i], 1, subparts-1)] = mw.ustring.sub(parts[i], subparts+1, -1)
if modulo then
else
return require(modulo)[funcion](tablaOrdenada, opciones)
table.insert(parameters, parts[i])
end
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 = captureEscapes(braces_expanded)
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
return text
end
 
-- Resolve Wikidata redirects, pending phab:T157868
-- Evitar que pete cuando se haga el find en opciones['formatoTexto'] si vale nil
local function resolveEntityId(id)
if not opciones['formatoTexto'] then
if not id or not mw.wikibase.isValidEntityId(id) then return id end
opciones['formatoTexto'] = ''
-- if no label in English, maybe it is a redirect
-- not using mw.title.new(id).isRedirect as it is expensive
-- currently getLabelByLang does not follows redirects
if mw.wikibase.getLabelByLang(id, 'en') == nil then
local entity = mw.wikibase.getEntity(id) -- expensive function
if not entity then return nil end
if id ~= entity.id then
-- Qid redirected to be fixed
-- see [[Special:WhatLinksHere/Template:Track/wikidata/redirect]]
require(wiki.module_title .. '/debug').track('redirect')
require(wiki.module_title .. '/debug').track('redirect/' .. id)
else
-- no redirect and no English label, fix it to avoid expensive functions
require(wiki.module_title .. '/debug').track('label')
require(wiki.module_title .. '/debug').track('label/' .. id)
end
return entity.id
end
return id
end
 
-- format data type math
--Dejar en su caso los valores de mayor rango
local function printDatatypeMath(data)
if (opciones.rangoMayor == 'sí') then
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
tablaOrdenada = p.filtrarDeclaracionPorRango(tablaOrdenada)
end
 
-- format data type musical-notation
local function printDatatypeMusical(data, formatting)
local attr = {}
if formatting == 'sound' then
attr.sound = 1
end
return mw.getCurrentFrame():extensionTag('score', data, attr)
end
 
-- format data type string
--Ordenar en su caso por fecha. Ver la función chronosort de :fr:Module:Wikidata/Récup
local function printDatatypeString(data, parameters)
if opciones.ordenar == 'por fecha' then
if mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
require('Módulo:Tablas').ordenar(tablaOrdenada,
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', {['$1'] = data}), parameters.formatting)
function(elemento1,elemento2)
elseif parameters.case then
local fecha1 = valinQualif(elemento1, datequalifiers) or '' -- elemento1.qualifiers.P580[1].datavalue.value.time or ''
return case(parameters.case, data, parameters.lang[1])
local fecha2 = valinQualif(elemento2, datequalifiers) or '' -- elemento2.qualifiers.P580[1].datavalue.value.time or ''
return fecha1 < fecha2
end
)
end
local data_number = string.match(data, "^%d+")
if data_number then -- sort key by initial number and remaining string
if not tablaOrdenada[1] then
local sortkey = string.format("%019d", data_number * 1000)
return
return data, sortkey .. string.sub(data, #data_number + 1)
end
return data
end
 
-- format data type url
-- == Si solo se desea que devuelva un valor ==
local function printDatatypeUrl(data, parameters)
-- Pendiente eliminar el parámetro y sustituirlo por un nuevo valor del parámetro lista=no que haría lo mismo que opciones.uno = sí
if parameters.formatting == 'weblink' then
if opciones.uno == 'sí' then -- Para que devuelva el valor de índice 1
local label_parts = mw.text.split(string.gsub(data, '/$', ''), '/')
tablaOrdenada = {tablaOrdenada[1]}
local label = string.gsub(label_parts[3], '^www%.', '')
elseif opciones.uno == 'último' then -- Para que devuelva la última entrada de la tabla
if #label_parts > 3 then
tablaOrdenada = {tablaOrdenada[#tablaOrdenada]}
label = label .. '…'
end
return '[' .. data .. ' ' .. label .. ']'
end
return printDatatypeString(data, parameters)
end
 
-- format data type external-id
-- == Creamos una tabla con los valores que devolverá ==
local function printDatatypeExternal(data, parameters)
if parameters.formatting == 'externalid' then
local p_stat = mw.wikibase.getBestStatements(parameters.property, 'P1630') -- formatter URL
local p_link_pattern = getSnak(p_stat, {1, "mainsnak", "datavalue", "value"})
if p_link_pattern then
local p_link = mw.ustring.gsub(p_link_pattern, '$1', {['$1'] = data})
return '[' .. p_link .. ' ' .. data .. ']'
end
end
return printDatatypeString(data, parameters)
end
 
-- format data type commonsMedia
local formatoDeclaraciones = {}
local function printDatatypeMedia(data, parameters)
local hayDeclaraciones
local icon
if not string.find((parameters.formatting or ''), '$1', 1, true) then
for indice, declaracion in pairs(tablaOrdenada) do
icon = "no-icon"
declaracionFormateada = p.formatoDeclaracion(declaracion, opciones)
if declaracionFormateada and declaracionFormateada ~= '' then
table.insert(formatoDeclaraciones, declaracionFormateada)
hayDeclaraciones = true
end
end
primera = true
if not hayDeclaraciones then
return
end
return printDatatypeString(data, parameters), icon
end
 
-- format data type globe-coordinate
-- Aplicar el formato a la lista de valores según el tipo de lista de las
local function printDatatypeCoordinate(data, formatting)
-- opciones
local function globes(globe_id)
local globes = {['Q3134']='callisto',['Q596']='ceres',['Q15040']='dione',['Q2']='earth',['Q3303']='enceladus',
['Q3143']='europa',['Q17975']='phoebe',['Q3169']='ganymede',['Q3123']='io',['Q17958']='iapetus',
['Q308']='mercury',['Q15034']='mimas',['Q405']='moon',['Q15050']='rhea',['Q15047']='tethys',
['Q111']='mars',['Q2565']='titan',['Q3359']='triton',['Q313']='venus',['Q3030']='vesta'}
return globes[globe_id]
end
local function roundPrecision(num, prec)
return p.formatoLista(formatoDeclaraciones, opciones)
if prec == nil or prec <= 0 then return num end
local sig = 10^math.floor(math.log10(prec)+.5) -- significant figure from sexagesimal precision: 0.00123 -> 0.001
return math.floor(num / sig + 0.5) * sig
end
local precision = data.precision
local latitude = roundPrecision(data.latitude, precision)
local longitude = roundPrecision(data.longitude, precision)
if formatting and string.find(formatting, '$lat', 1, true) and string.find(formatting, '$lon', 1, true) then
local ret = mw.ustring.gsub(formatting, '$l[ao][tn]', {['$lat'] = latitude, ['$lon'] = longitude})
if string.find(formatting, '$globe', 1, true) then
local myglobe = 'earth'
if isSet(data.globe) then
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
myglobe = globes(globenum) or 'earth'
end
ret = mw.ustring.gsub(ret, '$globe', myglobe)
end
return expandBraces(ret, formatting)
elseif formatting == 'latitude' then
return latitude, "no-icon"
elseif formatting == 'longitude' then
return longitude, "no-icon"
elseif formatting == 'dimension' then
return data.dimension, "no-icon"
else --default formatting='globe'
if isSet(data.globe) == false or data.globe == 'http://www.wikidata.org/entity/Q2' then
return 'earth', "no-icon"
else
local globenum = mw.text.split(data.globe, 'entity/')[2]
return globes(globenum) or globenum, "no-icon"
end
end
end
 
-- Local functions for data value quantity
-- Función que sirve para comprobar si una entidad tiene una propiedad con un
local function unitSymbol(id, lang) -- get unit symbol or code
-- valor específico
local unit_symbol = ''
-- Parámetros:
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
-- · entidad: tabla de la entidad de Wikidata
unit_symbol = require(wiki.module_title .. "/Units").getUnit(0, '', id, true)
-- · propiedad: identificador de Wikidata para la propiedad
end
-- · valor: valor de la propiedad en Wikidata
if unit_symbol == '' then
function p.tieneValorPropiedad(entidad, propiedad, valor)
-- fetch it
local claims = mw.wikibase.getBestStatements(id, 'P5061')
if entidad and entidad.claims and entidad.claims[propiedad] then
if #claims > 0 then
local mainsnaklangclaims = {}
table.insert(lang, 'mul') -- multilingual as last try
for key_,value snak in ipairs(entidad.claims[propiedad]) do
local snak_language = getSnak(snak, {"mainsnak", "datavalue", "value", "language"})
if value and value.mainsnak then
if snak_language and not langclaims[snak_language] then -- just the first one by language
mainsnak = value.mainsnak
langclaims[snak_language] = snak.mainsnak.datavalue.value.text
if mainsnak.datatype == 'wikibase-item' and
end
mainsnak.snaktype == 'value' and
end
mainsnak.datavalue.value.id == valor then
for _, l in ipairs(lang) do
return true
if langclaims[l] then
return langclaims[l]
end
end
end
end
return unit_symbol
return false
end
 
local function getUnit(amount, id, parameters) -- get unit symbol or name
-- Función que sirve para devolver la leyenda (P2096) de una imagen (P18) en Wikidata en un determinado idioma
local suffix = ''
-- La función se llama así: {{#invoke:Wikidata |getLeyendaImagen | <PARÁMETRO> | lang=<ISO-639code> |id=<QID>}}
if parameters.formatting == "unitcode" then
-- Devuelve PARÁMETRO, a menos que sea igual a "FETCH_WIKIDATA", del objeto QID (llamada que consume recursos)
-- get unit symbol
-- Si se omite QID o está vacio, se utiliza el artículo actual (llamada que NO consume recursos)
local unit_symbol = unitSymbol(id, parameters.lang)
-- Si se omite lang se utiliza por defecto el idioma local de la wiki, en caso contrario el idioma del código ISO-639
if isSet(unit_symbol) then
-- ISO-639 está documentado aquí: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447
suffix = unit_symbol
-- El ranking es: 'preferred' > 'normal' y devuelve la etiqueta de la primera imágen con ranking 'preferred'
end
-- O la etiqueta de la primera imagen with ranking 'normal' si no hay ningún 'preferred'
-- Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
 
p.getLeyendaImagen = function(frame)
-- busca un un elemento concreto en Wikidata (QID), en caso contrario que sea nil
local id = frame.args.id
if id and (#id == 0) then
id = nil
end
if suffix == '' then -- formatting=unit, or formatting=unitcode not found
-- get unit name
local unit_label, lang = getLabelByLangs(id, parameters.lang)
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
suffix = require(wiki.module_title .. "/Units").getUnit(amount, unit_label, id, false)
else
suffix = (unit_label or id) .. addLabelIcon(id, lang, parameters.lang[1], parameters.editicon)
end
end
if suffix ~= '' then
suffix = ' ' .. suffix
end
return suffix
end
 
local function roundDefPrecision(in_num, factor)
-- busca el parámetro del idioma que debería contender un código ISO-639 de dos dígitos
-- rounds out_num with significant figures of in_num (default precision)
-- si no se declara, toma por defecto el idioma local de la wiki (es)
local langout_num = frame.args.langin_num * factor
if factor/60 == math.floor(factor/60) then -- sexagesimal integer
if (not lang) or (#lang < 2) then
return out_num
lang = mw.language.getContentLanguage().code
end
-- first, count digits after decimal mark, handling cases like '12.345e6'
local exponent, prec
local integer, dot, decimals, expstr = in_num:match('^(%d*)(%.?)(%d*)(.*)')
local e = expstr:sub(1, 1)
if e == 'e' or e == 'E' then
exponent = tonumber(expstr:sub(2))
end
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
if exponent then
-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
prec = prec - exponent
end
-- significant figures
local in_bracket = 10^-prec -- -1 -> 10, 5 -> 0.00001
local out_bracket = in_bracket * out_num / in_num
out_bracket = 10^math.floor(math.log10(out_bracket)+.5) -- 1230 -> 1000, 0.00123 -> 0.001
-- round it (credit to Luc Bloom from http://lua-users.org/wiki/SimpleRound)
return math.floor(out_num/out_bracket + (out_num >=0 and 1 or -1) * 0.5) * out_bracket
end
 
-- format data type quantity
-- el primer parámetro sin nombrar es el parámetro local, si se declara
local function printDatatypeQuantity(data, parameters)
local input_parm = mw.text.trim(frame.args[1] or "")
local amount = data.amount
if input_parm == "FETCH_WIKIDATA" or input_parm == "" or input_parm == nil then
amount = mw.ustring.gsub(amount, "%+", "")
local ent = mw.wikibase.getEntityObject(id)
local imgssuffix = ""
local conv_amount, conv_suffix
if ent and ent.claims then
if string.sub(parameters.formatting or '', 1, 4) == "unit" or string.sub(parameters.formatting or '', 1, 8) == "duration" or parameters.convert then
imgs = ent.claims.P18
local unit_id = data.unit
end
unit_id = mw.ustring.sub(unit_id, mw.ustring.find(unit_id, "Q"), -1)
local imglbl
if imgsstring.sub(unit_id, 1, 1) == "Q" then
suffix = getUnit(amount, unit_id, parameters)
-- busca una imagen con ranking 'preferred'
local convert_to
for k1, v1 in pairs(imgs) do
if v1parameters.rankconvert == "preferreddefault" andor v1parameters.qualifiersconvert and== v1.qualifiers.P2096"default2" then
local imglblsexist, units = v1pcall(require, wiki.qualifiersmodule_title .P2096. "/Units")
if exist and next(units.convert_default) ~= nil then
for k2, v2 in pairs(imglbls) do
convert_to = units.convert_default[unit_id]
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
elseif string.sub(parameters.convert or '', 1, 1) == "Q" then
convert_to = resolveEntityId(parameters.convert)
elseif string.sub(parameters.formatting or '', 1, 8) == "duration" then
convert_to = 'Q11574' -- seconds
end
if convert_to and convert_to ~= unit_id then
-- si no hay ninguna, busca una con ranking 'normal'
-- convert units
if (not imglbl) then
local conv_temp = { -- formulae for temperatures ºC, ºF, ªK: [from] = {[to] = 'formula'}
for k1, v1 in pairs(imgs) do
['Q25267'] = {['Q42289'] = '$1*1.8+32', ['Q11597'] = '$1+273.15'},
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
['Q42289'] = {['Q25267'] = '($1-32)/1.8', ['Q11597'] = '($1+459.67)*5/9'},
local imglbls = v1.qualifiers.P2096
['Q11597'] = {['Q25267'] = '$1-273.15', ['Q42289'] = '($1-273.15)*1.8000+32.00'}
for k2, v2 in pairs(imglbls) do
}
if v2.datavalue.value.language == lang then
if conv_temp[unit_id] and conv_temp[unit_id][convert_to] then
imglbl = v2.datavalue.value.text
local amount_f = mw.getCurrentFrame():callParserFunction('#expr', mw.ustring.gsub(conv_temp[unit_id][convert_to], "$1", amount))
conv_amount = math.floor(tonumber(amount_f) + 0.5)
else
local conversions = getStatements(unit_id, 'P2442') -- conversion to standard unit
table.insert(conversions, mw.wikibase.getBestStatements(unit_id, 'P2370')[1]) -- conversion to SI unit
for _, conv in ipairs(conversions) do
if conv.mainsnak.snaktype == 'value' then -- no somevalue nor novalue
if conv.mainsnak.datavalue.value.unit == "http://www.wikidata.org/entity/" .. convert_to then
conv_amount = roundDefPrecision(amount, tonumber(conv.mainsnak.datavalue.value.amount))
break
end
Línea 408 ⟶ 592:
end
end
if conv_amount then
conv_suffix = getUnit(conv_amount, convert_to, parameters)
end
elseif parameters.convert == 'M' and tonumber(amount) > 10^8 then
conv_amount = math.floor(amount/10^6 + 0.5)
conv_suffix = ' M' .. string.sub(suffix, 2)
end
end
end
return imglbl
local lang_obj = mw.language.new(parameters.lang[1])
local sortkey = string.format("%019d", tonumber(amount) * 1000)
if string.sub(parameters.formatting or '', 1, 8) == "duration" then
local sec = tonumber(conv_amount or amount)
if parameters.formatting == 'durationhms' or parameters.formatting == 'durationh:m:s' then
local intervals = {"hours", "minutes", "seconds"}
local sec2table = lang_obj:getDurationIntervals(sec, intervals)
sec2table["seconds"] = (sec2table["seconds"] or 0) + tonumber("." .. (tostring(sec):match("%.(%d+)") or "0")) -- add decimals
local duration = ''
for i, v in ipairs(intervals) do
if parameters.formatting == 'durationh:m:s' then
if i == 1 and sec2table[v] then
duration = duration .. sec2table[v] .. ":"
elseif i == 2 then
duration = duration .. string.format("%02d", sec2table[v] or 0) .. ":"
elseif i == 3 then
local sec_str = tostring(lang_obj:formatNum(sec2table[v] or 0))
duration = duration .. (sec2table[v] < 10 and "0" or "") .. sec_str
end
elseif sec2table[v] then
duration = duration .. lang_obj:formatNum(sec2table[v]) .. i18n.datetime.hms[v] .. (i < 3 and " " or "")
end
end
return duration
else
return lang_obj:formatDuration(sec)
end
end
if parameters.case then
amount = case(parameters.case, amount, parameters.lang[1])
else
amount = lang_obj:formatNum(tonumber(amount))
return input_parm
end
if conv_amount then
local conv_sortkey = string.format("%019d", tonumber(conv_amount) * 1000)
conv_amount = lang_obj:formatNum(tonumber(conv_amount))
if parameters.convert == 'default2' then
return conv_amount .. conv_suffix .. ' (' .. amount .. suffix .. ')', conv_sortkey
else
return conv_amount .. conv_suffix, conv_sortkey
end
end
return amount .. suffix, sortkey
end
 
-- format data type time
-- Función que devuelve el valor de entidad.claims[idPropiedad][ocurrencia].mainsnak.datavalue.value.text
local function printDatatypeTime(data, parameters)
-- con entidad.claims[idPropiedad][ocurrencia].mainsnak.datavalue.value.language = 'es'
-- Dates and times are stored in ISO 8601 format
 
local timestamp = data.time
-- Útil para obtener valores de propiedades de tipo monolingualtext
local post_format
 
local calendar_add = ""
function p.getPropiedadEnEspanyol(idEntidad, idPropiedad)
local precision = data.precision or 11
-- Ver cs:Modul:Wikidata/item formatEntityWithGender
if string.sub(timestamp, 1, 1) == '-' then
--
post_format = i18n.datetime["bc"]
local entidad = mw.wikibase.getEntityObject(idEntidad)
elseif string.sub(timestamp, 2, 3) == '00' then
post_format = i18n.datetime["ad"]
elseif precision > 8 then
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
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
end
local function formatTime(form, stamp)
if not entidad then
local pattern
return
if type(form) == "function" then
pattern = form(stamp)
else
pattern = form
end
stamp = tostring(stamp)
if mw.ustring.find(pattern, "$1") then
return mw.ustring.gsub(pattern, "$1", stamp)
elseif string.sub(stamp, 1, 1) == '-' then -- formatDate() only supports years from 0
stamp = '+' .. string.sub(stamp, 2)
elseif string.sub(stamp, 1, 1) ~= '+' then -- not a valid timestamp, it is a number
stamp = string.format("%04d", stamp)
end
local ret = mw.language.new(parameters.lang[1]):formatDate(pattern, stamp)
ret = string.gsub(ret, "^(%[?%[?)0+", "%1") -- supress leading zeros
ret = string.gsub(ret, "( %[?%[?)0+", "%1")
return ret
end
local function postFormat(t)
local declaracion = elementoTabla(entidad,'claims', idPropiedad)
if post_format and mw.ustring.find(post_format, "$1") then
return mw.ustring.gsub(post_format, "$1", t)
if not declaracion then
returnend
return t
end
local intyear = tonumber(string.match(timestamp, "[+-](%d+)"))
local valor
local ret = ""
if precision <= 5 then -- precision is 10000 years or more
for k,v in pairs(declaracion) do
local factor = 10 ^ ((5 - precision) + 4)
valor = elementoTabla(v,'mainsnak', 'datavalue', 'value')
local y2 = math.ceil(math.abs(intyear) / factor)
local relative = formatTime(i18n.datetime[precision], y2)
if valor.language == 'es' then
if post_format == i18n.datetime["bc"] then
return valor.text
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
ret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
local ret_number = string.match(ret, "%d+")
if ret_number ~= nil then
ret = mw.ustring.gsub(ret, ret_number, mw.language.new(parameters.lang[1]):formatNum(tonumber(ret_number)))
end
elseif precision == 6 or precision == 7 then -- millennia or centuries
local card = math.floor((intyear - 1) / 10^(9 - precision)) + 1
ret = formatTime(i18n.datetime[precision], card)
ret = postFormat(ret)
elseif precision == 8 then -- decades
local card = math.floor(math.abs(intyear) / 10) * 10
ret = formatTime(i18n.datetime[8], card)
ret = postFormat(ret)
elseif intyear > 9999 then -- not a valid timestamp
return
elseif precision == 9 or parameters.formatting == 'Y' then -- precision is year
ret = formatTime(i18n.datetime[9], intyear)
if parameters.case then
ret = case(parameters.case, ret, parameters.lang[1])
end
ret = postFormat(ret) .. calendar_add
elseif precision == 10 then -- month
ret = formatTime(i18n.datetime[10], timestamp .. " + 1 day") -- formatDate yyyy-mm-00 returns the previous month
ret = postFormat(ret) .. calendar_add
else -- precision 11, day
ret = formatTime(parameters.formatting or i18n.datetime[11], timestamp)
ret = postFormat(ret) .. calendar_add
end
return ret, timestamp
end
 
-- format data value wikibase-entityid: types wikibase-item, wikibase-property
-- devuelve el ID de la página en Wikidata (Q...), o nada si la página no está conectada a Wikidata
local function p.pageIdprintDatatypeEntity(framedata, parameters)
local entityentity_id = mw.wikibase.getEntityObject()data['id']
if parameters.formatting == 'raw' then
if not entity then return nil else return entity.id end
return entity_id, entity_id
end
local entity_page = 'Special:EntityPage/' .. entity_id
local label, lang = getLabelByLangs(entity_id, parameters.lang)
local sitelink = mw.wikibase.getSitelink(entity_id)
local parameter = parameters.formatting
local labelcase = label or sitelink
if parameters.gender == 'feminineform' then
labelcase = feminineForm(entity_id, lang) or labelcase
end
if parameters.case ~= 'gender' then
labelcase = case(parameters.case, labelcase, lang, parameters.lang[1], entity_id, parameters.id)
end
local ret1, ret2
if parameter == 'label' then
ret1 = labelcase or entity_id
ret2 = labelcase or entity_id
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'd:' .. entity_page)
ret2 = sitelink or entity_id
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
ret1 = mw.ustring.gsub(parameter, '$1', labelcase or entity_id)
ret1 = expandBraces(ret1, parameter)
ret2 = labelcase or entity_id
else
if parameter == "ucfirst" or parameter == "ucinternallink" then
if labelcase and lang then
labelcase = mw.language.new(lang):ucfirst(labelcase)
end
-- 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 = '[[d:' .. entity_page .. '|' .. (labelcase or entity_id) .. ']]'
ret2 = labelcase or entity_id
end
end
return ret1 .. addLabelIcon(entity_id, lang, parameters.lang[1], parameters.editicon), ret2
end
 
-- format data type monolingualtext
function p.categorizar(opciones, declaracion)
local function printDatatypeMonolingual(data, parameters)
-- Evitar que pete cuando se haga el find en opciones['formatoTexto'] si vale nil
-- data fields: language [string], text [string]
if not opciones['formatoTexto'] then
opciones['formatoTexto'] = ''
end
local categoriaOpciones=opciones['categoría']
if parameters.list == "lang" and data["language"] ~= parameters.lang[1] then
if not categoriaOpciones 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('<span lang="$1">$2</span>', '$[12]', {["$1"]=data["language"], ["$2"]=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 getSnakValue(snak, parameters)
opciones['enlace'] = 'no'
if snak.snaktype == 'value' then
-- see Special:ListDatatypes
if snak.datatype == "string" then
return printDatatypeString(snak.datavalue.value, parameters)
-- other data value string, tabular-data not implemented
elseif snak.datatype == "commonsMedia" or snak.datatype == "geo-shape" then
return printDatatypeMedia(snak.datavalue.value, parameters)
elseif snak.datatype == "url" then
return printDatatypeUrl(snak.datavalue.value, parameters)
elseif snak.datatype == "external-id" then
return printDatatypeExternal(snak.datavalue.value, parameters)
elseif snak.datatype == 'math' then
return printDatatypeMath(snak.datavalue.value)
elseif snak.datatype == 'musical-notation' then
return printDatatypeMusical(snak.datavalue.value, parameters.formatting)
-- other data types
elseif snak.datatype == 'wikibase-item' or snak.datatype == 'wikibase-property' then
return printDatatypeEntity(snak.datavalue.value, parameters)
elseif snak.datatype == 'monolingualtext' then
return printDatatypeMonolingual(snak.datavalue.value, parameters)
elseif snak.datatype == "globe-coordinate" then
return printDatatypeCoordinate(snak.datavalue.value, parameters.formatting)
elseif snak.datatype == "quantity" then
return printDatatypeQuantity(snak.datavalue.value, parameters)
elseif snak.datatype == "time" then
return printDatatypeTime(snak.datavalue.value, parameters)
end
elseif snak.snaktype == 'novalue' then
if parameters.formatting == 'raw' then return end
return mw.message.new('Wikibase-snakview-snaktypeselector-novalue'):inLanguage(parameters.lang[1]):plain()
elseif snak.snaktype == 'somevalue' then
if parameters.formatting == 'raw' then return end
return mw.message.new('Wikibase-snakview-snaktypeselector-somevalue'):inLanguage(parameters.lang[1]):plain()
end
return mw.wikibase.renderSnak(snak)
end
 
local function printError(key)
-- Crear una tabla con los valores de la propiedad.
return '<span class="error">' .. i18n.errors[key] .. '</span>'
local valoresDeclaracion = {}
end
 
local function getQualifierSnak(claim, qualifierId, parameters)
if declaracion then
-- a "snak" is Wikidata terminology for a typed key/value pair
valoresDeclaracion = declaracion
-- a claim consists of a main snak holding the main information of this claim,
elseif opciones.propiedad then
-- as well as a list of attribute snaks and a list of references snaks
local propiedad = {}
if qualifierId then
if opciones.propiedad == 'precisión' or opciones.propiedad == 'latitud' or opciones.propiedad == 'longitud' then
-- search the attribute snak with the given qualifier as key
propiedad = 'P625' -- Si damos el valor latitud, longitud o precisión equivaldrá a dar p625
if claim.qualifiers then
else
local qualifier = claim.qualifiers[qualifierId]
propiedad = opciones.propiedad -- En el resto de casos se lee lo dado
if qualifier then
if qualifier[1].datatype == "monolingualtext" then
-- iterate over monolingualtext qualifiers to get local language
for idx in pairs(qualifier) do
if getSnak(qualifier[idx], {"datavalue", "value", "language"}) == parameters.lang[1] then
return qualifier[idx]
end
end
elseif parameters.list then
return qualifier
else
return qualifier[1]
end
end
end
return nil, printError("qualifier-not-found")
if not p.getDeclaraciones(opciones.entityId) then
return formatoError( 'other entity' )
elseif p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)] then
valoresDeclaracion = p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)]
else
return ''
end
else
-- otherwise return ''the main snak
return claim.mainsnak
end
end
 
local function getValueOfClaim(claim, qualifierId, parameters)
-- Creamos una tabla con cada categoría a partir de cada valor de la declaración
local snak, error = getQualifierSnak(claim, qualifierId, parameters)
local categorias = {}
if not snak then
local hayCategorias
return nil, nil, error
elseif snak[1] then -- a multi qualifier
if type(categoriaOpciones) == 'string' then
local ModuloPaginasresult, sortkey = require('Módulo:Páginas'){}, {}
local maxvals = tonumber(parameters.list)
for indice, valoridx in pairs(valoresDeclaracionsnak) do
result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
valorFormateado = p.formatoDeclaracion(valor, opciones)
if valorFormateadomaxvals and maxvals ~== ''#result then break end
categoria = ModuloPaginas.existeCategoria(categoriaOpciones:gsub('$1',valorFormateado))
if categoria then
table.insert(categorias, categoria)
hayCategorias = true
end
end
end
elseif type(categoriaOpciones) == 'table' then
for indice, valor in pairs(valoresDeclaracion) do
categoria = categoriaOpciones[elementoTabla(valor, 'mainsnak', 'datavalue', 'value', 'numeric-id')]
if categoria then
table.insert(categorias, 'Categoría:' .. categoria)
hayCategorias = true
end
end
return mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]
else -- a property or a qualifier
return getSnakValue(snak, parameters)
end
if hayCategorias then
return '[[' .. mw.text.listToText( categorias, ']][[',']][[') .. ']]'
end
return ''
end
 
local function getValueOfParentClaim(claim, qualifierId, parameters)
--[[ =========================================================================
local qids = mw.text.split(qualifierId, '/', true)
Función que comprueba si la página está enlazada a Wikidata
local valueraw, parent_claims, value, sortkey
en caso de estarlo pasa el valor como a argumento a la función formatSnak()
if qids[1] == parameters.property then
========================================================================= `-- ]]
valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=parameters.lang})
 
else
function p.formatoDeclaracion( declaracion, opciones)
valueraw, _, _ = getValueOfClaim(claim, qids[1], {["formatting"]="raw", ["lang"]=parameters.lang})
if not declaracion.type or declaracion.type ~= 'statement' then -- Se comprueba que tiene valor de tipo y que este sea statement (declaración) lo cual pasa siempre que existe la propiedad
return formatoError( 'unknown-claim-type' ) -- Si no se cumple devuelve error
end
if string.sub(valueraw or '', 1, 1) == "Q" then -- protection for 'no value'
parent_claims = mw.wikibase.getBestStatements(valueraw, qids[2])
-- En el caso de que haya calificador se devuelve a la derecha del valor de la
if parent_claims[1] ~= nil then
-- declaración entre paréntesis.
value, sortkey, _ = getValueOfClaim(parent_claims[1], nil, parameters)
-- raw parent value needed for while/black lists, lang for avoiding an error on types other than entity
local calificativo = opciones.calificativo or opciones.calificador
valueraw, _, _ = getValueOfClaim(parent_claims[1], nil, {["formatting"]="raw", ["lang"]=parameters.lang})
end
end
return value, sortkey, valueraw
end
 
-- see d:Help:Sources
if calificativo and declaracion.qualifiers then
local function getReferences(claim, lang)
-- De momento los calificativos, normalmente años, no se enlazan
local notproperref = {
local opcionesCalificativo = {['formatoTexto']='', enlace='no', ['formatoFecha']='año'} -- Pendiente
["P143"] = true, -- imported from
["P3452"] = true, -- inferred from
local wValorCalificativo
["P887"] = true, -- based on heuristic
local wValorCalificativoFormateado
["P4656"] = true -- Wikimedia import URL
}
local funcionCalificativo, mensajeError = obtenerFuncion(calificativo, opciones['módulo calificativo'])
local result = ""
-- traverse through all references
if mensajeError then
for ref in pairs(claim.references or {}) do
return mensajeError
local refparts
elseif funcionCalificativo then
local refs = {}
-- Utilizar la función recibida sobre todos los calificativos
local validref = true
wValorCalificativo = declaracion.qualifiers
local ref_name
wValorCalificativoFormateado = funcionCalificativo(wValorCalificativo, opcionesCalificativo)
-- traverse through all parts of the current reference
elseif opciones.formatoCalificador and opciones.formatoCalificador == '()' then
for snakkey, snakval in pairs(claim.references[ref].snaks or {}) do
wValorCalificativo = declaracion.qualifiers[mw.ustring.upper(calificativo)]
for partkey, _ in pairs(claim.references[ref].snaks[snakkey] or {}) do
if wValorCalificativo and wValorCalificativo[1] then
if notproperref[snakkey] then -- not a proper reference
wValorCalificativoFormateado = p.formatoDato(wValorCalificativo[1], opcionesCalificativo)
validref = false
break
end
end
if validref then
elseif opciones.formatoCalificador and table.getn(mw.text.split(opciones.formatoCalificador, '%.')) == 2 then
for snakidx = 1, #snakval do
moduloFormatoCalificador = mw.text.split(opciones.formatoCalificador, '%.')
if snakidx > 1 then refparts = refparts .. ", " end
formateado = require ('Módulo:' .. moduloFormatoCalificador[1])
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang=lang})
if not formateado then
end
return formatoError( 'value-module-not-found' )
refs[snakkey] = refparts
refparts = nil
if snakkey == "P248" then -- stated in
ref_name = snakval[1].datavalue.value.id
end
end
end
fun = formateado[moduloFormatoCalificador[2]]
if not fun then
-- fill missing values with parent item
return formatoError( 'value-function-not-found' )
if ref_name then
local function refParent(qid, pid, formatting)
local snak = getSnak(mw.wikibase.getBestStatements(qid, pid), {1, "mainsnak"})
return snak and getSnakValue(snak, {formatting=formatting, lang=lang})
end
refs['P50'] = refs['P50'] or refParent(ref_name, 'P50', 'label') -- author
if mw.ustring.find(opciones['formatoTexto'],'mayúscula', plain ) and
refs['P407'] = refs['P407'] or refParent(ref_name, 'P407', 'label') -- language of work
(primera or (opciones['separador'] and opciones['separador'] ~= 'null') or
refs['P123'] = refs['P123'] or refParent(ref_name, 'P123', 'label') -- publisher
(opciones['lista'] and opciones['lista'] ~= '')) then
refs['P577'] = refs['P577'] or refParent(ref_name, 'P577') -- date
opciones['mayúscula'] = 'sí'
refs['P1433'] = refs['P1433'] or refParent(ref_name, 'P1433', 'label') -- published in
primera = false
refs['P304'] = refs['P304'] or refParent(ref_name, 'P304') -- page(s)
refs['P433'] = refs['P433'] or refParent(ref_name, 'P433') -- issue
refs['P236'] = refs['P236'] or refParent(ref_name, 'P236') -- ISSN
refs['P356'] = refs['P356'] or refParent(ref_name, 'P356') -- DOI
end
-- get title of local templates for citing references
local template_web = mw.wikibase.getSitelink('Q5637226') or ""
template_web = mw.text.split(template_web, ":")[2] -- split off namespace from front
local template_journal = mw.wikibase.getSitelink('Q5624899') or ""
template_journal = mw.text.split(template_journal, ":")[2]
local citeParams = {}
if refs['P854'] and (refs['P1476'] or refs['P248']) and template_web then
-- if both "reference URL" and "title" (or "stated in") are present, then use cite web template
citeParams[i18n['cite']['url']] = refs['P854']
if refs['P248'] and refs['P1476'] == nil then
citeParams[i18n['cite']['title']] = refs['P248']:match("^%[%[.-|(.-)%]%]")
else
citeParams[i18n['cite']['title']] = refs['P1476']
citeParams[i18n['cite']['website']] = refs['P248']
end
citeParams[i18n['cite']['author']] = refs['P50']
citeParams[i18n['cite']['language']] = refs['P407']
if mw.ustring.find(opciones['formatoTexto'],'cursivas', plain ) then
citeParams[i18n['cite']['publisher']] = refs['P123']
opcionesEntidad.cursivas = 'sí'
citeParams[i18n['cite']['date']] = refs['P577']
citeParams[i18n['cite']['pages']] = refs['P304']
citeParams[i18n['cite']['access-date']] = refs['P813']
citeParams[i18n['cite']['archive-url']] = refs['P1065']
citeParams[i18n['cite']['archive-date']] = refs['P2960']
citeParams[i18n['cite']['quote']] = refs['P1683']
refparts = mw.getCurrentFrame():expandTemplate{title=template_web, args=citeParams}
elseif refs['P1433'] and (refs['P1476'] or refs['P248']) and template_journal then
-- if both "published in" and "title" (or "stated in") are present, then use cite journal template
citeParams[i18n['cite']['work']] = refs['P1433']
citeParams[i18n['cite']['title']] = refs['P1476'] or refs['P248']
citeParams[i18n['cite']['author']] = refs['P50']
citeParams[i18n['cite']['date']] = refs['P577']
citeParams[i18n['cite']['issue']] = refs['P433']
citeParams[i18n['cite']['pages']] = refs['P304']
citeParams[i18n['cite']['language']] = refs['P407']
citeParams[i18n['cite']['issn']] = refs['P236']
citeParams[i18n['cite']['doi']] = refs['P356']
refparts = mw.getCurrentFrame():expandTemplate{title=template_journal, args=citeParams}
elseif validref then
-- raw ouput
local snaksorder = claim.references[ref]["snaks-order"]
local function indexed(a)
for _, b in ipairs(snaksorder) do
if b == a then return true end
end
return false
end
for k, _ in pairs(refs or {}) do
if not indexed(k) then
table.insert(snaksorder, k)
end
end
local italics = "''"
for _, k in ipairs(snaksorder) do
if refs[k] then
refparts = refparts and refparts .. " " or ""
refparts = refparts .. mw.ustring.gsub(getLabelByLangs(k, lang), "^%l", mw.ustring.upper) .. ": "
refparts = refparts .. italics .. refs[k] .. italics .. "."
italics = ""
end
end
wValorCalificativoFormateado = fun( declaracion.qualifiers, opciones, marco)
--return require('Módulo:Tablas').tostring(declaracion)
else
-- Utilizar el primer valor del calificativo de la propiedad recibida
wValorCalificativo = declaracion.qualifiers[mw.ustring.upper(calificativo)]
if wValorCalificativo and wValorCalificativo[1] then
wValorCalificativoFormateado = p.formatoDato(wValorCalificativo[1], opcionesCalificativo)
end
end
if refparts then result = mw.getCurrentFrame():extensionTag("ref", refparts, {name=ref_name}) end
if opciones.separadorcalificador then separador = opciones.separadorcalificador else separador = ' ' end
if wValorCalificativoFormateado then
datoFormateado = p.formatoDato(declaracion.mainsnak, opciones)
return (datoFormateado and datoFormateado .. '&nbsp;<small>(' .. wValorCalificativoFormateado .. ')</small>') or nil
end
end
return result
end
 
-- Set whitelist or blacklist values
-- Si no hay calificativo.
local function setWhiteOrBlackList(type_list, num_qual, args)
return p.formatoDato(seleccionDeclaracion(declaracion, opciones), opciones, declaracion.qualifiers)
local listed = false
local list = {}
for i = 0, num_qual do
if isSet(args[type_list .. i]) then
listed = true
list[tostring(i)] = {}
for v in string.gmatch(args[type_list .. i], 'Q%d+') do
list[tostring(i)][resolveEntityId(v)] = true
end
end
end
return list, listed
end
 
local function tableParameters(args, parameters, column)
--[[ =========================================================================
local column_params = mw.clone(parameters)
Función que comprueba el tipo de dato (snaktype)
column_params.formatting = args["colformat"..column]; if column_params.formatting == "" then column_params.formatting = nil end
si es value pasa el valor como argumento a la función formatoValorDato()
column_params.convert = args["convert" .. column]
========================================================================= `-- ]]
if args["case" .. column] then
column_params.case = args["case" .. column]
end
return column_params
end
 
local function p.formatoDatogetEntityId( dato, opcionesframe, calificativosunnamed)
local args = frame.args or frame
local pargs = frame.args and frame:getParent().args
if not dato or dato == '' then
local id = args.item or args.from or (unnamed and mw.text.trim(args[1] or '') or nil)
return ''
if not isSet(id) and pargs then
id = pargs.item or pargs.from or (unnamed and mw.text.trim(pargs[1] or '') or nil)
end
if dato.snaktype == 'somevalue'isSet(id) then
if string.find(id, ":") then -- remove prefix as Property:Pid
-- Fecha más temprana
id = mw.text.split(id, ":")[2]
if calificativos then
if calificativos['P1319'] and calificativos['P1319'][1] and
calificativos['P1319'][1].datavalue and
calificativos['P1319'][1].datavalue.type=='time' then
local opcionesFecha={['formatoFecha']=opciones['formatoFecha'],enlace=opciones.enlace}
return 'post. ' .. require('Módulo:Wikidata/Fecha').FormateaFechaHora(calificativos['P1319'][1].datavalue.value, opcionesFecha)
end
end
-- Si no tiene un calificativo válido
return avisos['somevalue'] -- Valor desconocido
elseif dato.snaktype == 'novalue' then
return avisos['novalue'] -- Sin valor
elseif dato.snaktype == 'value' then
return formatoValorDato( dato.datavalue, opciones, calificativos) -- Si tiene el tipo de dato se pasa el valor a la función formatDatavalue()
else
id = mw.wikibase.getEntityIdForCurrentPage()
return formatoError( 'unknown-snak-type' ) -- Tipo de dato desconocido
end
return id
end
 
-- Main function claim ---------------------------------------------
--[[ =========================================================================
-- on debug console use: =p.claim{item="Q...", property="P...", ...}
Función que establece el tipo de formato en función del tipo de valor
function p.claim(frame)
(valorDato.type) y en caso de solicitarse un formato complemetario asocia
local is_sandbox = frame.args and isSet(frame:getParent().args.sandbox)
el módulo donde se establece el formato y la función de este que lo establece
if not required and is_sandbox then
========================================================================= `-- ]]
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).claim(frame)
 
end
function formatoValorDato( valorDato, opciones, calificativos)
local args = frame.args or frame -- via invoke or require
local funcion, mensajeError = obtenerFuncion(opciones['valor-función'] or opciones['value-function'] or opciones['funcion'], opciones['valor-módulo'] or opciones['modulo'])
--If a value is already set, use it
if isSet(args.value) then
if args.value == 'NONE' then
return
else
return args.value
end
end
-- arguments
if mensajeError then
local id = getEntityId(frame)
return mensajeError
elseifif funcionid == nil then return end
local property = string.upper(args.property or "")
local opcionesEntidad = {}
local qualifierId = {}
qualifierId[1] = isSet(args.qualifier) and string.upper(args.qualifier) or nil
for k, v in pairs(opciones) do
local i = 2
opcionesEntidad[k] = v
while isSet(args["qualifier" .. i]) do
qualifierId[i] = string.upper(args["qualifier" .. i])
i = i + 1
end
local formatting = isSet(args.formatting) and args.formatting or nil
local convert = isSet(args.convert) and args.convert or nil
local case = args.case
local list = args.list or true; if (list == "false" or list == "no") then list = false end
if list == 'firstrank' then list = 'bestrank' end -- alias
local sorting_col = args.tablesort
local sorting_up = (args.sorting or "") ~= "-1"
local separator = isSet(args.separator) and args.separator
local conjunction = isSet(args.conjunction) and args.conjunction or separator
local rowformat = args.rowformat
local references = args.references
local showerrors = args.showerrors
local default = args.default
if default then showerrors = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no" or formatting == "raw")
local parameters = {["id"] = id, ["property"] = property, ["formatting"] = formatting, ["convert"] = convert,
["list"] = list, ["case"] = case, ["editicon"] = editicon,
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
parameters.lang = findLang(args.lang)
-- fetch property
local claims = {}
local bestrank = (parameters.list == false or parameters.list == 'bestrank') and parameters.list ~= 'lang'
for p in string.gmatch(property, 'P%d+') do
claims = getStatements(id, p, bestrank)
if #claims > 0 then
parameters.property = p
break
end
end
if #claims == 0 then
if mw.ustring.find(opciones['formatoTexto'],'mayúscula', plain ) and
if showerrors then return printError("property-not-found") else return default end
(primera or (opciones['separador'] and opciones['separador'] ~= 'null') or
end
(opciones['lista'] and opciones['lista'] ~= '')) then
opcionesEntidad['mayúscula'] = 'sí'
-- defaults for table
primera = false
local preformat, postformat = "", ""
end
local whitelisted, blacklisted = false, false
local whitelist, blacklist = {}, {}
if mw.ustring.find(opciones['formatoTexto'],'cursivas', plain ) then
if parameters.formatting == "table" then
opcionesEntidad.cursivas = 'sí'
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
-- set whitelist and blacklist values
return funcion(valorDato.value, opcionesEntidad, marco, calificativos)
whitelist, whitelisted = setWhiteOrBlackList("whitelist", #qualifierId, args)
blacklist, blacklisted = setWhiteOrBlackList("blacklist", #qualifierId, args)
end
 
-- set feminine case if gender is requested
-- == Formatos por defecto en función del tipo de valor ==
local itemgender = args.itemgender
 
local idgender
-- * Para tipo coordenadas cuando se da como valor de propiedad: latitud, longitud o precisión
if itemgender then
 
if opcionesstring.propiedadmatch(itemgender, == 'latitud'"^P%d+$") then
local snak_id = getSnak(mw.wikibase.getBestStatements(id, itemgender), {1, "mainsnak", "datavalue", "value", "id"})
return valorDato.value['latitude']
if snak_id then
elseif opciones.propiedad == 'longitud' then
idgender = snak_id
return valorDato.value['longitude']
end
elseif opciones.propiedad == 'precisión' then
elseif string.match(itemgender, "^Q%d+$") then
return valorDato.value['precision']
idgender = itemgender
 
-- * Con el resto de valores en propiedad
 
elseif valorDato.type == 'wikibase-entityid' then -- Tipo: Número de entidad que puede ser un ítem o propiedad
local opcionesEntidad = {}
if mw.ustring.find(opciones['formatoTexto'],'mayúscula', plain ) and
(primera or (opciones['separador'] and opciones['separador'] ~= 'null') or
(opciones['lista'] and opciones['lista'] ~= '')) then
opcionesEntidad['mayúscula'] = 'sí'
primera = false
end
end
opcionesEntidad.enlace = opciones.enlace
local gender_requested = false
opcionesEntidad.etiqueta = opciones.etiqueta
if parameters.case == "gender" or idgender then
opcionesEntidad['debeExistir'] = opciones['debeExistir']
gender_requested = true
elseif parameters.formatting == "table" then
if mw.ustring.find(opciones['formatoTexto'],'cursivas', plain ) then
for i=0, #qualifierId do
opcionesEntidad.cursivas = 'sí'
if args["case" .. i] and args["case" .. i] == "gender" then
gender_requested = true
break
end
end
end
return p.formatoIdEntidad( SelecionEntidadPorValor( valorDato.value ), opcionesEntidad)
if gender_requested then
elseif valorDato.type == 'string' then -- Tipo: Cadena de texto (string)
if feminineGender(idgender or id) then
return valorDato.value
parameters.gender = "feminineform"
elseif valorDato.type == 'url' then --Tipo URL (dirección web)
return value.url
elseif valorDato.type == 'time' then -- Tipo: Fecha/hora
local opcionesFecha={['formatoFecha']=opciones['formatoFecha'],enlace=opciones.enlace}
if mw.ustring.find(opciones['formatoTexto'] or '','mayúscula', plain ) and primera then
opcionesFecha['mayúscula']='sí'
end
end
return require('Módulo:Wikidata/Fecha').FormateaFechaHora(valorDato.value, opcionesFecha, calificativos)
-- get initial sort indices
elseif valorDato.type == 'monolingualtext' then -- Tipo: monoligüe
local sortindices = {}
if valorDato.value then
for idx in pairs(claims) do
if opciones.idioma then
sortindices[#sortindices + 1] = idx
for k, v in pairs(valorDato) do
end
if v.language == opciones.idioma then
-- sort by claim rank
return v.text
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, result2
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 refs = {}
local rowlist = {} -- rows to list with whitelist or blacklist
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
local reference = {}
if not whitelisted then rowlist[idx] = true end
if parameters.formatting == "table" then
local params = tableParameters(args, parameters, "0")
value, sortkey, error = getValueOfClaim(claim, nil, params)
if value then
values[#values + 1] = {}
sortkeys[#sortkeys + 1] = {}
refs[#refs + 1] = {}
if whitelist["0"] or blacklist["0"] then
local valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=params.lang})
if whitelist["0"] and whitelist["0"][valueraw or ""] then
rowlist[#values] = true
elseif blacklist["0"] and blacklist["0"][valueraw or ""] then
rowlist[#values] = false
end
end
for i, qual in ipairs(qualifierId) do
local j = tostring(i)
params = tableParameters(args, parameters, j)
local valueq, sortkeyq, valueraw
if qual == property then -- hack for getting the property with another formatting, i.e. colformat1=raw
valueq, sortkeyq, _ = getValueOfClaim(claim, nil, params)
else
for q in mw.text.gsplit(qual, '%s*OR%s*') do
if string.find(q, ".+/.+") then
valueq, sortkeyq, valueraw = getValueOfParentClaim(claim, q, params)
elseif string.find(q, "^/.+") then
local claim2 = getStatements(id, string.sub(q, 2), bestrank)
if #claim2 > 0 then
valueq, sortkeyq, _ = getValueOfClaim(claim2[1], nil, params)
end
else
valueq, sortkeyq, _ = getValueOfClaim(claim, q, params)
end
if valueq then break end
end
end
values[#values]["col" .. j] = valueq
sortkeys[#sortkeys]["col" .. j] = sortkeyq or valueq
if whitelist[j] or blacklist[j] then
valueq = valueraw or getValueOfClaim(claim, qual, {["formatting"]="raw", ["lang"]=params.lang})
if whitelist[j] and whitelist[j][valueq or ""] then
rowlist[#values] = true
elseif blacklist[j] and blacklist[j][valueq or ""] then
rowlist[#values] = false
end
end
end
end
else
value, sortkey, error = getValueOfClaim(claim, qualifierId[1], parameters)
return valorDato.value.text
values[#values + 1] = {}
sortkeys[#sortkeys + 1] = {}
refs[#refs + 1] = {}
end
if not value and showerrors then value = error end
if value then
if references and claim.references then reference = claim.references end
refs[#refs]["col0"] = reference
values[#values]["col0"] = value
sortkeys[#sortkeys]["col0"] = sortkey or value
end
else
return ''
end
-- sort and format results
elseif valorDato.type == 'quantity' then -- Tipo: Cantidad
sortindices = {}
return require('Módulo:Wikidata/Formatos').formatoUnidad(valorDato, opciones)
for idx in pairs(values) do
elseif valorDato.value['latitude'] and valorDato.value['longitude'] then -- Tipo: Coordenadas
sortindices[#sortindices + 1] = idx
local globo = require('Módulo:Wikidata/Globos')[valorDato.value.globe]
 
--Concatenamos los valores de latitud y longitud dentro de la plantilla Coord
 
if globo ~= 'earth' then
return marco:preprocess('{{coord|' .. valorDato.value['latitude'] .. '|' ..
valorDato.value['longitude'] .. '|globe:' .. globo .. '_type:' .. opciones.tipo .. '|display=' ..
opciones.display ..'|formato=' .. opciones.formato..'}}')
else
return marco:preprocess('{{coord|' .. valorDato.value['latitude'] .. '|' ..
valorDato.value['longitude'] .. '|type:' .. opciones.tipo .. '|display=' ..
opciones.display ..'|formato=' .. opciones.formato..'}}')
end
if sorting_col then
 
local sorting_table = mw.text.split(sorting_col, '%D+')
local comparator = function(a, b)
local valuea, valueb
local i = 1
while valuea == valueb and i <= #sorting_table do
valuea = sortkeys[a]["col" .. sorting_table[i]] or ''
valueb = sortkeys[b]["col" .. sorting_table[i]] or ''
i = i + 1
end
if sorting_up then
return valueb > valuea
end
return valueb < valuea
end
table.sort(sortindices, comparator)
end
local maxvals = tonumber(parameters.list)
result = {}
for idx in pairs(values) do
local valuerow = values[sortindices[idx]]
local reference = getReferences({["references"] = refs[sortindices[idx]]["col0"]}, parameters.lang)
value = valuerow["col0"]
if parameters.formatting == "table" then
if not rowlist[sortindices[idx]] then
value = nil
else
local rowformatting = rowformat .. "$" -- fake end character added for easy gsub
value = mw.ustring.gsub(rowformatting, "$0", value)
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
for i, _ in ipairs(qualifierId) do
local 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 = captureEscapes(valueq)
valueq = mw.ustring.gsub(args["rowsubformat" .. i] .. "$", "$" .. i .. "(%D)", valueq .. "%1")
valueq = string.sub(valueq, 1, -2)
rowformatting = mw.ustring.gsub(rowformatting, "$" .. i .. "(%D)", args["rowsubformat" .. i] .. "%1")
end
valueq = valueq and captureEscapes(valueq) or ''
value = mw.ustring.gsub(value, "$" .. i .. "(%D)", valueq .. "%1")
end
value = string.sub(value, 1, -2) -- remove fake end character
value = expandBraces(value, rowformatting)
end
elseif value then
value = expandBraces(value, parameters.formatting)
value = value .. reference
end
if isSet(value) then
result[#result + 1] = value
if not parameters.list or (maxvals and maxvals == #result) then
break
end
end
end
-- in a table, add edit icon on last element
if parameters.formatting == 'table' and parameters.editicon then
result = addEditIconTable(result, parameters)
end
result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
else
-- return first element
return formatoError( 'unknown-datavalue-type' ) -- Si no es de ninguno de estos tipos devolverá error valor desconocido
local claim = claims[sortindices[1]]
result, result2, error = getValueOfClaim(claim, qualifierId[1], parameters)
if result and references then result = result .. getReferences(claim, parameters.lang) end
end
if isSet(result) then
if i18n.addpencil and not (parameters.formatting == 'table' or (result2 and result2 == 'no-icon')) then
-- add edit icon, except table added previously and except explicit no-icon internal flag
result = result .. addEditIcon(parameters)
end
else
if showerrors then result = error else result = default end
end
return result, (required and not is_sandbox) and untranslated or ''
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
Damos formato a los enlaces internos
-- 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.getEntity()
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
 
-- Local functions for getParentValues -----------------------
-- Opciones:
-- - enlace: Valores posibles 'sí' o 'no'
-- - mayúscula: Valores posibles 'sí' o 'no'
-- - cursivas: Valores posibles 'sí' o 'no'
 
local function p.formatoIdEntidaduc_first(idEntidad, opcionesword)
return mw.ustring.upper(mw.ustring.sub(word, 1, 1)) .. mw.ustring.sub(word, 2)
local enlace = mw.wikibase.sitelink(idEntidad)
local etiqueta = mw.wikibase.label(idEntidad)
return require('Módulo:Wikidata/Formatos').enlazar(enlace, etiqueta, idEntidad, opciones)
end
 
local function getPropertyValue(id, property, parameter, langs, editicon, case)
--[[ =========================================================================
local snaks = mw.wikibase.getBestStatements(id, property)
Función principal
local mysnak = getSnak(snaks, {1, "mainsnak"})
========================================================================= `-- ]]
if mysnak == nil then
 
function p.Wikidata( frame )
marco = frame
local args = frame.args
if args.valor == 'no' then
return
end
 
local parentArgs = frame:getParent().args
local entity_id
-- Copiar los argumentos
local argumentosresult = {}'-' -- default for 'no value'
if mysnak.datavalue then
entity_id = "Q" .. tostring(mysnak.datavalue.value['numeric-id'])
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon, case=case})
end
return entity_id, result
end
 
local function getParentObjects(id,
prop_format,
label_format,
languages,
propertySupString,
propertyLabel,
propertyLink,
labelShow,
editicon,
upto,
upto_linkId,
last_only,
grammatical_case,
include_self)
if upto_linkId == nil then upto_linkId = "" end
for k, v in pairs(args) do
local upto_link_ids = {}
argumentos[k] = v
for q in mw.text.gsplit(upto_linkId, '[^Q%d]') do
upto_link_ids[resolveEntityId(q)] = true
end
local propertySups = mw.text.split(propertySupString, '[^P%d]')
local lastlabel = uc_first(upto or '')
for k, v in pairs(parentArgs) do
local maxloop = tonumber(upto) or ((lastlabel .. upto_linkId) == '' and 10 or 50)
if not argumentos[k] then
argumentos[k] = v
local labelFilter = {}
if labelShow then
for _, v in ipairs(mw.text.split(labelShow, "/")) do
labelFilter[uc_first(v)] = true
end
end
local label_self
--if true then return require('Módulo:Tablas').tostring(argumentos) end
_, label_self = getPropertyValue(id, propertyLabel, label_format, languages)
local result = {}
-- No generar el valor de Wikidata si se ha facilitado un valor local y
-- el valor local es prioritario.
local valorWikidata;
if (args.prioridad ~= 'sí' or (args.importar and args.importar == 'no')) and args.valor and args.valor ~= '' then
valorWikidata = '';
else
local ent = SelecionEntidadPorId(argumentos.entityId)
argumentos.entityId = ent and ent.id or nil
valorWikidata = p.getPropiedad(argumentos, nil);
end
for iter = 1, maxloop do
local categorias = '';
local link, label, linktext, _id, _link
local namespace = frame:preprocess('{{NAMESPACENUMBER}}');
for _, propertySup in pairs(propertySups) do
_id, _link = getPropertyValue(id, propertySup, prop_format, languages, editicon, grammatical_case)
if (namespace == '0' and (not args.categorias or args.categorias ~= 'no') and
if _id and _link then id = _id; link = _link break end
args.propiedad and string.upper(args.propiedad) ~= 'P18' -- P18: imagen de Commons
and string.upper(args.propiedad) ~= 'P41' -- P41: imagen de la bandera
and string.upper(args.propiedad) ~= 'P94' -- P94: imagen del escudo de armas
and string.upper(args.propiedad) ~= 'P109' -- P109: firma de persona
and string.upper(args.propiedad) ~= 'P154') then -- P154: logotipo
if valorWikidata ~= '' and args.valor and args.valor ~= '' then
categorias = '[[Katiguriya:Wikipedia:Artículos con datos locales]]'
elseif valorWikidata and valorWikidata == '' and args.valor and args.valor ~= '' and
(not args.calificador or args.calificador == '') and
(not args.dato or args.dato == '' or args.dato ~= 'fuente')then
categorias = '[[Katiguriya:Wikipedia:Artículos con datos por trasladar a Wikidata]]'
end
end
 
if args.prioridad == 'sí' and valorWikidata ~= '' then -- Si se da el valor sí a prioridad tendrá preferencia el valor de Wikidata
if args.importar and args.importar == 'no' and args.valor and args.valor ~= '' then
return args.valor .. categorias
elseif valorWikidata then
return valorWikidata .. categorias -- valor que sustituye al valor de Wikidata parámetro 2
else
return categorias
end
elseif args.valor and args.valor ~= '' then
return args.valor .. categorias
elseif args.importar and args.importar == 'no' then
return ''
elseif valorWikidata then -- Si el valor es nil salta una excepcion al concatenar
return valorWikidata .. categorias
else
return ''
end
end
 
function obtenerFuncion(funcion, nombreModulo)
if not funcion then
return
elseif type(funcion) == 'function' then -- Uso desde LUA
return funcion
elseif funcion == '' or not nombreModulo or nombreModulo == '' then
return
else -- Uso desde una plantilla
local modulo
if not id or not link then break end
if not nombreModulo or nombreModulo == '' or nombreModulo == 'Wikidata/Formatos' then
modulo = require(modulosTipos[funcion] or 'Módulo:Wikidata/Formatos')
if propertyLink then
else
_, linktext = getPropertyValue(id, propertyLink, "label", languages)
modulo = require ('Módulo:' .. nombreModulo)
if linktext then
link = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")
end
end
_, label = getPropertyValue(id, propertyLabel, label_format, languages, false, "infoboxlabel")
if not modulo then
return nil, formatoError( 'value-module-not-found' )
elseifif notlabelShow modulo== nil or labelFilter[funcionlabel] then
result[#result + 1] = {label, link}
return nil, formatoError( 'value-function-not-found' )
else
if label then
return modulo[funcion]
labelFilter[label] = nil -- only first label found
end
end
end
if label == lastlabel or upto_link_ids[id] then
break
end
end
if last_only then
result = {result[#result]}
end
if include_self then table.insert(result, 1, {label_self, mw.title.getCurrentTitle().text}) end
return result
end
 
local function parentObjectsToString(result,
function p.addLinkback(valorPropiedad, idEntidad, idPropiedad)
rowformat,
local lidEntidad
cascade,
sorting)
local ret = {}
if valorPropiedad and idPropiedad then
local first = 1
lidEntidad= (idEntidad ~='' and idEntidad) or mw.wikibase.getEntityIdForCurrentPage()
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
 
if lidEntidadcascade then
local prefix = ""
return valorPropiedad .. '<span class=\"wikidata-link noprint\"> [[Archivo:Blue_pencil.svg|Ver y modificar los datos en Wikidata|10px|baseline|alt=Ver y modificar los datos en Wikidata|enlace=https://www.wikidata.org/wiki/' .. lidEntidad .. '?uselang=es#' .. idPropiedad ..
for i = 1, #ret do
']]</span>'
ret[i] = prefix .. "• " .. ret[i]
else
prefix = prefix .. "&nbsp;"
return valorPropiedad
end
end
return ret
end
 
-- Returns pairs of instance label and property value fetching a recursive tree
function p.formatoLista(tabla, opciones)
function p.getParentValues(frame)
if not tabla or not tabla[1] then
if not required and frame.args and frame:getParent().args.sandbox then
return
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).getParentValues(frame)
end
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame)
if id == nil then return end
local languages = findLang(args.lang)
local propertySup = args.property; if not isSet(propertySup) then propertySup = "P131" end --administrative entity
local propertyLabel = args.label; if not isSet(propertyLabel) then propertyLabel = "P31" end --instance
local propertyLink = args.valuetext; if propertyLink == "" then propertyLink = nil end --internallink
local property_format = args.formatting; if property_format == "" then property_format = nil end
local label_format = args.labelformat; if not isSet(label_format) then label_format = "label" end
local upto = args.upto; if upto == "" then upto = nil end
local last_only = (args.last_only == "true" or args.last_only == "yes")
local labelShow = args.labelshow; if labelShow == "" then labelShow = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local include_self = (args.include_self == "true" or args.include_self == "yes")
local case = args.case; if case == "" then case = nil end
if isSet(args.uptolabelid) then
local tipo_lista = opciones.lista
upto, _ = getLabelByLangs(args.uptolabelid, languages)
local lapiz
if opciones.linkback == 'sí' and opciones.entityId and opciones.propiedad then
lapiz = '<span class=\"wikidata-link noprint\"> [[Archivo:Blue_pencil.svg|Ver y modificar los datos en Wikidata|10px|baseline|alt=Ver y modificar los datos en Wikidata|enlace=https://www.wikidata.org/wiki/' .. opciones.entityId .. '?uselang=es#' .. opciones.propiedad ..
']]</span>'
else
lapiz = ''
end
if not tabla[2]isSet(args.showlabelid) then
local showLabelList = {}
-- Si la tabla solo tiene un elemento devolverlo
for substring in mw.text.gsplit(args.showlabelid, '[^Q%d]') do
return tabla[1] .. lapiz
table.insert(showLabelList, (getLabelByLangs(substring, languages)))
end
if #showLabelList > 0 then
labelShow = table.concat(showLabelList,"/")
end
end
local result = getParentObjects(id,
if tipo_lista == 'no ordenada' or tipo_lista == 'ordenada' or tipo_lista == 'nobullet' then
property_format,
local lista = mw.text.listToText( tabla, '</li><li>', '</li><li>' )
label_format,
languages,
if tipo_lista == 'no ordenada' then
propertySup,
return '<ul><li>' .. lista .. lapiz .. '</li></ul>'
propertyLabel,
elseif tipo_lista == 'ordenada' then
propertyLink,
return '<ol><li>' .. lista .. lapiz .. '</li></ol>'
labelShow,
else
editicon,
return '<ul style="list-style-type:none;list-style-image:none;margin-left:0;padding-left:0"><li>' .. lista .. lapiz .. '</li></ul>'
upto,
args.uptovalueid or args.uptolinkid,
last_only,
case,
include_self)
if #result == 0 then return end
local rowformat = args.rowformat; if not isSet(rowformat) then rowformat = "$0 = $1" end
local separator = args.separator; if not isSet(separator) then separator = "<br />" end
local sorting = args.sorting; if sorting == "" then sorting = nil end
local cascade = (args.cascade == "true" or args.cascade == "yes")
local ret = parentObjectsToString(result,
rowformat,
cascade,
sorting)
ret = addEditIconTable(ret, {property=propertySup, editicon=editicon, id=id, lang=languages})
return mw.text.listToText(ret, separator, separator)
end
 
-- Link with a parent label --------------------
function p.linkWithParentLabel(frame)
if not required and frame.args and isSet(frame:getParent().args.sandbox) then
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).linkWithParentLabel(frame)
end
local args = {}
if frame.args then
for k, v in pairs(frame.args) do -- metatable
args[k] = v
end
else
args = frame -- via require
local separadores = {
end
[''] = '',
if isSet(args.value) then
[','] = ', ',
return args.value
['null'] = ', ',
end
['no'] = ''
}
-- get id value of property/qualifier
local conjunciones = {
local largs = mw.clone(args)
[''] = '',
largs.list = tonumber(args.list) and args.list or "true"
['y'] = ' y ',
largs.formatting = "raw"
['o'] = ' o ',
largs.separator = "/·/"
['null'] = ' y ',
largs.editicon = "false"
['no'] = ''
local items_list, _ = p.claim(largs)
}
if not isSet(items_list) then return end
local items_table = mw.text.split(items_list, "/·/", true)
local separador = opciones.separador
local conjuncion = opciones['conjunción']
-- get internal link of property/qualifier
largs.formatting = "internallink"
if not separador then
local link_list, _ = p.claim(largs)
separador = ', '
local link_table = mw.text.split(link_list, "/·/", true)
else
separador = separadores[separador] or separador
-- get label of parent property
local parent_claim = getSnak(getStatements(items_table[1], args.parent, true), {1, "mainsnak", "datatype"})
if parent_claim == 'monolingualtext' then
largs.formatting = nil
largs.list = 'lang'
else
largs.formatting = "label"
largs.list = "false"
end
largs.property = args.parent
largs.qualifier = nil
for i, v in ipairs(items_table) do
largs.item = v
local link_label, _ = p.claim(largs)
if isSet(link_label) then
link_table[i] = mw.ustring.gsub(link_table[i] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
end
if not conjuncion then
conjuncion = ' y '
else
conjuncion = conjunciones[conjuncion] or conjuncion
end
if conjuncion == ' y ' and marco and tabla[2] then
conjuncion = ' ' .. marco:preprocess('{{y-e|{{Desvincular|' .. tabla[#tabla] .. '}}|sin texto}}') .. ' '
end
return mw.text.listToText( tabla, separador, conjuncion ) .. lapiz
end
args.editicon = not (args.editicon == "false" or args.editicon == "no")
args.id = getEntityId(frame)
args.lang = findLang(args.lang)
return mw.text.listToText(link_table) .. addEditIcon(args)
end
 
-- Calculate number of years old ----------------------------
-- Funciones existentes en otros módulos
function p.obtenerEtiquetaWikidatayearsOld(entidad, fallbackframe)
if not required and frame.args and frame:getParent().args.sandbox then
if not entidad then entidad = fallback end
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).yearsOld(frame)
if entidad and entidad.labels and entidad.labels.es then
return entidad.labels.es.value
end
local args = frame.args or frame -- via invoke or require
end
local id = getEntityId(frame)
 
local lang = mw.language.new('en')
function p.obtenerImagenWikidata(entidad, propiedad)
local imagen, valorImagen, piesDeImagen, k, pieDeImagen
local function getBestValue(id, prop)
if not entidad then
local snak_value = getSnak(mw.wikibase.getBestStatements(id, prop), {1, "mainsnak", "datavalue", "value"})
return snak_value
end
local birth = getBestValue(id, 'P569')
if type(birth) ~= 'table' or birth.time == nil or birth.precision == nil or birth.precision < 8 then
return
end
local death = getBestValue(id, 'P570')
-- Obtener la primera imagen en Wikidata de la persona
if type(death) ~= 'table' or death.time == nil or death.precision == nil then
local imagen = elementoTabla(entidad, 'claims', propiedad, 1)
death = {['time'] = lang:formatDate('c'), ['precision'] = 11} -- current date
if not imagen then
elseif death.precision < 8 then
return
end
valorImagen = elementoTabla(imagen, 'mainsnak', 'datavalue', 'value')
local dates = {}
piesDeImagen = elementoTabla(imagen, 'qualifiers', 'P2096')
dates[1] = {['min'] = {}, ['max'] = {}, ['precision'] = birth.precision}
-- Encontrar el pie en español
dates[1].min.year = tonumber(mw.ustring.match(birth.time, "^[+-]?%d+"))
if piesDeImagen then
dates[1].min.month = tonumber(mw.ustring.match(birth.time, "\-(%d%d)\-"))
for k,pieDeImagen in pairs(piesDeImagen) do
dates[1].min.day = tonumber(mw.ustring.match(birth.time, "\-(%d%d)T"))
if pieDeImagen.datavalue.value.language == 'es' then
dates[1].max = mw.clone(dates[1].min)
return valorImagen, pieDeImagen.datavalue.value.text
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
-- Si no hay pie de imagen en español comprueba si hay fecha especificada para la imagen
local function age(d1, d2)
piesDeImagen = elementoTabla(imagen, 'qualifiers', 'P585')
local years = d2.year - d1.year
if piesDeImagen and piesDeImagen[1] then
if d2.month < d1.month or (d2.month == d1.month and d2.day < d1.day) then
return valorImagen, 'En ' .. require('Módulo:Wikidata/Fecha').FormateaFechaHora(piesDeImagen[1].datavalue.value, {['formatoFecha']='año',['enlace']='no'})
years = years - 1
end
if d2.year > 0 and d1.year < 0 then
years = years - 1 -- no year 0
end
return years
end
-- Sin pie de imagen en español
local old_min = age(dates[1].max, dates[2].min)
return valorImagen
local old_max = age(dates[1].min, dates[2].max)
local old, old_expr
if old_min == 0 and old_max == 0 then
old = "< 1"
old_max = 1 -- expression in singular
elseif old_min == old_max then
old = old_min
else
old = old_min .. "/" .. old_max
end
if args.formatting == 'unit' then
local langs = findLang(args.lang)
local yo, yo_sg, yo_pl, yo_pau
if langs[1] == wiki.langcode then
yo_sg = i18n["years-old"].singular
yo_pl = i18n["years-old"].plural
yo_pau = i18n["years-old"].paucal
end
if not isSet(yo_pl) then
yo_pl, _ = getLabelByLangs('Q24564698', langs)
yo_sg = yo_pl
end
if not isSet(yo_pau) then
yo_pau = yo_pl
end
yo = mw.language.new(langs[1]):plural(old_max, {yo_sg, yo_pau, yo_pl})
if mw.ustring.find(yo, '$1', 1, true) then
old_expr = mw.ustring.gsub(yo, "$1", old)
else
old_expr = old .. '&nbsp;' .. yo
end
elseif args.formatting then
old_expr = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
else
old_expr = old
end
return old_expr
end
 
-- Gets a label in a given language (content language by default) or its fallbacks, optionnally linked.
function p.propiedad(entidad, idPropiedad, opciones)
function p.getLabel(frame)
if entidad and entidad.claims and entidad.claims[idPropiedad] then
if not required and frame.args and frame:getParent().args.sandbox then
if not opciones then
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).getLabel(frame)
opciones = {['linkback']='sí'}
end
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame, true)
if id == nil then return end
local editicon = not (args.editicon == "false" or args.editicon == "no") and mw.wikibase.isValidEntityId(id)
local label_icon = ''
local label, lang
if args.label then
label = args.label
else
local languages = findLang(args.lang)
-- exceptions or labels fixed
local exist, labels = pcall(require, wiki.module_title .. "/labels" .. (languages[1] == wiki.langcode and '' or '/' .. languages[1]))
if exist and next(labels.infoboxLabelsFromId) ~= nil then
label = labels.infoboxLabelsFromId[id]
end
opciones.entityId = entidad.id
opciones.propiedad = idPropiedad
if label == nil then
return p.getPropiedad(opciones, entidad.claims[idPropiedad])
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
label_icon = addLabelIcon(id, lang, languages[1], editicon)
end
end
local linked = args.linked
if isSet(linked) and linked ~= "no" then
local article = mw.wikibase.getSitelink(id) or ("d:Special:EntityPage/" .. id)
return "[[" .. article .. "|" .. (label or id) .. "]]" .. label_icon, not required and '' or untranslated
else
return (label or id) .. label_icon, not required and '' or untranslated
end
end
 
-- Utilities -----------------------------
function p.esUnValor(entidad, idPropiedad, idaBuscar)
-- See also module ../debug.
if not entidad or not idPropiedad then
 
return false
-- Copied from Module:Wikibase
end
function p.getSiteLink(frame)
local declaracionid = elementoTablagetEntityId(entidadframe, 'claims', idPropiedad1)
if id == nil then
local idBuscado
return
if not declaracion then
return false
end
return mw.wikibase.getSitelink(id, mw.text.trim(frame.args[2] or ''))
end
 
-- Helper function for the default language code used
for k,v in pairs(declaracion) do
function p.lang(frame)
idBuscado = elementoTabla(v,'mainsnak','datavalue','value','id')
local lang = frame and frame.args[1] -- nil via require
if idBuscado == idaBuscar then
return truefindLang(lang)[1]
end
 
-- Number of statements
function p.numStatements(frame)
local id = getEntityId(frame)
if id == nil then return 0 end
local prop = mw.text.trim(frame.args[1])
local num = {}
if frame.args[2] then -- qualifier
local qual = mw.text.trim(frame.args[2])
local values = p.claim{item=id, property=prop, qualifier=qual, formatting='raw', separator='/·/'}
if values then
num = mw.text.split(values, '/·/')
end
else
num = mw.wikibase.getBestStatements(id, prop)
end
return false#num
end
 
-- Returns true if property datavalue is found excluding novalue/somevalue
function p.validProperty(frame)
local property = mw.text.trim(frame.args[1])
local item = getEntityId(frame)
if item == nil then return end
local prop_data = getSnak(mw.wikibase.getBestStatements(item, property), {1, "mainsnak", "datavalue"})
return prop_data and true or nil
end
 
"https://qu.wikipedia.org/wiki/Módulo:Wikidata" p'anqamanta chaskisqa (Wikipedia, Qhichwa / Quechua)