Модуль:High-use

Матеріал з Вікіпедії — вільної енциклопедії.
Перейти до навігації Перейти до пошуку
{{i}} Документація модуля[перегляд] [редагувати] [історія] [очистити кеш]

Впроваджує {{High-use}}. Використовує значення, що оновлюються ботом, з підсторінок Module:Transclusion_count/data/, коли наявні.

Використання[ред. код]

{{#invoke:High-use|main|1=кількість включень|2=сторінка обговорення або використання запису із +|all-pages=|info=|demo=|form=|expiry=}}

  • number of transclusions: Перший параметр є статичним числом кількості включень шаблону або словом «risk» (без лапок), щоб відобразити текст «дуже великій кількості сторінок» замість справжнього значення. Значення цього параметра ігнорується, якщо наявні дані включень для цієї сторінки.
  • сторінка обговорення або використання запису із +: Другий параметр є перевантаженим. Якщо встановлено значення «yes» (без лапок), то кількість включень відобразиться як «## ###+» замість «близько ## ###». Коли використано цей метод запису, то округлення відбувається в меншу сторону замість округлення до найближчого числа відповідною кількістю значущих цифр. Коли вказано будь-яке інше не пусте значення, то буде замінено посилання, що веде на сторінку обговорення шаблону, на значення, яке вказане в параметрі (наприклад, 2=ВП:КТП вставить посилання на ВП:КТП),
  • |all-pages=yes: Також відображатиме відсоток скільки сторінок використовують шаблон від усієї кількості сторінок. Це повинно використовуватися лише для шаблонів з дуже великою кількістю включень, а відсоток відображуватиметься лише, якщо він більший за 1%.
  • |info=додаткова інформація: Коли вказано непусте значення, то вставляється додаткова інформація в текст шаблону, якщо шаблон має більше ніж 10 000 включень або вказано значення «risk» в параметрі 1.
  • |demo=Назва_шаблону: буде використовувати кількість включень для шаблону Шаблон:Назва_шаблону замість визначення назви шаблону зі сторінки, де використано цей модуль. Капіталізація має точно відповідати значенню, що вказано в Спеціальна:Покажчик за початком назви/Module:Transclusion_count/data/.
  • |form=: Коли встановлено значення «editnotice», то повідомлення відображається за використанням {{editnotice}} замість {{ombox}}.
  • |expiry=: Встановлює параметр |expiry= для {{editnotice}}.
  • |system=в системних повідомленнях: якщо його зазначити, то цей модуль виглядатиме як {{Використовується в системі}}.
  • |fetch=: якщо вказано false, то модуль не намагатиметься отримати дані включень з модуля Модуль:Transclusion count.

Інші функції[ред. код]

num
Створює текст і посилання на toolforge з приводу кількості включень.
risk
При виклику цієї функції, якщо передано risk в перший неназваний параметр або є вже більше ніж 100k включень, то вона поверне risk.
text
Повертає текст тіла цього шаблону, зі значенням кількості включень або nil.

{{#invoke:High-use|назва функції}}

local p = {}

-- _fetch looks at the "demo" argument.
local _fetch = require('Module:Transclusion_count').fetch
local yesno = require('Module:Yesno')

function p.num(frame, count)
	if count == nil then
		if yesno(frame.args['fetch']) == false then
			if (frame.args[1] or '') ~= '' then count = tonumber(frame.args[1]) end
		else
			count = _fetch(frame)
		end
	end
	
	-- Build output string
	local return_value = ""
	if count == nil then
		if frame.args[1] == "risk" then
			return "дуже великій кількості сторінок"
		else
			return "багатьох сторінках"
		end
	else
		-- Use 2 significant figures for smaller numbers and 3 for larger ones
		local sigfig = 2
		if count >= 100000 then
			sigfig = 3
		end
		
		-- Prepare to round to appropriate number of sigfigs
		local f = math.floor(math.log10(count)) - sigfig + 1
		
		-- Round and insert "approximately" or "+" when appropriate
		if (frame.args[2] == "yes") or (mw.ustring.sub(frame.args[1],-1) == "+") then
			-- Round down
			return_value = string.format("%s+ сторінках", mw.getContentLanguage():formatNum(math.floor( (count / 10^(f)) ) * (10^(f))) )
		else
			-- Round to nearest
			return_value = string.format("близько %s сторінках", mw.getContentLanguage():formatNum(math.floor( (count / 10^(f)) + 0.5) * (10^(f))) )
		end

		-- Insert percentage of pages if that is likely to be >= 1% and when |no-percent= not set to yes
		if count and count > 250000 and not yesno (frame:getParent().args['no-percent']) then
			local percent = math.floor( ( (count/frame:callParserFunction('NUMBEROFPAGES', 'R') ) * 100) + 0.5)
			if percent >= 1 then
				return_value = string.format("%s  або близько %s%% всіх сторінок", return_value, percent)
			end
		end	
	end
	
	return return_value
end

-- Actions if there is a large (greater than or equal to 100,000) transclusion count
function p.risk(frame)
	if frame.args[1] == "risk" then
		return "risk"
	else
		local count = _fetch(frame)
		if count and count >= 100000 then
			return "risk"
		end
	end
	return ""
end

function p.text(frame, count)
	-- Only show the information about how this template gets updated if someone
	-- is actually editing the page and maybe trying to update the count.
	local bot_text = --[[ (frame:preprocess("{{REVISIONID}}") == "") and "\n\n----\n'''Preview message''': Transclusion count updated automatically (Template:High-use/doc#Technical details|see documentation)." or ]] ''
	
	if count == nil then
		if yesno(frame.args['fetch']) == false then
			if (frame.args[1] or '') ~= '' then count = tonumber(frame.args[1]) end
		else
			count = _fetch(frame)
		end
	end
	local title = mw.title.getCurrentTitle()
	if title.subpageText == "документація" or title.subpageText == "пісочниця" then
		title = title.basePageTitle
	end
	
	local systemMessages = frame.args['system']
	if frame.args['system'] == '' then
		systemMessages = nil
	end
	
	-- This retrieves the project URL automatically to simplify localiation.
	local is_module = mw.title.getCurrentTitle().namespace == 828
	local templateCount = ('на [https://linkcount.toolforge.org/index.php?project=%s&page=%s %s]'):format(
		mw.title.getCurrentTitle():fullUrl():gsub('//(.-)/.*', '%1'),
		mw.uri.encode(title.fullText), p.num(frame, count))
	local used_on_text = "'''Цей " .. (is_module and "модуль Lua" or "шаблон") .. ' використовується ';
	if systemMessages then
		used_on_text = used_on_text .. systemMessages ..
			((count and count > 2000) and ("''' і " .. templateCount) or ("'''"))
	else
		used_on_text = used_on_text .. templateCount .. "'''"
	end
	
	

	local sandbox_text =  ("підсторінках [[%s/пісочниця|/пісочниці]] та [[%s/тести|/тестів]] цього %s, або у ваш%s [[%s]]"):format(
		title.fullText, title.fullText,
		(is_module and "модуля" or "шаблону"),
		is_module and "ій" or "ому",
		is_module and "Модуль:Пісочниця|пісочниці модуля" or "Вікіпедія:Підсторінки#Як створювати користувацькі підсторінки|особистому просторі"
	)
	
	local is_risk = frame.args[1] == "risk" or (count and count >= 100000)
	local infoArg = frame.args["info"] ~= "" and frame.args["info"]
	if (systemMessages or is_risk ) then
		local info = systemMessages and '.<br/>Його зміни можуть призвести до миттєвих змін у користувацькому інтерфейсі Вікіпедії.' or '.'
		if infoArg then
			info = info .. "<br />" .. infoArg
		end
		sandbox_text = info .. '<br /> Для уникнення великомасштабних збоїв' ..
			(count and count >= 100000 and ' та непотрібного навантаження на сервер' or '') ..
			(', будь-які зміни спочатку потрібно перевірити на ') .. sandbox_text ..
			'. Потім перевірені зміни можуть бути впроваджені на цій сторінці єдиним редагуванням. '
	else
		sandbox_text = (infoArg and ('.<br />' .. infoArg .. ' Й') or ' і й') ..
			'ого зміни будуть дуже помітними. Будь ласка, перевіряйте будь-які зміни на ' .. sandbox_text
	end

	
--	local discussion_text = systemMessages and 'Будь ласка, обговорюйте будь-які зміни ' or ', та зважайте на обговорення змін ' (реалізація англ. вікі)
	local discussion_text = (systemMessages or is_risk) and 'Будь ласка, обговорюйте будь-які зміни ' or ', та зважайте на обговорення змін '
	if frame.args["2"] and frame.args["2"] ~= "" and frame.args["2"] ~= "yes" then
		discussion_text = string.format("%sна [[%s]]", discussion_text, frame.args["2"])
	else
		discussion_text = string.format("%sна [[%s|сторінці обговорення]]", discussion_text, title.talkPageTitle.fullText )
	end
	
	return used_on_text .. sandbox_text .. discussion_text .. " перед їхнім впровадженням." .. bot_text
end

function p.main(frame)
	local count = nil
	if yesno(frame.args['fetch']) == false then
		if (frame.args[1] or '') ~= '' then count = tonumber(frame.args[1]) end
	else
		count = _fetch(frame)
	end
	local image = "[[File:Ambox warning yellow.svg|40px|alt=Увага|link=]]"
	local type_param = "style"
	local epilogue = ''
	if frame.args['system'] and frame.args['system'] ~= '' then
		image = "[[File:Ambox important.svg|40px|alt=Увага|link=]]"
		type_param = "content"
		local nocat = frame:getParent().args['nocat'] or frame.args['nocat']
		local categorise = (nocat == '' or not yesno(nocat))
		if categorise and not mw.title.getCurrentTitle().isRedirect then
			epilogue = frame:preprocess('{{Sandbox other||{{#switch:{{#invoke:Effective protection level|{{#switch:{{NAMESPACE}}|File=upload|#default=edit}}|{{FULLPAGENAME}}}}|sysop|interfaceadmin=|#default=[[Category:Сторінки, що використані в системних повідомленнях та потребують захисту]]}}}}')
		end
	elseif (frame.args[1] == "risk" or (count and count >= 100000)) then
		image = "[[File:Ambox warning orange.svg|40px|alt=Увага|link=]]"
		type_param = "content"
	end
	
	if frame.args["form"] == "editnotice" then
		return frame:expandTemplate{
				title = 'editnotice',
				args = {
						["image"] = image,
						["text"] = p.text(frame, count),
						["expiry"] = (frame.args["expiry"] or "")
				}
		} .. epilogue
	else
		return require('Module:Message box').main('ombox', {
			type = type_param,
			image = image,
			text = p.text(frame, count),
			expiry = (frame.args["expiry"] or "")
		}) .. epilogue
	end
end

return p