Модуль:Football box/base

Википедия — ирекле энциклопедия мәғлүмәте

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

local p = {}

p.labels = {
	['penalties'] = '[[Послематчевые пенальти|Пенальти]]',
	['shootout'] = '[[Послематчевые пенальти|Пенальти]]',
	['pen'] = '[[Послематчевые пенальти|пен.]]',
	['пен'] = '[[Послематчевые пенальти|пен.]]',
	['so'] = '[[Послематчевые пенальти|пен.]]',
	['aet'] = '[[Дополнительное время#В футболе|доп. вр.]]',
	['agg'] = 'по сумме двух матчей',
	['stadium'] = 'Стадион:', 
	['стадион'] = 'Стадион:', 
	['attendance'] = 'Зрителей:',
	['зрителей'] = 'Зрителей:',
	['referee'] = 'Судья:',
	['судья'] = 'Судья:',
	['assistantreferees'] = 'Помощники судьи:',
	['assistantreferee1'] = 'Помощник судьи:',
	['assistantreferee2'] = 'Помощник судьи:',
	['assistantreferees2'] = '<span style="visibility:hidden">Помощники судьи:</span>',
	['fourthofficial'] = 'Резервный судья:',
	['fifthofficial'] = 'Пятый судья:',
	['goallineassistants'] = 'Судьи на линии:',
	['goallineassistant2'] = '<span style="visibility:hidden">Судьи на линии:</span>',
	['VAR'] = 'Видеопомощник судьи (VAR):',
	['assistantVAR'] = 'Ассистент видеопомощника судьи (VAR):',
	['assistantsVAR'] = 'Ассистенты видеопомощника судьи (VAR):',
	['motm'] = 'Игрок матча:',
	['potm'] = 'Игрок матча:',
	['mvp'] = 'MVP:',
	['note'] = 'Примечание:',
	['squad1'] = 'Первая команда:',
	['squad2'] = 'Вторая команда:',
	['seealso'] = 'См. также:'
}

p.valid_args = {
	['aet'] = true, --допвремя
	['aggregatescore'] = true, --общий_счёт
	['assistantreferee2'] = true, --помощник2
	['assistantreferees'] = true, --помощники
	['attendance'] = true, --зрители
	['bars'] = true,
	['bg'] = true,
	['class'] = true,
	['date'] = true, --дата
	['fifthofficial'] = true, --судья5
	['format'] = true, --формат
	['fourthofficial'] = true, --судья4
	['goallineassistant2'] = true, --на_линии_2
	['goallineassistants'] = true, --на_линии
	['goals1'] = true, --голы1
	['goals2'] = true, --голы2
	['id'] = true,
	['location'] = true, --место
	['motm'] = true,
	['mvp'] = true,
	['nobars'] = true,
	['note'] = true, --примечание
	['penalties1'] = true, --пенальти1
	['penalties2'] = true, --пенальти2
	['penaltyscore'] = true, --пенальти
	['potm'] = true,
	['referee'] = true, --судья
	['report'] = true, --протокол
	['result'] = true, --результат
	['round'] = true, --раунд
	['score'] = true, --счёт
	['score1'] = true, --счёт1
	['score2'] = true, --счёт2
	['scorenote'] = true, --примечание_счёт
	['seealso'] = true, --см_также
	['shootout1'] = true, 
	['shootout2'] = true,
	['shootoutscore'] = true,
	['size'] = true, --размер
	['squad1'] = true, --состав1
	['squad2'] = true, --состав2
	['stack'] = true,
	['stadium'] = true, --стадион
	['team1'] = true, --команда1
	['team2'] = true, --команда2
	['time'] = true, --время
	['VAR'] = true, --видеопомощник судьи
	['assistantVAR'] = true, --ассистент видеопомощника судьи
	['assistantsVAR'] = true, --ассистенты видеопомощника судьи
}


function p.isnotempty(s)
	return s and s:match( '^%s*(.-)%s*$' ) ~= ''
end


local rus_args = {
	['допвремя'] = 'aet',
	['дополнительное время'] = 'aet',
	['общий_счёт'] = 'aggregatescore',
	['помощник2'] = 'assistantreferee2',
	['помощники'] = 'assistantreferees',
	['зрители'] = 'attendance',
	['фон'] = 'bg',
	['дата'] = 'date',
	['судья5'] = 'fifthofficial',
	['формат'] = 'format',
	['судья4'] = 'fourthofficial',
	['на_линии_2'] = 'goallineassistant2',
	['на_линии'] = 'goallineassistants',
	['голы1'] = 'goals1',
	['голы2'] = 'goals2',
	['место'] = 'location',
	['примечание'] = 'note',
	['отчет'] = 'report',
	['отчёт'] = 'report',
	['пенальти1'] = 'penalties1',
	['пенальти2'] = 'penalties2',
	['пенальти'] = 'penaltyscore',
	['игрок_матча'] = 'potm',
	['судья'] = 'referee',
	['протокол'] = 'report',
	['результат'] = 'result',
	['раунд'] = 'round',
	['счёт'] = 'score',
	['счёт1'] = 'score1',
	['счёт2'] = 'score2',
	['примечание_счёт'] = 'scorenote',
	['см_также'] = 'seealso',
	['размер'] = 'size',
	['состав1'] = 'squad1',
	['состав2'] = 'squad2',
	['стадион'] = 'stadium',
	['команда1'] = 'team1',
	['команда2'] = 'team2',
	['время'] = 'time',
	['ВАР'] = 'VAR',
	['ассистентВАР'] = 'assistantVAR',
	['ассистентыВАР'] = 'assistantsVAR',
}

