Ir para o conteúdo

Módulo:InfoboxImage

De Wiki TokuDrive
Revisão de 04h55min de 5 de julho de 2026 por Tavoraadmin (discussão | contribs) (Importando predefinição/módulo da Wikipédia em português para manter layout)
(dif) ← Edição anterior | Revisão atual (dif) | Versão posterior → (dif)

-- Entradas (Inputs): -- image / imagem - Pode ser o nome puro do arquivo (com ou sem o prefixo Ficheiro:/File:) ou um link de imagem totalmente formatado. -- page / página - Página a ser exibida para imagens multipáginas (ex: arquivos DjVu). -- size / tamanho - Tamanho (largura) em que a imagem será exibida. -- maxsize / tamanhomáx - Tamanho máximo limite para a exibição da imagem. -- sizedefault / tamanhopadrão - Tamanho padrão a ser exibido caso o parâmetro de tamanho esteja em branco. -- alt - Texto alternativo (alt text) para acessibilidade da imagem. -- title / título - Texto de título/legenda interna para a imagem. -- border / borda - Define como "yes" (ou "sim") para adicionar uma borda ao redor da imagem. -- center / centro - Define como "yes" (ou "sim") se a imagem precisar ser centralizada. -- upright - Parâmetro multiplicador de tamanho relativo (upright). -- suppressplaceholder / suprimirsubstituto - Se definido como "yes" (ou "sim"), verifica se a imagem é um substituto padrão (placeholder) e a oculta. -- link / ligação - Página da wiki para onde o usuário será direcionado ao clicar na imagem. -- class / classe - Classes HTML personalizadas a serem adicionadas à tag da imagem. -- Saídas (Outputs): -- Imagem devidamente formatada em código MediaWiki. -- Mais detalhes disponíveis na página de documentação "Módulo:InfoboxImage/doc".

local i = {}

local defaultThumbnailSize = 220

-- Carrega o módulo utilitário para tratamento de valores booleanos (sim/não, yes/no) local yesno = require('Módulo:Yesno')

-- Otimização: Cache dos nomes válidos para o Namespace de Arquivos/Ficheiros uma única vez local fileNamespaces = {} do

   local ns6 = mw.site.namespaces[6]
   -- Insere o nome local (Ficheiro), o canônico (File) e todos os aliases existentes
   table.insert(fileNamespaces, mw.ustring.lower(ns6.name))
   table.insert(fileNamespaces, mw.ustring.lower(ns6.canonicalName))
   for _, alias in ipairs(ns6.aliases) do
       table.insert(fileNamespaces, mw.ustring.lower(alias))
   end

end

-- Função de categorização que consome o submódulo aplicando Lazy Loading (carregamento apenas quando necessário) local function trackingCat(catKey)

   local ns = mw.title.getCurrentTitle().nsText:lower()
   if ns == 'user' or ns == 'user talk' then return "" end
   
   local categories = mw.loadData('Módulo:InfoboxImage/data').categories
   return categories[catKey] or ""

end

-- Remove os prefixos de namespace (ex: "Ficheiro:", "File:") do início de uma string local function stripNamespace(imageName)

   imageName = mw.ustring.gsub(imageName, '^[ ]*(.-)[ ]*$', '%1') -- Trim original
   for _, name in ipairs(fileNamespaces) do
       local prefixLen = mw.ustring.len(name) + 1
       if mw.ustring.lower(mw.ustring.sub(imageName, 1, prefixLen)) == name .. ":" then
           imageName = mw.ustring.sub(imageName, prefixLen + 1)
           break
       end
   end
   return mw.ustring.gsub(imageName, '^[ ]*(.-)[ ]*$', '%1') -- Trim pós-remoção

end

function i.IsPlaceholder(image)

   image = mw.ustring.gsub(image, "_", " ")
   if mw.ustring.sub(image,1,2) == "[[" then
       image = mw.ustring.sub(image,3)
       image = mw.ustring.gsub(image, "([^|]*)|.*", "%1")
   end
   
   image = stripNamespace(image)
   image = mw.ustring.upper(mw.ustring.sub(image,1,1)) .. mw.ustring.sub(image,2)
   -- Carregamento tardio (Lazy Load) para otimização do parsing de tabelas de dados
   local placeholder_images = mw.loadData('Módulo:InfoboxImage/data').placeholder_image
   return placeholder_images[image] or false

end

local function isempty(x)

   return (not x) or x == ""

end

