Модуль:Не переведено: различия между версиями

Материал из Википедии — свободной энциклопедии
Перейти к навигации Перейти к поиску
[отпатрулированная версия][отпатрулированная версия]
Содержимое удалено Содержимое добавлено
мНет описания правки
отслеживать язык в четвёртом параметре вместо пятого, вроде {{iw|Климов, Григорий Петровичъ|Григорий Климов||bg|Григорий Климов}}
Строка 98: Строка 98:
return error{'шаблон не поддерживает такой синтаксис'} .. categories
return error{'шаблон не поддерживает такой синтаксис'} .. categories
end
end
if is_empty(lang) and not is_empty(iw_title) and iw_title:match('^[a-z][a-z]$') then
if allow_cat or true then
categories = categories .. '[[Категория:Википедия:Статьи с предположительно неверными параметрами в шаблонах серии Не переведено]]'
end
end
if is_empty(text) then
if is_empty(text) then
text = title
text = title

Версия от 16:45, 20 октября 2020

Документация

Служит для работы шаблонов {{не переведено}}, {{не переведено 2}}, {{не переведено 3}}, {{не переведено 4}} и {{не переведено 5}}.

См. также: Модуль:Не переведено/песочница (сравнить) и Шаблон:Не переведено/тесты.

TODO

  • внешний вид нп3
  • возможно, что-то с nil из [1]
local getArgs = require('Module:Arguments').getArgs
local p = {}

local function is_empty(param)
	return param == nil or param == ''
end

local function wikilink(title, text, tooltip, lang)
	if lang ~= nil and lang ~= 'ru' then
		title = string.format(':%s:%s', lang, title)
	end
	if tooltip ~= nil then
		if is_empty(text) then
			text = title
		end
		text = tostring(
			mw.html.create('span')
			:attr('title', tooltip)
			:wikitext(text)
		)
	end
	if not is_empty(text) and text ~= title then
		title = title .. '|' .. text
	end
	return string.format('[[%s]]', title)
end

local function italic(s)
	return tostring(
		mw.html.create('span')
		:css('font-style', 'italic')
		:wikitext(s)
	)
end

