Diferencia entre revisiones de «Módulo:Wikidata»

mSin resumen de edición
m 485 revisiones importadas
 
(No se muestran 50 ediciones intermedias de 11 usuarios)
Línea 5: Línea 5:
* específico a una propiedad de Wikidata.
* específico a una propiedad de Wikidata.
*
*
* Fecha última revisión: 2 de mayo de 2019.
* Fecha última revisión: 30 de junio de 2021.
*
*
* Estado: En uso.
* Estado: En uso.
*
*
*********************************************************************************`-- ]]
*********************************************************************************`-- ]]
local p = {}
local p = {}
local datequalifiers = {'P585', 'P571', 'P580', 'P582'}
local datequalifiers = {'P585', 'P571', 'P580', 'P582'}
Línea 20: Línea 19:
  ========================================================================= `-- ]]
  ========================================================================= `-- ]]


local avisos = {
local avisos = mw.loadData('Módulo:Wikidata/mensajes')
["errores"] = {
["property-param-not-provided"] = "Parámetro de la propiedad no proporcionado.",
["entity-not-found"] = "Entrada no encontrada.",
["unknown-claim-type"] = "Tipo de notificación desconocida.",
["unknown-snak-type"] = "Tipo de dato desconocido.",
["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''",
["novalue"] = ""
}


-- Módulos y funciones utilizadas
-- Módulos y funciones utilizadas
Línea 43: Línea 27:
-- diferentes de Wikidata/Formatos
-- diferentes de Wikidata/Formatos
--
--
local modulosTipos =  {
local modulosTipos =  mw.loadData('Módulo:Wikidata/modulosTipos')
['altura'] = 'Módulo:Wikidata/Formato magnitud',
 
['área'] = 'Módulo:Wikidata/Formato magnitud',
local modulosTiposComplejos = {
['educado en'] = 'Módulo:Wikidata/Formatos educación',
['nacionalidad'] = 'Módulo:Wikidata/Formatos país',
['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',
}
}


Línea 74: Línea 51:
return mw.wikibase.getEntityObject()
return mw.wikibase.getEntityObject()
end
end
end
end


Línea 126: Línea 102:
local tablaAuxiliar = tablaDeclaraciones
local tablaAuxiliar = tablaDeclaraciones
tablaDeclaraciones = {}
tablaDeclaraciones = {}
if rango == 'deprecated' then
return {}
end


for indice, declaracion in pairs(tablaAuxiliar) do
for indice, declaracion in pairs(tablaAuxiliar) do
Línea 169: Línea 149:


function p.getDeclaraciones(entityId)
function p.getDeclaraciones(entityId)


-- == Comprobamos que existe un ítem enlazado a la página en Wikidata ==
-- == Comprobamos que existe un ítem enlazado a la página en Wikidata ==
Línea 176: Línea 155:
end
end
local entidad  = SelecionEntidadPorId(entityId)
local entidad  = SelecionEntidadPorId(entityId)
if not entidad then
if not entidad then
return  '' -- Si la página no está enlazada a un ítem no devuelve nada
return  '' -- Si la página no está enlazada a un ítem no devuelve nada
Línea 187: Línea 165:
end
end
-- == Declaración de formato y concatenado limpio ==
-- == Declaración de formato y concatenado limpio ==
return entidad.claims
return entidad.claims
end
end
Línea 198: Línea 175:
local claimqualifs = claim.qualifiers
local claimqualifs = claim.qualifiers
local i,qualif
local i,qualif
local vals, vals1, datavalue, value
local vals, vals1, datavalue, value, datatype
if not claimqualifs then
if not claimqualifs then
Línea 211: Línea 188:
if datavalue then
if datavalue then
datatype = datavalue.type
value = datavalue.value
value = datavalue.value
if value then
if datatype == 'time' and value then
return value.time
return value.time
elseif datatype == 'string' and value then
return value
end
end
end
end
Línea 224: Línea 204:
function p.getPropiedad(opciones, declaracion)
function p.getPropiedad(opciones, declaracion)
local propiedad = {}
local propiedad = {}
local tablaOrdenada = {}


if opciones.propiedad == 'precisión' or opciones.propiedad == 'latitud' or opciones.propiedad == 'longitud'  then
-- Resolver alias de propiedad
propiedad = 'P625' -- Si damos el valor latitud, longitud o precisión equivaldrá a dar p625
if opciones.propiedad == 'precisión' or opciones.propiedad == 'latitud' or opciones.propiedad == 'longitud'  then --latitud, longitud o precisión
propiedad = 'P625'
else
else
propiedad = opciones.propiedad -- En el resto de casos se lee lo dado
propiedad = opciones.propiedad -- En el resto de casos se lee lo dado
end
    end


if not propiedad then -- Comprobamos si existe la propiedad dada y en caso contrario se devuelve un error
if not propiedad then -- Comprobamos si existe la propiedad dada y en caso contrario se devuelve un error
return formatoError( 'property-param-not-provided' )
return formatoError( 'property-param-not-provided' )
end
end
 
local tablaOrdenada
if declaracion then
if declaracion then
tablaOrdenada = declaracion
tablaOrdenada = declaracion
elseif not p.getDeclaraciones(opciones.entityId) then
elseif mw.wikibase.isValidEntityId(tostring(opciones.entityId)) and mw.wikibase.isValidEntityId(tostring(propiedad)) then
return formatoError( 'other entity' )
tablaOrdenada = mw.wikibase.getAllStatements( opciones.entityId, mw.ustring.upper(propiedad) )
elseif p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)] then
if not tablaOrdenada[1] then return '' end
tablaOrdenada = p.getDeclaraciones(opciones.entityId)[mw.ustring.upper(propiedad)]
else
else
return ''
return ''
end
end
-- Función que separa la cadena de texto 'inputstr' utilizando un separador 'sep'
function split(inputstr, sep)
sep=sep or '%s'
local t={}
for field,s in string.gmatch(inputstr, "([^"..sep.."]*)("..sep.."?)") do
table.insert(t,field) 
if s=="" then
return t
end
end
end
tablaOrdenada = p.filtroDesconocidos(tablaOrdenada)
-- Aplicar filtro de calificador
if (opciones.filtroCalificador ~= nil and opciones.filtroCalificador ~= '') then
local opts = split(opciones.filtroCalificador, ';')
local negative = false
if (#opts > 2) then
if (opts[3]=='n') then
negative = true
elseif (opts[3]=='p') then
negative = false
end
end
tablaOrdenada = p.filtroCalificadores(tablaOrdenada, opts[1], split(opts[2], ','), negative)
end
-- Aplicar filtro de valor
if (opciones.filtroValor ~= nil and opciones.filtroValor ~= '') then
local opts = split(opciones.filtroValor, ';')
local negative = false
if (#opts > 1) then
if (opts[2]=='n') then
negative = true
elseif (opts[2]=='p') then
negative = false
end
end
tablaOrdenada = p.filtroValores(tablaOrdenada, split(opts[1], ','), negative)
end
-- Aplicar función de formato
local modulo, funcion
funcion = opciones['valor-función'] or opciones['value-function'] or opciones['funcion']
if funcion then
modulo = modulosTiposComplejos[funcion]
if modulo then
return require(modulo)[funcion](tablaOrdenada, opciones)
end
end


-- Evitar que pete cuando se haga el find en opciones['formatoTexto'] si vale nil
-- Evitar que pete cuando se haga el find en opciones['formatoTexto'] si vale nil
Línea 251: Línea 285:
end
end


--Dejar en su caso los valores de mayor rango
-- Aplicar filtro de mayor rango
if (opciones.rangoMayor == 'sí') then
if (opciones.rangoMayor == 'sí') then
tablaOrdenada = p.filtrarDeclaracionPorRango(tablaOrdenada)
tablaOrdenada = p.filtrarDeclaracionPorRango(tablaOrdenada)
end
end


--Ordenar en su caso por fecha. Ver la función chronosort de :fr:Module:Wikidata/Récup
-- Ordenarsegún el calificador "orden dentro de la serie"
if opciones.ordenar == 'sí' then
require('Módulo:Tablas').ordenar(tablaOrdenada,
function(elemento1,elemento2)
local orden1 = valinQualif(elemento1, { 'P1545' }) or '' -- elemento1.qualifiers.P1545[1].datavalue.value or ''
local orden2 = valinQualif(elemento2, { 'P1545' }) or '' -- elemento2.qualifiers.P1545[1].datavalue.value or ''
return orden1 < orden2
end
)
end
 
--Ordenar según la fecha. [Véase la función chronosort de :fr:Module:Wikidata/Récup]
if opciones.ordenar == 'por fecha' then
if opciones.ordenar == 'por fecha' then
require('Módulo:Tablas').ordenar(tablaOrdenada,
require('Módulo:Tablas').ordenar(tablaOrdenada,
Línea 268: Línea 314:
end
end
-- Si después de todo no queda nada en la tabla retornar
if not tablaOrdenada[1] then
if not tablaOrdenada[1] then
return
return
Línea 345: Línea 392:
-- busca un un elemento concreto en Wikidata (QID), en caso contrario que sea nil
-- busca un un elemento concreto en Wikidata (QID), en caso contrario que sea nil
local id = frame.args.id
local id = frame.args.id
if id and (#id == 0) then
if id and (#id == 0) then
id = nil
id = nil
Línea 425: Línea 473:
valor = elementoTabla(v,'mainsnak', 'datavalue', 'value')
valor = elementoTabla(v,'mainsnak', 'datavalue', 'value')
if valor.language == 'es' then
if valor and valor.language == 'es' then
return valor.text
return valor.text
end
end
Línea 509: Línea 557:
return ''
return ''
end
--[[ =========================================================================
Función que filtra los valores de una propiedad y devuelve solo los que
tengan el calificador "qualifier" indicado con uno de los valores "values" 
========================================================================= `-- ]]
function p.filtroCalificadores(t, qualifier, values, negativo)
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
for k,v in pairs(t) do
local counts = false
if(v["qualifiers"] ~= nil and v["qualifiers"][qualifier] ~= nil) then
for k2,v2 in pairs(v["qualifiers"][qualifier]) do
-- Comprobar si el identificador del valor del cualificador está en la lista
for k3,v3 in pairs(values) do
if (v2["datavalue"] ~= nil and v2["datavalue"]["value"] ~= nil and v2["datavalue"]["value"]["id"] ~= nil and v3 == v2["datavalue"]["value"]["id"])then 
counts = true -- Si está marcar como true
end
end
end
end
if counts and not negativo then -- Si uno de los valores del cualificador dio true se inserta el elemento
table.insert(f, v)
elseif not counts and negativo then -- Si ninguno de los valores del cualificador dio true se inserta el elemento
table.insert(f, v)
end
end
return f
end
--[[ =========================================================================
Función que filtra los valores de una propiedad y devuelve solo los que
tengan uno de los valores "values" 
========================================================================= `-- ]]
function p.filtroValores(t, values, negativo)
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
for k,v in pairs(t) do
local counts = false
if(v["mainsnak"]["datavalue"]["value"]["id"] ~= nil) then
for k2,v2 in pairs(values) do
if (v2 == v["mainsnak"]["datavalue"]["value"]["id"])then 
counts = true -- Si está marcar como true
end
end
end
if counts and not negativo then -- Si uno de los valores del cualificador dio true se inserta el elemento
table.insert(f, v)
elseif not counts and negativo then -- Si ninguno de los valores del cualificador dio true se inserta el elemento
table.insert(f, v)
end
end
return f
end
--[[ =========================================================================
Función que filtra los valores de una propiedad y devuelve solo los que
tengan formatos de valor, omitiendo los de formato desconocido o sin valor
========================================================================= `-- ]]
function p.filtroDesconocidos(t)
for k,v in pairs(t) do
if(v["mainsnak"]["snaktype"] ~= "value") then
t[k] = nil
end
local qual = v["qualifiers"]
if(qual ~= nil) then
for qualk,qualv in pairs(qual) do
local prop = qualv
for propk,propv in pairs(prop) do
if(propv["snaktype"] ~= "value") then
prop[propk] = nil
-- same as: qual[prop] = nil
-- same as: t["qualifiers"][prop] = nil
end
end
if #prop == 0 then
prop = nil
qual[qualk] = nil
end
end
if #qual == 0 then
qual = nil
end
end
end
return t
end
end


Línea 581: Línea 715:
if wValorCalificativoFormateado then
if wValorCalificativoFormateado then
datoFormateado = p.formatoDato(declaracion.mainsnak, opciones)
datoFormateado = p.formatoDato(declaracion.mainsnak, opciones)
-- Si el parámetro especificado era "|calificador="" no devolver propiedad y paréntesis
if(opciones.calificador ~= nil and opciones.calificador ~= '') then
return wValorCalificativoFormateado
end
-- Si el parámetro especificado era "|calificativo="" devolver propiedad y calificativo entre paréntesis
return (datoFormateado and datoFormateado .. '&nbsp;<small>(' .. wValorCalificativoFormateado .. ')</small>') or nil
return (datoFormateado and datoFormateado .. '&nbsp;<small>(' .. wValorCalificativoFormateado .. ')</small>') or nil
end
end
Línea 656: Línea 796:


-- == Formatos por defecto en función del tipo de valor ==
-- == Formatos por defecto en función del tipo de valor ==
--   * Para tipo coordenadas cuando se da como valor de propiedad: latitud, longitud o precisión
if opciones.propiedad == 'latitud' then
return valorDato.value['latitude']
elseif opciones.propiedad == 'longitud' then
return valorDato.value['longitude']
elseif opciones.propiedad == 'precisión' then
return valorDato.value['precision']


--   * Con el resto de valores en propiedad
--   * 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
if valorDato.type == 'wikibase-entityid' then -- Tipo: Número de entidad que puede ser un ítem o propiedad
local opcionesEntidad = {}
local opcionesEntidad = {}
if mw.ustring.find(opciones['formatoTexto'],'mayúscula', plain ) and
if mw.ustring.find(opciones['formatoTexto'],'mayúscula', plain ) and
Línea 696: Línea 827:
return require('Módulo:Wikidata/Fecha').FormateaFechaHora(valorDato.value, opcionesFecha, calificativos)
return require('Módulo:Wikidata/Fecha').FormateaFechaHora(valorDato.value, opcionesFecha, calificativos)
elseif valorDato.type == 'monolingualtext' then   -- Tipo: monoligüe
elseif valorDato.type == 'monolingualtext' then   -- Tipo: monolingüe
if valorDato.value then
if valorDato.value then
if opciones.idioma then
if opciones.idioma then
Línea 713: Línea 844:
return require('Módulo:Wikidata/Formatos').formatoUnidad(valorDato, opciones)
return require('Módulo:Wikidata/Formatos').formatoUnidad(valorDato, opciones)
elseif  valorDato.value['latitude']  and valorDato.value['longitude'] then -- Tipo: Coordenadas
elseif  valorDato.value['latitude']  and valorDato.value['longitude'] then -- Tipo: Coordenadas
--   * Para tipo coordenadas cuando se da como valor de propiedad: latitud, longitud o precisión
if TIPOLLP == 'latitud' then
return valorDato.value['latitude']
elseif TIPOLLP == 'longitud' then
return valorDato.value['longitude']
elseif TIPOLLP == 'precisión' then
return valorDato.value['precision']
    else
local globo = require('Módulo:Wikidata/Globos')[valorDato.value.globe]
local globo = require('Módulo:Wikidata/Globos')[valorDato.value.globe]


Línea 726: Línea 868:
  opciones.display ..'|formato=' .. opciones.formato..'}}')
  opciones.display ..'|formato=' .. opciones.formato..'}}')
end
end
 
    end
else
else
return formatoError( 'unknown-datavalue-type' ) -- Si no es de ninguno de estos tipos devolverá error valor desconocido
return formatoError( 'unknown-datavalue-type' ) -- Si no es de ninguno de estos tipos devolverá error valor desconocido
Línea 752: Línea 894:


function p.Wikidata( frame )
function p.Wikidata( frame )
    TIPOLLP="" --Variable global para identificar los casos de latitud, longitud o precisión
   
marco = frame
marco = frame
local args = frame.args
local args = frame.args
Línea 760: Línea 905:


local parentArgs = frame:getParent().args
local parentArgs = frame:getParent().args
 
 
-- Copiar los argumentos
-- Copiar los argumentos
local argumentos = {}
local argumentos = {}
Línea 773: Línea 919:
end
end
end
end
 
    if argumentos[1]=='longitud' or argumentos[1]=='latitud' or argumentos[1]=='precisión' then
      TIPOLLP=argumentos[1]
      marco.args[argumentos[1]]='P625'
    end
 
--if true then return require('Módulo:Tablas').tostring(argumentos) end
--if true then return require('Módulo:Tablas').tostring(argumentos) end
Línea 780: Línea 931:
local valorWikidata;
local valorWikidata;
if (args.prioridad ~= 'sí' or (args.importar and args.importar == 'no')) and args.valor and args.valor ~= '' then
if (args.prioridad ~= 'sí' or (args.importar and args.importar == 'no')) and args.valor and args.valor ~= '' then
valorWikidata = '';
valorWikidata = nil;
else
else
if not mw.wikibase.isValidEntityId(tostring(argumentos.entityId)) then
argumentos.entityId = mw.wikibase.getEntityIdForCurrentPage() or nil
end
valorWikidata = p.getPropiedad(argumentos, nil);
valorWikidata = p.getPropiedad(argumentos, nil);
end
end
Línea 794: Línea 948:
  and string.upper(args.propiedad) ~= 'P109' -- P109: firma de persona
  and string.upper(args.propiedad) ~= 'P109' -- P109: firma de persona
  and string.upper(args.propiedad) ~= 'P154') then -- P154: logotipo
  and string.upper(args.propiedad) ~= 'P154') then -- P154: logotipo
if valorWikidata ~= '' and args.valor and args.valor ~= '' then
if valorWikidata and valorWikidata ~= '' and args.valor and args.valor ~= '' then
categorias = '[[Categoría:Wikipedia:Artículos con datos locales]]'
categorias = '[[Categoría:Wikipedia:Artículos con datos locales]]'
elseif valorWikidata and valorWikidata == '' and args.valor and args.valor ~= '' and
elseif valorWikidata and valorWikidata == '' and args.valor and args.valor ~= '' and
(not args.calificador or args.calificador == '') and
(not args.calificador or args.calificador == '') and
(not args.dato or args.dato == '' or args.dato ~= 'fuente')then
(not args.dato or args.dato == '' or args.dato ~= 'fuente') then
categorias = '[[Categoría:Wikipedia:Artículos con datos por trasladar a Wikidata]]'
categorias = '[[Categoría:Wikipedia:Artículos con datos por trasladar a Wikidata]]'
end
end
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.prioridad == 'sí' and valorWikidata 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
if args.importar and args.importar == 'no' and args.valor and args.valor ~= '' then
return args.valor .. categorias
return args.valor .. categorias
Línea 856: Línea 1010:


if lidEntidad then
if lidEntidad then
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 ..
return valorPropiedad .. '<span class=\"wikidata-link lapiz 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 ..
']]</span>'
']]</span>'
else
else
Línea 872: Línea 1026:
if opciones.linkback == 'sí' and opciones.entityId and opciones.propiedad then
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 ..
lapiz = '<span class=\"wikidata-link lapiz 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>'
']]</span>'
else
else
Línea 932: Línea 1086:


-- Funciones existentes en otros módulos
-- Funciones existentes en otros módulos
function p.obtenerEtiquetaWikidata(entidad)
function p.obtenerEtiquetaWikidata(entidad, fallback)
if not entidad then entidad = Entidad end
if not entidad then entidad = fallback end
if entidad and entidad.labels and entidad.labels.es then
if entidad and entidad.labels and entidad.labels.es then
return entidad.labels.es.value
return entidad.labels.es.value
Línea 939: Línea 1093:
end
end


function p.obtenerImagenWikidata(propiedad)
function p.obtenerImagenWikidata(entidad, propiedad)
local imagen, valorImagen, piesDeImagen, k, pieDeImagen
local imagen, valorImagen, piesDeImagen, k, pieDeImagen
if not Entidad then
if not entidad then
return
return
end
end
--  Obtener la primera imagen en Wikidata de la persona
--  Obtener la primera imagen en Wikidata de la persona
local imagen = elementoTabla(Entidad, 'claims', propiedad,1)
local imagen = elementoTabla(entidad, 'claims', propiedad, 1)
--[[
-- Obtener el objeto de imagen, ya sea la primera, la última (WIP) o por fecha (WIP)
local imagen = (function()
local ImagenObj = elementoTabla(entidad, 'claims', idPropiedad)
if opciones.ordenar == 'por fecha' then
--
end
 
return elementoTabla(ImagenObj, 1)
end)()
--]]
if not imagen then
if not imagen then
return
return
end
end
valorImagen =  elementoTabla(imagen, 'mainsnak','datavalue','value')
valorImagen =  elementoTabla(imagen, 'mainsnak', 'datavalue', 'value')
piesDeImagen =  elementoTabla(imagen, 'qualifiers','P2096')
piesDeImagen =  elementoTabla(imagen, 'qualifiers', 'P2096')
-- Encontrar el pie en español
-- Encontrar el pie en español
if piesDeImagen then
if piesDeImagen then
Línea 962: Línea 1128:
piesDeImagen = elementoTabla(imagen, 'qualifiers', 'P585')
piesDeImagen = elementoTabla(imagen, 'qualifiers', 'P585')
if piesDeImagen and piesDeImagen[1] then
if piesDeImagen and piesDeImagen[1] then
return valorImagen, nombre .. ' en ' .. require('Módulo:Wikidata/Fecha').FormateaFechaHora(piesDeImagen[1].datavalue.value, {['formatoFecha']='año',['enlace']='no'})
return valorImagen, 'En ' .. require('Módulo:Wikidata/Fecha').FormateaFechaHora(piesDeImagen[1].datavalue.value, {['formatoFecha']='año',['enlace']='no'})
end
end
-- Sin pie de imagen en español
-- Sin pie de imagen en español
Línea 968: Línea 1134:
end
end


function p.propiedad(idPropiedad,opciones)
function p.propiedad(entidad, idPropiedad, opciones)
if Entidad and Entidad.claims and Entidad.claims[idPropiedad] then
if entidad and entidad.claims and entidad.claims[idPropiedad] then
if not opciones then
if not opciones then
opciones = {['linkback']='sí'}
opciones = {['linkback']='sí'}
end
end
opciones.entityId  = Entidad.id
--[[
local ValorPosicional = (function()
if opciones['valor_posicional'] == 'último' then return -1 end
if type(opciones['valor_posicional']) == 'number' then return opciones['valor_posicional'] end
return 1
end)()
 
local ValorPosicionalCalif =(function()
if opciones['valor_posicional_calif'] == 'último' then return -1 end
if type(opciones['valor_posicional_calif']) == 'number' then return opciones['valor_posicional_calif'] end
return 1
end)()
local Calificador = opciones['calificador']
 
local Obj = (function()
local Obj = (function()
local Obj = elementoTabla(entidad, 'claims', idPropiedad)
if ValorPosicional == -1 then return elementoTabla(Obj, #Obj) end
return elementoTabla(Obj, ValorPosicional)
end)()
 
if Calificador then
Obj = (function()
local Obj = elementoTabla(Obj, 'qualifiers', Calificador)
if ValorPosicionalCalif == -1 then return elementoTabla(Obj, #Obj) end
return elementoTabla(Obj, ValorPosicionalCalif)
end)()
end
return Obj
end)()
Tipo = elementoTabla(Obj, 'datavalue', 'type')
-- Devolver el ID de la entidad, para propiedades de entidad
if opciones['formato'] == 'entidadID' then
return elementoTabla(Obj, 'datavalue', 'value', 'id')
end
-- Preparar para devolver el archivo más reciente en la propiedad. Buscar cómo hacerlo con los calificadores
if opciones['formato'] == 'archivo' then
if Calificador then return elementoTabla(Obj, 'datavalue', 'value') end
if not opciones['uno'] then opciones['uno'] = 'último' end
opciones['ordenar'] = 'por fecha'
end
 
-- Obtener la propiedad como cadena sin formato
if opciones['formato'] == 'cadena' then
opciones['linkback'] = 'no'
if Tipo == 'string' then
return elementoTabla(Obj, 'datavalue', 'value')
end
end
 
-- Devolver una cadena numérica correctamente formateada
if opciones['formato'] == 'número' then
if Tipo == 'quantity' then
return formatoNumero(elementoTabla(Obj, 'datavalue', 'value', 'amount'))
end
end
 
-- Devolver una cadena numérica con su unidad
if opciones['formato'] == 'unidad' then
if elementoTabla(entidad, 'claims', idPropiedad, 2, 'mainsnak', 'datavalue') then
return formatoNumero(elementoTabla(entidad, 'claims', idPropiedad, 1, 'mainsnak', 'datavalue', 'value', 'amount')) .. '&nbsp;-&nbsp;' .. numeroUnidad(elementoTabla(entidad, 'claims', idPropiedad, 2, 'mainsnak', 'datavalue'), opciones)
else
return numeroUnidad(elementoTabla(entidad, 'claims', idPropiedad, 1, 'mainsnak', 'datavalue'), opciones)
end
end
--]]
opciones.entityId  = entidad.id
opciones.propiedad = idPropiedad
opciones.propiedad = idPropiedad
valorPropiedad = p.getPropiedad(opciones,Entidad.claims[idPropiedad])
return valorPropiedad
return p.getPropiedad(opciones, entidad.claims[idPropiedad])
end
end
end
end
Línea 998: Línea 1235:
end
end
return false
return false
end
-- Obtener el objeto mw.language, para usar sus funciones en otros módulos
function p.language()
return es
end
end


return p
return p