Модуль:Песочница/Обавторе

Материал из Викитеки — свободной библиотеки

Для документации этого модуля может быть создана страница Модуль:Песочница/Обавторе/Документация

-- ToDo:	По возможности заменить вызовы шаблонов на код Lua или вызовы соотв. модулей.
--			Учесть, что в Викиданных свойства могут иметь несколько значений, тогда брать с rank=='preferred'
--			(например, указанно несколько изображений, или категорий на Commons). 
--			Категория и Commons из Викиданный сейчас не работает.
--			Добавить взятие ссылок на персоналии в энциклопедиях с Викиданных (небыло в оригинальном шаблоне)
--			Проверить установку категорий (были запутаны, частичны, в оригинальном шаблоне)

local p = {}

-- объект с методами. здесь сборка результата
-- заметка: в Lua метод из метода вызывается с self, напр.: self.div_m5(self, s)
local about = {
		t = {},  -- текст
		c = {},  -- категории
	}
function about:result() return table.concat(self.t) .. table.concat(self.c) end
function about:add(s) if type(s) == 'string' then table.insert(self.t, s) 
	elseif type(s) == 'table' then table.insert(self.t, table.concat(s)) end end
function about:add_div_m5(s)
	local _s; if type(s) == 'string' then _s = s elseif type(s) == 'table' then _s = table.concat(s) end
	self.add(self, {'<div style="margin:5px;">', _s, '</div>'}) end
function about:add_category(s) table.insert(self.c, '[[Категория:'..s..']]') end
function about:add_category_author_wd(s) table.insert(self.c, '[[Категория:Авторы:Ссылка из Викиданных:'..s..']]') end
function about:add_category_manual_link(s) table.insert(self.c, '[[Категория:Авторы:Ручная ссылка:'..s..']]') end


-- подготовка параметров
local function args_normalization(frame)
	local pargs = frame:getParent().args
	local title_obj = mw.title.getCurrentTitle()
	local d = {
		pagename = title_obj.text,
		namespace = title_obj.namespace,
		edo = frame:expandTemplate{ title = 'ЕДО'}, -- {{ЕДО}}
		entity = mw.wikibase.getEntity(),  -- for test 'Q13054180', 'Q43718'
		
		family = is(pargs['ФАМИЛИЯ']),
		names = is(pargs['ИМЕНА']),
		names_variants = is(pargs['ВАРИАНТЫИМЁН']),
		date_birth = is(pargs['ДАТАРОЖДЕНИЯ']),
		date_death = is(pargs['ДАТАСМЕРТИ']),
		place_birth = is(pargs['МЕСТОРОЖДЕНИЯ']),
		place_death = is(pargs['МЕСТОСМЕРТИ']),
		desc = is(pargs['ОПИСАНИЕ']),
		other = is(pargs['ДРУГОЕ']),
		image = is(pargs['ИЗОБРАЖЕНИЕ']),
		wikipedia = is(pargs['ВИКИПЕДИЯ']),
		wikiquote = is(pargs['ВИКИЦИТАТНИК']),
		commons = is(pargs['ВИКИСКЛАД']),
		wikispecies = is(pargs['ВИКИВИДЫ']),
		wikinews = is(pargs['ВИКИНОВОСТИ']),
		wikilivres = is(pargs['ВИКИЛИВР']),
		wikilivres_ru = is(pargs['ВИКИЛИВРУ']),
		disambig = is(pargs['НЕОДНОЗНАЧНОСТЬ']),
		esbe = is(pargs['ЭСБЕ']),
		mesbe = is(pargs['МЭСБЕ']),
		eebe = is(pargs['ЕЭБЕ']),
		nes = is(pargs['НЭС']),
		el = is(pargs['ЭЛ']),
		resb = is(pargs['РЭСБ']),
		beu = is(pargs['БЭЮ']),
		beu2 = is(pargs['БЭЮ2']),
		bse1 = is(pargs['БСЭ1']),
		rbs = is(pargs['РБС']),
		pbe = is(pargs['ПБЭ']),
		ve = is(pargs['ВЭ']),
		msr = is(pargs['МСР']),
		rskd = is(pargs['РСКД']),
		bbsrp = is(pargs['ББСРП']),
		esg = is(pargs['ЭСГ']),
		scolrs = is(pargs['СЧОЛРС']),
		britannica = is(pargs['Britannica']),
		lentapedia = is(pargs['ЛЕНТАПЕДИЯ']),
	}
	return d
