[go: nahoru, domu]

Saltar para o conteúdo

Módulo:Infobox/Localidade

Permanently protected module
Origem: Wikipédia, a enciclopédia livre.

local localdata = require 'Módulo:Infobox/Localdata'
local general = require "Módulo:Infobox/Funções"
local wikidata = require "Módulo:Infobox/Wikidata"
local linguistic = require "Módulo:Linguística"
local convert = require "Módulo:Conversão"
local country = wikidata.stringTable{entity = localdata.item, property = "P17", displayformat = "raw"}
local countryid
if country then
    countryid = country[1]
end

local defaultlinks = { -- versão da Wikipedia para usar links na ausência de artigos portugueses
    Q29 = 'eswiki', -- Espanha
    Q17 = 'jawiki', -- Japão
    Q182 = 'dewiki', -- Alemanha
    Q40 = 'dewiki',    -- Áustria
    Q38 = 'itwiki', -- Itália
}
local defaultlink = {'enwiki'}
if defaultlinks[countryid] then
    table.insert(defaultlink, defaultlinks[countryid])
end


local function getVal(addargs) -- para uma dada propriedade, retorna o melhor valor, assim como sua data, sua referência, e se vem da Wikidata ou não
    local args = {numval = 1, entity = localdata.item, showunit = '-', displayformat = 'raw', precision = 'year'}
    for i, j in pairs(addargs or {}) do
        args[i] = j
    end
    local statements = wikidata.getClaims(args)
    if not statements then
        return nil
    end
    local val = statements[1]
    local v = wikidata.formatStatement(val, args)
    local period = wikidata.getFormattedDate(val, args)
     local ref = nil -- TODO : fonction dans Módulo:Wikidata pour récupérer les refs
    
     return v, period, ref, args.property
end



-- Funções de recuperação de dados válidas em vários campos (e chamadas várias vezes)

local pop, popdate, popref, popprop = localdata["população"], localdata["ano pop"], localdata["população notas"], nil
if not pop then
    pop, popdate, popref, popprop = getVal({property = "P1082", sorttype="inverted"})
end

local area, areadate, arearef, areaprop = localdata["superfície"], localdata["ano superfície"], localdata["superfície notas"], nil
if not area then
    area, areadate, arearef, areaprop = getVal({property = "P2046", targetunit = "square kilometer", sorttype="inverted"})
end

if pop then pop = tonumber(pop) end
if area then area = tonumber(area) end

-- Funções de formatação

local function formatVal(val, period, ref, prop)
    local s = tostring(val)
    if period then
        s = s .. "<small>" .. linguistic.inparentheses(period) .. "</small>"
    end
    if ref then
        s = s .. "<ref>" .. ref .. "</ref>"
    end
   
    if prop then
        s = wikidata.formatAndCat{entity = localdata.item, property = prop, value = s} -- permite colocar o trackback no final
    end
    return s
end

local function formatPop()
    if not pop then
        return nil
    end
   
    local popstr = convert.displayvalue(pop)
    popstr = string.gsub(popstr, "+", "") -- deve ser feito a montante
    popstr = popstr .. " hab."
   
    return formatVal(popstr, popdate, popref, popprop)
end

local function formatArea()
    if not area then
        return nil
    end

    -- arrondi
    local rounding = 2
    if area < 1 then
        rounding = 2
    end
   
    -- conversão para hectares se for muito pequena ?
   
    local areastr = convert.displayvalue(area, 'square kilometer', {showunit = true, rounding = rounding})
    return formatVal(areastr, areadate, arearef, areaprop)
end

local function density()
    -- TODO : verificar se a data da população corresponde à da área, para alguns casos de mudança de fronteira

    if not (pop and area) then
        return nil
    end
    local density = pop / area
    local rounding = 1
    if density < 0.1 then
        rounding = 2
    end
    local s = convert.displayvalue(density, nil, {rounding = rounding})
    s = s .. " hab./km<sup>2</sup>"
   
    return formatVal(s, popdate)
end

-- divisões administrativas

