Módulo:Wikidata/Formatos

De Wikinoticias, la fuente libre de noticias
[ver · editar · actualizar]
Documentación de módulo
Aún no se han escrito las instrucciones sobre este módulo. Añádelas.


local p = {}
local es = mw.language.new('es')
local moduloTablas  = require('Módulo:Tablas') 
local elementoTabla = moduloTablas.elemento
local enTabla = moduloTablas.en

function p.formatImage( value, options )
    local str = '[[Image:' .. value .. '|thumb'
    if options.legend then
        str = str .. '|' .. options.legend
    end
    return str .. ']]'
end
function p.formatBandera(value, options, frame)
	local coincidenciafor
	if frame == nil then
	    frame = marco
	end
    local label = mw.wikibase.label( 'Q' .. value['numeric-id'] )
    
    if not label then 
    	return
    end
    
    local link  = mw.wikibase.sitelink('Q' .. value['numeric-id'] )
    local nombre 
    local tipo = mw.ustring.gsub(label,'(%D+)%sde%s%D+','%1')
    if options.cortar and options.cortar ~= '' then
        coincidencia = mw.ustring.find( es:lc(options.cortar), es:lc(tipo), plain )
    end
    if coincidencia then
    	nombre = mw.ustring.gsub(label,'%D+%sde%s(%D+)','%1')
    else
    	nombre = label
    end	
    local str2
    if mw.title.new('Plantilla:Geodatos '.. label ).exists  then
        str2 = frame:preprocess('{{bandera2|' .. label ..'|nombre ='.. nombre .. '}}')
    elseif link and label then
        str2 = '[[' .. link .. '|' .. nombre .. ']]'
    elseif label then
        str2 = nombre
    else
        str2 = ''
    end
    return str2 
end
function p.formatCoor(value)
    local cadenacoor = value
    return marco:preprocess('{{coord|' .. cadenacoor[tostring('latitude')] ..'|'.. cadenacoor[tostring('longitude')] .. '|format=dms}}')
end

-- Funciones para entidades de Wikidata
local noMostrarPremio={
	['Q20899118'] = true, -- NPR Top 100 Science Fiction and Fantasy Books
}

function p.formatoPremio(valor)
	local enlace, etiqueta, idEntidad = p.obtenerDatos(valor)
	
	if idEntidad and noMostrarPremio[idEntidad] then 
		return
	end
	
    -- Eliminar de la etiqueta la categoría del premio
        
    if etiqueta then
      	etiqueta = etiqueta:match('^(.*)%s+a%s.*$')  or  -- Ejemplo: Premio Nébula a la mejor novela corta  --> Premio Nébula
    	           etiqueta:match('^(.*)%s+al%s.*$') or  -- Ejemplo: Premio Hugo al mejor relato --> Premio Hugo
    	           etiqueta:match('^(.*) en la categoría') or  -- Ejemplo: Premio Prometheus en la categoría Hall of Fame --> Premio Prometheus
       	           etiqueta
    end

    return p.enlazar(enlace, etiqueta, idEntidad)
end

function p.formatoGentilicio(valor, opciones, frame)
	local enlacePais, etiquetaPais, idEntidadPais = p.obtenerDatos(valor)
	
	local gentilicio 
	
	if etiquetaPais then 
		gentilicio = frame:preprocess('{{gentilicio|'.. etiquetaPais .. '|fs}}')
		
		if not gentilicio or gentilicio == '' then
			gentilicio = etiquetaPais
		end
	end
	
	return p.enlazar(enlacePais, gentilicio, idEntidadPais, opciones)
end