end

-- карточка
function render_infobox(d, frame)
	local infobox = {
		t = {
			'<table class="prettytable" style="width:250px;float:right;font-size:95%;margin:0 0 1em 1em;">',
			'<tr><th style="background-color:#DDDDFF;font-size:large;text-align:center;">',
			'<span id="ws-name">',
			(function () if d.names or d.family then return d.names..' '..d.family else return d.pagename end end)(),
			'</span>',
			'</th></tr>'}
	}
	function infobox:result() return table.concat(self.t) end
	function infobox:add(s) table.insert(self.t, s) end
	function infobox:add_td(s) if is(s) then self.add(self, '<tr align=center><td>'..s..'</td></tr>') end end
	-- function infobox:nf() if d.names or d.family then return d.names..' '..d.family else return d.pagename end end

	-- tbl= mw.html.create('table'):attr('class','prettytable'):css('width','250px'):css('float','right'):css('font-size','95%'):css('margin','0 0 1em 1em')
	-- tbl:tag('tr'):tag('th'):wikitext('[[file:logo]]')
	-- table.insert(str, tostring(tbl))
	--tbl:tag('th'):node(tr)
	-- mw.logObject(tbl,"tbl")
	--tbl = mw.text.tag{ name = 'table', attrs = {class='prettytable', style="width:250px;float:right;font-size:95%;margin:0 0 1em 1em;"},content = ''}
	--tr = mw.text.tag{ name = 'tr', attrs = {style="background-color: #DDDDFF;font-size:large;text-align:center;"},content = '' }
	--tbl:node('tr'):node('th'):node('tr')
	--tbl:node('<span id="ws-name">]].. nf(names, family, pagename) ..'</span></th></tr>'')

	-- изображение
	local image_link_wd = frame:expandTemplate{ title = 'wikidata/p18', args = {[1]=d.image, size='220px'} }
	infobox:add_td(image_link_wd)
	-- if d.entity then
	--     local othersources = require('Модуль:Другие источники') 
	-- 	-- local image = othersources.getClaimValues(d.entity,'P18')[1]; --if d.image then d.image= d.image[1] end
	mw.logObject(d.image,"d.image")
	-- 	if d.image then
	-- 		local img = frame:expandTemplate{ title = 'wikidata/p18', args = {[1]=d.image, size='220px'} }
	-- 		mw.logObject(img,"img")
	-- 		table.insert(infobox, render_td(img))
	-- 	end
	-- end
	
	-- local image_link_wd = nil
	-- local image_link_wd = is(d.entity:formatPropertyValues( 'P18' ).value)
	-- mw.logObject(image_link_wd,"image_link_wd")
	if image_link_wd then about:add_category_author_wd('Изображение') end
	if d.image then about:add_category_manual_link('Изображение') end
	if d.image == image_link_wd then about:add_category_manual_link('Изображение:Совпадает со ссылкой из Викиданных') end
	
	
	if d.names_variants then infobox:add_td(d.names_variants) end

	-- даты и места рождения и смерти
	-- local db, dd, pb, pd
	-- if d.entity then  -- если есть элемент Викиданных используем
	-- 	db = frame:expandTemplate{ title = 'wikidata/p569'} --args = {tostring(d.date_birth), tostring(d.date_death)}
	-- 		-- othersources.getClaimValues( d.entity, 'p569' )[1] 	
	-- 	dd = frame:expandTemplate{ title = 'wikidata/p570', args = {d.date_death or d.date_birth, d.date_death}}
	-- 		-- othersources.getClaimValues( d.entity, 'p570' )[1]
	-- 	pb = frame:expandTemplate{ title = 'wikidata/p19', args = {d.place_birth or ''}}
	-- 		-- othersources.getClaimValues( d.entity, 'p19' )[1]
	-- 	pd = frame:expandTemplate{ title = 'wikidata/p20', args = {d.place_death}}
	-- 		-- othersources.getClaimValues( d.entity, 'p20' )[1] -- 
	-- else  -- иначе параметры шаблона
	-- 	db = d.date_birth
	-- 	dd = d.date_death
	-- 	pb = d.place_birth
	-- 	pd = d.place_death
	-- end
	local db = d.date_birth or frame:expandTemplate{ title = 'wikidata/p569'} --args = {tostring(d.date_birth), tostring(d.date_death)}
	local dd = d.date_death or frame:expandTemplate{ title = 'wikidata/p570', args = {d.date_death or d.date_birth, d.date_death}}
	local pb = d.place_birth or frame:expandTemplate{ title = 'wikidata/p19', args = {d.place_birth or ''}}
	local pd = d.place_death or frame:expandTemplate{ title = 'wikidata/p20', args = {d.place_death}}
	-- mw.logObject(db,"db")
	-- mw.logObject(dd,"dd")
	-- mw.logObject(pb,"pb")
	-- mw.logObject(pd,"pd")
	if is(db) then
		local s = 'р. <span id="ws-birthdate">' ..db ..'</span>'
		if is(pb) then s = s..', '..pb end
		infobox:add_td(s)	end
	if is(dd) then 
		local s = 'ум. <span id="ws-deathdate">' ..dd ..'</span>'
		if is(pd) then s = s..', '..pd end
		infobox:add_td(s)	end
	
	if d.desc then infobox:add_td('<span id="ws-description">'..d.desc..'</span>') end
	if d.other then infobox:add_td(d.other) end

	infobox:add('</table>')
	return infobox:result()
