Módulo:Alto uso

Origem: Wikipédia, a enciclopédia livre.
local p = {}

-- "_fetch" examina o argumento "demo"
local _fetch = require('Módulo:Testes/Gkiyoshinishimoto/Transclusion_count').fetch
local yesno = require('Módulo: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
	
	-- Constrói a sequência ('string') de saída
	local return_value = ""
	if count == nil then
		if frame.args[1] == "risk" then
			return_value = "um número muito grande de"
		else
			return_value = "muitas"
		end
	else
		-- Usa 2 algarismos significativos para números menores e 3 para os maiores
		local sigfig = 2
		if count >= 100000 then
			sigfig = 3
		end
		
		-- Prepara para arredondar para o número apropriado de "sigfigs"
		local f = math.floor(math.log10(count)) - sigfig + 1
		
		-- Arredonda e insere "aproximadamente" ou "+" quando apropriado
		if (frame.args[2] == "yes") or (mw.ustring.sub(frame.args[1],-1) == "+") then
			-- Arredonda para baixo
			return_value = string.format("%s+", mw.getContentLanguage():formatNum(math.floor( (count / 10^(f)) ) * (10^(f))) )
		else
			-- Arredonda para o mais próximo
			return_value = string.format("aproximadamente %s", mw.getContentLanguage():formatNum(math.floor( (count / 10^(f)) + 0.5) * (10^(f))) )
		end

		-- Insere a porcentagem de páginas se for >= 1% e quando "|no-percent=" não estiver definido como sim
		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 páginas, ou aproximadamente %s%% de todas", return_value, percent)
			end
		end	
	end
	
	return return_value
end

-- Ações se houver uma contagem de transclusões grande (maior ou igual a 100.000)
function p.risk(frame)
	local return_value = ""
	if frame.args[1] == "risk" then
		return_value = "risco"
	else
		local count = _fetch(frame)
		if count and count >= 100000 then return_value = "risco" end
	end
	return return_value
end

function p.text(frame, count)
	-- Só mostra as informações sobre como este modelo é atualizado se alguém 
	-- estiver realmente editando a página e talvez tentando atualizar a contagem.
	local bot_text = (frame:preprocess("{{REVISIONID}}") == "") and "\n\n----\n'''Mensagem de pré-visualização''': Contagem de transclusões atualizada automaticamente.<!-- ([[:en:Template:High-use/doc#Technical details|ver documentação]]). -->" 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 == "doc" or title.subpageText == "Testes" then
		title = title.basePageTitle
	end
	
	local systemMessages = frame.args['system']
	if frame.args['system'] == '' then
		systemMessages = nil
	end
	
	-- Isso recupera o localizador de recursos uniforme (L.R.U., 'U.R.L.') do projeto automaticamente para simplificar a localização
	local templateCount = ('em [https://linkcount.toolforge.org/index.php?project=%s&page=%s %s páginas]'):format(
		mw.title.getCurrentTitle():fullUrl():gsub('//(.-)/.*', '%1'),
		mw.uri.encode(title.fullText), p.num(frame, count))
	local used_on_text = "'''Est" .. (mw.title.getCurrentTitle().namespace == 828 and "e módulo ''Lua''" or "a predefinição") .. ' é usad' .. (mw.title.getCurrentTitle().namespace == 828 and "o " or "a ");
	if systemMessages then
		used_on_text = used_on_text .. systemMessages ..
			((count and count > 2000) and ("''', e " .. templateCount) or ("'''"))
	else
		used_on_text = used_on_text .. templateCount .. "'''"
	end
	
	
	local sandbox_text =  ("subpáginas, [[%s/Testes|/Testes]] ou [[%s/Exemplos para testes|/Exemplos para testes]] " .. (mw.title.getCurrentTitle().namespace == 828 and "do " or "da ") .. "%s, ou em sua própria [[%s]]. "):format(
		title.fullText, title.fullText,
		(mw.title.getCurrentTitle().namespace == 828 and "módulo" or "predefinição"),
		mw.title.getCurrentTitle().namespace == 828 and "Módulo:Testes|subpágina de testes de módulos" or "Wikipédia:Página de usuário#Subpáginas|subpágina de usuário"
	)
	
	local infoArg = frame.args["info"] ~= "" and frame.args["info"]
	if (systemMessages or frame.args[1] == "risk" or (count and count >= 100000) ) then
		local info = systemMessages and '.<br/>As mudanças, feitas aqui, podem causar mudanças imediatas na <i>interface</i> de usuário da Wikipédia.' or '.'
		if infoArg then
			info = info .. "<br />" .. infoArg
		end
		sandbox_text = info .. '<br /> Para evitar grandes transtornos' ..
			(count and count >= 100000 and ' e carga do servidor' or '') ..
			', quaisquer mudanças devem ser testadas nas ' .. sandbox_text ..
			'As mudanças testadas podem ser adicionadas a essa página em uma única edição. '
	else
		sandbox_text = (infoArg and ('.<br />' .. infoArg .. ' A') or ' e a') ..
			's mudanças podem ser amplamente notadas. Teste as mudanças nas ' .. sandbox_text
	end

	
	local discussion_text = systemMessages and 'Por favor, discuta as mudanças ' or 'Considere discutir as mudanças '
	if frame.args["2"] and frame.args["2"] ~= "" and frame.args["2"] ~= "yes" then
		discussion_text = string.format("%sem [[%s]]", discussion_text, frame.args["2"])
	else
		discussion_text = string.format("%sna [[%s|página de discussão]]", discussion_text, title.talkPageTitle.fullText )
	end
	
	return used_on_text .. sandbox_text .. discussion_text .. " antes de implementá-las." .. 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 = "[[Ficheiro:Ambox warning yellow.svg|40px|alt=Aviso|link=]]"
	local type_param = "style"
	local epilogue = ''
	if frame.args['system'] and frame.args['system'] ~= '' then
		image = "[[Ficheiro:Ambox important.svg|40px|alt=Aviso|link=]]"
		type_param = "content"
		local nocat = frame:getParent().args['nocat'] or frame.args['nocat']
		local categorise = (nocat == '' or not yesno(nocat))
		if categorise then
			epilogue = frame:preprocess('{{Testes outro||{{#switch:{{#invoke:Nível efetivo de proteção|{{#switch:{{NAMESPACE}}|File=upload|#default=edit}}|{{FULLPAGENAME}}}}|sysop|templateeditor|interfaceadmin=|#default=[[Categoria:!Páginas usadas em mensagens do sistema que precisam de proteção]]}}}}')
		end
	elseif (frame.args[1] == "risk" or (count and count >= 100000)) then
		image = "[[Ficheiro:Ambox warning orange.svg|40px|alt=Aviso|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('Módulo:Message box').main('ombox', {
			type = type_param,
			image = image,
			text = p.text(frame, count),
			expiry = (frame.args["expiry"] or "")
		}) .. epilogue
	end
end

return p