--- por parâmetros locais
local function localDivRows() -- lista de linhas de divisão administrativa com base em dados locais
    local rows = {}
    local hasrows = false -- torna-se verdadeiro se um valor não for nulo
    for i = 1, 10 do
        i = tostring(i)
        if i == "1" then
            i = ""
        end
        local param, labelparam = "divisão" .. i, "nome divisão" .. i --"nome de divisião" .. i
        if localdata[param] then
            hasrows = true
            local label = localdata[labelparam] or "Subdivision"
            table.insert(rows, {type = "row", label = label, value = function() return localdata[param] end})
        end
    end
    if hasrows then
        return rows
    end
end

--- por Wikidata
local function wikidataDivRows()  -- lista de linhas de divisão administrativa com base nos dados do Wikidata
    if not localdata.item then
        return nil
    end
    -- recuperação dos valores
    local list = wikidata.transitiveVals(localdata.item, {property = "P131", atdate = "today", excludespecial = true}, 3, 5, countryid)
    if not list then
        return nil
    end

    -- création des colonnes
    local rows = {}
    for i, div in pairs(list) do
        if (div == countryid) then
            break
        end
        local rowlabel, rowlabelid, rowlabeltext, rowlabellink, rowvalue
        rowlabelid = wikidata.formatStatements{entity= div, property = 'P31', numval = 1, displayformat = 'raw', excludespecial = true}
        rowlabeltext = wikidata.getLabel(rowlabelid, 'fr', function(id)
            local str = wikidata.getLabel(id)
            if str then
                return linguistic.ucfirst(linguistic.removecomplement(str))  -- imposta pela formulação não muito lógica do Wikidata do tipo "cantão da Suíça" em vez de "cantão"        else
            end
                return ''
            end
        )
        if (not rowlabeltext) then
            rowlabeltext = 'Divisão'
        end
        rowlabellink = wikidata.siteLink(rowlabelid, {defaultlink = '-', defaultlinkquery= {property = "P2354"}} ) -- se não houver link, link para a página da lista, por exemplo, lista de estados da Califórnia

        if rowlabellink then
            rowlabel = "[[" .. rowlabellink .. "|" .. rowlabeltext .. "]]"
        else
            rowlabel = rowlabeltext
        end
        rowvalue = wikidata.formatEntity(div, {labelformat = function(id)
            local str = wikidata.getLabel(id) or ""
            if mw.ustring.match(rowlabel, str) then
                str = linguistic.keepcomplement(str)-- se o nome da divisão administrativa exibida estiver presente, não o repita
            end
            return str
            end})
       
        table.insert(rows, 1, {type = "row", label = rowlabel, value = function() return rowvalue end})
    end
    return rows
end

--========================================

