Перейти к содержимому страницы
Открыть меню
Переключить меню настроек
Открыть персональное меню
Вы не представились системе
Ваш IP-адрес будет виден всем, если вы внесёте какие-либо изменения.

Модуль:Infocards

Материал из вики «Вече»
Версия от 18:41, 3 августа 2026; wp>ru.wikipedia (Импорт из русской Википедии, версия 154235056)
(разн.) ← Предыдущая версия | Текущая версия (разн.) | Следующая версия → (разн.)

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

local infocards = {}
local calculateAge = true
local dateCat = require( 'Module:Infocards/dateCat' )
local moduleDates = require( 'Module:Dates' )

--[[
Helper function that populates the argument list given that user may need to use a mix of
named and unnamed parameters.  This is relevant because named parameters are not
identical to unnamed parameters due to string trimming, and when dealing with strings
we sometimes want to either preserve or remove that whitespace depending on the application.
]]
function infocards._getParameters( frame_args, arg_list )
	local new_args = {}
	local index = 1
	local value

	for i,arg in ipairs( arg_list ) do
		value = frame_args[arg]
		if value == nil then
			value = frame_args[index]
			index = index + 1
		end
		new_args[arg] = value
	end

	return new_args
end

function infocards.isBlank( someString )
	return someString == nil or mw.ustring.match(someString, '^%s*$') ~= nil
end

function infocards.isDate ( frame )
	local new_args = infocards._getParameters( frame.args, {'s', 't', 'f'} )
	local s = new_args['s'] or ''
	local t = new_args['t'] or ''
	local f = new_args['f'] or ''

	local result = infocards.isDateImpl ( s )
	if (result) then
		return t
	else
		return f
	end
end

function infocards.isDateImpl ( s )
	local converted = infocards.convertToDate ( s )
	return converted ~= nil
end

function infocards.extractDateAndRefs( dateStr )
	if type(dateStr) ~= 'string' or dateStr == '' then return dateStr, '' end
	local dateClean, refs = mw.ustring.match(dateStr, '^(.-)(%s*[<{%[\127].*)$')
	if dateClean and infocards.convertToDate(dateClean) then
		return dateClean, refs
	end
	return dateStr, ''
end

function infocards.dateOfBirth( frame )
	local new_args = infocards._getParameters( frame.args, {'dateOfBirth', 'dateOfDeath', 'suppressAge', 'nocat'} )
	local dateOfBirth = new_args['dateOfBirth'] or ''
	local dateOfDeath = new_args['dateOfDeath'] or ''
	local suppressAge = new_args['suppressAge'] or ''
	local nocat = new_args['nocat'] or mw.title.getCurrentTitle().nsText

	return infocards.dateOfBirthImpl( dateOfBirth, dateOfDeath, suppressAge, nocat )
end

function infocards.dateOfBirthImpl( dateOfBirth, dateOfDeath, suppressAge, nocat )

	local appendToCategory = infocards.isBlank( nocat )
	local bRefs = ''
	dateOfBirth, bRefs = infocards.extractDateAndRefs( dateOfBirth )
	dateOfDeath = infocards.extractDateAndRefs( dateOfDeath )

	if ( infocards.isBlank( dateOfBirth ) ) then
		if ( appendToCategory ) then
			return dateCat.categoryNoBirthDate
		else
			return ''
		end
	end

	if ( mw.ustring.match( dateOfBirth, '^%s*неизвестн.%s*$' ) ~= nil
			or mw.ustring.match( dateOfBirth, '^%s*%?%s*$' ) ~= nil ) then
		if ( appendToCategory ) then
			return "''неизвестно''" .. bRefs .. dateCat.categoryUnknownBirthDate
		else
			return "''неизвестно''" .. bRefs
		end
	end

	local appendAge = not (suppressAge ~= '' or not calculateAge) and infocards.isBlank( dateOfDeath )

	local parsedDate = infocards.convertToDate ( dateOfBirth )
	if ( parsedDate == nil ) then
		--[[ Temporary hack in order to enable export dates to wikidata ]]
		local bDateStart = '<span class="no-wikidata" data-wikidata-property-id="P569">'
		local bDateEnd = '</span>'

		if ( appendToCategory ) then
			return bDateStart .. dateOfBirth .. bDateEnd .. bRefs .. dateCat.categoryManualWikification
		else
			return bDateStart .. dateOfBirth .. bDateEnd .. bRefs
		end
	end

	local result = infocards.formatDateImpl ( parsedDate, 'bday', appendToCategory and 'Родившиеся' or nil )
	local categories = ''

	if ( appendAge ) then
		-- TODO: месяцы и дни для (нескольких) новорождённых (см. новейшие [[Категория:Родившиеся в ГГГГ году]])
		local age = infocards.age ( parsedDate,  os.date("*t") )
		if ( age and age < 125) then
			result = result .. ' <span class="nowrap">(' .. age .. ' ' .. mw.language.new( 'ru' ):plural( age, 'год', 'года', 'лет') .. ')</span>'
		end

		if ( appendToCategory ) then
			if (not age and parsedDate and parsedDate.year ) then
				age = os.date('*t').year - parsedDate.year -- при неточной дате
 			end
			if ( age ) then
				if ( age > 115 ) then
					categories = categories .. dateCat.categoryBigCurrentAge

				-- Возраст от 0 до 115 лет + не существует даты смерти (в т. ч. не написано "неизвестно")
				elseif ( age >= 0 ) then
					categories = categories .. dateCat.categoryBiographiesOfLivingPersons
				else
					categories = categories .. dateCat.categoryNegativeAge
				end
			end
		end
	end

	return result .. bRefs .. categories
