Модуль:Ф

Поделись знанием:
Перейти к: навигация, поиск
 Документация

Реализация режима подстановки в шаблоне {{Ф}}.

Во избежание поломок страниц, использующих данный модуль, желательно экспериментировать в Песочнице для модулей.

local p = {}

local monthNames = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'}

if not getArgs then
	getArgs = require('Модуль:Arguments').getArgs
end

local function findInTable(table, value)
	for k, v in pairs(table) do
		if v == value then
			return true
		end
	end
	return false
end

-- map(function, table)
-- e.g: map({1,2,3}, double)    -> {2,4,6}
local function map(tbl, func)
	local newtbl = {}
	for i,v in pairs(tbl) do
		newtbl[i] = func(v)
	end
	return newtbl
end

-- используется в шаблоне {{Ф}}
function p.get_topic_archiving_details(frame)
	local args = getArgs(frame)
	local wikilink = args[1]
	local displayedText = args[2]
	if not wikilink then return "''Ошибка при подстановке шаблона {{Ф}}: не передана вики-ссылка''" end
	
	local pageTitle, sectionHeading
	pageTitle, sectionHeading = wikilink:match('(.-)#(.+)')
	if pageTitle then
		pageTitle = mw.title.new(pageTitle)
	end
	if pageTitle and pageTitle.redirectTarget then
		pageTitle = pageTitle.redirectTarget
	end
	if pageTitle then
		pageTitleText = pageTitle.prefixedText
	end
	
	local standardForums = {'Общий', 'Новости', 'Правила', 'Предложения', 'Вопросы', 'Вниманию участников', 'Технический', 'Авторское право', 'Иноязычный'}
	local standardForumsPaths = map(standardForums, function (v)
		return 'Википедия:Форум/' .. v
	end)
	
	local isStandardForum = false
	local archivingType, archivePath, archivingDelay
	if findInTable(standardForumsPaths, pageTitleText) then
		isStandardForum = true
		archivePath = 'Архив/%(год)/%(месяц)' -- относительный путь для главных форумов для обратной совместимости
	end
	local archivePage = mw.title.new(pageTitleText .. '/Архивация')
	local archivePageContent = archivePage:getContent()
	if archivePageContent then
		archivingType = mw.text.trim(mw.ustring.match(archivePageContent, '|%s*тип%s*=%s*([^\n]*)') or '')
		if archivingType == '' then archivingType = nil end
		if archivingType and archivingType ~= 'страница' and archivingType ~= 'нумерация' then
			archivingDelay = tonumber(mw.text.trim(mw.ustring.match(archivePageContent, '|%s*срок%s*=%s*([^\n]*)') or ''))
			if not isStandardForum then
				archivePath = mw.text.trim(mw.ustring.match(archivePageContent, '|%s*формат%s*=%s*([^\n]*)') or '')
				if archivePath == '' then archivePath = nil end
				local isAbsolutePath = mw.text.trim(mw.ustring.match(archivePageContent, '|%s*абсолютный путь%s*=%s*([^\n]*)') or '')
				if isAbsolutePath == '' then isAbsolutePath = nil end
				if not isAbsolutePath then
					archivePath = pageTitleText .. '/' .. archivePath
				end
			end
		end
	end
	
	local parse_section_content = require('Модуль:Get page content')._parse_section_content
	local sectionContent = parse_section_content{pageTitle, sectionHeading}
	local day, mesyats, year = mw.ustring.match('\n' .. sectionContent, '%d%d:%d%d, (%d%d?) (%w+) (%d%d%d%d) %(UTC%)')
	local month
	for k, v in pairs(monthNames) do
		if v == mesyats then
			month = string.format('%.2d', k)
		end
	end
	if not year or not month or not day then return '{{Ф|' .. pageTitleText .. '|' .. sectionHeading .. '|}}' end
	day = string.format('%.2d', day)
	
	if archivePath then
		local quater = math.floor((month - 1) / 3) + 1
		local halfyear = math.floor((month - 1) / 6) + 1
		
		archivePath = mw.ustring.gsub(archivePath, '%%%(год%)', year)
		archivePath = mw.ustring.gsub(archivePath, '%%%(месяц%)', month)
		archivePath = mw.ustring.gsub(archivePath, '%%%(квартал%)', quater)
		archivePath = mw.ustring.gsub(archivePath, '%%%(полугодие%)', halfyear)
	end
	
	local titleParam
	if isStandardForum then
		titleParam = mw.ustring.gsub(pageTitleText, 'Википедия:Форум/', '')
		archivePath = mw.ustring.gsub(archivePath, 'Архив/', '')
	else
		titleParam = pageTitleText
	end
		
	code = '{{Ф|' .. titleParam .. '|' .. sectionHeading .. '|' .. (archivePath and archivePath or '') .. '|первое сообщение=' .. year .. '-' .. month .. '-' .. day
	if archivingDelay then
		code = code .. '|задержка архивации=' .. archivingDelay
	end
	if displayedText then
		code = code .. '|' .. displayedText
	end
	code = code .. '}}'
	
	return code
end

return p