Ir al contenido

Módulo:Encabezado

De Wikisource, la biblioteca libre.
Documentación del módulo


Uso

Módulo sucesor de la plantilla {{Encabezado}}
Esta documentación está transcluida desde Módulo:Encabezado/doc.
Los editores pueden experimentar en la zona de pruebas
Por favor, añade las categorías a la subpágina de documentación.
(subpáginas - enlaces)

require('strict')
local p = {}
local QID = mw.wikibase.getEntityIdForCurrentPage()
local Str = require('Módulo:String')
	local delink = Str.delink
local Args = require('Módulo:Arguments')
local Enlaces = require('Módulo:Enlaces')
local Obra = require('Módulo:Obra')
local Wikidata = require('Módulo:Wikidata')
local Box = require('Módulo:Box')
local categorias = {}
local errorcats = {}
local lang = mw.language.new('es')

--parámetros reconocidos. 1 = vigente, 0 = obsoleto. En orden alfabético:
local params = {['ano']=1,['anterior']=1,['audio']=1,['autor']=1,["bilingüe"]=1,['catálogo']=0,['commons']=1,['commonscat']=1,['derechos']=1,['desambiguación']=1,
	['editor']=1,  ['editorial']=1, ['enlaces']=1,['históricos']=1,['ilustrador']=1,['imprenta']=1, ['lugar']=1, ['más info']=1,['meta']=1,['noano']=1,['notas']=1, 
	['progreso']=1, ['próximo']=1, ['sección']=1,['sección autor']=1,['sub-titulo']=1,['subsección']=1,['subpágina']=1,['titulo']=1,['traductor']=1,['última muerte']=1,
	['volumen']=1, ['wikcionario']=1,['wikidata']=1,['wikilibros']=1,['wikinoticias']=1,['wikipedia']=1,['wikiquote']=1,['wikispecies']=1,['wikiversidad']=1,
	['obra'] = 1,
	['header']=1, ['index']=1, ['index_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',
	['subpagina']='subpágina',
	['seccion']='sección', 
	['seccion autor']='sección autor',	['seccion-autor']='sección autor',	['sección-autor']='sección autor'
}
local function link(s)
	if s:find("[%[%{%<]") then
		return s
	else
		return '[[Autor:'..s..'|'..s..']]'
	end
end
local function aCadena(t)
	mw.logObject(t)
	if not t then return '' end
	if type(t) == 'string' then
		t = mw.text.split(t, '[/,]')
		for i, v in ipairs(t) do
			t[i] = {text = v}
		end
	end
	local z = {}
	for i, creator in ipairs(t) do
		z[i] = creator.text
		if (z[i] == 'Anónimo')  or  (z[i] == 'valor desconocido') then
			z[i] = '[[Portal:Anónimo|Anónimo]]'
		elseif z[i] == 'Wikisource' then
			z[i] = '[[Ayuda:Directrices para traducciones|Wikisource]]'
		else
			z[i] = link(z[i])
		end
		
	end
	return mw.text.listToText(z)	
end


local 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)
	table.insert(errorcats, '[[Categoría:Wikisource:Páginas con errores en la plantilla Encabe]]')
	return tostring(html)
end

local deAutor = function(s) --Para [[Autor:AAA|BBB]], devuelve AAA
	-- remover entidades html
	s = s:gsub("<[%a%d%s%\"'/#;:=]+>", "")
	
	local m = mw.ustring.match(s, '%[%[Autor:(.+)%|.+%]%]')
	if m and m ~= '' then return m end
	
	m = mw.ustring.match(s, '%[%[Autor:(.+)%]%]')
	if m and m ~= '' then return m end
	
	--enlaces a wikidata u otros
	m = mw.ustring.match(s, '%[%[.+%|(.+)%]%]')
	if m and m ~= '' then return m end
	
	return delink(s)
end

local function enlaceMicroformato(param, valor)
	if valor and valor ~= '' then
		if type(valor) == 'string' then
			return mw.html.create('span')
	        :addClass('ws-' .. param)	--ws-author, ws-title, etc.
	        :wikitext(delink(valor))
		elseif type(valor) == 'table' then
			local spans = {}
			for i, v in ipairs(valor) do
				-- creadores
				if type(v)=='table' then
					v = v.wsPage or v.label
				end
				table.insert(spans, tostring(mw.html.create('span')
			        :addClass('ws-' .. param)
			        :wikitext(delink(v)))
				)
			end
			return table.concat(spans)
		end
	end
	return ''