end	


-- ссылки на братские проекты и соответствующая категоризация
-- Проверка на ручные ссылки и Проверка совпадения ручной ссылки со ссылкой из Викиданных
function links_to_wikiprojects(d, frame)
	local wdwp = require('Модуль:Wikidata/Wikipedia')
	
	-- wikisource
	if d.wikisource then
		--mw.logObject(d.wikisource, "d.wikisource")
		about:add_category_manual_link('Викитека') 
	end
	
	-- wikipedia
	local w_link_wd = wdwp.getWikipediaLink()
	if d.wikipedia or w_link_wd then
		local w_link; if d.wikipedia then w_link = 'w:'..d.wikipedia elseif w_link_wd then w_link = w_link_wd end
		about:add_div_m5({
			'[[Файл:Wikipedia-logo.png|20px|link='..w_link..']]',
			' [['..w_link..'|Биография в Википедии]]',
			'<span id="ws-wikipedia" style="display: none;">'..w_link..'</span>'})
		if d.wikipedia then about:add_category_manual_link('Википедия') end
		if w_link_wd and d.namespace == 0 then
			about:add_category_author_wd('Википедия')
			if d.wikipedia == w_link_wd then about:add_category_manual_link('Википедия:Совпадает со ссылкой из Викиданных') end
		end
	end
	
	-- wikiquote
	local q_link_wd = wdwp.getWikiquoteLink()
	if d.wikiquote or q_link_wd then
		-- mw.logObject(q_link_wd, "w_link_wd")
		-- mw.logObject(d.wikiquote, "d.wikipedia")
		local q_link; if d.wikiquote then q_link = 'q:'..d.wikiquote elseif q_link_wd then q_link = q_link_wd end
		about:add_div_m5({
			'[[Файл:Wikiquote-logo.svg|20px|link='..q_link..']]',
			' [['..q_link..'|Сборник цитат в Викицитатнике]]',
			'<span id="ws-wikiquote" style="display: none;">'..q_link..'</span>'})
		if q_link_wd then
			about:add_category_author_wd('Викицитатник')
			if d.wikiquote == q_link_wd then 
				about:add_category_manual_link('Викицитатник:Совпадает со ссылкой из Викиданных') end
		end 
	end

	-- commons 
	-- local c_link_wd = is(entity:formatPropertyValues( 'p373' ).value)  -- категория Commons
	local c_link_wd = nil
	if d.commons then
		-- mw.logObject(d.commons, "d.commons")
		local c_link = 'commons:'..d.commons
		about:add_div_m5({
			'[[Файл:Commons-logo.svg|20px|link='..c_link..']]', 
			' [['..c_link..'|Изображения и медиаданные на Викискладе]]'})
		about:add_category_manual_link('Викисклад')
		if d.commons == c_link_wd then about:add_category_manual_link('Викисклад:Совпадает со ссылкой из Викиданных') end
	else 
		about:add(
			frame:expandTemplate{ title = 'wikidata/p373', 
				args = {icon='true', icon_size='20x100px',
					text_before='<div style="margin:5px;">',
					text='Изображения и медиаданные на Викискладе',
					text_after='</div>'}})
	end
	if c_link_wd then about:add_category_author_wd('Викисклад') end
	
	-- wikispecies
	local species_link_wd =  wdwp.getWikispeciesLink()
	if d.wikispecies or species_link_wd then
		-- mw.logObject(species_link_wd, "species_link_wd")
		-- mw.logObject(d.wikispecies, "d.wikispecies")
		local species_link; if d.wikispecies then species_link = 'species:'..d.wikispecies 
			elseif species_link_wd then species_link = species_link_wd end
		about:add_div_m5({
			'[[Файл:Wikispecies-logo.svg|20px|link='..species_link..']]',
			' [['..species_link..'|'..d.names..' '..d.family..' в Викивидах]]'})
		if d.wikispecies then about:add_category_manual_link('Викивиды') end
	end
	
	-- wikinews
	if d.wikinews then
		-- mw.logObject(wikinews_link_wd, "wikinews_link_wd")
		-- mw.logObject(d.wikinews, "d.wikinews")
		local n_link = 'n:'..d.wikinews
		about:add_div_m5({
			'[[Файл:Wikinews-logo.svg|20px|link='..n_link..']]',
			' [['..n_link..'|'..d.names..' '..d.family..' в Викиновостях]]',
			'<span id="ws-wikinews" style="display: none;">'..n_link..'</span>'})
		about:add_category_manual_link('Викиновости')
	end

	-- wikilivres
	if d.wikilivres then
		-- mw.logObject(wikilivres_link_wd, "wikilivres_link_wd")
		-- mw.logObject(d.wikilivres, "d.wikilivres")
		local l_link = 'wikilivres:'..d.wikilivres
		about:add_div_m5({
			'[[Файл:Wikilivres-logo.svg|20px|link='..l_link..']]',
			' [['..l_link..'|'..d.names..' '..d.family..' в Wikilivres]]'})
		about:add_category_manual_link('Викиливр')
	end
		
	-- wikilivres.ru
	if d.wikilivres_ru then
		-- mw.logObject(wikilivres_ru_link_wd, "wikilivres_ru_link_wd")
		-- mw.logObject(d.wikilivres_ru, "d.wikilivres_ru")
		about:add_div_m5({
			'[[Файл:Wlru-logo.png|20px|link=]]',
			frame:expandTemplate{ title = 'wikilivres.ru', 
				args = {d.wikilivres_ru, d.names..' '..d.family..' в Wikilivres.ru', nopic='yes'}}})
		about:add_category_manual_link('Викиливру')	
	end
	mw.logObject(d.wikilivres_ru, "d.wikilivres_ru")


	-- Изображение и его категория обрабатывается в блоке infobox
	
