Módulo:Encabezado
Esta documentación está transcluida desde Módulo:Encabezado/doc.
Los editores pueden experimentar en la zona de pruebas de este módulo.
Por favor, añade las categorías e interwikis a la subpágina de documentación. Subpáginas de este módulo.
Los editores pueden experimentar en la zona de pruebas de este módulo.
Por favor, añade las categorías e interwikis a la subpágina de documentación. Subpáginas de este módulo.
local p = {}
local Wikidata = require('Módulo:Wikidata')
local Str = require('Módulo:String')
local Entidad = mw.wikibase.getEntityObject() or '' -- Tabla con los datos en Wikidata
local lang = mw.language.new('es')
--parámetros reconocidos. 1 = vigente, 0 = obsoleto
local categorias = ''
local params = {['titulo']=1,['sub-titulo']=1, ['ano']=1,['autor']=1,['más info']=1,['anterior']=1, ['traductor'] = 1, ['ilustrador'] = 1, ["bilingüe"] =1, ['enlaces']=1,
['notas']=1, ['derechos']=1, ['noano']=1,
['subsección']=1,['sección']=1,['sección autor']=1,['próximo']=1,['última muerte']=1,['desambiguación']=1,['históricos']=1,['catálogo']=0,['wikipedia'] =1 , ['commons'] =1 , ['commonscat'] =1 , ['wikiquote'] =1 , ['wikinoticias'] =1 , ['wikcionario'] =1 , ['wikilibros'] =1 , ['wikiversidad'] =1, ['wikispecies'] =1 , ['meta'] =1 , ['wikidata'] =1}
local enlacePagina = mw.title.getCurrentTitle().text
local textoenlace=mw.uri.encode(enlacePagina,QUERY)
local altparams= {['título']='titulo', ['title']='titulo',
['subtítulo']='sub-titulo', ['subtitulo']='sub-titulo', ['sub-título']='sub-titulo', ['sub-title']='sub-titulo', ['subtitle']='sub-titulo',
['left']='anterior',
['right']='próximo', ['siguiente']='próximo',
['author']='autor',
['traducción']='traductor',
['año']='ano',
['bilingue']='bilingüe',
['noaño']='noano',
['nota']='notas',
['seccion']='sección',
['seccion autor']='sección autor', ['seccion-autor']='sección autor', ['sección-autor']='sección autor'
}
function errorMessage(text)
-- Función que entrega un mensaje de error formateado como tal
local html = mw.html.create('div')
html:addClass('error')
:wikitext(text)
categorias=categorias..'[[Categoría:Wikisource:Páginas con errores en la plantilla Encabe]]'
return tostring(html)
end
local function link(s)
if s:match("%[") then
return s
else
return '[[Autor:'..s..'|'..s..']]'
end
end
local function delink(s)
if not s:match("%[") then
return s
end
local result = s
result = mw.uri.decode(result, "PATH") -- decode percent-encoded entities. Leave underscores and plus signs.
result = mw.text.decode(result, true) -- decode HTML entities.
-- Remove the colon if the link is using the [[Help:Colon trick]].
if result:match("%[%[:") then
result = "[[" .. result:match("%[%[:(.*%]%])")
end
-- Find the display area of the wikilink
if result:match("|") then -- Find if we're dealing with a pipecd link.
result = result:match("%[%[.-%|(.+)%]%]")
-- Remove new lines from the display of multiline piped links,
-- where the pipe is before the first new line.
result = result:gsub("\n", "")
else
result = result:match("%[%[(.-)%]%]")
end
return result
end
local function crearenlace(argus, nombre, imagen, texto1, texto2)
local texto=''
local sitio =''
local sitios ={ --esta variable contiene los sitios reconocidos con posibles enlaces, y su nombre técnico
['wikipedia']= {'eswiki','w:'},
['wikiquote']={'eswikiquote','q:'},
['commonscat']={'commonswiki','commons:'},
['wikispecies']={'specieswiki','species:'},
['wikidata']={'wikidata','d:'},
['wikcionario']={'eswiktionary','wikt:'},
}
if argus[nombre] == 'none' then
return ''
end
if sitios[nombre] then
sitio = sitios[nombre]
end
if argus[nombre] and argus[nombre] ~= '' then
if imagen == '' then
texto = '[['..texto1..'|'..texto2..']]. '
else
texto = '[[File:'..imagen..'|16px]] '..'[['..texto1..'|'..texto2..']]. '
end
elseif sitio~='' and Entidad ~= '' then
if sitio[1] == 'wikidata' then
argus[nombre] = sitio[2]..mw.wikibase.getEntityIdForCurrentPage()
texto = '[[File:'..imagen..'|16px]] '..'[['..argus[nombre]..'|'..texto2..']]. '
elseif Entidad:getSitelink(sitio[1]) ~= nil and Entidad:getSitelink(sitio[1]) ~= '' then
argus[nombre] = sitio[2]..Entidad:getSitelink(sitio[1])
texto = '[[File:'..imagen..'|16px]] '..'[['..argus[nombre]..'|'..texto2..']]. '
elseif sitio[1] =='commonswiki' and propiedad('p373') ~= '' then --categoría en commons
texto = '[[File:'..imagen..'|16px]] '..'[[commons:Category:'..propiedad('p373')..'|'..texto2..']]. '
end
end
return texto
end
local function enlaceMicroformato(param, valor)
if valor~= nil and valor ~= '' then
return mw.html.create('span')
:addClass('ws-' .. param)
:wikitext(delink(valor))
else
return ''
end
end
function p.encabe( frame )
local argus = {}
local titulo = mw.title.getCurrentTitle()
local essub = titulo.isSubpage
for k,v in pairs(frame:getParent().args) do -- crea una tabla con los parámetros incluídos en la plantilla, y elimina parámetros vacíos
if v ~= '' then
argus[mw.ustring.lower(tostring(k))] = v -- todos los parámetros en minúsculas por defecto:
end
end
-- HTML
local html = mw.html.create()
-- corregir parámetros con nombres alternativos
for k,v in pairs(altparams) do
if argus[k] and not argus[v] then
argus[v] = argus[k]
elseif argus[k] and argus[v] then
html:wikitext(errorMessage('Error: los parámetros '..k..' y '..v..' son redundantes.'))
categorias=categorias..'[[Categoría:Wikisource:Páginas que usan parámetros redundantes en la plantilla Encabe]]'
end
end
--variables matemática derechos de autor
local anosmuerte
local anospub
if argus['ano'] and tonumber(argus['ano']) ~= nil then
anospub = tonumber(lang:formatDate('Y')) - tonumber(argus['ano'])
end
if argus['última muerte'] and tonumber(argus['última muerte']) ~= nil then
anosmuerte = tonumber(lang:formatDate('Y')) - tonumber(argus['última muerte'])
end
local divgrande = html:tag('div'):attr('id','headertemplate'):addClass('noprint ws-noexport') -- div principal que contiene al resto
local anterior = divgrande:tag('div'):attr('id','headerprevious')
if argus['anterior'] and argus['anterior'] ~= '' then
local anteriorspan = anterior:tag('span'):addClass('prev-span')
anteriorspan:tag('span'):addClass('prev-span-arrow'):wikitext('← ')
anteriorspan:wikitext(' '..argus['anterior'])
if argus['enlaces'] and mw.ustring.lower(argus['enlaces']) == 'no' then
anteriorspan:cssText('display:none')
end
end
local medio = divgrande:tag('div'):addClass('middle-div')
if argus['titulo'] then
medio:wikitext("'''''​"..argus['titulo'].."​'''''")
if argus['sub-titulo'] then
medio:wikitext('<br/>'..'<small>'..argus['sub-titulo']..'</small>')
end
if argus['ano'] and not argus['noano'] then
medio:wikitext(' ('..argus['ano']..')')
categorias = categorias..'[[Categoría:P'..argus['ano']..']]'
end
end
if argus['autor'] then
medio:wikitext(' de ')
local i = #mw.text.split(argus['autor'], '[/,]')
for _,v in ipairs(mw.text.split(argus['autor'], '[/,]')) do
i = i-1
medio:wikitext(link(v))
if i >0 then medio:wikitext(', ') end
end
end
medio:tag('br')
if argus['traductor'] and argus['traductor'] ~= '' then
if argus['traductor'] == 'Wikisource' then
medio:wikitext('traducción de [[Ayuda:Directrices para traducciones|Wikisource]]')
else
medio:wikitext('traducción de ')
local i = #mw.text.split(argus['traductor'], '[/,]')
for _,v in ipairs(mw.text.split(argus['traductor'], '[/,]')) do
i = i-1
medio:wikitext(link(v))
if delink(v) == 'Anónimo' then
v = 'autor anónimo'
end
categorias = categorias..'[[Categoría:Traducciones de '..delink(v)..']]'
if i >0 then medio:wikitext(', ') end
end
end
medio:tag('br')
end
if argus['ilustrador'] and argus['ilustrador'] ~= '' then
medio:wikitext('ilustración de '..link(argus['ilustrador']))
medio:tag('br')
end
if argus['más info'] then
medio:wikitext(argus['más info'])
medio:tag('br')
end
if argus['sección'] then
medio:wikitext("''"..argus['sección'].."''")
if argus['sección autor'] then
medio:wikitext(' de ')
local i = #mw.text.split(argus['sección autor'], '[/,]')
for _,v in ipairs(mw.text.split(argus['sección autor'], '[/,]')) do
i = i-1
medio:wikitext(link(v))
if i >0 then medio:wikitext(', ') end
end
end
if argus['subsección'] then
medio:tag('br')
medio:tag('span'):cssText('font-size: 83%;'):wikitext(argus['subsección'])
end
end
local proximo = divgrande:tag('div'):attr('id','headernext')
if argus['próximo'] and argus['próximo']~= '' then
local proximospan = proximo:tag('span'):addClass('next-span')
:wikitext(' '..argus['próximo'])
proximospan:tag('span'):addClass('next-span-arrow'):wikitext(' →')
if argus['enlaces'] and mw.ustring.lower(argus['enlaces']) == 'no' then
proximospan:cssText('display:none')
end
end
--enlaces pequeños en la parte inferior
inferior = medio:tag('div'):addClass('noprint plainlinks lower-div')
--matematica y manejo derechos de autor
if argus['derechos'] then
inferior:wikitext('[[File:PD-icon.svg|14px]] [[Wikisource:Duración de derechos de autor por país#'..argus['derechos']..'|'..argus['derechos']..']] ')
if argus['última muerte'] == 'seudónimo' then
numero = math.floor((anospub - 1)/10)
if numero > 10 then numero = 10 end
inferior:wikitext(', [[Wikisource:Duración de derechos de autor por país#'..tostring(numero*10)..' p.a.p.|'..tostring(numero*10)..' p.a.p. o menos]]. ')
categorias = categorias..'[[Categoría:'..tostring(numero*10)..' p.a.p.]]'
elseif argus['última muerte'] then
numero = math.floor((anosmuerte - 1)/10)
if numero > 4 then --a partir de 50 p.m.a.
if numero > 10 then numero = 10 end
inferior:wikitext(', [[Wikisource:Duración de derechos de autor por país#'..tostring(numero*10)..' p.m.a.|'..tostring(numero*10)..' p.m.a. o menos]]. ')
categorias = categorias..'[[Categoría:'..tostring(numero*10)..' p.m.a.]]'
end
end
categorias = categorias..'[[Categoría:Publicado en '..argus['derechos']..']]'
end
--enlaces parte inferior
inferior:wikitext(crearenlace(argus, 'wikidata', 'Wikidata-logo.svg', argus['wikidata'] or '','metadatos'))
inferior:wikitext(crearenlace(argus, 'desambiguación', 'Disambiguation.svg', argus['desambiguación'],'títulos similares u otras versiones'))
inferior:wikitext(crearenlace(argus, 'wikipedia','Wikipedia-logo.svg','w:'..(argus['wikipedia'] or ''),'artículo enciclopédico'))
inferior:wikitext(crearenlace(argus, 'commonscat','Commons-logo.svg','commons:Category:'..(argus['commonscat'] or ''),'categoría multimedia'))
inferior:wikitext(crearenlace(argus, 'wikiquote','Wikiquote-logo.svg','q:'..(argus['wikiquote'] or ''),'citas'))
inferior:wikitext(crearenlace(argus, 'wikilibros','Wikibooks-logo.svg','b:'..(argus['wikilibros'] or ''),'libro'))
inferior:wikitext(crearenlace(argus, 'wikiversidad','Wikiversity-logo.svg','v:'..(argus['wikiversidad'] or ''),'clase'))
inferior:wikitext(crearenlace(argus, 'wikispecies','Wikispecies-logo.svg','species:'..(argus['wikispecies'] or ''),'taxonomía'))
inferior:wikitext(crearenlace(argus, 'wikcionario','Wiktionary_small-es.svg','wikt:'..(argus['wikcionario'] or ''),'diccionario'))
if argus['bilingüe'] and argus['bilingüe'] ~= '' then
inferior:wikitext('['..titulo:fullUrl({['match']=argus['bilingüe']})..' ver texto bilingüe]')
end
--Enlaces de descarga
if not essub then
inferior:wikitext("<div style=\"font-size:80%\">Descargar como [[Archivo:EPUB silk icon.svg|12px|link=https://wsexport.toolforge.org/tool/book.php?lang=es&format=epub&page=" .. textoenlace .."|Descargar en formato ePub]] [[Archivo:Document-pdf.svg|15px|link=https://wsexport.toolforge.org/tool/book.php?lang=es&page=" .. textoenlace .. "&format=pdf-a5|Descargar en formato PDF]] [[Archivo:Mobi_icon.svg|22px|link=https://wsexport.toolforge.org/tool/book.php?lang=es&page=" .. textoenlace .. "&format=mobi|Descargar en formato mobi]]</div>")
end
if argus['notas'] and argus['notas'] ~= '' then
html:tag('div'):addClass('notes noprint ws-noexport'):wikitext("'''Nota:''' "..argus['notas']):tag('hr')
end
--categorías automáticas
if not essub then
categorias = categorias..'[[Categoría:ES-'..Str.CaracterParaOrdenar(titulo.subpageText)..']]'
else
categorias = '[[Categoría:'..titulo.rootText..']]'
end
--palabra mágica, subpáginas no deben estar conectadas normalmente a Wikidata
if essub then
html:wikitext('__EXPECTED_UNCONNECTED_PAGE__')
end
for k,v in pairs(argus) do
if params[k] or altparams[k] then
if params[k] == 0 then
categorias = categorias..'[[Categoría:Wikisource:Páginas que usan parámetros obsoletos en la plantilla Encabe]]' --añade categoría de seguimiento a parámetros obsoletos (declarados arriba)
end
else
html:wikitext(errorMessage('Error: parámetro '..k..' no reconocido'))
categorias=categorias..'[[Categoría:Wikisource:Páginas que usan parámetros no reconocidos en la plantilla Encabe]]'
end
end
if titulo.namespace ~= 0 then --solo categorías en el espacio principal
categorias = ''
end
divgrande:wikitext(categorias)
--microformato
local microformato = html:tag('div'):cssText('display:none'):attr('id', 'ws-data'):addClass('ws-noexport')
microformato:node( enlaceMicroformato( 'title', argus['titulo'] ) )
if argus.autor and argus.autor ~= '' then
microformato:node( enlaceMicroformato( 'author', argus.autor ) )
end
if argus.traductor and argus.traductor ~= '' then
microformato:node( enlaceMicroformato( 'translator', argus.traductor ) )
end
if argus.illustrador and argus.illustrador ~= '' then
microformato:node( enlaceMicroformato( 'illustrator', argus.illustrador ) )
end
--if argus.school and argus.school ~= '' then
-- microformato:node( enlaceMicroformato( 'school', argus.school ) )
--end
--if argus.editeur and argus.editeur ~= '' then
-- microformato:node( enlaceMicroformato( 'publisher', argus.editeur ) )
--end
if argus['ano'] and argus['ano'] ~= '' then
microformato:node( enlaceMicroformato( 'year', argus['ano'] ) )
end
--if argus.lieu and argus.lieu ~= '' then
-- microformato:node( enlaceMicroformato( 'place', argus.lieu ) )
--end
if argus.progreso and argus.progreso ~= '' then
microformato:node( enlaceMicroformato( 'progress', argus.progreso ) )
end
--if argus.volume and argus.volume ~= '' then
-- microformato:node( enlaceMicroformato( 'volume', argus.volume ) )
--end
if argus.current and argus.current ~= '' then
microformato:node( enlaceMicroformato( 'chapter', argus.current ) )
end
if argus.index then
microformato:node( enlaceMicroformato( 'scan', argus.index ) )
if argus.image and mw.ustring.match(argus.image, '^%d+$') ~= nil then
microformato:node( enlaceMicroformato( 'cover', argus.index .. '/' .. argus.image ) )
end
end
if from ~= '' and to ~= '' then
if from == to then
microformato:node( enlaceMicroformato( 'pages', from ) )
else
microformato:node( enlaceMicroformato( 'pages', from .. '-' .. to ) )
end
end
if argus.wikipedia and argus.wikipedia ~= '' then
microformato:node( enlaceMicroformato( 'wikipedia', argus.wikipedia ) )
end
if argus.wikiquote and argus.wikiquote ~= '' then
microformato:node( enlaceMicroformato( 'wikiquote', argus.wikiquote ) )
end
if argus.commonscat and argus.commonscat ~= '' then
microformato:node( enlaceMicroformato( 'commons', argus.commons ) )
end
return tostring(html)
end
-- Función que devuelve la lista de los valores de una propiedad en Wikidata formateados
function propiedad(idPropiedad,opciones)
if Entidad and Entidad.claims then --and Entidad.claims[idPropiedad] then
if not opciones then
opciones = {}
end
opciones['propiedad'] = idPropiedad
valorPropiedad = Wikidata.getPropiedad(opciones,Entidad.claims[idPropiedad])
if not valorPropiedad or valorPropiedad == '' then
return ''
end
return valorPropiedad
else return ''
end
end
return p