function p.main(frame)
	local yesno = require('Module:Yesno')
	local args = getArgs(frame)
	local languages = mw.loadData('Module:Languages/data')
	local error = require('Module:Error').error
	local prepositional = require('Module:Languages')._transform_lang

	local categories = ''
	local nocat = yesno(args['nocat'])
	local allow_cat = mw.title.getCurrentTitle().namespace == 0 and not nocat
	local orphan_categories = {
		['error'] = '[[Категория:Википедия:Статьи с некорректно заполненным шаблоном Не переведено]]',
		['outdated'] = '[[Категория:Википедия:Статьи с неактуальным шаблоном Не переведено]]',
		['redirect'] = '[[Категория:Википедия:Запросы на замену перенаправлений переводами]]'
	}
	local mode = tonumber(args['mode'])
	
	local redundant_params = {}
	local good_params = {'mode', 1, 2, 3, 4, 'l', 'leave', 'r', 'q', 'nocat'}
	if mode == 2 then
		table.insert(good_params, 5)
		table.insert(good_params, 'text')
		table.insert(good_params, 'текст')
	end
	for k, _ in pairs(args) do
		local is_good_param = false
		for _, v in pairs(good_params) do
		  	if k == v then
		  		is_good_param = true
		  	end
		end
		if not is_good_param then
			table.insert(redundant_params, k)
		end
	end
	if allow_cat and #redundant_params > 0 then
		categories = categories .. '[[Категория:Википедия:Статьи с неизвестными параметрами шаблонов серии Не переведено]]'
		if frame:preprocess('{{REVISIONID}}') == '' then
			categories = categories .. '<span class="error untranslated_hidden_error" style="display:none;">Лишние параметры ' .. mw.text.listToText(redundant_params) .. '</span>'
		end
	end

	local title = args[1]
	local text = args[2]
	local lang = mw.ustring.lower(args[3] or '')
	local iw_title = args[4]
	local iw_text = args[5]
	
	if mw.isSubsting() and mode ~= 2 then
		return wikilink(title, text)
	end
	
	if is_empty(title) then
		if allow_cat then
			categories = categories .. orphan_categories['error']
		end
		return error{'не указано название статьи'} .. categories
	end
	if title:match('^:[a-z-]+:') then
		if allow_cat then
			categories = categories .. '[[Категория:Википедия:Статьи с полустарым синтаксисом в шаблонах серии Не переведено]]'
		end
		return error{'шаблон не поддерживает такой синтаксис'} .. categories
	end
	if is_empty(lang) and not is_empty(iw_title) and iw_title:match('^[a-z][a-z]$') then
		if allow_cat or true then
			categories = categories .. '[[Категория:Википедия:Статьи с предположительно неверными параметрами в шаблонах серии Не переведено]]'
		end
	end
	
	if is_empty(text) then
		text = title
	end
	if is_empty(lang) then
		lang = 'en'
	end
	local orig_iw_title = iw_title
	if is_empty(iw_title) then
		iw_title = title
	end
	if is_empty(iw_text) then
		iw_text = iw_title
	end

	local ru_page = mw.title.new(title)
	if ru_page == nil then
		if allow_cat then
			categories = categories .. orphan_categories['error']
		end
		return error{'некорректные символы в названии статьи'} .. categories
	end
	
	local iw_page = mw.title.new(iw_title)
	if iw_page == nil then
		if allow_cat then
			categories = categories .. orphan_categories['error']
		end
		return error{'некорректные символы в названии статьи'} .. categories
	end
	
	local leave_always = yesno(args['l']) or yesno(args['leave'])
	local leave_if_redirect = yesno(args['r'])
	if leave_if_redirect and not ru_page.isRedirect then
		leave_if_redirect = false
	end
	local exists = ru_page.exists and not ( leave_always or leave_if_redirect )
	if leave_if_redirect and allow_cat then
		categories = categories .. orphan_categories['redirect']
	end
	
	local iw_tooltip
	local ucfirst_title = mw.getContentLanguage():ucfirst(title)
	if lang == 'd' then
		if mode == 1 or mode == 2 then
			iw_tooltip = string.format('Элемент статьи «%s» в Викиданных', ucfirst_title)
		elseif mode == 5 then
			iw_tooltip = string.format('Страница статьи «%s» в Викиданных', ucfirst_title)
			iw_title = iw_title .. '#sitelinks-wikipedia' -- осторожно, может сломать что-то
		end
	else
		if mode == 1 or mode == 2 then
			iw_tooltip = string.format('Версия статьи «%s» на %s', ucfirst_title, prepositional(lang))
		elseif mode == 4 then
			iw_tooltip = string.format('Эквивалент статьи «%s» на %s', ucfirst_title, prepositional(lang))
		elseif mode == 5 then
			local pref
			if is_empty(orig_iw_title) then
				pref = 'Версия статьи'
			else
				pref = string.format('%s — версия статьи', iw_title)
			end
			iw_tooltip = string.format('%s «%s» на %s', pref, ucfirst_title, prepositional(lang))
		end
	end

	-- форматирование первой части - основной ссылки
	local main_text
	if exists or mode == 1 or mode == 2 or mode == 5 then
		if mode == 5 and ru_page.isRedirect then
			main_text = string.format('[%s %s]', tostring(mw.uri.fullUrl(title,'redirect=no')), text)
		else
			main_text = wikilink(title, text)
		end
		if exists and not mw.isSubsting() and (mode == 1 or mode == 2 or mode == 3) then
			main_text = tostring(
				mw.html.create('span')
				:css('background', '#ffff00')
				:wikitext(main_text)
			)
		end
	else
		main_text = wikilink(iw_title, text, iw_tooltip, lang)
	end
	if mode == 4 and yesno(args['q']) then
		main_text = '«' .. main_text .. '»'
	end
	
	-- форматирование второй части - языковой метки
	local lang_text
	local lang_title
	if lang == 'd' then
		lang_text = 'd'
	elseif languages[lang] == nil then
		if allow_cat then
			categories = categories .. orphan_categories['error']
		end
		return error{'некорректный ISO-код «' .. lang .. '»'} .. categories
	else
		lang_text = languages[lang][1]
		lang_title = languages[lang][2]
	end
	
	local post_text = ''
	if (not exists and not mw.isSubsting()) or mode == 2 or (mode == 5 and ru_page.isRedirect) then
		if mode == 1 then
			local iw_link = wikilink(iw_title, lang_text, iw_tooltip, lang)
			post_text = tostring(
				mw.html.create('span')
				:addClass('noprint')
				:css('white-space', 'nowrap')
				:css('font-size', '85%')
				:wikitext(' (' .. iw_link .. ')')
			)
		elseif mode == 2 then
			local iw_link = ''
			if lang == 'd' then
				return error{'шаблон Не переведено 2 не поддерживает Викиданные вместо языка'}
			else
				local lang_template = mw.title.new('Template:Lang-' .. lang)
				if not lang_template.exists then
					if allow_cat then
						categories = categories .. '[[Категория:Википедия:Статьи с шаблоном Не переведено 2, использующие несуществующий шаблон lang-XX]]'
					end
					return error{'не найден шаблон ' .. frame:expandTemplate{ title = 'tl', args = { 'lang-' .. lang } } } .. categories
				end
				
				if mw.isSubsting() then
					iw_link = '{{lang-' .. lang .. '|' .. iw_text .. '}}'
				elseif exists then
					iw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { iw_text } }
				else
					iw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { wikilink(iw_title, iw_text, iw_tooltip, lang) } }
				end
			end
			
			local addition = args['text'] or args['текст']
			if not is_empty(addition) then
				addition = '; ' .. addition
			else 
				addition = ''
			end
			post_text = ' (' .. iw_link .. addition .. ')'
		elseif mode == 3 then
			local ref = frame:expandTemplate{ title = 'ref-' .. lang, args = {} }
			post_text = '<span style="white-space: nowrap"><span class="noprint" style="font-size:95%; '
				.. 'position: relative; top: .4em;">' .. ref .. '</span><span class="link-ru metadata noprint" '
				.. 'style="font-size:80%; margin-left:-1.7em; position: relative; top: -.4em;">'
				.. wikilink(title, 'русск.') .. '</span></span>'
		elseif mode == 4 then
			local styles = ''
			if lang == 'fr' then
				styles = 'margin-right:0.3em;'
			elseif lang == 'fi' then
				styles = 'margin-right:0.35em;'
			elseif lang == 'it' then
				styles = 'margin-right:0.5em;'
			end
			post_text = '<sup class="noprint" style="font-style:normal; margin-left:2px; position:relative; top:-1px;">'
				.. wikilink(title, 'ru', 'Статья «' .. title .. '» в русском разделе отсутствует') .. '</sup>'
				.. '<sub class="noprint" style="font-style:normal; margin-left:-0.94em; ' .. styles .. '" title="По ссылке доступна статья на '
				.. prepositional(lang) .. '">' .. lang .. '</sub>'
		else
			post_text = '<sup class="iw__note noprint" style="font-style:normal; font-weight:normal;">'
				.. string.format('[[:%s:%s|<span class="iw__tooltip" title="%s">[%s]</span>]]</sup>', lang, iw_title, iw_tooltip, lang)
		end
	end
	
	-- форматирование третьей части - уведомления о существовании страницы
	local exist_message = ''
	if exists then
		if allow_cat and (mode ~= 5 or not ru_page.isRedirect) then
			categories = categories .. orphan_categories['outdated']
		end
		if allow_cat and (mode == 5 and ru_page.isRedirect) then
			categories = categories .. orphan_categories['redirect']
		end
		
		if mode == 1 or mode == 2 or mode == 3 then
			local exist_tooltip = ''
			if mode == 1 or mode == 2 then
				exist_tooltip = 'Пожалуйста, удалите шаблон, заменив «{{не переведено» на  «{{подст:не переведено»'
			else
				exist_tooltip = 'Пожалуйста, удалите шаблон, заменив «{{не переведено 3» на  «{{подст:переведено 3»'
			end
			
			local docname = 'Шаблон:Не переведено'
			if mode == 2 or mode == 3 then
				docname = docname .. ' ' .. mode
			end
			
			exist_message = string.format(
				'&#91;\'\'%s\'\'&#93;',
				wikilink(
					docname .. '#Действия после появления страницы', 
					'убрать шаблон',
					exist_tooltip
				)
			)
			exist_message = tostring(
				mw.html.create('sup')
				:addClass('noprint')
				:wikitext(exist_message)
			)
		elseif mode == 4 then
			exist_message = '<sup class="noprint">[[Шаблон:Не переведено 4#Действия после появления страницы|'
				.. '<span style="background:yellow; color:red; font-style:normal;" title="Пожалуйста, '
				.. 'замените шаблон «Не переведено 4» простой вики-ссылкой">\'\'\'?!\'\'\'</span>]]</sup>'
		else
			if ru_page.isRedirect then
				exist_message = '<sup class="iw__notice noprint" style="font-style:normal; font-weight:normal; margin:0 0 0 1px;">'
						.. '[[Шаблон:Не переведено 5#Если существует перенаправление|'
						.. '<span style="color:red; font-weight:bold;" title="Замените название перенаправления на название статьи либо уберите шаблон «Не переведено 5»">*</span>]]'
						.. '</sup>'
			else
				exist_message = '<sup class="iw__notice noprint">[[Шаблон:Не переведено 5#Если существует статья|'
				.. '<span style="color:red; font-style:normal; font-weight:bold;" title="Уберите шаблон «Не переведено 5» из статьи '
				.. 'и замените его простой вики-ссылкой">?!</span>]]</sup>'
			end
		end
	end
	
	local result
	result = main_text .. post_text
	if not mw.isSubsting() then
		result = result .. exist_message .. categories
	end
	if mode == 5 then
		local langName = ''
		if lang ~= 'd' then
			langName = ' data-lang-name="' .. (languages[lang][1] and languages[lang][1] or '???') .. '"'
		end
		
		local class = (exists and (ru_page.isRedirect and ' iw--redirect' or ' iw--exists') or '')
		result = string.format('<span class="iw%s plainlinks" data-title="%s" data-lang="%s"' .. langName .. '>', class, ucfirst_title, lang)
			.. result .. '</span>'
	end
	
	return result
end

return p