Módulo:Infobox/Localidade

Permanently protected module
Origem: Wikipédia, a enciclopédia livre.
Documentação do módulo[ver] [editar] [histórico] [purgar]

Descrição

Este módulo tem funções auxiliares para criar infocaixas.

Uso

Outra documentação:

local localdata = require 'Módulo:Infobox/Localdata'
local general = require "Módulo:Infobox/Funções"
local building = require "Módulo:Infobox/Funções/Edifício"
local wikidata = require "Módulo:Infobox/Wikidata"
local linguistic = require "Módulo:Linguística"
local convert = require "Módulo:Conversão"
--local str = require "Módulo:Str" -- Adaptado de https://fr.wiktionary.org/wiki/Module:str de TAKASUGI Shinji para textos em script
--local lng = require "Módulo:Langue"
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
    Q142 = 'frwiki', -- França
    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 : funções no Módulo:Infobox/Wikidata para mostrar as 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['área'], localdata['ano área'], localdata['área 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

    -- arredondar
    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

local function devise() -- função para por em forma as moedas. exemplo :
            -- En [[anglais]] : ''The Gateway to Alberta'' (« La porte d'entrée de l'Alberta ») com módulos em falta
    local devises = localdata['moeda']
    if devises then -- données entrées en paramètre de l'infobox
        local langDevise = localdata["língua_moeda"]
        if langDevise and langDevise ~= '' then
            if str.non_latin({args={devises}}) == '' then
                devises = "<i>" .. devises .. "</i>"
            end
            devises = "en ".. langDevise .. " : " .. devises
            local traductionDevise = localdata["tradução_moeda"]
            local transcriptionDevise = localdata["transcrição_moeda"]
            if transcriptionDevise then
                if traductionDevise then
                    devises = devises .. " (<i>" .. transcriptionDevise .. "</i>, « " .. traductionDevise .. " »)"
                else
                    devises = devises .. " (<i>" .. transcriptionDevise .. "</i>)"
                end
            elseif traductionDevise then
                    devises = devises .. " ( « " .. traductionDevise .. " »)"
            end
        end
        local noteDevise = localdata["nota_moeda"]
        if noteDevise then
            devises = devises .. noteDevise
        end
    else -- dados recuperado do Wikidata
        local query = { property = "P1451", entity = localdata.item}
       
        local claims = wikidata.getClaims(query)
        if not claims or claims == {} then
            return nil
        end
        for i, j in pairs(claims) do
            local devise = wikidata.formatStatement(j, query)
            local langDevise = j.mainsnak.datavalue.value.language
           
            local noteDevise = '' -- recuperação de eventuais fontes
            local sources, hashes = wikidata.getReferences(j)
            if sources then
                local source = wikidata.sourceStr(sources, hashes)
                if source then
                    noteDevise = noteDevise .. source
                end
            end
           
            if langDevise ~= 'pt' and langDevise ~= '' then
                local fullLanguage = "[[" .. lng.articleLangue(langDevise) .. "|" ..
                        lng.nomLangue(langDevise) .. "]]"
                if str.non_latin({args={devise}}) == '' then
                    devise = "<i>" .. devise .. "</i>"
                end
                local traductionDevise
                if j.qualifiers and j.qualifiers.P2441 then
                    for _, v in pairs(j.qualifiers.P2441) do
                        if v.datavalue.value.language == 'pt' then
                            traductionDevise = v.datavalue.value.text
                        end
                    end
                end
                if traductionDevise then
                    claims[i] = "en ".. fullLanguage .. " : " .. devise ..
                            " (« " .. traductionDevise .. " »)" .. noteDevise
                else
                    claims[i] = "en ".. fullLanguage .. " : " .. devise .. noteDevise
                end
            else
                claims[i] = devise .. noteDevise
            end
        end
       
        devises = linguistic.conj(claims, 'new line') .. wikidata.addTrackingCat("P1451")
        devises = wikidata.addLinkBack(devises, localdata.item, "P1451")
    end
    return devises
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 = "região" .. i, "nome região" .. i --'nome de divisão ou região' .. i
        if localdata[param] then
            hasrows = true
            local label = localdata[labelparam] or "Departamento" -- ou localidade subdivisao
            table.insert(rows, {type = "row", label = label, value = function() return localdata[param] end})
        end
    end
    if hasrows then
        return rows
    end
end

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

local natureformats = {
    --{elemento Wikidata, nome charte, cor do título, cores do sub-título, cor texto, ícone)  devem ter classes desde as mais específicas até às gerais
    {'Q23442' , 'ilha', '#7793E0', '' , '#FFFFFF', 'mapa'},
    {'Q123705', 'bairro' , '#ECE5CA' , '' , '' , 'mapa'},
    {'Q8502' , 'montanha' , '#996633', '' , '#FFFFFF' , 'mapa'},
    {'Q12280' , 'ponte', '#D4D0BA' , '' , '' , 'mapa' },
}

local function setformat() --retourne une table contenant la couleur principale de l'infobox et l'icône de titre
    local natures = wikidata.getIds(localdata.item, {property = 'P31'}) -- récupère les Qid des natures

    if not natures or (#natures > 1) then -- si plusieurs natures, on ne sait pas lequel choisir
        return  {'Q', '', '#DDFFDD', '', '', 'map'}
    end
    natures = wikidata.addVals(natures, {property = 'P279'}, 2) -- nombre d'étages de sous-classes à remonter
    for i, j in pairs(natures) do
        for k, l in pairs(natureformats) do
            if l[1] == j then
                return l
            end
        end
    end
    return {'Q', '', '#DDFFDD', '', '' , 'map'}
end
local function setcharte()
    local charte = localdata['charte']
    if charte then
        for i, j in pairs(natureformats) do
            if j[2] == charte then
                return j
            end
        end
    end
    return setformat()
end
local natureformat = setcharte()
return {
    maincolor = natureformat[3],
    secondcolor = natureformat[4],
    thirdcolor = natureformat[5],
    parts =
        {
            general.title( natureformat[6]),
            {
                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", "P5252", "P3451", "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 = {'nome local', 'nome'}, 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)
                general.country(),
                {type = "multi", rows = localDivRows() or general.wikidataDivRows(countryid) 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', value = {'sede de concelho', 'sede'}, property = 'P36'},
                {type = "row", label = "Capital de", value = "capital de",
                    wikidata = {property = "P1376", showdate = true, precision = 'year', sorttype = 'chronological', conjtype = 'new line', showsource = false}
                },
                {type = 'row', label = 'Exclave de', value = 'exclave de', property = 'P500'},
                {type = 'row', label = 'Enclave em', value = 'enclave em', property = 'P501'},
                {type = 'row', label = 'Reivindicado por', value = 'reivindicado por', property = 'P1336'},
                {type = 'row', label = 'Banhado por', value = 'banhado por', property = 'P206'},
                {type = 'row', label = 'Área', value = function() return formatArea() end },
                {type = 'row', label = 'Área da água', value = 'área da água', property = 'P2927'},
                {type = 'row', label = 'Departamento', plurallabel = 'Departamentos', value = 'departamento', 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'} },
                building.mountainrange(),
                {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 = 'Densidade', value = function() return density() end},
                {type = 'row', label = 'Gentílico', value = 'gentílico', property = 'P1549'},
                }
            },
            {type = 'table', title = 'Funcionamento', rows = {
            {type = 'row', label = 'Estatuto', value = 'estatuto', wikidata = {property = 'P31',
                excludevalues = {"Q515", "Q532", "Q486972", "Q123705", "Q3957", "Q3257686", "Q23413", "Q82794", "Q1549591", "Q15661340", "Q23442", "Q23442", "Q33837", "Q37901", "Q37901", "93352", "Q1637706", "Q50330360", "Q8502", "Q39594", "Q207524", "Q27590", "Q40080", "Q839954","Q1021711"}, -- exclui valores que não correspondem a um status administrativo
                defaultlinkquery = {property = "P2354"}, showdate = true}, showsource = false},
            {type = 'row', label = 'Constituição', value = 'constituição'},
            {type = 'row', label = localdata['rótulo presidente'] or 'Presidente', value = {'prefeito', 'presidente'}, wikidata = {property = 'P6', showdate = true, textformat='long', sorttype = 'inverted', numval = 1}}, -- para o rótulo utilizar P1313 posto ocupado pelo chefe executivo
            {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'},
            building.protection(),
            {type = "row", label = "[[Propriété contributrice à un district historique|Propriété contributrice]]", plurallabel = "[[Propriété contributrice à un district historique|Propriétés contributrices]]", value = "propriété contributrice", wikidata = {property = "P527", numval = "5", showdate = true, textformat = "minimum", precision = "year", sorttype = "chronological", qualifier = "P3831", qualifiervalue = "Q1129142"}, showsource = false},
            {type = "row", label = "Contem a localidade", plurallabel = "Contem as localidades",value = "contem a localidade", wikidata = {property = "P1383", showdate = true}, showsource = false},
            {type = "row", label = "Membro de", value = "membro de", wikidata = {property = "P463", showdate = true}, showsource = false},
            {type = "row", label = "Geminação", plurallabel = "Geminações", value = "geminação", wikidata = {property = "P190", showdate = true}, showsource = false},
            {type = 'row', label = "[[:fr:Office de tourisme|Informações]]", value = "informações", wikidata = {property = 'P2872', numval = '1'}, showsource = false},
            }
            },
            {type = "table", title = "História", rows = {
                {type = "row", label = "Origem do nome", value = "origem do nome", property = "P138", showsource = false},
                {type = "row", label = "Designer", plurallabel = "Designers", value = "designer", property = "P287", showsource = false},
                {type = "row", label = "Fundação", value = "fundação", property = "P571", showsource = false},
                {type = "row", label = "Fundador", plurallabel = "Fundadores", value = "fundador", property = "P112", showsource = false},
                {type = "row", label = "Arquiteto", plurallabel = "Arquitestos", value = "arquiteto", property = "P84", showsource = false},
                building.archistyle(),
                {type = "row", label = "Substitui", value = "subsitui", property = "P1365", showsource = false},
                {type = "row", label = "Substituído por", value = "substituído por", property = "P1366", showsource = false},
                {type = "row", label = "Evento chave", plurallabel = "Eventos chaves", value = "evento chave", wikidata = {property = "P793", showdate = true}, showsource = false},
                {type = 'row', label = 'História', value = 'história', wikidata = {property = 'P2184', withlink = 'ptwiki', numval = '1'}, showsource = false},
                {type = "row", value = "extinção", property = "P576", showsource = false , label = function() return localdata['extinção título'] or 'Extinção' end, },
                {type = "row", label = "Direção das escavações", value = "excavações", property = "P4345", showsource = false},
                }
            },
            {type = "table", title = "Identidade", rows = {
                {type = "row", label = "ISO 3166-2", value = "iso", property = "P300", showsource = false},
                {type = "row", label = "Língua oficial", plurallabel = "Língua oficiais", value = "língua oficial", property = "P37", showsource = false},
                {type = 'row', label = 'Moeda', plurallabel = 'Moedas', value = 'moeda', property = 'P38'},
--                {type = "row", label = "Moeda", value = function() return devise() end, showsource = false},
                {type = "row", label = "Brazão", value = "brazão", property = "P237", showsource = false},
                {type = "row", label = "Bandeira", value = "descrição bandeira", property = "P163", showsource = false},
                {type = 'row', label = 'Hino', plurallabel = 'Hinos', value = 'hino', property = 'P85', showsource = false},
                {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", showsource = false},
                {type = 'row', label = "[[Statistisches Bundesamt|AGS]]", value = "AGS",Iproperty = 'P439'},
                {type = 'row', label = "[[:fr:Statistique Indonésie|Code de desa]]", value = "BPS", property = 'P1588'},
                {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://edits.nationalmap.gov/apps/gaz-domestic/public/summary/$1"}},
                {type = 'row', label = "[[Instituto Nacional de Estatística (Espanha)|INE]]", value = "INE municipalités", property = 'P772'},
                {type = 'row', label = "[[Instituto Brasileiro de Geografia e Estatística|IBGE]]", value = "IBGE", property = 'P1687'},
                {type = 'row', label = "[[Code Insee|INSEE]]", value = 'INSEE', property = 'P374'},
                {type = 'row', label = "[[Istituto nazionale di statistica|ISTAT]]", value = "ISTAT", property = 'P635'},
                {type = 'row', label = "Code [[Departamento Administrativo Nacional de Estadística|DANE]]", value = "DANE", property = 'P7325'},
                {type = 'row', label = "[[OKATO]]", value = "OKATO", property = 'P721'},
                {type = 'row', label = "[[Office for National Statistics|Code ONS]]", value = "ONS"},
                {type = 'row', label = "[[Classificação geográfica padrão (Canadá)|CGT]]", value = "statcan","CGT", property="P3012"},
                {type = 'row', label = "TGN", value = "TGN", wikidata = {property = "P1667", urlpattern= "http://vocab.getty.edu/page/tgn/$1"}},
                {type = "row", label = "[[Prefixo telefônico]]", value = "prefixo telefônico", property = "P473", showsource = false},
                {type = 'row', label = "[[Placa de identificação de veículos|matrícula]]", value = 'immatriculation', property = 'P395', showsource = false},
                general.website(),
                {type = "row", label = "Representado por", value = "representado por", property = "P1875", showsource = false},
                {type = "row", label = "Distinção", plurallabel = "Distinções", value = "distinção", wikidata = {property = "P166", showdate = true}, showsource = false},
                }
            },
            general.geoloc({default_zoom = 7, marker = 'village', maptype = localdata["tipo mapa"], width = localdata["tamanho mapa"]}),
            general.prononciation(),
    }
}