end


-- рендеринг ссылок на словарные персоналии об авторе и соответствующая категоризация
function personalies_links(d)
	local x = {} 
	function add(s) table.insert(x, s) end
	local dict_params = {
		{'ЭСБЕ', d.esbe}, {'МЭСБЕ', d.mesbe}, {'НЭС', d.nes}, {'ЭЛ', d.el}, {'РЭСБ', d.resb}, {'БЭЮ', d.beu}, {'БЭЮ2', d.beu2}, 
		{'БСЭ1', d.bse1}, {'ЕЭБЕ', d.eebe}, {'ПБЭ', d.pbe}, {'РБС', d.rbs}, {'ВЭ', d.ve}, {'МСР', d.msr}, {'РСКД', d.rskd}, 
		{'ББСРП', d.bbsrp}, {'ЭСГ', d.esg}, {'СЧОЛРС', d.scolrs}, {'Britannica', d.britannica}, {'Лентапедия', d.lentapedia}, 
	}
	for _, v in ipairs(dict_params) do 
		local abbr, dpage = v[1], v[2]
		if dpage then 
			-- добавление словарей. вначале особые случаи, ниже общий
			if abbr == 'ЭЛ' then
				local _do; if mw.title.new('ЭЛ/ВТ/'..dpage).exists then _do = 'ВТ' else _do = 'ДО' end
				add('[[ЭЛ/'.._do..'/'..dpage..'|ЭЛ]]')
			elseif abbr == 'Britannica' then
				add('[[:en:1911 Encyclopædia Britannica/'..dpage..'|'..abbr..']]') 
			else
				add('[['..abbr..'/'..dpage..'|'..abbr..']]')
			end
			about:add_category_manual_link(abbr)  -- добавление категории "Ручная ссылка"
		end 
	end
	local dicts = table.concat(x, ' &bull;&nbsp;') -- конвертация списка в строку с разделителем

	-- сборка ссылок
	if #dicts>0 or d.wikisource then
		x = {}
		add('[[Файл:Wikisource-logo.svg|20px|link=]] ')
		if #dicts>0 then
			if d.wikisource then
				add('[['..d.wikisource..'|Материалы об авторе в Викитеке:]]&nbsp;')
			else add('Биография в ') end
			add(dicts)
		elseif d.wikisource then
			add('[['..d.wikisource..'|Материалы об авторе в Викитеке]]')
		end
		
		about:add_div_m5(x)
		-- mw.logObject(x)
	 end
