Diferencia entre revisiones de «Módulo:Wikidata»

2075 bytes añadidos ,  4 marzo
m
1 revisión importada
m (1 revisión importada)
m (1 revisión importada)
 
(No se muestran 12 ediciones intermedias de 5 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',
['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 modulosTiposComplejos =  {
local modulosTiposComplejos =  {
Línea 79: Línea 51:
return mw.wikibase.getEntityObject()
return mw.wikibase.getEntityObject()
end
end
end
end


Línea 131: 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 174: 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 181: 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 192: 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 203: 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 216: 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 229: 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
-- Tierra
propiedad = 'P625'  
-- Luna
        if mw.wikibase.getEntityObject() and mw.wikibase.getEntityObject():formatPropertyValues("p376")["value"] == 'Luna' then
    propiedad = 'P8981'
        end
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)  
function split(inputstr, sep)  
sep=sep or '%s'  
sep=sep or '%s'  
Línea 262: Línea 243:
end
end
tablaOrdenada = p.filtroDesconocidos(tablaOrdenada)
-- Aplicar filtro de calificador
if (opciones.filtroCalificador ~= nil and opciones.filtroCalificador ~= '') then
if (opciones.filtroCalificador ~= nil and opciones.filtroCalificador ~= '') then
local opts = split(opciones.filtroCalificador, ';')
local opts = split(opciones.filtroCalificador, ';')
local negative = false
tablaOrdenada = p.filtroCalificadores(tablaOrdenada, opts[1], split(opts[2], ','))
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
end
-- Aplicar filtro de valor
if (opciones.filtroValor ~= nil and opciones.filtroValor ~= '') then
if (opciones.filtroValor ~= nil and opciones.filtroValor ~= '') then
tablaOrdenada = p.filtroValores(tablaOrdenada, split(opciones.filtroValor, ','))
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
end
-- Aplicar función de formato
local modulo, funcion
local modulo, funcion
funcion = opciones['valor-función'] or opciones['value-function'] or opciones['funcion']
funcion = opciones['valor-función'] or opciones['value-function'] or opciones['funcion']
if funcion then  
if funcion then  
modulo = modulosTiposComplejos[funcion]
modulo = modulosTiposComplejos[funcion]
Línea 289: Línea 291:
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 306: Línea 320:
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 383: Línea 398:
-- 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 554: Línea 570:
========================================================================= `-- ]]
========================================================================= `-- ]]
 
 
function p.filtroCalificadores(t, qualifier, values)
function p.filtroCalificadores(t, qualifier, values, negativo)
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
for k,v in pairs(t) do
for k,v in pairs(t) do
Línea 568: Línea 584:
end
end
end
end
if counts then -- Si uno de los valores del cualificador dio true se inserta el elemento
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)
table.insert(f, v)
end
end
Línea 580: Línea 598:
========================================================================= `-- ]]
========================================================================= `-- ]]
 
 
function p.filtroValores(t, values)
function p.filtroValores(t, values, negativo)
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
local f = {}  -- Tabla que se devolverá con el resultado del filtrado
for k,v in pairs(t) do
for k,v in pairs(t) do
Línea 591: Línea 609:
end
end
end
end
if counts then -- Si uno de los valores dio true se inserta el elemento
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)
table.insert(f, v)
end
end
end
end
return f
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 668: Línea 721:
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 743: Línea 802:


-- == 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 783: Línea 833:
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 800: Línea 850:
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 813: Línea 874:
  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 839: Línea 900:


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 847: Línea 911:


local parentArgs = frame:getParent().args
local parentArgs = frame:getParent().args
 
 
-- Copiar los argumentos
-- Copiar los argumentos
local argumentos = {}
local argumentos = {}
Línea 860: Línea 925:
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 867: Línea 937:
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
local ent = SelecionEntidadPorId(argumentos.entityId)
if not mw.wikibase.isValidEntityId(tostring(argumentos.entityId)) then
argumentos.entityId = ent and ent.id or nil
argumentos.entityId = mw.wikibase.getEntityIdForCurrentPage() or nil
end
valorWikidata = p.getPropiedad(argumentos, nil);
valorWikidata = p.getPropiedad(argumentos, nil);
end
end
Línea 883: Línea 954:
  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 945: Línea 1016:


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 961: Línea 1032:
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
MediaWiki spam blocked by CleanTalk.