Módulu:Wikidata/Formatos

De Wikipedia

La documentación pa esti módulu pue crease en Módulu:Wikidata/Formatos/usu

local p = {}
local ast = mw.language.new('ast')
local moduloTablas  = require('Módulu:Tables') 
	local elementoTabla   = moduloTablas.elemento
	local enTabla         = moduloTablas.en
	local insertarEnTabla = moduloTablas.insertar
local moduloWikidata = require('Módulu:Wikidata')
	local getPropiedadWikidata = moduloWikidata.getPropiedad
	local formatoDatoWikidata  = moduloWikidata.formatoDato
local enlazarURL    = require('Módulu:URL').enlazar

function p.formatoImagen( valor, opciones, frame, calificativos )
	--if true then return require('Módulu:Tables').tostring(calificativos) end
	--if true then return require('Módulu:Tables').tostring(opciones) end
	
	local formato, alineacion, tamanno, descripcion, alternativo, enlace
	
	-- Los nombres de los parámetros son los mismos que en Ayuda:Imágenes añadiendo "imagen"
	if opciones then
		formato     = opciones['formatu imaxe']
		alineacion  = opciones['alliniación imaxe']
		tamanno     = opciones['tamañu imaxe']
		descripcion = opciones['descripción imaxe']
		alternativo = opciones['testu alternativu imaxe']
		enlace      = opciones['enllaz imaxe']
	end
	
    if calificativos and not descripcion then
    	local piesDeImagen = calificativos.P2096
    	local k,pieDeImagen
    		
    	-- Encontrar el pie n'asturianu (aquel con datavalue.value.language = "ast")
    	if piesDeImagen then
    		for k,pieDeImagen in pairs(piesDeImagen) do
    			if pieDeImagen.datavalue.value.language=='ast' then
					descripcion = pieDeImagen.datavalue.value.text
				end
			end
		end
	end

	local resultado = '[[Archivu:' .. valor
	
	if formato and formato ~='' then
		resultado = resultado .. '|' .. formato
	end
	
	if alineacion and alineacion ~='' then
		resultado = resultado .. '|' .. alineacion
	end	
	
	if tamanno and tamanno ~='' then
		resultado = resultado .. '|' .. tamanno
	end
	
	if alternativo and alternativo ~='' then
		resultado = resultado .. '|alt=' .. alternativo
	end

	if enlace and enlace ~='' then
		resultado = resultado .. '|link=' .. enlace
	end
	
	if not descripcion or descripcion =='' then
		return resultado .. ']]'
	elseif formato == 'thumb' then
		return resultado .. '|' .. descripcion .. ']]'
	else
		return resultado .. ']]' .. '<br /><span>' .. descripcion .. '</span>'
	end			
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( ast:lc(options.cortar), ast: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('Plantía:Xeodatos '.. label ).exists  then
        str2 = frame:preprocess('{{bandera2|' .. label ..'|nome ='.. 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 pa entidaes 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('{{xentiliciu|'.. 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 idLugar, enlaceLugar, etiquetaLugar, lugarEnlazado
	local entidadTerritorialAdministrativaEnlazada	
	local idPais, enlacePais, etiquetaPais, 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')))
		enlacePais, etiquetaPais, idPais         = p.obtenerDatos(elementoTabla(calificativos,'P17',1,'datavalue','value'))
		paisEnlazado                             = p.enlazar(enlacePais, etiquetaPais, idPais)
	end

	if paisEnlazado then
		enlaceLugar, etiquetaLugar, idLugar = p.obtenerDatos(valor)
		lugarEnlazado = p.enlazar(enlaceLugar, etiquetaLugar, idLugar)
	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 entidad
		
		idLugar = 'Q' .. valor['numeric-id']
		entidad = mw.wikibase.getEntityObject(idLugar)
		
		if not entidad then
			return
		end
		
		enlaceLugar   = elementoTabla(entidad,'sitelinks','astwiki','title')
		etiquetaLugar = elementoTabla(entidad,'labels','ast','value')
		lugarEnlazado = p.enlazar(enlaceLugar, etiquetaLugar, idLugar, opciones)
		enlacePais, etiquetaPais, idPais = p.obtenerDatos(elementoTabla(entidad,'claims','P17',1,'mainsnak','datavalue','value'))
		paisEnlazado  = p.enlazar(enlacePais, etiquetaPais, idPais)
	end
	
	
	if idLugar == idPais then -- Si el lugar es un país, por ejemplo, Estaos Xuníos, en Wikidata tiene la propiedad país informada con Estaos Xuníos.
		return lugarEnlazado
	else
		return require('Módulu:Formatu testu').separadosPorComa({lugarEnlazado, entidadTerritorialAdministrativaEnlazada, paisEnlazado})
	end
	
    
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 and unidad:match("^.*[aeiou]$") then	
		textoUnidad = unidad..'s'
	elseif unidad and tonumber(cantidad) > 1 then
		textoUnidad = unidad..'ast'
	end
	
	if not unidad or (opciones['formatoUnidad'] and opciones['formatoUnidad'] == 'númberu') then
		return tonumber(cantidad)
	elseif unidad and opciones['formatoUnidad'] and opciones['formatoUnidad'] == 'minutos' and unidad == 'segundu' then
		local segundos = tostring(tonumber(cantidad)%60)
		if mw.ustring.len(segundos) == 1 then segundos = '0' .. segundos end
		return math.floor(tonumber(cantidad)/60) .. ':' .. segundos .. ' ' .. 'minutos'
	else
		return p.formatoNumero(cantidad) .. ((textoUnidad and ' ' .. textoUnidad) or '')
	end
end

function p.formatoNumero(valor, opciones)
	
	if not tonumber(valor) then return valor end
	
	local formato = valor
	while true do  
		formato, k = string.gsub(formato, "^(-?%d+)(%d%d%d)", '%1&nbsp;%2')
		if (k==0) then
			break
		end
	end
	return formato
end

function p.formatoCargo(valor, opciones, frame, calificativos)
	local enlaceCargo, etiquetaCargo, idEntidadCargo = p.obtenerDatos(valor)
	local cargoEnlazado = p.enlazar(enlaceCargo, etiquetaCargo, idEntidadCargo, opciones)
	
	if not cargoEnlazado then 
		return
	end
	
	-- De
	local enlaceDe, etiquetaDe, idEntidadDe = p.obtenerDatos(elementoTabla(calificativos,'P642',1,'datavalue','value'))
	local deEnlazado = p.enlazar(enlaceDe, etiquetaDe, idEntidadDe, opciones)
	
	if deEnlazado then 
		cargoEnlazado = cargoEnlazado .. ' de ' .. deEnlazado
	end
	
	-- Distrito electoral
	local enlaceDistritoElectoral, etiquetaDistritoElectoral, idEntidadDistritoElectoral = p.obtenerDatos(elementoTabla(calificativos,'P768',1,'datavalue','value'))
	local DistritoElectoralEnlazado = p.enlazar(enlaceDistritoElectoral, etiquetaDistritoElectoral, idEntidadDistritoElectoral, opciones)
	
	if DistritoElectoralEnlazado then 
		cargoEnlazado = cargoEnlazado .. ' por ' .. DistritoElectoralEnlazado
	end
	
	-- Empleador
	local enlaceEmpleador, etiquetaEmpleador, idEntidadEmpleador = p.obtenerDatos(elementoTabla(calificativos,'P108',1,'datavalue','value'))
	local EmpleadorEnlazado = p.enlazar(enlaceEmpleador, etiquetaEmpleador, idEntidadEmpleador, opciones)
	
	if EmpleadorEnlazado then 
		cargoEnlazado = cargoEnlazado .. ' de ' .. EmpleadorEnlazado
	end
	
	local periodo = p.formatoPeriodo(calificativos, {})
	
	if periodo then
		return cargoEnlazado .. '&nbsp;<small>(' .. periodo .. ')</small>'
	else
		return cargoEnlazado
	end
end

-- Formatos de calificativos

function p.formatoPeriodo(valor, opciones)
	if not valor then
		return
	end
	
	local anyoInicio, anyoFin
	local fechaInicio, fechaFin
	local opcionesFecha= {['formatoTexto']='mayúscula', ['formatoFecha'] = 'añu', ['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ódulu:Tables').tostring(fechasInicio[1]) end
	    anyoInicio = formatoDatoWikidata(fechasInicio[1],opcionesFecha , {})
	    fechaInicio= anyoInicio -- de momento
	end
	
	if fechasFin and fechasFin[1] then
	    anyoFin  = formatoDatoWikidata(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 = formatoDatoWikidata(fechasInicio[iFechaInicio],opcionesFecha , {})
		    	fechaInicio= anyoInicio -- de momento
		    else
		    	anyoInicio	= nil
		    	fechaInicio= nil
		    end
		    
		    if fechasFin[iFechaFin] then
		    	anyoFin = formatoDatoWikidata(fechasFin[iFechaFin],opcionesFecha , {})
		    	fechaFin= anyoFin -- de momento
		    else
		    	anyoFin	= nil
		    	fechaFin= nil
		    end		    
		elseif anyoInicio then
			table.insert(periodos, 'dende ' .. anyoInicio)
			
			iFechaInicio = iFechaInicio + 1
		    if fechasInicio[iFechaInicio] then
		    	anyoInicio = formatoDatoWikidata(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 = formatoDatoWikidata(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áxines con propiedaes de Wikidata cola etiqueta n\'otru idioma]]'
	
	if enlace and etiqueta then
		return etiqueta .. ' <small>([[:' .. idioma .. ':' .. enlace .. '|' .. idioma .. ']])</small>' .. categoria
	elseif etiqueta then
		return etiqueta .. ' <small>(' .. idioma .. ')</small>' .. categoria
	elseif enlace then
		return enlace .. ' <small>([[:' .. idioma .. ':' .. enlace .. '|' .. idioma .. ']])</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 = ast: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ódulu:Páxines').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, francesa o española
       local entidad=mw.wikibase.getEntityObject(idEntidad)
       
       --if true then return require('Módulu:Tables').tostring(entidad) end

       if entidad then
       		local idioma
       		for k, idioma in pairs({'en', 'fr', 'it', 'es'}) do
       	  		etiqueta = elementoTabla(entidad, 'labels', idioma, 'value')
       	  		enlace   = elementoTabla(entidad, 'sitelinks', idioma .. 'wiki', 'title')
       	  		if etiqueta or enlace then
       	     		resultado = p.enlazarEnOtroIdioma(enlace, etiqueta, idioma)
       	     		break
       	  		end
       		end
       	end
       
        if not resultado then
        	return '[[:d:'.. idEntidad .. '|sin etiquetar]]' .. 
              '[[Categoría:Wikipedia:Páxines con propiedaes 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ódulu: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ódulu: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( ast:lc(options.cortar), ast: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ódulu: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;'.. ast: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

--*****************************************************************************
-- Funciones para un elemento/entidad de Wikidata
--*****************************************************************************
function p.formatoObraAutor(valor, opciones, frame, calificativos)
	local idObra       = 'Q' .. valor['numeric-id']
	local entidadObra  = mw.wikibase.getEntityObject(idObra)
	local enlaceObra   = elementoTabla(entidadObra,'sitelinks','astwiki','title')
	local etiquetaObra = elementoTabla(entidadObra,'labels','ast','value')
	local tituloObraEnlazado = p.enlazar(enlaceObra, etiquetaObra, idObra, opciones)
	
	local declaracionAutores = elementoTabla(entidadObra, 'claims', 'P50')
	
	if declaracionAutores then
	   local autores = getPropiedadWikidata({['propiedad']='P50'}, entidadObra.claims['P50'])
	   
	   if autores then 
	   	   return "''" .. tituloObraEnlazado .. "'' de " .. autores
	   end
	end
	
	return "''" .. tituloObraEnlazado .. "''"
end

function p.formatoObraAnyo(valor, opciones, frame, calificativos)
	local idObra       = 'Q' .. valor['numeric-id']
	local entidadObra  = mw.wikibase.getEntityObject(idObra)
	local enlaceObra   = elementoTabla(entidadObra,'sitelinks','astwiki','title')
	local etiquetaObra = elementoTabla(entidadObra,'labels','ast','value')
	local tituloObraEnlazado = p.enlazar(enlaceObra, etiquetaObra, idObra, opciones)
	
	local declaracionFechaPublicacion = elementoTabla(entidadObra, 'claims', 'P577')
	
	if declaracionFechaPublicacion then
	   local anyoPublicacion = getPropiedadWikidata({['propiedad']='P577', ['formatuFecha']='añu', ['rangoMayor']='sí', ['enlace']='no'}, declaracionFechaPublicacion)
	   
	   if anyoPublicacion then 
	   	   return "''" .. tituloObraEnlazado .. "'' (" .. anyoPublicacion .. ")"
	   end
	end
	
	return "''" .. tituloObraEnlazado .. "''"
end

function p.formatoObraTituloOriginalAnyo(valor, opciones, frame, calificativos)
	local idObra       = 'Q' .. valor['numeric-id']
	local entidadObra  = mw.wikibase.getEntityObject(idObra)
	local enlaceObra   = elementoTabla(entidadObra,'sitelinks','astwiki','title')
	local etiquetaObra = elementoTabla(entidadObra,'labels','ast','value')
	local tituloObraEnlazado = p.enlazar(enlaceObra, etiquetaObra, idObra, opciones)
	
	local tituloOriginal = elementoTabla(entidadObra, 'claims', 'P1476',1,'mainsnak','datavalue','value','text')
	
	local declaracionFechaPublicacion = elementoTabla(entidadObra, 'claims', 'P577')
	local anyoPublicacion
	
	if declaracionFechaPublicacion then
	   anyoPublicacion = getPropiedadWikidata({['propiedad']='P577', ['formatuFecha']='añu', ['enlace']='no'}, declaracionFechaPublicacion)
	end
	
	if tituloOriginal and anyoPublicacion then
		return "''" .. tituloObraEnlazado .. "'' (''" .. tituloOriginal .. "'', " .. anyoPublicacion .. ")"
	elseif tituloOriginal then
		return "''" .. tituloObraEnlazado .. "'' (''" .. tituloOriginal .. "'')"
	elseif anyoPublicacion then
		return "''" .. tituloObraEnlazado .. "'' (" .. anyoPublicacion .. ")"
	else
		return "''" .. tituloObraEnlazado .. "''"
	end
end

local decadaAnterior

function p.formatoPersonaPremiadaPor(valor, opciones, frame, calificativos)
	local enlacePersona, etiquetaPersona, idEntidadPersona = p.obtenerDatos(valor)
	local personaEnlazada =  p.enlazar(enlacePersona, etiquetaPersona, idEntidadPersona, {['enlace'] =  'sí'})
	local fecha, decada, decadaFormateada
	local enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1, obraPremiadaEnlazada1
	local enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2, obraPremiadaEnlazada2
	local obraPremiadaEnlazada
	local opcionesFecha= {['formatoTexto']='mayúscula', ['formatuFecha'] = 'añu', ['enlace']='no'}
	
	if calificativos then
		fecha = formatoDatoWikidata(elementoTabla(calificativos,'P585',1), opcionesFecha , {}) -- Primera fecha
		
		enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1 = p.obtenerDatos(elementoTabla(calificativos,'P1686',1,'datavalue','value'))-- Premiado por
		enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2 = p.obtenerDatos(elementoTabla(calificativos,'P1686',2,'datavalue','value'))-- Premiado por		
		obraPremiadaEnlazada1 = p.enlazar(enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1, {['enlace'] =  'sí'})
		obraPremiadaEnlazada2 = p.enlazar(enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2, {['enlace'] =  'sí'})		
		
		obraPremiadaEnlazada  = (obraPremiadaEnlazada1 and obraPremiadaEnlazada2 and (obraPremiadaEnlazada1 .. ' / ' .. obraPremiadaEnlazada2)) or
			obraPremiadaEnlazada1	or
			obraPremiadaEnlazada2
	end
	
	decadaFormateada = ''
	
	if fecha then
		decada = tostring(fecha):sub(1,3)
		
		if decada ~= decadaAnterior then
			decadaAnterior = decada
			decadaFormateada = "</ul>'''" .. fecha .. "-" .. decada .. "9'''\n<ul><li>"
		end
	end

	return decadaFormateada .. 
		(obraPremiadaEnlazada and ("''" .. obraPremiadaEnlazada .. "''") or '') .. 
		(obraPremiadaEnlazada and personaEnlazada and ' de ' or '') .. 
		personaEnlazada .. 
		(fecha and ' (' .. fecha .. ')' or '')
			
end

function p.formatoPersonaPremiadaPor2(valor, opciones, frame, calificativos)
	local enlacePersona, etiquetaPersona, idEntidadPersona = p.obtenerDatos(valor)
	local personaEnlazada =  p.enlazar(enlacePersona, etiquetaPersona, idEntidadPersona, {['enlace'] =  'sí'})
	local fecha, decada, decadaFormateada
	local enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1, obraPremiadaEnlazada1
	local enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2, obraPremiadaEnlazada2
	local obraPremiadaEnlazada
	local opcionesFecha= {['formatoTexto']='mayúscula', ['formatuFecha'] = 'añu', ['enlace']='no'}
	
	if calificativos then
		fecha = formatoDatoWikidata(elementoTabla(calificativos,'P585',1), opcionesFecha , {}) -- Primera fecha
		
		enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1 = p.obtenerDatos(elementoTabla(calificativos,'P1686',1,'datavalue','value'))-- Premiado por
		enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2 = p.obtenerDatos(elementoTabla(calificativos,'P1686',2,'datavalue','value'))-- Premiado por		
		obraPremiadaEnlazada1 = p.enlazar(enlaceObraPremiada1, etiquetaObraPremiada1, idEntidadObraPremiada1, {['enlace'] =  'sí'})
		obraPremiadaEnlazada2 = p.enlazar(enlaceObraPremiada2, etiquetaObraPremiada2, idEntidadObraPremiada2, {['enlace'] =  'sí'})		
		
		obraPremiadaEnlazada  = (obraPremiadaEnlazada1 and obraPremiadaEnlazada2 and (obraPremiadaEnlazada1 .. ' / ' .. obraPremiadaEnlazada2)) or
			obraPremiadaEnlazada1	or
			obraPremiadaEnlazada2
	end	
	return '<td>' .. fecha .. 
		'</td><td>' .. (obraPremiadaEnlazada and ("''" .. obraPremiadaEnlazada .. "''") or '') .. 
		'</td><td>' .. (personaEnlazada or '') .. '</td>'
end

--*****************************************************************************
-- Funciones para los tipos de dato URL
--*****************************************************************************

function p.formatoURL(valor, opciones, marco)
	return enlazarURL(valor)
end

function p.formatoTwitter(valor, opciones, marco)
	return '[https://twitter.com/' .. valor .. ' ' .. valor .. ']'
end

function p.formatoFacebook(valor, opciones, marco)
	return '[https://www.facebook.com/' .. valor .. ' ' .. valor .. ']'
end

--*****************************************************************************
-- Funciones para cantidades
--*****************************************************************************

function p.formatoPeriodicidad(valor, opciones, marco)
	local resultado
  	--if true then return require('Módulu:Tables').tostring(valor) end
  	
  	local function sinSigno(valor)
  		if valor and valor:sub(1,1) == '+' then
  			return valor:sub(2,valor:len())
  		else
  			return valor
  		end
  	end
  
	if valor.unit == 'http://www.wikidata.org/entity/Q5151' then
  		if valor.amount == '+1' then 
  			resultado = 'mensual'
  		elseif valor.amount == '+2' then 
  			resultado = 'bimestral'
  		elseif valor.amount == '+3' then 
  			resultado = 'trimestral'
  		elseif valor.amount == '+4' then 
  			resultado = 'cuatrimestral'
  		elseif valor.amount == '+6' then 
  			resultado = 'semestral'
  		else
  			resultado = 'cada ' .. sinSigno(valor.amount) .. ' meses'
  		end
  	elseif valor.unit == 'http://www.wikidata.org/entity/Q23387' then
  		if valor.amount == '+1' then 
  			resultado = 'selmanal'
  		elseif valor.amount == '+2' then 
  			resultado = 'quincenal'
  		else
  			resultado = 'cada ' .. sinSigno(valor.amount) .. ' selmanes'
  		end
	elseif valor.unit == 'http://www.wikidata.org/entity/Q577' then
		if valor.amount == '+1' then 
  			resultado = 'añal'		
  		else
  			resultado = 'cada ' .. sinSigno(valor.amount) .. ' años'
  		end  			
	elseif valor.unit == 'http://www.wikidata.org/entity/Q573' then
		if valor.amount == '+1' then 
  			resultado = 'caldía'		
  		else
  			resultado = 'cada ' .. sinSigno(valor.amount) .. ' díes'
  		end  					
	else 
		if valor.amount == '+1' then 
			resultado = 'cada ' .. valor.unit
		else
			resultado = 'cada ' .. sinSigno(valor.amount) .. ' ' .. valor.unit
		end
	end

	if resultado and opciones and opciones['mayúscula'] == 'sí' then
		return ast:ucfirst(resultado)
	else
		return resultado
	end
end

function p.formatoArea(valor, opciones, marco, calificativos)
	local function formatearArea(numero, unidad, opciones)
		--if true then return require('Módulu:Tables').tostring(opciones) end
		local plural = {['acre'] = 'acres'}
		local enlace ={['acre'] = 'acre (unidá de superficie)', ['km²'] = 'quilómetru cuadráu', ['ha'] = 'hectárea', ['m²'] = 'metru cuadráu', ['mi²'] = 'milla cuadrada'}
		
		-- Redondear a dos decimales, formatear y añadir la unidad enlazada en su caso
		if numero == 1 then
			return ast:formatNum(math.floor(numero * 100 + 0.5) / 100) .. '&nbsp;' .. p.enlazar(enlace[unidad] or unidad, unidad, nil, opciones)
		else
			return ast:formatNum(math.floor(numero * 100 + 0.5) / 100) .. '&nbsp;' .. p.enlazar(enlace[unidad] or unidad, plural[unidad] or unidad, nil, opciones)
		end
	end
	local cantidad,  idUnidad
	
	if not valor or not valor.amount then
		return
	end
	
	idUnidad   = valor.unit:gsub('^.-/(Q%d+)$', '%1')
	cantidad = tonumber(valor.amount:gsub('+','') or '')
	
	if not cantidad then
		return
	end
	
	if idUnidad == 'Q712226' then -- quilómetru cuadráu
		return formatearArea(cantidad, 'km²', opciones)
	elseif idUnidad == 'Q35852' then -- hectárea
		if cantidad >= 100 then
			return formatearArea(cantidad / 100, 'km²', opciones)
		else
			return formatearArea(cantidad, 'ha', opciones)
		end
	elseif idUnidad == 'Q25343' then -- metru cuadráu
		if cantidad >= 10000 then
			return formatearArea(cantidad / 10000, 'km²', opciones)
		elseif cantidad >= 100 then
			return formatearArea(cantidad / 100, 'ha', opciones)
		else
			return formatearArea(cantidad, 'm²', opciones)
		end
	elseif idUnidad == 'Q81292' then -- acre
		return formatearArea(cantidad, 'acre', opciones) .. ' (' .. formatearArea(cantidad * 0.0040468564224, 'km²', opciones) .. ')'
	elseif idUnidad == 'Q232291' then -- milla cuadrada
		return formatearArea(cantidad, 'mi²', opciones) .. ' (' .. formatearArea(cantidad * 2.589988110336 , 'km²', opciones) .. ')'
	else
		return formatearArea(cantidad, mw.wikibase.label(idUnidad), opciones)
	end
	
  	--if true then return require('Módulu:Tables').tostring(valor) end
end

--*****************************************************************************
-- Alias de formatos para utilizar en la plantilla propiedad
--*****************************************************************************
p['área']        = p['formatoArea']
p['bandera']     = p['formatBandera']
p['cargo']       = p['formatoCargo']
p['gentilicio']  = p['formatoGentilicio']
p['formatImage'] = p['formatoImagen']
p['imagen']      = p['formatoImagen']
p['lugar']       = p['formatoLugar']
p['periodicidad'] = p['formatoPeriodicidad']
p['personaPremiadaPor'] = p['formatoPersonaPremiadaPor']
p['premio']      = p['formatoPremio']

p['facebook']  = p['formatoFacebook']
p['twitter']   = p['formatoTwitter']
p['url']       = p['formatoURL']
	
return p