end

function p.render(frame)
	-- mw.logObject(frame,"frame")
	local d = args_normalization(frame)  -- параметры шаблона
	-- mw.logObject(d,"d")
	-- mw.logObject(d.entity,"entity")
	
	if d.disambig then about:add({
		'<div style="font-size:0.9em; margin-left:2em;" class="similar">',
		"''См. [["..d.disambig.."|других авторов с подобными именами]].''",
		'</div>'})
	end
	
	-- {{Footer|{{Внешние ссылки|nocat=yes}}}}
	about:add({'<div id="ws-footer" style="display: none">',
		frame:expandTemplate{ title = 'Внешние ссылки', args = {nocat='yes'}},
		'</div>'})
	
	-- frame:extensionTag{ name = 'div', 
	-- 	content = frame:expandTemplate{ title = 'Внешние ссылки', args = {nocat='yes'}}, 
	-- 	args = { id = 'ws-footer', style = 'display: none' } }
	
	about:add('<br clear="all" style="line-height:0px" />')
	
	-- карточка
	about:add(render_infobox(d, frame))
	
	-- ссылки на братские проекты и соответствующая категоризация
	about:add(links_to_wikiprojects(d, frame))
	--mw.logObject(about)
	
	-- ссылки на персоналии в словарях Викитеки
	about:add(personalies_links(d))
	
	if d.google then 
		about:add_div_m5({
			'[[Файл:Google free icon.svg|20px|link=w:Google]]',
			'[http://books.google.com/books'..d.google..' Книги на сайте books.google.com]'})
		about:add_category_manual_link('Google')
	end


	-- if not othersources.getClaimValues(d.entity,'P21')[1] and d.namespace == 0 then 
	-- 	about:add_category('Авторы:Не персона') end
	
	
	if d.family then
		local cnames; if d.names then cnames = ', '..d.names end
		about:add({
			-- frame:callParserFunction('{{DEFAULTSORT:'..d.family..cnames..'}}'),
			frame:callParserFunction('DEFAULTSORT:'..d.family..cnames),
			'<span id="ws-key" style="display: none;">', d.family, cnames, '</span>'})
	
		-- Категория с первой заглавной буквой фамилии
		about:add_category('Авторы-'..mw.ustring.upper(mw.ustring.sub(d.family, 1, 1)))  
	else about:add_category('Авторы без параметра ФАМИЛИЯ в шаблоне Обавторе')	
	end

	if d.category or (d.names and d.family) then
		about:add_category(d.category or (d.names..' '..d.family)..'|*')
		about:add_category('Все авторы|'..d.family)
	end
	
	result = about:result()
	-- mw.logObject(about,"about")
	-- mw.logObject(result,"result")
	return result 
end

	
-- проверка переменной, возврат её или nil если пустая
function is(v) if (v=='' or v==nil) then return nil else return v end end
	
--end
return p