-- Esta função interna processa estritamente os argumentos normalizados function i._InfoboxImage(args)

   local image = args["image"]
   
   if isempty(image) then return "" end
   if image == " " then return image end
   
   if args["suppressplaceholder"] ~= "no" then
       if i.IsPlaceholder(image) == true then return "" end
   end
   
   if string.find(image, "^%[*https?:") then
       return trackingCat("url_image_links")
   end
   if mw.ustring.sub(image,1,2) == "[[" then
       local cat = ""
       if mw.title.getCurrentTitle().namespace == 0 and (mw.ustring.find(image, "|%s*thumb%s*[|%]]") or mw.ustring.find(image, "|%s*thumbnail%s*[|%]]")) then
           cat = trackingCat("thumbnail_images")
       end
       return image .. cat
   elseif mw.ustring.sub(image,1,2) == "{{" and mw.ustring.sub(image,1,3) ~= "{{{" then
       return image
   elseif mw.ustring.sub(image,1,1) == "<" then
       return image
   elseif mw.ustring.sub(image,1,8) == mw.ustring.char(127).."'\"`UNIQ" then
       return image
   else
       local result = ""
       local page = args["page"]
       local upright = args["upright"] or ""
       local size = args["size"]
       local maxsize = args["maxsize"]
       local sizedefault = args["sizedefault"]
       local alt = args["alt"]
       local link = args["link"]
       local title = args["title"]
       local border = args["border"]
       local thumbtime = args["thumbtime"] or ""
       local center = args["center"]
       local class = args["class"]
       
       image = stripNamespace(image)
       
       if not isempty(maxsize) then
           if isempty(sizedefault) and isempty(upright) then
               sizedefault = maxsize
           end
           local maxsizenumber = tonumber(mw.ustring.match(maxsize,"%d*")) or 0
           if not isempty(size) then
               local sizenumber = tonumber(mw.ustring.match(size,"%d*")) or 0
               if sizenumber > maxsizenumber and maxsizenumber > 0 then
                   size = maxsize
               end
           end
           if not isempty(upright) then
               local uprightnumber = tonumber(upright) or (upright == "yes" and 0.75) or 0
               if uprightnumber*defaultThumbnailSize > maxsizenumber and maxsizenumber > 0 then
                   upright = tostring(maxsizenumber/defaultThumbnailSize)
               end
           end
       end
       
       if (tonumber(size) or 0) > 0 then size = size .. "px" end
       if (tonumber(sizedefault) or 0) > 0 then sizedefault = sizedefault .. "px" end
       
       result = "[[Ficheiro:" .. image
       if not isempty(page) then result = result .. "|page=" .. page end
       
       if not isempty(size) then
           result = result .. "|" .. size
       elseif not isempty(sizedefault) and isempty(upright) then
           result = result .. "|" .. sizedefault
       else
           result = result .. "|frameless"
       end
       
       if center == "yes" then result = result .. "|center" end
       
       -- Validação Segura de Alt (Garante a checagem de palavras reservadas ANTES de embutir na string final)
       if not isempty(alt) then
           if alt ~= "thumbnail" and alt ~= "thumb" and alt ~= "frameless" and alt ~= "left" and alt ~= "center" and alt ~= "right" and alt ~= "upright" and alt ~= "border" and mw.ustring.match(alt, '^[0-9]*px$', 1) == nil then
               result = result .. "|alt=" .. alt
           end
       end
       
       if not isempty(link) then result = result .. "|link=" .. link end
       if border == "yes" then result = result .. "|border" end
       
       if upright == "yes" then
           result = result .. "|upright"
       elseif upright ~= "" then
           result = result .. "|upright=" .. upright
       end
       if thumbtime ~= "" then result = result .. "|thumbtime=" .. thumbtime end
       if not isempty(class) then result = result .. "|class=" .. class end
       
       if not isempty(title) then
           if mw.ustring.match(mw.getCurrentFrame():preprocess(title), 'UNIQ%-%-templatestyles', 1) == nil then
               result = result .. "|" .. title
           end
       end
       result = result .. "]]"
       
       return result
   end

end

-- Porta de entrada oficial chamada pela Predefinição function i.InfoboxImage(frame)

   local origArgs = frame.args
   local normalizedArgs = {}
   
   -- Mapeamento/Tradução dos parâmetros para o motor interno
   normalizedArgs["image"] = origArgs["image"] or origArgs["imagem"]
   normalizedArgs["page"] = origArgs["page"] or origArgs["página"]
   normalizedArgs["size"] = origArgs["size"] or origArgs["tamanho"]
   normalizedArgs["maxsize"] = origArgs["maxsize"] or origArgs["tamanhomáx"]
   normalizedArgs["sizedefault"] = origArgs["sizedefault"] or origArgs["tamanhopadrão"]
   normalizedArgs["alt"] = origArgs["alt"]
   normalizedArgs["link"] = origArgs["link"] or origArgs["ligação"]
   normalizedArgs["title"] = origArgs["title"] or origArgs["título"]
   normalizedArgs["thumbtime"] = origArgs["thumbtime"] or origArgs["tempominiatura"]
   normalizedArgs["class"] = origArgs["class"] or origArgs["classe"]
   
   -- Normalização robusta com Módulo:Yesno para flags booleanas
   local suppress = origArgs["suppressplaceholder"] or origArgs["suprimirsubstituto"]
   if yesno(suppress, true) then
       normalizedArgs["suppressplaceholder"] = "yes"
   else
       normalizedArgs["suppressplaceholder"] = "no"
   end
   
   if yesno(origArgs["border"] or origArgs["borda"]) then 
       normalizedArgs["border"] = "yes" 
   end
   
   -- Aceita 'sim', 'yes', 'centro' ou 'center'
   local centerArg = origArgs["center"] or origArgs["centro"]
   if yesno(centerArg) or centerArg == "centro" or centerArg == "center" then 
       normalizedArgs["center"] = "yes" 
   end
   -- Normalização do upright (Trata se o usuário passar 'sim', mapeando para o padrão 'yes')
   local uprightArg = origArgs["upright"]
   if yesno(uprightArg) then
       normalizedArgs["upright"] = "yes"
   else
       normalizedArgs["upright"] = uprightArg or ""
   end
   
   return i._InfoboxImage(normalizedArgs)

end

return i