Módulo:Lista de arquivos

Fonte: Enciclopédia de conhecimento da Igreja de Deus
Saltar para a navegação Saltar para a pesquisa

A documentação para este módulo pode ser criada na página Módulo:Lista de arquivos/doc

-- Processar um argumento numérico para ter certeza que é um positivo
-- inteiro.
local function processNumArg( num )
				if num then
								num = tonumber( num )
								if type( num ) == 'number' then
												num = math.floor( num )
												if num >= 0 then
																return num
												end
								end
				end
				return nil
end
-- Verifica se existe uma página, passando por pcall
local function checkPageExists( title )
				if not title then
								error('Nenhum título passou em checkArchiveExists', 2)
				end
				local noError, titleObject = pcall(mw.title.new, title)
				if not noError then
								-- Se está acima do limite da função, então assumimos
								-- que a página não existe.
								return false
				else
								if titleObject then
												return titleObject.exists
								else
												return false -- Retornará falso se for dado um título ruim.
								end
				end
end
-- Checa cada Arquivo n para ver se ele existe, e retorna o
-- o número do primeiro Arquivo que não existe. É
-- necessário fazer isso em lotes, porque cada checagem é uma
-- função longa e nós queremos evitar fazer demasiadas
-- deles de modo a não exceder o limite de função.
local function checkArchives( prefixo, n, inicio )
				local i = inicio
				local exists = true
				while exists do
								exists = checkPageExists( prefixo .. tostring( i ) )
								if exists then
												i = i + n
								end
				end
				return i
end
-- Retorna o maior número do Arquivo, utilizando checkArchives()
-- e iniciando em intervalos de 1000. Isto deve levar-nos a
-- mmáximo de 500.000 arquivos possíveis antes ir para a
-- o limite da função
local function getBiggestArchiveNum( prefixo, max )
				-- Retorna o valor para max se for especificado.
				max = processNumArg( max )
				if max then
								return max
				end
				
				-- Caso contrário, detecta o maior número do Arquivo.
				local check1000 = checkArchives( prefixo, 1000, 1 )
				if check1000 == 1 then
								return 0 -- Retorna 0 se nenhum Arquivo fr encontrado.
				end
				local check200 = checkArchives( prefixo, 200, check1000 - 1000 )
				local check50 = checkArchives( prefixo, 50, check200 - 200 )
				local check10 = checkArchives( prefixo, 10, check50 - 50 )
				local check1 = checkArchives( prefixo, 1, check10 - 10 )
				-- check1 é a primeira página que não existe, por isso queremos
				-- subtrai-lo por um para encontrar o maior arquivo existente.
				return check1 - 1
end
-- Retorna o link do prefixo do Arquivo (o título das páginas de Arquivos
-- menos o número).
local function getPrefixo( raiz, prefixo, prefixoEsp )
				local ret = raiz or mw.title.getCurrentTitle().prefixedText
				ret = ret .. '/'
				if prefixo then
								ret = ret .. prefixo
								if prefixoEsp == 'sim' then
												ret = ret .. ' '
								end
				else
								ret = ret .. 'Arquivo '
				end
				return ret
end
-- Retorna o número de arquivos para colocar em uma linha. Definido como
-- math.huge se não deve haver quebras de linha.
local function getLineNum( links, nobr, isLongo )
				local linksToNum = tonumber( links )
				local lineNum
				if nobr == 'sim' or (links and not linksToNum) then
								lineNum = math.huge
				-- Se links é um número, é processado. Os valores negativos e expressões
				-- como links=8/2 vamos ignorar para simplificar.
				elseif type(linksToNum) == 'number' and linksToNum >= 0 then
								lineNum = math.floor( linksToNum )
								if lineNum == 0 then
												lineNum = math.huge
								end
				else
					if isLongo==true then
						lineNum = 3 -- Padrão de 3 links no longo
					else
									lineNum = 10 -- Padrão de 10 no curto
								end
				end
				return lineNum
end
-- Obtém o prefixo para colocar antes dos links de arquivos.
local function getLinkPrefixo( prefixo, esp, isLongo )
				-- Retorna o link do prefixo.
				local ret = ''
				if isLongo==true then 
					if type(prefixo) == 'string' then
						if prefixo == 'nenhum' then -- 'nenhum' substitui o prefixo vazio
							ret = ''
							else
								ret = prefixo
								if esp == 'sim' then
									ret = ret .. ' '
								end
				end
			else
				ret = 'Arquivo '
		end
	else --Tipo não é longo
		if type(prefixo) == 'string' then
									ret = prefixo
									if esp == 'sim' then
													ret = ret .. ' '
									end
					end
				end
				return ret
end
-- Retorna o número para começar a listar os arquivos.
local function getInicio( inicio )
				inicio = processNumArg( inicio )
				if inicio then
								return inicio
				else
								return 1
				end
end
-- Processa o parâmetro separador.
local function getSeparator( sep )
				if sep and type(sep) == 'string' then
								if sep == 'dot' 
												or sep =='pipe'
												or sep == 'comma'
												or sep == 'tpt-languages' then
												return mw.message.new( sep .. '-separator' ):plain()
								else
												return sep
								end
				else
								return nil
				end