function p.formatoLugar(valor, opciones, frame, calificativos)
	-- Función que devuelve algo de la forma Lugar, entidad territorial administrativa, país
	
	local lugarEnlazado, entidadTerritorialAdministrativaEnlazada, paisEnlazado
	
	-- Validar que está informado el id del lugar.
	if not valor or not valor['numeric-id'] then 
		return
	end	
	
	-- Obtener primero la entidad territorial administrativa y el país de los calificativos si es posible
	-- No se obtiene primero el lugar, que sería lo más lógico, porque se obtendrá de forma diferente según
	-- estén o no informados los calificativos
	
	if calificativos then
		entidadTerritorialAdministrativaEnlazada = p.enlazar(p.obtenerDatos(elementoTabla(calificativos,'P131',1,'datavalue','value')))
		paisEnlazado                             = p.enlazar(p.obtenerDatos(elementoTabla(calificativos,'P17',1,'datavalue','value')))
	end

	if paisEnlazado then
		lugarEnlazado = p.enlazar(p.obtenerDatos(valor))
	else
	 -- Si el lugar no tiene el calificativo de país obtenerlo de la propiedad país de la 
	 -- entidad de Wikidata del lugar.
	 
	 -- De momento no se obtiene la entidad administrativa (tiene unas barbaridades...)
		local idLugar, enlaceLugar, etiquetaLugar
		local entidad
		
		idLugar = 'Q' .. valor['numeric-id']
		entidad = mw.wikibase.getEntityObject(idLugar)
		
		if not entidad then
			return
		end
		
		enlaceLugar   = elementoTabla(entidad,'sitelinks','eswiki','title')
		etiquetaLugar = elementoTabla(entidad,'labels','es','value')
		lugarEnlazado = p.enlazar(enlaceLugar, etiquetaLugar, idLugar, opciones)
		paisEnlazado  = p.enlazar(p.obtenerDatos(elementoTabla(entidad,'claims','P17',1,'mainsnak','datavalue','value')))
	end
	
	if lugarEnlazado == paisEnlazado then -- La ciudad de El Vaticano tiene en Wikidata como país a sí misma
		paisEnlazado = nil
	end
	
    return require('Módulo:Formato texto').separadosPorComa({lugarEnlazado, entidadTerritorialAdministrativaEnlazada, paisEnlazado})
end

function p.formatoUnidad(valor, opciones)
	cantidad = mw.ustring.gsub(valor.value['amount'], '+','')
	unidad = mw.wikibase.label(mw.ustring.gsub(valor.value['unit'], '^.-/(Q%d+)$', '%1'))
	if unidad and tonumber(cantidad) > 1 then	
		textoUnidad = unidad..'s'
	end
	
	if not unidad or (opciones['formatoUnidad'] and opciones['formatoUnidad'] == 'número') then
		return tonumber(cantidad)
	elseif unidad and opciones['formatoUnidad'] and opciones['formatoUnidad'] == 'minutos' and unidad == 'segundo' then
		return math.floor(tonumber(cantidad)/60) .. ':' .. (tonumber(cantidad)%60) .. ' ' .. 'minutos'
	else
		return cantidad .. ((textoUnidad and ' ' .. textoUnidad) or '')
	end
end

-- Formatos de calificativos

