Изменения

Перейти к навигации Перейти к поиску
из песочницы переработанная версия, но почти без содержательных изменений (https://web.archive.org/web/20201029192129/https://ru.wikipedia.org/wiki/Шаблон:Не_переведено/тесты)
Строка 1: Строка 1: −
local getArgs = require('Module:Arguments').getArgs
   
local p = {}
 
local p = {}
   Строка 6: Строка 5:  
end
 
end
   −
local function wikilink(title, text, tooltip, lang)
+
local function wikilink(title, text, tooltip, lang, style, is_redirect)
if lang ~= nil and lang ~= 'ru' then
+
if is_empty(text) then
 +
text = title
 +
end
 +
if not is_empty(lang) and lang ~= 'ru' then
 
title = string.format(':%s:%s', lang, title)
 
title = string.format(':%s:%s', lang, title)
 
end
 
end
if tooltip ~= nil then
+
if not is_empty(tooltip) then
if is_empty(text) then
+
text = string.format('<span title="%s">%s</span>', tooltip, text)
text = title
+
end
end
+
if not is_empty(style) then
text = tostring(
+
text = string.format('<span style="%s">%s</span>', style, text)
mw.html.create('span')
+
end
:attr('title', tooltip)
+
if is_redirect then
:wikitext(text)
+
return string.format(
 +
'<span class="plainlinks">[%s %s]</span>',
 +
tostring(mw.uri.fullUrl(title,'redirect=no')),
 +
text
 
)
 
)
 +
else
 +
return string.format('[[%s|%s]]', title, text)
 
end
 
end
if not is_empty(text) then
+
end
title = title .. '|' .. text
+
 
 +
local categories = {
 +
['error'] = 'Википедия:Статьи с некорректно заполненным шаблоном Не переведено',
 +
['outdated'] = 'Википедия:Статьи с неактуальным шаблоном Не переведено',
 +
['redirect'] = 'Википедия:Запросы на замену перенаправлений переводами',
 +
['unknown'] = 'Википедия:Статьи с неизвестными параметрами шаблонов серии Не переведено',
 +
['semiold'] = 'Википедия:Статьи с полустарым синтаксисом в шаблонах серии Не переведено',
 +
['probably_wrong'] = 'Википедия:Статьи с предположительно неверными параметрами в шаблонах серии Не переведено',
 +
['lang-not-exists'] = 'Википедия:Статьи с шаблоном Не переведено 2, использующие несуществующий шаблон lang-XX',
 +
}
 +
 
 +
local function throwError(text, category_code, allow_cat)
 +
local error = require('Module:Error').error
 +
if category_code and allow_cat then
 +
return error{text} .. '[[Category:' .. categories[category_code] .. ']]'
 +
else
 +
return error{text}
 
end
 
end
return string.format('[[%s]]', title)
   
end
 
end
    
function p.main(frame)
 
function p.main(frame)
 
local yesno = require('Module:Yesno')
 
local yesno = require('Module:Yesno')
local args = getArgs(frame)
+
local getArgs = require('Module:Arguments').getArgs
 
local languages = mw.loadData('Module:Languages/data')
 
local languages = mw.loadData('Module:Languages/data')
local error = require('Module:Error').error
   
local prepositional = require('Module:Languages')._transform_lang
 
local prepositional = require('Module:Languages')._transform_lang
   −
local categories = ''
+
local args = getArgs(frame)
 +
 
 +
local categories_list = {}
 
local nocat = yesno(args['nocat'])
 
local nocat = yesno(args['nocat'])
 
local allow_cat = mw.title.getCurrentTitle().namespace == 0 and not nocat
 
local allow_cat = mw.title.getCurrentTitle().namespace == 0 and not nocat
local orphan_categories = {
+
['error'] = '[[Категория:Википедия:Статьи с некорректно заполненным шаблоном Не переведено]]',
+
-- определение какой из шаблонов "не переведено N"
['outdated'] = '[[Категория:Википедия:Статьи с неактуальным шаблоном Не переведено]]',
  −
['redirect'] = '[[Категория:Википедия:Запросы на замену перенаправлений переводами]]'
  −
}
   
local mode = tonumber(args['mode'])
 
local mode = tonumber(args['mode'])
 +
local template_name = 'Не переведено'
 +
if mode ~= 1 then
 +
template_name = template_name .. ' ' .. tostring(mode)
 +
end
 
 
 +
-- проверка не неизвестные параметры
 
local redundant_params = {}
 
local redundant_params = {}
 
local good_params = {'mode', 1, 2, 3, 4, 'l', 'leave', 'r', 'q', 'nocat'}
 
local good_params = {'mode', 1, 2, 3, 4, 'l', 'leave', 'r', 'q', 'nocat'}
Строка 61: Строка 86:  
end
 
end
 
end
 
end
if allow_cat and #redundant_params > 0 then
+
if #redundant_params > 0 then
categories = categories .. '[[Категория:Википедия:Статьи с неизвестными параметрами шаблонов серии Не переведено]]'
+
table.insert(categories_list, 'unknown')
if frame:preprocess('{{REVISIONID}}') == '' then
  −
categories = categories .. '<span class="error untranslated_hidden_error" style="display:none;">Лишние параметры ' .. mw.text.listToText(redundant_params) .. '</span>'
  −
end
   
end
 
end
    +
-- получение параметров (кроме nocat)
 
local title = args[1]
 
local title = args[1]
 
local text = args[2]
 
local text = args[2]
local lang = mw.ustring.lower(args[3] or '')
+
local lang = args[3]
 
local iw_title = args[4]
 
local iw_title = args[4]
 
local iw_text = args[5]
 
local iw_text = args[5]
 +
local quotes = yesno(args['q'])
 +
local addition = args['text'] or args['текст']
 +
local leave_always = yesno(args['l']) or yesno(args['leave'])
 +
local leave_if_redirect = yesno(args['r'])
 
 
if mw.isSubsting() and mode ~= 2 then
+
-- проверка правильности сырых параметров
return wikilink(title, text)
+
if not mw.isSubsting() then
end
+
if is_empty(title) then
+
return throwError('не указано название статьи', 'error', allow_cat)
if is_empty(title) then
  −
if allow_cat then
  −
categories = categories .. orphan_categories['error']
   
end
 
end
return error{'не указано название статьи'} .. categories
+
if title:match('^:[a-z-]+:') then
end
+
return throwError('шаблон не поддерживает такой синтаксис', 'semiold', allow_cat)
if title:match('^:[a-z-]+:') then
  −
if allow_cat then
  −
categories = categories .. '[[Категория:Википедия:Статьи с полустарым синтаксисом в шаблонах серии Не переведено]]'
   
end
 
end
return error{'шаблон не поддерживает такой синтаксис'} .. categories
+
if is_empty(lang) and not is_empty(iw_title) and iw_title:match('^[a-z][a-z]$') then
end
+
table.insert(categories_list, 'probably_wrong')
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
 
end
 
end
 
 
 +
-- приведение параметров к нужному виду
 
if is_empty(text) then
 
if is_empty(text) then
 
text = title
 
text = title
Строка 101: Строка 120:  
if is_empty(lang) then
 
if is_empty(lang) then
 
lang = 'en'
 
lang = 'en'
 +
else
 +
lang = mw.ustring.lower(lang)
 
end
 
end
local orig_iw_title = iw_title
   
if is_empty(iw_title) then
 
if is_empty(iw_title) then
 
iw_title = title
 
iw_title = title
Строка 109: Строка 129:  
iw_text = iw_title
 
iw_text = iw_title
 
end
 
end
 
+
 +
-- если используется с подстановкой, выбросить почти без обработки
 +
if mw.isSubsting() then
 +
local ru_link = wikilink(title, text)
 +
if mode == 2 then
 +
local iw_link = '{{lang-' .. lang .. '|' .. iw_text .. '}}'
 +
if is_empty(addition) then
 +
return string.format('%s (%s)', ru_link, iw_link)
 +
else
 +
return string.format('%s (%s; %s)', ru_link, iw_link,  addition)
 +
end
 +
else
 +
return ru_link
 +
end
 +
end
 +
 +
-- получение страницы, чтобы знать, существует ли она и является ли она перенаправлением
 
local ru_page = mw.title.new(title)
 
local ru_page = mw.title.new(title)
 +
local leave = ru_page.exists and not leave_always and not (ru_page.isRedirect and leave_if_redirect)
 +
 +
-- проверка правильности обработанных параметров
 
if ru_page == nil then
 
if ru_page == nil then
if allow_cat then
+
return throwError('некорректные символы в названии русской статьи', 'error', allow_cat)
categories = categories .. orphan_categories['error']
+
end
end
+
if not is_empty(iw_title) and mw.title.new(iw_title) == nil then -- TODO: ищется в рувики
return error{'некорректные символы в названии статьи'} .. categories
+
return throwError('некорректные символы в названии статьи в другом разделе', 'error', allow_cat)
 +
end
 +
if lang ~= 'd' and languages[lang] == nil then
 +
return throwError('некорректный ISO-код «' .. lang .. '»', 'error', allow_cat)
 +
end
 +
if mode == 2 and lang == 'd' then
 +
return throwError('шаблон Не переведено 2 не поддерживает Викиданные вместо языка')
 
end
 
end
+
if mode == 2 and not mw.title.new('Template:Lang-' .. lang).exists then
local iw_page = mw.title.new(iw_title)
+
return throwError('не найден шаблон ' .. frame:expandTemplate{ title = 'tl', args = { 'lang-' .. lang } },
if iw_page == nil then
+
'probably_wrong', allow_cat)
if allow_cat then
  −
categories = categories .. orphan_categories['error']
  −
end
  −
return error{'некорректные символы в названии статьи'} .. categories
   
end
 
end
 
 
local leave_always = yesno(args['l']) or yesno(args['leave'])
+
if ru_page.isRedirect and leave_if_redirect then -- TODO: почему не на все перенаправления?
local leave_if_redirect = yesno(args['r'])
+
table.insert(categories_list, 'redirect')
if leave_if_redirect and not ru_page.isRedirect then
  −
leave_if_redirect = false
   
end
 
end
local exists = ru_page.exists and not ( leave_always or leave_if_redirect )
+
if leave then
if leave_if_redirect and allow_cat then
+
if mode == 5 and ru_page.isRedirect then
categories = categories .. orphan_categories['redirect']
+
table.insert(categories_list, 'redirect')
 +
else
 +
table.insert(categories_list, 'outdated')
 +
end
 
end
 
end
 
 
 +
-- всплывающая подсказка к ссылке на иноязычную статью
 
local iw_tooltip
 
local iw_tooltip
 
local ucfirst_title = mw.getContentLanguage():ucfirst(title)
 
local ucfirst_title = mw.getContentLanguage():ucfirst(title)
 
if lang == 'd' then
 
if lang == 'd' then
 
iw_tooltip = string.format('Элемент статьи «%s» в Викиданных', ucfirst_title)
 
iw_tooltip = string.format('Элемент статьи «%s» в Викиданных', ucfirst_title)
iw_title = iw_title .. '#sitelinks-wikipedia' -- осторожно, может сломать что-то
+
iw_title = iw_title .. '#sitelinks-wikipedia'
 
else
 
else
local pref
+
iw_tooltip = string.format('%s — версия статьи «%s» на %s', iw_title, ucfirst_title, prepositional(lang))
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
 
local main_text
if exists or mode == 1 or mode == 2 or mode == 5 then
+
if leave or mode == 1 or mode == 2 or mode == 5 then
if ru_page.isRedirect then
+
main_text = wikilink(title, text, nil, nil, nil, ru_page.isRedirect)
main_text = '<span class="plainlinks">'
  −
.. string.format('[%s %s]', tostring(mw.uri.fullUrl(title,'redirect=no')), text) .. '</span>'
  −
else
  −
main_text = wikilink(title, text)
  −
end
   
else
 
else
 
main_text = wikilink(iw_title, text, iw_tooltip, lang)
 
main_text = wikilink(iw_title, text, iw_tooltip, lang)
 
end
 
end
if mode == 4 and yesno(args['q']) then
+
if mode == 4 and quotes then -- TODO: все шаблоны или отключить
 
main_text = '«' .. main_text .. '»'
 
main_text = '«' .. main_text .. '»'
 
end
 
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 = ''
 
local post_text = ''
if (not exists and not mw.isSubsting()) or mode == 2 or (mode == 5 and ru_page.isRedirect) then
+
if not leave or mode == 2 or (mode == 5 and ru_page.isRedirect) then
 +
-- для шаблона "не переведено"
 
if mode == 1 then
 
if mode == 1 then
 +
local lang_text
 +
if lang == 'd' then
 +
lang_text = 'd'
 +
else
 +
lang_text = languages[lang][1]
 +
end
 +
 
local iw_link = wikilink(iw_title, lang_text, iw_tooltip, lang)
 
local iw_link = wikilink(iw_title, lang_text, iw_tooltip, lang)
post_text = tostring(
+
post_text = string.format(
mw.html.create('span')
+
'<span class="noprint" style="white-space: nowrap; font-size: 85%%;"> (%s)</span>',
:addClass('noprint')
+
iw_link
:css('white-space', 'nowrap')
  −
:css('font-size', '85%')
  −
:wikitext(' (' .. iw_link .. ')')
   
)
 
)
 +
 +
-- для шаблона "не переведено 2"
 
elseif mode == 2 then
 
elseif mode == 2 then
 
local iw_link = ''
 
local iw_link = ''
if lang == 'd' then
+
if leave then
return error{'шаблон Не переведено 2 не поддерживает Викиданные вместо языка'}
+
iw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { iw_text } }
 
