Diferencia entre revisiones de «Módulo:Wikidata»
Apariencia
Sin resumen de edición |
Revertidos los cambios de Juan Mayordomo a la última edición de Juan Mayordomo |
||
| Línea 5: | Línea 5: | ||
* a una propiedad de Wikidata. | * a una propiedad de Wikidata. | ||
* | * | ||
* Fecha última revisión: | * Fecha última revisión: 1 de febrero de 2014. | ||
* | * | ||
* Estado: En uso. | * Estado: En uso. | ||
| Línea 22: | Línea 22: | ||
["entity-not-found"] = "Entrada no encontrada.", | ["entity-not-found"] = "Entrada no encontrada.", | ||
["unknown-claim-type"] = "Tipo de notificación desconocida.", | ["unknown-claim-type"] = "Tipo de notificación desconocida.", | ||
["unknown-snak-type"] = "Tipo de | ["unknown-snak-type"] = "Tipo de snak desconocido.", | ||
["unknown-datavalue-type"] = "Tipo de dato desconocido.", | ["unknown-datavalue-type"] = "Tipo de dato desconocido.", | ||
["unknown-entity-type"] = "Tipo de entrada desconocido.", | ["unknown-entity-type"] = "Tipo de entrada desconocido.", | ||
| Línea 49: | Línea 49: | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function getEntityIdFromValue( value ) | ||
local | local prefix = '' | ||
if | if value['entity-type'] == 'item' then | ||
prefix = 'q' | |||
elseif | elseif value['entity-type'] == 'property' then | ||
prefix = 'p' | |||
else | else | ||
return | return formatError( 'unknown-entity-type' ) | ||
end | end | ||
return | return prefix .. value['numeric-id'] | ||
end | end | ||
| Línea 65: | Línea 65: | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatError( key ) | ||
return '<span class="error">' .. i18n.errors[ | return '<span class="error">' .. i18n.errors[key] .. '</span>' | ||
end | end | ||
--[[ ========================================================================= | --[[ ========================================================================= | ||
Función para recopilar los valores | Función para recopilar los valores y crear la cadena que devolverá | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatStatements( options ) | ||
if | if options.property == 'precisión' or options.property == 'latitud' or options.property == 'longitud' then | ||
propiedad = 'p625' -- Si damos el valor latitud | propiedad = 'p625' -- Si damos el valor latitud o longitud equivaldrá a dar p625 | ||
else | else | ||
propiedad = | propiedad = options.property -- 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 | return formatError( 'property-param-not-provided' ) | ||
end | end | ||
-- == Comprobamos que existe un ítem enlazado a la página en Wikidata == | -- == Comprobamos que existe un ítem enlazado a la página en Wikidata == | ||
local | local entity = getEntityFromId( options.entityId ) | ||
if not | if not entity then | ||
return '' -- | return ''--formatError( 'entity-not-found' ) | ||
end | end | ||
-- == Comprobamos que el ítem tiene declaraciones (claims) == | -- == Comprobamos que el ítem tiene declaraciones (claims) == | ||
if ( | if (entity.claims == nil) or (not entity.claims[string.lower(propiedad)]) then | ||
return '' -- | return '' --TODO error? | ||
end | end | ||
| Línea 99: | Línea 99: | ||
local propiedad = {} | local propiedad = {} | ||
if | if options.property == 'latitud' or options.property == 'longitud' or options.property == 'precisión' then | ||
propiedad = 'p625' | propiedad = 'p625' | ||
else | else | ||
propiedad = | propiedad = options.property | ||
end | end | ||
local | local cadena = entity.claims[string.lower(propiedad)] | ||
-- == Hacemos que índice | -- == Hacemos que índice 0 pase a ser 1. Necesario para que todo quede en el mismo orden que en ítem == | ||
local s = {} | |||
local | for k, v in pairs(cadena) do | ||
for | s[k+1] = v | ||
end | end | ||
-- == Creamos una tabla (array) con los valores que devolverá == | -- == Creamos una tabla (array) con los valores que devolverá == | ||
local | local formattedStatements = {} | ||
for | for i, statement in pairs(s) do | ||
table.insert( | table.insert( formattedStatements, formatStatement( statement, options ) ) | ||
end | end | ||
return mw.text.listToText( | return mw.text.listToText( formattedStatements, options.separator, options.conjunction ) | ||
end | end | ||
| Línea 128: | Línea 127: | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatStatement( statement, options ) | ||
if not | if not statement.type or statement.type ~= 'statement' then | ||
return | return formatError( 'unknown-claim-type' ) | ||
end | end | ||
return | return formatSnak( statement.mainsnak, options ) | ||
-- | --TODO reference and qualifiers | ||
end | end | ||
--[[ ========================================================================= | --[[ ========================================================================= | ||
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 | si es value pasa el valor como argumento a la función formatDatavalue() | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatSnak( snak, options ) | ||
if | if snak.snaktype == 'somevalue' then | ||
return i18n['somevalue'] | return i18n['somevalue'] | ||
elseif | elseif snak.snaktype == 'novalue' then | ||
return i18n['novalue'] | return i18n['novalue'] | ||
elseif | elseif snak.snaktype == 'value' then | ||
return | return formatDatavalue( snak.datavalue, options ) | ||
else | else | ||
return | return formatError( 'unknown-snak-type' ) | ||
end | end | ||
end | end | ||
| Línea 156: | Línea 155: | ||
--[[ ========================================================================= | --[[ ========================================================================= | ||
Función que establece el tipo de formato en función del tipo de valor | 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 | el módulo donde se establece el formato y la función de este que lo establece | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatDatavalue( datavalue, options ) | ||
if options['value-module'] or options['value-function'] then | |||
if not options['value-module'] or not options['value-function'] then | |||
if | return formatError( 'unknown-value-module' ) | ||
if not | |||
return | |||
end | end | ||
local | local formatter = require ('Module:' .. options['value-module']) | ||
if | if formatter == nil then | ||
return | return formatError( 'value-module-not-found' ) | ||
end | end | ||
local fun = | local fun = formatter[options['value-function']] | ||
if fun == nil then | if fun == nil then | ||
return | return formatError( 'value-function-not-found' ) | ||
end | end | ||
return fun( datavalue.value, | return fun( datavalue.value, options ) | ||
end | end | ||
-- == Formatos por defecto en función del tipo de valor == | -- == Formatos por defecto en función del tipo de valor == | ||
if options.property == 'latitud' then --Para las coordenadas | |||
return datavalue.value['latitude'] | |||
if | elseif options.property == 'longitud' then | ||
return | return datavalue.value['longitude'] | ||
elseif | elseif options.property == 'precisión' then | ||
return | return datavalue.value['precision'] | ||
elseif | elseif datavalue.type == 'wikibase-entityid' then | ||
return | return formatEntityId( getEntityIdFromValue( datavalue.value ), options ) | ||
elseif datavalue.type == 'string' then -- tipo cadena | |||
return datavalue.value --TODO ids + media | |||
elseif datavalue.type == 'time' then -- Fecha/hora | |||
elseif | return FormateaFechaHora(datavalue.value,options) | ||
return | elseif datavalue.type == 'quantity' then -- tipo cantidad | ||
elseif | return mw.ustring.gsub(datavalue.value['amount'], '+','').. '±' .. datavalue.value['unit'] | ||
return | elseif datavalue.value['latitude'] and datavalue.value['longitude'] then -- tipo coordenadas | ||
elseif | return marco:preprocess('{{coord|' .. datavalue.value['latitude'] .. '|' .. | ||
return FormateaFechaHora( | datavalue.value['longitude'] .. '|globe:' .. options.cuerpo .. '_type:' .. options.tipo .. '|display=' .. | ||
elseif | options.display ..'|format=' .. options.formato..'}}') | ||
return mw.ustring.gsub( | |||
elseif | |||
return marco:preprocess('{{coord|' .. | |||
else | else | ||
return | return formatError( 'unknown-datavalue-type' ) | ||
end | end | ||
end | end | ||
| Línea 215: | Línea 205: | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function | function formatEntityId( entityId, options ) | ||
local | local label = mw.wikibase.label( entityId ) | ||
if | local link = mw.wikibase.sitelink( entityId ) | ||
if | if link and options['link'] ~= 'no' then | ||
return '[[' .. | if label then | ||
return '[[' .. link .. '|' .. label .. ']]' | |||
else | else | ||
return '[[' .. | return '[[' .. link .. ']]' | ||
end | end | ||
elseif label then | |||
return label --TODO what if no links and label + fallback language? | |||
elseif | |||
return | |||
else | else | ||
return '' | return '' | ||
end | end | ||
end | end | ||
function FormateaFechaHora(fechahora, opciones) | function FormateaFechaHora(fechahora, opciones) | ||
| Línea 248: | Línea 229: | ||
local dia, mes, anyo | local dia, mes, anyo | ||
if | if precision == 11 then -- Fecha de la que se conoce el año, el mes y el día | ||
return formatError( 'unknown-datavalue-type' ) | |||
elseif precision == 10 then -- Fecha de la que se conoce el año y el mes | elseif precision == 10 then -- Fecha de la que se conoce el año y el mes | ||
return formatError( 'unknown-datavalue-type' ) | |||
elseif precision == 9 then -- Fecha de la que se conoce el año | elseif precision == 9 then -- Fecha de la que se conoce el año | ||
return formatError( 'unknown-datavalue-type' ) | |||
elseif precision == 8 then -- Fecha de la que se conoce la década | elseif precision == 8 then -- Fecha de la que se conoce la década | ||
return formatError( 'unknown-datavalue-type' ) | |||
elseif precision == 7 then -- Fecha de la que se conoce el siglo | elseif precision == 7 then -- Fecha de la que se conoce el siglo | ||
return formatError( 'unknown-datavalue-type' ) | |||
elseif precision == 6 then -- Fecha de la que se conoce el milenio | elseif precision == 6 then -- Fecha de la que se conoce el milenio | ||
return formatError( 'unknown-datavalue-type' ) | |||
else | else | ||
return formatError( 'unknown-datavalue-type' ) | |||
end | |||
end | end | ||
| Línea 278: | Línea 251: | ||
========================================================================= `-- ]] | ========================================================================= `-- ]] | ||
function p. | function p.formatStatements( frame ) | ||
marco = frame | marco = frame | ||
local args = frame.args | local args = frame.args | ||
local | local valorwikidata = formatStatements( frame.args ) | ||
if args.prioridad == 'sí' and | if args.prioridad == 'sí' and valorwikidata ~= '' then -- Si se da el valor sí a prioridad tendrá preferencia el valor de Wikidata | ||
return | return formatStatements( frame.args ) -- valor que sustituye al valor de Wikidata parámetro 2 | ||
elseif args. | elseif args.value and args.value ~= '' then | ||
return args. | return args.value | ||
else | else | ||
return | return formatStatements( frame.args ) | ||
end | end | ||
end | end | ||
return p | return p | ||
Revisión del 14:11 4 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.
*
*********************************************************************************`-- ]]
local p = {}
--[[ =========================================================================
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 correspondiente a la página o otro dado.
Esto último aún no funciona.
========================================================================= `-- ]]
function getEntityFromId( id )
if id then
return mw.wikibase.getEntity( id )
end
return mw.wikibase.getEntity()
end
--[[ =========================================================================
Función que identifica si el valor devuelto es un ítem o una propiedad
y en función de eso añade el prefijo correspondiente
========================================================================= `-- ]]
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
--[[ =========================================================================
Función auxiliar para dar formato a los mensajes de error
========================================================================= `-- ]]
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 == 'time' then -- Fecha/hora
return FormateaFechaHora(datavalue.value,options)
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
function FormateaFechaHora(fechahora, opciones)
local etiqueta = fechahora.label
local timestamp = fechahora.time
local precision = fechahora.precision
local dia, mes, anyo
if precision == 11 then -- Fecha de la que se conoce el año, el mes y el día
return formatError( 'unknown-datavalue-type' )
elseif precision == 10 then -- Fecha de la que se conoce el año y el mes
return formatError( 'unknown-datavalue-type' )
elseif precision == 9 then -- Fecha de la que se conoce el año
return formatError( 'unknown-datavalue-type' )
elseif precision == 8 then -- Fecha de la que se conoce la década
return formatError( 'unknown-datavalue-type' )
elseif precision == 7 then -- Fecha de la que se conoce el siglo
return formatError( 'unknown-datavalue-type' )
elseif precision == 6 then -- Fecha de la que se conoce el milenio
return formatError( 'unknown-datavalue-type' )
else
return formatError( 'unknown-datavalue-type' )
end
end
--[[ =========================================================================
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 -- Si se da el valor sí a prioridad tendrá preferencia el valor de Wikidata
return formatStatements( frame.args ) -- valor que sustituye al valor de Wikidata parámetro 2
elseif args.value and args.value ~= '' then
return args.value
else
return formatStatements( frame.args )
end
end
return p