end

local function microformato(d, argus)
	local microformat = mw.html.create('div')
			:cssText('display:none')
			:attr('id', 'ws-data')
			:addClass('ws-noexport')
	
-- todo: no captura datos del Índice si tiene otro Wikidata (p.ej. Q88887973)
-- todo: los que no están en  [[Plantilla:Proofreadpage header template]] (lugar, volumen, nivel) no llegan del
--		índice y sólo los captura de Wikidata.
	if d.title and d.title ~= '' then
		microformat:node( enlaceMicroformato( 'title', d.title ) )
		microformat:node( enlaceMicroformato( 'key', d.title ) )	--todo: mejorable
	end
	if d.pubYear and d.pubYear ~= '' then
        microformat:node( enlaceMicroformato( 'year', d.pubYear ) )
    end
    if d.author and d.author ~= '' then
        microformat:node( enlaceMicroformato( 'author', d.author ) )
    end
    if d.translator and d.translator ~= '' then
        microformat:node( enlaceMicroformato( 'translator', d.translator ) )
    end
    if d.illustrator and d.illustrator ~= '' then
        microformat:node( enlaceMicroformato( 'illustrator', d.illustrator ) )
    end
    if argus["sección"] and argus["sección"] ~= '' then
        microformat:node( enlaceMicroformato( 'chapter', argus["sección"] ) )
    end
    if d.printer and d.printer ~= '' then	--ojo: Editorial ~= Editor ~= Imprenta
        microformat:node( enlaceMicroformato( 'publisher', d.printer ) )
    end
    if d.place and d.place ~= '' then
        microformat:node( enlaceMicroformato( 'place', d.place ) )
    end
    if d.progress then
        microformat:node( enlaceMicroformato( 'progress', argus.progreso ) ) --puede que esté roto
    end
    if d.volume and d.volume ~= '' then
        microformat:node( enlaceMicroformato( 'volume', d.volume ) )
    end
	--todo: pdte. (¿adaptar de [[:ca:Module:Header]]?)
	--if argus.index then
    --    microformat:node( enlaceMicroformato( 'scan', argus.index ) )
    --    if argus.image and mw.ustring.match(argus.image, '^%d+$') ~= nil then
    --        microformat:node( enlaceMicroformato( 'cover', argus.index .. '/' .. argus.image ) )
    --    end
    -- end

	--todo: ¿extraer de listaenlaces? argus.x ~= listaenlaces
	if argus.wikipedia and argus.wikipedia ~= '' then
        microformat:node( enlaceMicroformato( 'wikipedia', argus.wikipedia ) )
    end
    if argus.wikiquote and argus.wikiquote ~= '' then
        microformat:node( enlaceMicroformato( 'wikiquote', argus.wikiquote ) )
    end
    if argus.commonscat and argus.commonscat ~= '' then
        microformat:node( enlaceMicroformato( 'commons', argus.commons ) )
    end

	if argus.notas and argus.notas ~= '' then
        microformat:tag('div')   --no puede ser span
        :addClass('ws-notes')    --ws-summary?
        :wikitext(argus.notas)	
    end
    
    return tostring(microformat)
end
local function buscaDesam(title)
	local match = string.match( title.text, '(.-) %(.-%)')
	if not match then return end
	local desam = mw.title.new(match)
	for i, cat in ipairs(desam.categories) do
		if cat == 'Wikisource:Páginas de desambiguación' then
			return match
		end
	end
end
local function personaCats(t, catprefix, cats)
	if not t then return '' end
	if type(t) == 'string' then
		t = mw.text.split(t, '[/,]')
		for i, v in ipairs(t) do
			t[i] = {text = v}
		end
	end
	if t then
		for i, creator in ipairs(t) do
			local name = creator.text
			local delinked = delink(name)
			if (delinked == 'Anónimo')  or  (delinked == 'valor desconocido') then
				
				table.insert(cats, '[[Categoría:'..catprefix..' de autor anónimo]]')
			else
				table.insert(cats, '[[Categoría:'..catprefix..' de '..deAutor(name):match("^%s*(.-)%s*$") ..']]')
			end
		end
	end
	if catprefix ~= '' then return cats end
	return ''