function p.checkarg(k,v, cat, tracking, preview)
	if k and type(k) == 'string' then
		if p.valid_args[k] then
			-- valid and not tracked
		elseif p.isnotempty(rus_args[k]) then
			-- valid rus param
		else
			-- invalid
			local vlen = mw.ustring.len(k)
			k = mw.ustring.sub(k, 1, (vlen < 25) and vlen or 25) 
			k = mw.ustring.gsub(k, '[^%w\-_ ]', '?')
			if tracking ~= nil then
				table.insert(tracking, '[[Категория:' .. cat .. '|' .. k .. ']]')
			end
			if preview ~= nil then
				table.insert(preview, '"' .. k .. '"')
			end
		end
	end
end

function p.trim(s)
	if p.isnotempty(s) then
		s = s:match('^[\'"%s]*(.-)[\'"%s]*$')
		return p.isnotempty(s) and s or nil
	end
	return nil
end


function p.bold(s)
	if p.isnotempty(s) then
		return "'''" .. s .. "'''"
	end
	return ""
end

function p.italic(s)
	if p.isnotempty(s) then
		return "''" .. s .. "''"
	end
	return ""
end

function p.small(s)
	if p.isnotempty(s) then
		return '<small>' .. s .. '</small>'
	end
	return ''
end

function p.nowrap(s)
	if p.isnotempty(s) then
		return '<span style="white-space:nowrap">' .. s .. '</span>'
	end
	return ''
end

function p.fmtlist(s)
	s = mw.ustring.gsub(s or '', '%[%[ *([%?-]) *%]%]', '%1')
	s = mw.ustring.gsub(s, '%[%[ *[%?-] *| *(.-) *%]%]', '%1')
	if mw.ustring.sub(s, 1, 1) == '*' then
		return tostring(mw.html.create('div'):addClass('plainlist'):newline():wikitext(s))
	end
	return s
end


function p.makelink(s,t)
	if s:match('^http') then
		return '[' .. s .. ' ' .. t .. ']'
	end
	return s
end


--здесь бы подошло регулярное выражение, похожее на 
--^(?:\{\{.+\}\})?\s*(?:\[\[(?:[^\]]+\|)?)?([^\]]+)(?:\]\])?\s*(?:\{\{.+\}\})?
--, но в Lua есть  паттерны, а не регулярные выражения, поэтому перебираем варианты руками
local span_begin = '<span class="flagicon">'
local span_end = '</span>'

local any_file = '%[%[File:.+%]%]'
local any_file_ru = '%[%[Файл:.+%]%]'
local any_space = '%s*'
local nbsp = '&nbsp;'
local flagicon = span_begin .. '%[%[Файл:.+%]%]' .. span_end
local clarification = '%b()'
local wikilink_text = '%[%[.+|([^%]]+)%]%]'
local wikilink_same = '%[%[([^%]]+)%]%]'
local nolink = '([^%[%]]+)'

local spaces = {any_space, nbsp}
local targets = { wikilink_text, wikilink_text .. any_space .. clarification, wikilink_same, wikilink_same .. any_space .. clarification, nolink, nolink .. any_space .. clarification }

local function check_any_pattern(s, patterns)
	for _, pattern in ipairs(patterns) do
		for m in mw.ustring.gmatch(s, pattern) do
			return p.trim(m)
		end
	end
	return s
end

local function pattern_maker(list, fun)
	for _, target in ipairs(targets) do
		for _, space in ipairs(spaces) do
			table.insert(list, fun(space, target) .. "$")
		end
	end
end

function p.check_team_pattern(s)
	local team_with_possible_flags = {}
	-- сначала проверяем шаблон {{флаг|}}, чтобы gmatch не захватывал открывающий <span>
	pattern_maker(team_with_possible_flags, function(space, target) return flagicon .. space .. target end)  -- {{флаг|XX}} спереди
	pattern_maker(team_with_possible_flags, function(space, target) return target .. space .. flagicon end)  -- {{флаг|XX}} сзади
	pattern_maker(team_with_possible_flags, function(space, target) return any_file .. space .. target end) -- {{флаг XX}} спереди
	pattern_maker(team_with_possible_flags, function(space, target) return target .. space .. any_file end) -- {{флаг XX}} сзади
	pattern_maker(team_with_possible_flags, function(space, target) return any_file_ru .. space .. target end) -- {{флаг XX}} спереди, в шаблоне используется синтаксис Файл:
	pattern_maker(team_with_possible_flags, function(space, target) return target .. space .. any_file_ru end) -- {{флаг XX}} сзади, в шаблоне используется синтаксис Файл:
	for _, t in ipairs(targets) do
		table.insert(team_with_possible_flags, t)
	end
	return check_any_pattern(s, team_with_possible_flags)
end

function p.process_rus_params(args)
	for rus, en in pairs(rus_args) do
		if p.isnotempty(args[rus]) then
			args[en] = args[rus]
			args[rus] = nil
		end
	end
end

function p.print_rus_params(frame)
	local wtable = mw.html.create('table'):addClass("wikitable sortable")
	local row = wtable:tag('tr')
	row:tag('th'):wikitext('Русский параметр')
	row:tag('th'):wikitext('Английский параметр')
	local sorted = {}
	for k, _ in pairs(rus_args) do
		sorted[#sorted+1] = k 
	end
	table.sort(sorted)
	for _, rus in ipairs(sorted) do
		row = wtable:tag('tr')
		row:tag('td'):wikitext(rus)
		row:tag('td'):wikitext(rus_args[rus])
	end
	return tostring(wtable)
end

return p