end

function infocards.dateOfDeath( frame )
	local new_args = infocards._getParameters( frame.args, {'dateOfBirth', 'dateOfDeath', 'nocat'} )
	local dateOfBirth = new_args['dateOfBirth'] or ''
	local dateOfDeath = new_args['dateOfDeath'] or ''
	local nocat = new_args['nocat'] or mw.title.getCurrentTitle().nsText

	return infocards.dateOfDeathImpl( dateOfBirth, dateOfDeath, nocat )
end

function infocards.dateOfDeathImpl( dateOfBirth, dateOfDeath, nocat )
	local bRefs = ''
	local dRefs = ''
	dateOfBirth, bRefs = infocards.extractDateAndRefs( dateOfBirth )
	dateOfDeath, dRefs = infocards.extractDateAndRefs( dateOfDeath )

	if ( infocards.isBlank( dateOfDeath ) ) then
		return ''
	end

	local appendToCategory = infocards.isBlank( nocat )

	if ( mw.ustring.match( dateOfDeath, '^%s*неизвестн.%s*$' ) ~= nil
			or mw.ustring.match( dateOfDeath, '^%s*%?%s*$' ) ~= nil ) then
		if ( appendToCategory ) then
			return "''неизвестно''" .. dRefs .. dateCat.categoryUnknownDeathDate
		else
			return "''неизвестно''" .. dRefs
		end
	end

	local parsedDateOfBirth = infocards.convertToDate ( dateOfBirth )
	local parsedDateOfDeath = infocards.convertToDate ( dateOfDeath )

	if ( parsedDateOfDeath == nil ) then
		--[[ Temporary hack in order to enable export dates to wikidata ]]
		local dDateStart = '<span class="no-wikidata" data-wikidata-property-id="P570">'
		local dDateEnd = '</span>'

		if ( appendToCategory ) then
			return dDateStart .. dateOfDeath .. dDateEnd .. dRefs .. dateCat.categoryManualWikification
		else
			return dDateStart .. dateOfDeath .. dDateEnd .. dRefs
		end
	end

	local result = infocards.formatDateImpl ( parsedDateOfDeath, 'dday', appendToCategory and 'Умершие' or nil )
	local categories = ''

	if ( calculateAge ) then
		local age = infocards.age ( parsedDateOfBirth, parsedDateOfDeath )
		if ( age and age > 0 ) then
			result = result .. ' <span class="nowrap">(' .. age .. ' ' .. mw.language.new( 'ru' ):plural( age, 'год', 'года', 'лет') .. ')</span>'
		end

		-- returns category to recently deceased persons
		local unixAvailable, unixDateOfDeath = pcall(function()
			local r = os.time(parsedDateOfDeath)
			if ( r ~= os.time() ) then
				return r
			end
			error()
		end)
		if (appendToCategory) then
			if ( unixAvailable and os.time() - unixDateOfDeath < 31536000 ) then
				categories = categories .. dateCat.categoryRecentlyDeceased
			elseif (age and age < 0) then
				categories = categories .. dateCat.categoryNegativeAge
			end
		end
	end

	return result .. dRefs .. categories
end