end
-- Gera a lista de links de Arquivos. glargs.max deve ser zero (para
-- sem arquivos) ou um valor inteiro positivo.
local function generateLinks( glargs )
				if type( glargs ) ~= 'table' or not glargs.max or not glargs.prefixo then
								error('argumentos insuficientes passados para generateLinks', 2)
				end
				-- Se não houver arquivos ainda, retorna uma mensagem e um
				-- link para criar o Arquivo um
				if glargs.max == 0 then
					if glargs.isLongo == true then
						glargs.max = 1 -- Um link vermelho de Arquivo é mostrado no formato Longo
					else -- Erro e link para criar um arquivo é mostrado no formato curto
									return 'sem arquivos ainda ([[' .. glargs.prefixo .. '1|criar]])' 
								end
				end
				-- Retorna um erro em html se o número de inicio é maior que o 
				-- número máximo.
				local inicio = glargs.inicio or 1
				if inicio > glargs.max then
								return '<span class="error">Valor de inicio "' 
												.. tostring( inicio ) 
												.. '" é maior do que o número do Arquivo mais recente "' 
												.. tostring( glargs.max ) 
												.. '".</span>'
				end
				local linkPrefixo = glargs.linkPrefixo or ''
								local lineNum = glargs.lineNum or 10
				local sep = '' -- O valor separador de Longo é um elemento de cécula, na versão cruta é ', '
				local linhaSep = '' -- Quabra de linha padrão de Longo são elementos de linha, na versão curta é '\n'
				if glargs.isLongo==true then 
					sep = glargs.sep or ''
					sep = sep .. '</td><td>'
					linhaSep = glargs.linhaSep or ''
		linhaSep = linhaSep .. '</td></tr><tr><td>'
				else
					sep = glargs.sep or mw.message.new( 'comma-separator' ):plain()
					linhaSep = glargs.linhaSep or '<br />'
				end
				-- Gera os links dos Arquivos.
				local lineCounter = 1 -- O contador para ver se precisamos de uma quebra de linha ou não.
				local ret = {} -- Uma tabela contendo os valores para serem devolvidos.
				if glargs.isLongo == true then --Versão Longo é uma tabela
					table.insert(ret, "<table style=\"width: 100%; padding: 0px; text-align: center; background-color: transparent;\"><tr><td>")
				end
				for archiveNum = inicio, glargs.max do
								local link = mw.ustring.format(
												'[[%s%d|%s%d]]',
												glargs.prefixo, archiveNum, linkPrefixo, archiveNum
								)
								table.insert( ret, link )
								-- Se nós não precisamos de uma nova linha é poduzida uma vírgula. Nós não precisamos
								-- de uma vírgula depois do último arquivo. 
								if lineCounter < lineNum and archiveNum < glargs.max then
												table.insert( ret, sep )
												lineCounter = lineCounter + 1
								-- Produz novas linhas se nencessário. Nós não precisamos de uma nova linha após
								-- o último link.
								elseif lineCounter >= lineNum and archiveNum < glargs.max then
												table.insert( ret, linhaSep )
												lineCounter = 1
								end
				end
				if glargs.isLongo == true then --Versão Longo é uma tabela
					table.insert(ret, "</td></tr></table>")
				end
				return table.concat( ret )
end
-- Determinar se o formato deve ser longo
local function findFormType( auto )
	if auto == nil or auto == '' then
		return false
	elseif auto == 'longo' then
			return true
	else
		return false
	end
end
-- Obteém os dados de arquivo e passando para generateLinks().
local function _principal( args )
	local isLongo = findFormType( args.auto )
				local prefixo = getPrefixo( args.raiz, args.prefixo, args.prefixoesp )
				local max = getBiggestArchiveNum( prefixo, args.max )
				local lineNum = getLineNum( args.links, args.nobr, isLongo )
				local linkPrefixo = getLinkPrefixo( args.linkprefixo, args.linkprefixoesp, isLongo )
				local inicio = getInicio( args.inicio )
				local sep = getSeparator( args.sep )
				local linhaSep = getSeparator( args.linhasep )
				local glargs = {
								inicio = inicio,
								max = max,
								prefixo = prefixo,
								linkPrefixo = linkPrefixo,
								isLongo = isLongo,
								sep = sep,
								lineNum = lineNum,
								linhaSep = linhaSep
				}
				return generateLinks( glargs )
end
-- A função de mensagens para fazer getBiggestArchiveNum() disponível a partir de
-- #invoke.
local function _cont( args )
				local prefixo = getPrefixo( args.raiz, args.prefixo, args.prefixoesp )
				local archiveMax = getBiggestArchiveNum( prefixo )
				return archiveMax
end
function makeWrapper( func )
				return function( frame )
								-- Se chamado a partir de #invoke, retorna os args de #invoke
								-- se existem, ou então se os argumentos passados para os quadros
								-- parentes. Caso contrário, assume os argumentos estão sendo passados diretamente
								-- a partir de outro módulo ou a partir do console de depuração.
								local origArgs
								if frame == mw.getCurrentFrame() then
												origArgs = frame:getParent().args
												for k, v in pairs( frame.args ) do
																origArgs = frame.args
																break
												end
								else
												origArgs = frame
								end
								
								-- Ignorar valores de parâmetros em branco, exceto "links",
								-- que funciona de forma diferente dependendo se se trata de
								-- de branco ou ausente.
								local args = {}
								for k, v in pairs( origArgs ) do
												if k == 'links' or v ~= '' then
																args[k] = v
												end
								end
								
								return func( args )
				end
end
return {
				principal = makeWrapper( _principal ),
				cont = makeWrapper( _cont )
}