end
function p.encabe( frame ) 
    local titulo = mw.title.getCurrentTitle()
    local html = mw.html.create()
    local argus = Args.getArgs(frame)
	argus = Args.alias(argus, altparams)
	
	-- QID real prevalece sobre el importado desde el índice (importante en subdivisiones)
	argus.index_wikidata = argus.wikidata -- guarda el QID del Índice, por si difiere de la obra/subdivisión
	argus.wikidata = (QID ~= '' and QID) or argus.wikidata
	local essub = titulo.isSubpage
    
	if argus['subpágina'] == 'no' then
		essub = false
    end
    
	-- obtener todos los datos
	local d = Obra.newWork((QID or titulo.text), argus)
	
	--variables matemática derechos de autor
	local anosmuerte
	local anospub
	if d.pubYear and tonumber(d.pubYear) ~= nil  then
		anospub = tonumber(lang:formatDate('Y')) - tonumber(d.pubYear)
	end
	if argus['última muerte'] and tonumber(argus['última muerte']) ~= nil then
		anosmuerte = tonumber(lang:formatDate('Y')) - tonumber(argus['última muerte'])
	end
	
	-- estructura HTML
	
	local content = {}
		
	----- enlaces de navegación
	if argus['anterior'] and argus['anterior'] ~= '' then
		content.anterior = argus['anterior']
	end
    if argus['próximo'] and argus['próximo'] ~= '' then
		content.proximo = argus['próximo']
	end

	-- Datos al medio
	local medio = mw.html.create('div'):addClass('middle-div')
    if d.parentWork then
    	-- TODO: hacer algo con las obras que son parte de otras 	
    end
    -- datos bibliográficos
    if d.mainTitle then
		-- si tiene título secundario, es sub-obra
		if d.m_qid and d.title ~= d.mainTitle then
			local titlelink = Wikidata.printDatatypeEntity({id=d.m_qid}, {lang={'es'}})
			medio:wikitext("'''''".. titlelink .."'''''")
		else
	    	medio:wikitext("'''''".. d.mainTitle .."'''''")
		end
    	if d.subtitle then
    		medio:wikitext(': '..'<span style="font-size:83%;">'.. d.subtitle ..'</span>')	
    	end
    	if d.pubYear and not argus['noano'] then
    		medio:wikitext(' ('.. d.pubYear ..')')
    		if tonumber(d.pubYear) ~= nil then
	    		table.insert(categorias, '[[Categoría:P'.. d.pubYear ..']]')
	    	end
    	end
		medio:wikitext('<br>')
    else
    	table.insert(errorcats, '[[Categoría:Wikisource:Textos sin título]]')
    end
    
	if d.mainAuthor then
		personaCats(d.author, '', {})
		medio:wikitext('de '.. aCadena(d.mainAuthor) ..'<br>')
	end
    if d.translator then
		personaCats(d.translator, 'Traducciones', categorias)
    	medio:wikitext('traducción de '..aCadena(d.translator)..'<br>')
    end
    if d.illustrator then
		personaCats(d.illustrator, 'Ilustraciones', categorias)
    	medio:wikitext('ilustración de '..aCadena(d.illustrator)..'<br>')
    end
	
    if argus['más info'] then
    	medio:wikitext(argus['más info']..'<br>')
    end

    if d.title and d.title ~= d.mainTitle then -- "sección" pasa a "title" cuando este último no existe
    	medio:tag('span'):cssText('font-style:italics'):wikitext(d.title)
    	if d.author and aCadena(d.mainAuthor) ~= aCadena(d.author) then
    		medio:wikitext(' de '..aCadena(d.author))
    	end
   		if argus['subsección'] then
   			medio:tag('span'):cssText('font-size: 83%;'):wikitext('<br>'..argus['subsección'])
   		end
    end
    content.medio = tostring(medio)
	
	--    ENLACES A PROYECTOS HERMANOS
	if not argus['desambiguación'] and not essub then 
    	argus['desambiguación'] = buscaDesam(titulo)
    end
	local listaenlaces = Enlaces.all(argus)   
   -- TODO: pasarlo al módulo enlaces, o es muy específico de encabezado?
	if d.editionof then
   		listaenlaces[3] = {
 			['name']   = 'Otras versiones',
			['image']  = 'OOjs_UI_icon_book-ltr.svg',
			['text']   = 'otras versiones',
			['prefix'] = '',
			['title']  = d.editionof[1].localPage,}
 
   	end
    --matematica y manejo derechos de autor
    if not argus['derechos'] or argus['derechos'] == '' then
		if d.place then
			argus['derechos'] = require('Módulo:Obra/países').get_country(d.place[1])
		end
	end	
	if argus['derechos'] then
    	listaenlaces[1] = {['text']   = argus.derechos,
					['image']  = 'PD-icon.svg',
					['prefix'] = ':Wikisource:Duración de derechos de autor por país#',
					['title']  = argus.derechos}
				
		if (argus['última muerte'] == 'seudónimo' or argus['última muerte'] == 'anónimo') and (anospub ~= nil) then
    		local numero = math.floor((anospub - 1)/10)
    		if numero > 10 then numero = 10 end
    		listaenlaces[2] = {['image']  = nil,
					['text']   = tostring(numero*10)..' p.a.p. o menos',
					['prefix'] = ':Wikisource:Duración de derechos de autor por país#',
					['title']  = tostring(numero*10)..' p.a.p.'}
    		table.insert(categorias, '[[Categoría:'..tostring(numero*10)..' p.a.p.]]')
    	elseif argus['última muerte']  and (anosmuerte ~= nil) then
			local numero = math.floor((anosmuerte - 1)/10)
    		if numero > 4 then --a partir de 50 p.m.a.
    			if numero > 10 then numero = 10 end
    			listaenlaces[2] = {['image']  = nil,
					['text']   = tostring(numero*10)..' p.m.a. o menos',
					['prefix'] = ':Wikisource:Duración de derechos de autor por país#',
					['title']  = tostring(numero*10)..' p.m.a.'}
    			table.insert(categorias, '[[Categoría:'..tostring(numero*10)..' p.m.a.]]')
    		end
    	end
    	local cadena = argus.derechos:gsub(" y ", ", ")

		-- Usar string.gmatch para separar por comas y procesar directamente
		for nombre in cadena:gmatch("([^,]+)") do
			table.insert(categorias, '[[Categoría:Publicado en '.. nombre:match("^%s*(.-)%s*$") ..']]')
		end
	end
	
	local enlaces = Enlaces.formattedlinks(listaenlaces)
	
	if argus['bilingüe'] and argus['bilingüe'] ~= '' then
		enlaces = enlaces .. (' ['..titulo:fullUrl({['match']=argus['bilingüe']})..' ver texto bilingüe]')
	end
	--Enlaces de descarga
	if not essub then
		local LinkExport='https://ws-export.wmcloud.org/?lang=es&page='..textoenlace..'&format='
		local w = "<div style=\"font-size:80%\">Descargar como &nbsp;"
		w = w .. "[[Archivo:EPUB silk icon.svg|12px|link="..LinkExport.."epub|Descargar en formato ePub]]&nbsp;"
		w = w .. "[[Archivo:Document-pdf.svg|15px|link="..LinkExport.."pdf|Descargar en formato PDF]]&nbsp;"
		w = w .. "[[Archivo:Mobi_icon.svg|22px|link="..LinkExport.."mobi|Descargar en formato mobi]]</div>"
		enlaces = enlaces .. w
	end 
	content.enlaces = enlaces

	if argus['notas'] and argus['notas'] ~= '' then
		content.notas = argus.notas
	end
	if argus['audio'] and argus['audio'] ~= '' then
		content.notas2 = frame:expandTemplate{ title = 'Multimedia', args = { argus['audio'] } }
	end
	
	--categorías automáticas
	if not essub then
		table.insert(categorias, '[[Categoría:ES-'..Str.CaracterParaOrdenar(titulo.rootText)..']]')
		if not argus.wikidata then
			table.insert(errorcats, '[[Categoría:Wikisource:Textos no conectados a Wikidata]]')
		end
	else
		categorias = {'[[Categoría:'..titulo.rootText..']]'}
		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
				table.insert(errorcats, '[[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'))
			table.insert(errorcats, '[[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
	html:wikitext(Wikidata.badge{qid=argus.wikidata, ws=argus.progreso, indicator=1, category=(not essub) })
	html:wikitext(Box.box(content))
	table.sort(categorias)
	html:wikitext(table.concat(categorias))
	html:wikitext(table.concat(errorcats))

	html:wikitext(microformato(d, argus))
	
    return tostring(html)

end
return p