function infocards.age( parsedBirthDate, parsedFinishDate )
	if ( parsedBirthDate == nil or parsedFinishDate == nil ) then
		return nil
	end

	local bd = parsedBirthDate["day"]
	local bm = parsedBirthDate["month"]
	local by = parsedBirthDate["year"]

	local dd = parsedFinishDate["day"]
	local dm = parsedFinishDate["month"]
	local dy = parsedFinishDate["year"]

	if ( bd and bm and by and dd and dm and dy ) then
		if ( dm > bm or ( dm == bm and dd >= bd ) ) then
			return dy - by
		else
			return dy - by - 1
		end
	else
		return nil
	end
end

function infocards.formatDateImpl( parsedDate, infocardClass, categoryNamePrefix )
	local datePart = '<span class="nowrap">'

	--Temporary hack in order to enable export dates to wikidata
	if infocardClass == "bday" then
		datePart = '<span class="no-wikidata" data-wikidata-property-id="P569">'
	elseif infocardClass == "dday" then
		datePart = '<span class="no-wikidata" data-wikidata-property-id="P570">'
	end

	local t1 = { day = parsedDate.osday, month = parsedDate.osmonth, year = parsedDate.osyear }
	local t2 = { day = parsedDate.day, month = parsedDate.month, year = parsedDate.year }
	datePart = datePart .. moduleDates.formatWikiImpl( t1, t2, infocardClass, categoryNamePrefix )

	datePart = datePart .. '</span>'

	return datePart
end

function infocards.convertToDate( possibleDateString )

	possibleDateString = mw.ustring.gsub( possibleDateString, '−', '-')

	local simpleDate = mw.ustring.match(possibleDateString, '^%s*([%-%d%.]+)%s*$', 0)
	if ( simpleDate ) then
		return infocards.convertToDateNewStylePart( simpleDate )
	end

	local complexDate1, complexDate2 = mw.ustring.match(possibleDateString, '^%s*([%-%d%.]+)%s*%(([%-%d%.]+)%)%s*$', 0)
	if ( complexDate1 and complexDate2) then
		local table1 = infocards.convertToDateNewStylePart( complexDate1 )
		local table2 = infocards.convertToDateOldStylePart( complexDate2 )
		if ( table1 and table2 ) then
			return {
					year = table1["year"], month = table1["month"], day = table1["day"], 
					osyear = table2["year"], osmonth = table2["month"], osday = table2["day"]
				}
		else
			return nil
		end
	end

	return nil
end

function infocards.convertToDateNewStylePart( possibleDateString )

	local ny = mw.ustring.match(possibleDateString, '^(%-?%d+)$', 0)
	if (ny ~= nil) then
		return {year = tonumber(ny)}
	end

	return infocards.convertToDateCommonPart( possibleDateString )
end

function infocards.convertToDateOldStylePart( possibleDateString )

	local nd = mw.ustring.match(possibleDateString, '^(%-?%d+)$', 0)
	if (nd ~= nil) then
		return {day = tonumber(nd)}
	end

	return infocards.convertToDateCommonPart( possibleDateString )
end


function infocards.convertToDateCommonPart( possibleDateString )
	local sDay, sMonth, sYear
	local day, month, year

	sDay, sMonth, sYear = mw.ustring.match( possibleDateString, '^(%d?%d)%.(%d?%d)%.(%-?%d+)$', 0 )
	if sDay ~= nil and sMonth ~= nil and sYear ~= nil then
		day = tonumber( sDay )
		month = tonumber( sMonth )
		year = tonumber( sYear )
		if day >= 1 and day <= 32 and month >= 1 and month <= 12 then
			return { day = day, month = month, year = year }
		end
	end

	sDay, sMonth = mw.ustring.match( possibleDateString, '^(%d?%d)%.(%d?%d+)$', 0 )
	if sDay ~= nil and sMonth ~= nil then
		day = tonumber( sDay )
		month = tonumber( sMonth )
		if day >= 1 and day <= 32 and month >= 1 and month <= 12 then
			return { day = day, month = month }
		end
	end

	sMonth, sYear = mw.ustring.match( possibleDateString, '^(%d?%d)%.(%-?%d+)$', 0 )
    if sMonth ~= nil and sYear ~= nil then
    	month = tonumber( sMonth )
    	year = tonumber( sYear )
    	if month >= 1 and month <= 12 then
        	return { month = month, year = year }
        end
    end

	return nil
end

return infocards