function p.formatoPeriodo(valor, opciones)
	local anyoInicio, anyoFin
	local fechaInicio, fechaFin
	local opcionesFecha= {['formatoTexto']='mayúscula', ['formatoFecha'] = 'año', ['enlace']='no'}

    local fechasInicio = valor['P580']
    local fechasFin    = valor['P582']
    local iFechaInicio = 1
    local iFechaFin    = 1
    
    if not fechasInicio and not fechasFin then
    	return
    end
    
    local periodos    = {}

	if fechasInicio and fechasInicio[1] then
		--if true then return require('Módulo:Tablas').tostring(fechasInicio[1]) end
	    anyoInicio = require('Módulo:Wikidata').formatoDato(fechasInicio[1],opcionesFecha , {})
	    fechaInicio= anyoInicio -- de momento
	end
	
	if fechasFin and fechasFin[1] then
	    anyoFin  = require('Módulo:Wikidata').formatoDato(fechasFin[1], opcionesFecha, {})
	    fechaFin = anyoFin -- de momento
	end
	
    while fechaInicio or fechaFin do -- Por cada periodo
    	if fechaInicio and fechaFin and tonumber(fechaInicio) and tonumber(fechaFin) and (tonumber(fechaInicio) <= tonumber(fechaFin)) then
    		if anyoInicio == anyoFin then
    			table.insert(periodos, anyoInicio)
    		else
    			table.insert(periodos, anyoInicio .. '–' .. anyoFin)
    		end
		    iFechaInicio = iFechaInicio + 1
		    iFechaFin    = iFechaFin    + 1
		    
		    if fechasInicio[iFechaInicio] then
		    	anyoInicio = require('Módulo:Wikidata').formatoDato(fechasInicio[iFechaInicio],opcionesFecha , {})
		    	fechaInicio= anyoInicio -- de momento
		    else
		    	anyoInicio	= nil
		    	fechaInicio= nil
		    end
		    
		    if fechasFin[iFechaFin] then
		    	anyoFin = require('Módulo:Wikidata').formatoDato(fechasFin[iFechaFin],opcionesFecha , {})
		    	fechaFin= anyoFin -- de momento
		    else
		    	anyoFin	= nil
		    	fechaFin= nil
		    end		    
		elseif anyoInicio then
			table.insert(periodos, 'desde ' .. anyoInicio)
			
			iFechaInicio = iFechaInicio + 1
		    if fechasInicio[iFechaInicio] then
		    	anyoInicio = require('Módulo:Wikidata').formatoDato(fechasInicio[iFechaInicio],opcionesFecha , {})
		    	fechaInicio= anyoInicio -- de momento
		    else
		    	anyoInicio	= nil
		    	fechaInicio= nil
		    end			
		elseif anyoFin then
			table.insert(periodos, 'hasta ' .. anyoFin)
		    iFechaFin    = iFechaFin    + 1			
			
		    if fechasFin[iFechaFin] then
		    	anyoFin = require('Módulo:Wikidata').formatoDato(fechasFin[iFechaFin],opcionesFecha , {})
		    	fechaFin= anyoFin -- de momento
		    else
		    	anyoFin	= nil
		    	fechaFin= nil
		    end				
		end
    end
	
	return table.concat(periodos, ', ')
end

-- Funciones internas

-- Las siguientes funciones hacen prácticamente lo mismo que la función
-- formatoIdEntidad del módulo Wikidata.
-- p.obtenerDatos obtiene los datos de la entidad y p.enlazar los formatea.

function p.obtenerDatos(valor)
	if valor and valor['numeric-id'] then
	    local idEntidad = 'Q' .. valor['numeric-id']

        local etiqueta  = mw.wikibase.label( idEntidad )
        local enlace    = mw.wikibase.sitelink( idEntidad )	
        
        return enlace, etiqueta, idEntidad 
    end
end

function p.enlazarEnOtroIdioma(enlace, etiqueta, idioma)
	local categoria = '[[Categoría:Wikipedia:Páginas con propiedades de Wikidata con etiqueta en otro idioma]]'
	
	if enlace and etiqueta then
		return etiqueta .. ' <small>([[:en:' .. enlace .. '|en]])</small>' .. categoria
	elseif etiqueta then
		return etiqueta .. ' <small>(en)</small>' .. categoria
	elseif enlace then
		return enlace .. ' <small>([[:en:' .. enlace .. '|en]])</small>' .. categoria
	end
end

local yaEnlazado = {}