return
    {
    maincolor = "DDFFDD",
    parts =
        {
            general.title( "mapa"),
            {
            type = 'images',
            imageparameters =  {'brazão', 'bandeira'},
            wikidata = {property = {'P94', 'P41'}},
            numval = 2,
            defaultupright = '0.8'
            },   
            general.logo(),
            general.mainimage{
                cat = "!Subdivisão administrativa ilustrada por padrao.svg",
                defaultimage = "Padrao 2.svg",
                wikidata = {property = {"P2716", "P18", "P1766"}, numval = 1}
            },
            {type = "table", rows = {
                {type = "row", label = "Nome oficial", plurallabel = "Nome oficiais", value = "nome oficial", wikidata = {property = "P1448", showlang = true, showdate = true, precision = 'year', sorttype = 'chronological', conjtype = 'new line'} },
                {type = "row", label = "Nome local", plurallabel = "Nomes locais", value = "nom local", wikidata = {property = "P1705", showlang = true} },
                {type = 'row', label = 'Outro nome', plurallabel = "Outros nomes", value = "outro nome", property = 'P1449'}, -- outros nomes
                }
            },
            {type = "table", title = "Geografia", rows = {
                {type = 'row', label = 'Astro', value = 'astro', wikidata = { property = 'P376', excludevalue = 'Q2' }}, -- corpo astronômico onde o lugar é mencionado (útil para lugares fictícios)
                {type = "row", label = "Continente", plurallabel = "Continentes", value = "continente", property = "P30"},
                general.country(),
                {type = "multi", rows = localDivRows() or wikidataDivRows() or {}},   
                {type = "row", label = "Ilha", value = "ilha", property = "P5130"},
                {type = "row", label = "Localização geográfica", value = "localização geográfica", property = "P706"},
                {type = "row", label = "Parte de", value = "parte de", property = "P361"},
                {type = "row", label = "[[Sede de concelho]]", value = "sede de concelho", property = "P36"},
                {type = "row", label = "Capital de", value = "capital de", property = "P1376"},
                {type = "row", label = "Exclave de", value = "exclave de", property = "P500"},
                {type = "row", label = "Enclave em", value = "enclavé em", property = "P501"},
                {type = "row", label = "Revendicado por", value = "revendicado por", property = "P1336"},
                {type = "row", label = "Banhado por", value = "banhado por", property = "P206"},
                {type = "row", label = "Clima", plurallabel = "Climas", value = "clima", property = "P2564"},
                {type = "row", label = "Superfície", value = function() return formatArea() end },
                {type = "row", label = "Superfície da água", value = "superfície da água", property = "P2927"},
                {type = "row", label = "Subdivisão", plurallabel = "Subdivisões", value = "subdivisão", wikidata =
                    function(item)
                    local vals = wikidata.getClaims{entity = item, property = 'P150', atdate = 'today'}
                    if (not vals) or (#vals > 5) then -- se muitas subdivisões, é necessário colocar-me no corpo do texto, não é legível na infobox
                        return nil
                    end
                    return wikidata.formatAndCat{claims = vals, property = 'P150', defaultlink = defaultlink, conjtype = 'new line'}, #vals
                    end
                },
                {type = "row", label = "Ponto mais baixo", plurallabel = "Pontos mais baixos", value = "ponto mais baixo", property = "P1589"},
                {type = "row", label = "Ponto culminante", plurallabel = "Pontos culminantes", value = "ponto culminante", property = "P610"},
                {type = "row", label = "Altitude", value = "altitude", wikidata = {property = "P2044", targetunit = "metro", rounding = "0"} },
                {type = "row", label = "Área protegida", plurallabel = "Áreas protegidas", value = "área protegida", property = "P3018"},
                {type = "row", label = "Geografia", value = "geografia", property = "P2633"},
                general.coordenadas(),
                }
            },
            general.locationmap(),
            {type = "table", title = "Demografia", rows = {
                {type = "row", label = "População", value = function() return formatPop() end },
                {type = "row", label = "Nome de lares", value = "nome de lares", wikidata = {property = "P1538", showqualifiers = {"P585"} , sorttype="inverted", numval = 1}},
                {type = "row", label = "Densidade", value = function() return density() end},
                {type = "row", label = "Gentílico", value = "gentílico", property = "P1549"},
                {type = "row", label = "Taxa de desemprego", value = "taxa de desemprego", property = "P1198"},
                {type = "row", label = "Eleitorado", value = "elitorado", property = "P1831"},
                }
            },
            {type = "table", title = "Funcionamento", rows = {
                {type = "row", label = "Estatudo", value = "estatuto", wikidata = {property = "P31", excludevalues = {"Q515", "Q532", "Q486972", "Q123705", "Q3957", "Q3257686", "Q23413"}, defaultlinkquery = {property = "P2354"}, showdate = true}}, -- exclui valores que não correspondem a um status administrativo
                {type = 'row', label = 'Constituição', value = 'constituição'},
                {type = "row", label = "Chefe do Executivo", value = "chefe do executivo", wikidata = {property = "P6", showqualifiers = {"P580","p582","P585"} , sorttype="inverted", numval = 1}},
                {type = "row", label = "Assembleia deliberante", value = "assembleia", wikidata = {property = "P194", defaultlink = defaultlink}},
                {type = "row", label = "Moeda", plurallabel = "Moedas", value = "moeda", property = "P38"},
                {type = "row", label = "Equipamento", plurallabel = "Equipamentos", value = "equipamento", property = "P912"},
                {type = "row", label = "Empregados", value = "empregados", property = "P1128"},
                {type = "row", label = "Diocése", value = "diocése", property = "P708"},
                {type = "row", label = "Estatudo patrimonial", value = "estatuto patrimonial", wikidata = {property = "P1435", showqualifiers = {"P580","P582","P585"}}},
                {type = "row", label = "Membro de", value = "membro de", property = "P463"},
                {type = "row", label = "Geminação", plurallabel = "Geminações", value = "geminação", property = "P190"},
                }
            },
            {type = "table", title = "História", rows = {
                {type = "row", label = "Origem do nome", value = "origem do nome", property = "P138"},
                {type = "row", label = "Estilista", plurallabel = "Estilistas", value = "estilista", property = "P287"},
                {type = "row", label = "Fundação", value = "fundação", property = "P571"},
                {type = "row", label = "Fundador", plurallabel = "Fundadores", value = "fundador", property = "P112"},
                {type = "row", label = "Arquiteto", plurallabel = "Arquitetos", value = "arquiteto", property = "P84"},
                {type = "row", label = "Substitui", value = "substitui", property = "P1365"},
                {type = "row", label = "Evento chave", plurallabel = "Eventos chaves", value = "evento chave", property = "P793"},
                {type = "row", label = "História", value = "história", property = "P2184"},
                {type = "row", label = "Extinção", value = "extinção", property = "P576"},
                }
            },
            {type = "table", title = "identidade", rows = {
                {type = "row", label = "Língua oficial", plurallabel = "Língua oficiais", value = "língua oficial", property = "P37"},
                {type = "row", label = "Divisa", value = "divisa", property = "P1451"},
                {type = "row", label = "Brasão", value = "brasão", property = "P237"},
                {type = "row", label = "Bandeira", value = "descrição bandeira", property = "P163"},
                {type = 'row', label = 'Hino', plurallabel = 'Hinos', value = 'hino', property = 'P85'},
                {type = "row", label = "Símbolo", plurallabel = "Símbolos", value = "símbolo", property = "P2238"},
                {type = "row", label = "Festa", plurallabel = "Festas", value = "festa", property = "P841"},
                {type = "row", label = "Santo padroeiro", plurallabel = "Santos padroeiros", value = "santo padroeiro", property = "P417"},
                {type = "row", label = "Prato tradicional", plurallabel = "Pratos tradicionais", value = "prato tradicional", property = "P868"},
                }
            },
            {type = "table", title = "Identificadores", rows = {
                {type = "row", label = "Código postal", value = "código postal", property = "P281"},
                {type = "row", label = "[[Federal Information Processing Standard|Code FIPS]]", value = "FIPS", property = "P774"},
                {type = "row", label = "[[Geographic Names Information System|GNIS]]", value = "GNIS", wikidata = {property = "P590", urlpattern= "https://geonames.usgs.gov/pls/gnispublic/f?p=gnispq:3:::NO::P3_FID:$1"}},
                {type = 'row', label = "[[Código Insee|INSEE]]", value = 'INSEE', property = 'P374'},
                {type = 'row', label = "[[OKATO]]", value = "OKATO", property = 'P721'},
                {type = 'row', label = "[[Instituto Nacional de Estatística (Espanha)|INE]]", value = "INE municipalidades", property = 'P772'},
                {type = 'row', label = "[[Istituto nazionale di statistica|ISTAT]]", value = "ISTAT", property = 'P635'},
                {type = 'row', label = "[[Oficinal Federal de Estatística da Alemanha|AGS]]", value = "AGS", property = 'P439'},
                {type = 'row', label = "[[Office for National Statistics|Code ONS]]", value = "ONS"},
                {type = "row", label = "[[Prefixo telefônico]]", value = "Prefixo telefônico", property = "P473"},
                general.website(),
                {type = "row", label = "Representado por", value = "representado por", property = "P1875"},
                {type = "row", label = "Distinção", plurallabel = "Distinções", value = "distinção", property = "P166"},
                }
            },
            general.geoloc({marker = 'aldeia'}),
    }
}