Diferencia entre revisiones de «Módulo:Wikidata»
Apariencia
Sin resumen de edición |
Sin resumen de edición |
||
| Línea 63: | Línea 63: | ||
function formatStatements( options ) | function formatStatements( options ) | ||
if options.property == 'precisión' or options.property == 'latitud' or options.property == 'longitud' then | if options.property == 'precisión' or options.property == 'latitud' or options.property == 'longitud' then | ||
propiedad = 'p625' | propiedad = 'p625' -- Si damos el valor latitud o longitud equivaldrá a dar p625 | ||
else | else | ||
propiedad = options.property | propiedad = options.property -- En el resto de casos se lee lo dado | ||
end | end | ||
if not propiedad then | if not propiedad then -- Comprobamos si existe la propiedad dada y en caso contrario se devuelve un error | ||
return formatError( 'property-param-not-provided' ) | return formatError( 'property-param-not-provided' ) | ||
end | end | ||
-- | -- == Comprobamos que existe un ítem enlazado a la página en Wikidata == | ||
local entity = getEntityFromId( options.entityId ) | |||
local entity = getEntityFromId( options.entityId ) | |||
if not entity then | if not entity then | ||
return ''--formatError( 'entity-not-found' ) | return ''--formatError( 'entity-not-found' ) | ||
end | end | ||
-- == Comprobamos que el ítem tiene declaraciones (claims) == | |||
if (entity.claims == nil) or (not entity.claims[string.lower(propiedad)]) then | if (entity.claims == nil) or (not entity.claims[string.lower(propiedad)]) then | ||
return '' --TODO error? | return '' --TODO error? | ||
end | end | ||
--Declaración de formato y concatenado limpio | -- == Declaración de formato y concatenado limpio == | ||
local propiedad = {} | local propiedad = {} | ||
| Línea 89: | Línea 92: | ||
propiedad = options.property | propiedad = options.property | ||
end | end | ||
local cadena = entity.claims[string.lower(propiedad)] | local cadena = entity.claims[string.lower(propiedad)] | ||
-- == Hacemos que índice 0 pase a ser 1. Necesario para que todo quede en el mismo orden que en ítem == | |||
local s = {} | |||
for k, v in pairs(cadena) do | for k, v in pairs(cadena) do | ||
s[k+1] = v | s[k+1] = v | ||
end | end | ||
-- == Creamos una tabla (array) con los valores que devolverá == | |||
local formattedStatements = {} | local formattedStatements = {} | ||
for i, statement in pairs(s) do | for i, statement in pairs(s) do | ||
| Línea 102: | Línea 111: | ||
--[[ ========================================================================= | --[[ ========================================================================= | ||
Función que comprueba si la página está enlazada a Wikidata | |||
en caso de estarlo pasa el valor como a argumento a la función formatSnak() | |||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
| Línea 115: | Línea 125: | ||
--[[ ========================================================================= | --[[ ========================================================================= | ||
Función que comprueba el tipo de dato (snak) | Función que comprueba el tipo de dato (snak) | ||
si es value pasa el valor como argumento a la función formatDatavalue() | |||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
| Línea 137: | Línea 148: | ||
function formatDatavalue( datavalue, options ) | function formatDatavalue( datavalue, options ) | ||
if options['value-module'] or options['value-function'] then | if options['value-module'] or options['value-function'] then | ||
if not options['value-module'] or not options['value-function'] then | if not options['value-module'] or not options['value-function'] then | ||
| Línea 152: | Línea 163: | ||
return fun( datavalue.value, options ) | return fun( datavalue.value, options ) | ||
end | end | ||
-- | |||
-- == Formatos por defecto en función del tipo de valor == | |||
if options.property == 'latitud' then --Para las coordenadas | if options.property == 'latitud' then --Para las coordenadas | ||
return datavalue.value['latitude'] | return datavalue.value['latitude'] | ||
Revisión del 18:58 1 feb 2014
La documentación para este módulo puede ser creada en Módulo:Wikidata/doc
--[[*********************************************************************************
* 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: 1 de febrero de 2014.
*
* Estado: En uso.
*
*********************************************************************************`-- ]]
--[[ =========================================================================
Mensajes de error
========================================================================= `-- ]]
local i18n = {
["errors"] = {
["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 snak desconocido.",
["unknown-datavalue-type"] = "Tipo 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 value-module.",
["value-function-not-found"] = "No se ha encontrado la función apuntada por value-function."
},
["somevalue"] = "''valor desconocido''",
["novalue"] = "''sin valor''"
}
--[[ =========================================================================
Función para identificar el ítem y la propiedad
========================================================================= `-- ]]
function getEntityFromId( id )
if id then
return mw.wikibase.getEntity( id )
end
return mw.wikibase.getEntity()
end
function getEntityIdFromValue( value )
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'q'
elseif value['entity-type'] == 'property' then
prefix = 'p'
else
return formatError( 'unknown-entity-type' )
end
return prefix .. value['numeric-id']
end
function formatError( key )
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
--[[ =========================================================================
Función para recopilar los valores y crear la cadena que devolverá
========================================================================= `-- ]]
function formatStatements( options )
if options.property == 'precisión' or options.property == 'latitud' or options.property == 'longitud' then
propiedad = 'p625' -- Si damos el valor latitud o longitud equivaldrá a dar p625
else
propiedad = options.property -- En el resto de casos se lee lo dado
end
if not propiedad then -- Comprobamos si existe la propiedad dada y en caso contrario se devuelve un error
return formatError( 'property-param-not-provided' )
end
-- == Comprobamos que existe un ítem enlazado a la página en Wikidata ==
local entity = getEntityFromId( options.entityId )
if not entity then
return ''--formatError( 'entity-not-found' )
end
-- == Comprobamos que el ítem tiene declaraciones (claims) ==
if (entity.claims == nil) or (not entity.claims[string.lower(propiedad)]) then
return '' --TODO error?
end
-- == Declaración de formato y concatenado limpio ==
local propiedad = {}
if options.property == 'latitud' or options.property == 'longitud' or options.property == 'precisión' then
propiedad = 'p625'
else
propiedad = options.property
end
local cadena = entity.claims[string.lower(propiedad)]
-- == Hacemos que índice 0 pase a ser 1. Necesario para que todo quede en el mismo orden que en ítem ==
local s = {}
for k, v in pairs(cadena) do
s[k+1] = v
end
-- == Creamos una tabla (array) con los valores que devolverá ==
local formattedStatements = {}
for i, statement in pairs(s) do
table.insert( formattedStatements, formatStatement( statement, options ) )
end
return mw.text.listToText( formattedStatements, options.separator, options.conjunction )
end
--[[ =========================================================================
Función que comprueba si la página está enlazada a Wikidata
en caso de estarlo pasa el valor como a argumento a la función formatSnak()
========================================================================= `-- ]]
function formatStatement( statement, options )
if not statement.type or statement.type ~= 'statement' then
return formatError( 'unknown-claim-type' )
end
return formatSnak( statement.mainsnak, options )
--TODO reference and qualifiers
end
--[[ =========================================================================
Función que comprueba el tipo de dato (snak)
si es value pasa el valor como argumento a la función formatDatavalue()
========================================================================= `-- ]]
function formatSnak( snak, options )
if snak.snaktype == 'somevalue' then
return i18n['somevalue']
elseif snak.snaktype == 'novalue' then
return i18n['novalue']
elseif snak.snaktype == 'value' then
return formatDatavalue( snak.datavalue, options )
else
return formatError( 'unknown-snak-type' )
end
end
--[[ =========================================================================
Función que establece el tipo de formato en función del tipo de valor
(datavalue.type) y en caso de solicitarse un formato complemetario asocia
el módulo donde se establece el formato y la función de este que lo establece
========================================================================= `-- ]]
function formatDatavalue( datavalue, options )
if options['value-module'] or options['value-function'] then
if not options['value-module'] or not options['value-function'] then
return formatError( 'unknown-value-module' )
end
local formatter = require ('Module:' .. options['value-module'])
if formatter == nil then
return formatError( 'value-module-not-found' )
end
local fun = formatter[options['value-function']]
if fun == nil then
return formatError( 'value-function-not-found' )
end
return fun( datavalue.value, options )
end
-- == Formatos por defecto en función del tipo de valor ==
if options.property == 'latitud' then --Para las coordenadas
return datavalue.value['latitude']
elseif options.property == 'longitud' then
return datavalue.value['longitude']
elseif options.property == 'precisión' then
return datavalue.value['precision']
elseif datavalue.type == 'wikibase-entityid' then
return formatEntityId( getEntityIdFromValue( datavalue.value ), options )
elseif datavalue.type == 'string' then -- tipo cadena
return datavalue.value --TODO ids + media
elseif datavalue.type == 'quantity' then -- tipo cantidad
return mw.ustring.gsub(datavalue.value['amount'], '+','').. '±' .. datavalue.value['unit']
elseif datavalue.value['latitude'] and datavalue.value['longitude'] then -- tipo coordenadas
return marco:preprocess('{{coord|' .. datavalue.value['latitude'] .. '|' ..
datavalue.value['longitude'] .. '|globe:' .. options.cuerpo .. '_type:' .. options.tipo .. '|display=' ..
options.display ..'|format=' .. options.formato..'}}')
else
return formatError( 'unknown-datavalue-type' )
end
end
--[[ =========================================================================
Damos formato a los enlaces internos
========================================================================= `-- ]]
function formatEntityId( entityId, options )
local label = mw.wikibase.label( entityId )
local link = mw.wikibase.sitelink( entityId )
if link and options['link'] ~= 'no' then
if label then
return '[[' .. link .. '|' .. label .. ']]'
else
return '[[' .. link .. ']]'
end
elseif label then
return label --TODO what if no links and label + fallback language?
else
return ''
end
end
local p = {}
--[[ =========================================================================
Función principal
========================================================================= `-- ]]
function p.formatStatements( frame )
marco = frame
local args = frame.args
local valorwikidata = formatStatements( frame.args )
if args.prioridad == 'sí' and valorwikidata ~= '' then
return formatStatements( frame.args )
elseif args.value and args.value ~= '' then
return args.value
else
return formatStatements( frame.args )
end
end
return p