function p.enlazar(enlace, etiqueta, idEntidad, opciones)
	if not enlace and not etiqueta and not idEntidad then
		return
	end
	
	if opciones then
		-- Opciones de las etiquetas
		
		if opciones.etiqueta and opciones.etiqueta ~= 'null' then		-- Por averiguar dónde se usa.
			etiqueta = opciones.etiqueta
		end
		
		--  Convertir el primer carácter a mayúscula en su caso    
		if etiqueta and opciones['mayúscula'] == 'sí' then
			etiqueta = es:ucfirst(etiqueta)
		end
		
		-- Opciones del enlace
		if opciones['enlace'] ==  'no'  then
			-- No p.enlazar
			enlace = nil
		elseif opciones['debeExistir'] == 'sí' then
			-- No devolver nada si no está informado el artículo de Wikipedia
			if not enlace then
				return
			end
		elseif opciones['enlace'] ==  'sí' then
			if not enlace and etiqueta and not require('Módulo:Páginas').existe(etiqueta) then
				-- Tomar como enlace la etiqueta si no existe el correspondiente artículo
				enlace   = etiqueta
			end			
		end
	end
	
	-- No enlazar varias veces lo mismo
	if enlace and yaEnlazado[enlace] then
		enlace = nil
	end
	
	-- Según esté informada la etiqueta o el enlace
	local resultado
	
    if etiqueta and enlace and etiqueta ~= enlace then --Ambos si no son iguales
       resultado = '[[' .. enlace .. '|' .. etiqueta .. ']]'
       yaEnlazado[enlace] = true
    elseif enlace then    -- Solo el enlace o ambps y son iguales
        resultado = '[[' .. enlace .. ']]'
        yaEnlazado[enlace] = true
    elseif etiqueta then  -- Solo la etiqueta
        resultado = etiqueta
    elseif idEntidad then -- Solo la entidad
       -- Obtener la etiqueta y el enlace de Wikidata de la Wikipedia inglesa.
       local entidad=mw.wikibase.getEntityObject(idEntidad)
       
       --if true then return require('Módulo:Tablas').tostring(entidad) end
       
       if entidad then
       	  if entidad.labels and
       	     entidad.labels.en then
       	     etiqueta = entidad.labels.en.value
       	  end
       	  
       	  if entidad.sitelinks and entidad.sitelinks.enwiki then
       	     enlace   = entidad.sitelinks.enwiki.title
       	  end
       	  
       	  if etiqueta or enlace then
       	     resultado = p.enlazarEnOtroIdioma(enlace, etiqueta, 'en')
       	  end
       end
       
        if not resultado then
        	return '[[:d:'.. idEntidad .. '|sin etiquetar]]' .. 
              '[[Categoría:Wikipedia:Páginas con propiedades de Wikidata sin etiqueta]]'
        end
    end
    
    -- Añadir cursivas
    
    if opciones and opciones.cursivas == 'sí' then
    	resultado = "''" .. resultado .. "''"
    end
    
    return resultado
end

function p.formatId( value, options )
	local wikidata = require('Módulo:Wikidata')
    local id =  'Q'.. value['numeric-id']
    local opciones = {separador = '<br>',propiedad = options.propiedadValor, uno = 'sí', entityId = id, formatoTexto = 'mayúscula'}
    return wikidata.getPropiedad(opciones)
end

function p.formatBandera2( value, options )
	local bandera = require('Módulo:Bandera')
	local id =  'Q'.. value['numeric-id']
	local label = mw.wikibase.label( 'Q' .. value['numeric-id'] ) or ''
	local tipo = mw.ustring.gsub(label,'(%D+)%sde%s%D+','%1')
	
	 if options.cortar and options.cortar ~= '' then
        coincidencia = mw.ustring.find( es:lc(options.cortar), es:lc(tipo), plain )
    end
    if coincidencia then
    	nombre = mw.ustring.gsub(label,'%D+%sde%s(%D+)','%1')
    elseif label and label ~= '' then
    	nombre = label
    end
    return bandera.banderaLua(id, '20px', '', nombre)
end
function p.formatFicha( value, options )
	local ficha = require('Módulo:Ficha')
	local opciones = {propiedadValor='P31'} 
	local etiqueta  = p.formatId( value, opciones)
	options.cortar = etiqueta
	local parametros = {
		child = 'si',
		estiloetiqueta1 = 'border:0;font-weight:100;padding:0px 7px',
		estilodatos1 = 'border:0;font-weight:100;padding:0px 7px 0px 2px', 
		etiqueta1='&bull;&nbsp;'.. es:ucfirst(etiqueta),
		datos1 = p.formatBandera2(value, options)}
    return ficha.infobox(parametros)
end

function p.formatoId ( value, options )
	return value['numeric-id'] and 'Q' .. value['numeric-id']
end

return p