else
 
else
local lang_template = mw.title.new('Template:Lang-' .. lang)
+
iw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { wikilink(iw_title, iw_text, iw_tooltip, 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
 
end
 
 
local addition = args['text'] or args['текст']
+
if is_empty(addition) then
if not is_empty(addition) then
+
post_text = string.format(' (%s)', iw_link)
addition = '; ' .. addition
+
else
else  
+
post_text = string.format(' (%s; %s)', iw_link,  addition)
addition = ''
   
end
 
end
post_text = ' (' .. iw_link .. addition .. ')'
+
 +
-- для шаблона "не переведено 3"
 
elseif mode == 3 then
 
elseif mode == 3 then
local ref = frame:expandTemplate{ title = 'ref-' .. lang, args = {} }
+
local ref = string.format(
post_text = '<span style="white-space: nowrap"><span class="noprint" style="font-size:95%; '
+
'<span style="font-size:95%%; position: relative; top: .4em;">%s</span>',
.. 'position: relative; top: .4em;">' .. ref .. '</span><span class="link-ru metadata noprint" '
+
frame:expandTemplate{ title = 'ref-' .. lang, args = {} }
.. 'style="font-size:80%; margin-left:-1.7em; position: relative; top: -.4em;">'
+
)
.. wikilink(title, 'русск.') .. '</span></span>'
+
local ru_link = string.format(
 +
'<span class="link-ru metadata" style="font-size:80%%; margin-left:-1.7em; position: relative; top: -.4em;">%s</span>',
 +
wikilink(title, 'русск.')
 +
)
 +
post_text = string.format(
 +
'<span class="noprint" style="white-space: nowrap;">%s%s</span>',
 +
ref, ru_link
 +
)
 +
 +
-- для шаблона "не переведено 4"
 
elseif mode == 4 then
 
elseif mode == 4 then
 
local styles = ''
 
local styles = ''
Строка 237: Строка 257:  
styles = 'margin-right:0.5em;'
 
styles = 'margin-right:0.5em;'
 
end
 
end
post_text = '<sup class="noprint" style="font-style:normal; margin-left:2px; position:relative; top:-1px;">'
+
.. wikilink(title, 'ru', 'Статья «' .. title .. '» в русском разделе отсутствует') .. '</sup>'
+
local ru_link = string.format(
.. '<sub class="noprint" style="font-style:normal; margin-left:-0.94em; ' .. styles .. '" title="По ссылке доступна статья на '
+
'<sup class="noprint" style="margin-left:2px; position:relative; top:-1px;">%s</sup>',
.. prepositional(lang) .. '">' .. lang .. '</sub>'
+
wikilink(title, 'ru', 'Статья «' .. title .. '» в русском разделе отсутствует')
 +
)
 +
local ref = string.format(
 +
'<sub class="noprint" style="margin-left:-0.94em; %s" title="По ссылке доступна статья на %s">%s</sub>',
 +
styles, prepositional(lang), lang
 +
)
 +
post_text = string.format('%s%s', ru_link, ref)
 +
 +
-- для шаблона "не переведено 5"
 
else
 
else
post_text = '<sup class="iw__note noprint" style="font-style:normal; font-weight:normal;">'
+
post_text = string.format(
.. string.format('[[:%s:%s|<span class="iw__tooltip" title="%s">[%s]</span>]]</sup>', lang, iw_title, iw_tooltip, lang)
+
'<sup class="noprint">%s</sup>',
 +
wikilink(iw_title, '[' .. lang .. ']', iw_tooltip, lang)
 +
)
 
end
 
end
 
end
 
end
 
 
-- форматирование третьей части - уведомления о существовании страницы
+
if mode == 3 or mode == 4 or mode == 5 then -- TODO: или для всех?
 +
post_text = string.format('<span style="font-style:normal; font-weight:normal;">%s</span>', post_text)
 +
end
 +
 +
-- формирование третьей части - уведомления о существовании страницы
 
local exist_message = ''
 
local exist_message = ''
if exists then
+
if leave then
if allow_cat and (mode ~= 5 or not ru_page.isRedirect) then
+
local exist_message_link
categories = categories .. orphan_categories['outdated']
+
if mode == 5 then
end
+
if ru_page.isRedirect then
if allow_cat and (mode == 5 and ru_page.isRedirect) then
+
exist_message_link = 'Шаблон:' .. template_name .. '#Если существует перенаправление'
categories = categories .. orphan_categories['redirect']
+
else
 +
exist_message_link = 'Шаблон:' .. template_name .. '#Если существует статья'
 +
end
 +
else
 +
exist_message_link = 'Шаблон:' .. template_name .. '#Действия после появления страницы'
 
end
 
end
 
 
 
if mode == 5 and ru_page.isRedirect then
 
if mode == 5 and ru_page.isRedirect then
exist_message = '<sup class="iw__notice noprint" style="font-style:normal; font-weight:normal; margin:0 0 0 1px;">'
+
exist_message = string.format(
.. '[[Шаблон:Не переведено 5#Если существует перенаправление|'
+
'<sup class="noprint" style="margin:0 0 0 1px;">%s</sup>',
.. '<span style="color:red; font-weight:bold;" title="Замените название перенаправления на название статьи либо уберите шаблон «Не переведено 5»">*</span>]]'
+
wikilink(exist_message_link, '*', 'Замените название перенаправления на название статьи либо уберите шаблон «' .. template_name .. '»', nil, 'color:red;')
.. '</sup>'
+
)
 
else
 
else
local template_name = 'Не переведено'
+
exist_message = string.format(
if mode ~= 1 then
+
'<sup class="noprint">%s</sup>',
template_name = template_name .. ' ' .. tostring(mode)
+
wikilink(exist_message_link, '?!', 'Уберите шаблон «' .. template_name .. '» из статьи и замените его простой вики-ссылкой', nil, 'color:red;')
end
+
)
+
end
local exist_message_link
+
if mode == 5 then
+
exist_message = string.format('<span style="font-style:normal; font-weight:bold;">%s</span>', exist_message)
exist_message_link = 'Шаблон:' .. template_name .. '#Если существует статья'
+
end
else
+
exist_message_link = 'Шаблон:' .. template_name .. '#Действия после появления страницы'
+
local categories_text = ''
end
+
if allow_cat then
+
for _, code in pairs(categories_list) do
exist_message = '<sup class="iw__notice noprint">[[' .. exist_message_link .. '|'
+
categories_text = categories_text .. '[[Category:' .. categories[code] .. ']]'
.. '<span style="color:red; font-style:normal; font-weight:bold;" title="Уберите шаблон «' ..template_name .. '» из статьи '
  −
.. 'и замените его простой вики-ссылкой">?!</span>]]</sup>'
   
end
 
end
 
end
 
end
 
 
 
local result
 
local result
if mw.isSubsting() then
+
if mode == 2 then
result = main_text .. post_text
+
result = main_text .. exist_message .. post_text .. categories_text
 
else
 
else
if mode == 2 then
+
result = main_text .. post_text .. exist_message .. categories_text
result = main_text .. exist_message .. post_text .. categories
  −
else
  −
result = main_text .. post_text .. exist_message .. categories
  −
end
  −
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" data-title="%s" data-lang="%s"' .. langName .. '>', class, ucfirst_title, lang)
  −
.. result .. '</span>'
   
end
 
end
 
 
Анонимный участник

Реклама:

Навигация