Modulo:Sandbox/moroboshi2

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca
    local p = {}
    local mWikidata = require('Modulo:Wikidata')
    local mChart = require('Modulo:Graph')
    local getArgs = require('Module:Arguments').getArgs

-- =============================================================
-- Funzioni copiate da Modulo:Wikidata
-- =============================================================

-- Messaggi di errore
local i18n = {
    ["errors"] = {
        ["entityid-param-not-provided"] = "Parametro ''entityid'' non fornito",
        ["property-param-not-provided"] = "Parametro ''property'' non fornito",
        ["qualifier-param-not-provided"] = "Parametro ''qualifier'' non fornito",
        ["value-param-not-provided"] = "Parametro ''valore'' da ricercare non fornito",
        ["entity-not-found"] = "Entità non trovata",
        ["unknown-claim-type"] = "Tipo asserzione sconosciuta",
        ["unknown-snak-type"] = "Tipo di snak sconosciuto",
        ["unknown-datavalue-type"] = "Tipo di dato sconosciuto",
        ["unknown-entity-type"] = "Tipo di entità sconosciuta"
    },
    ["somevalue"] = "''valore sconosciuto''",
    ["novalue"] = "''nessun valore''"
}

-------------------------------------------------------------------------------
--                             Formatters
-------------------------------------------------------------------------------

local function errhandler(msg)
    local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
    return string.format('<span class="error">%s</span>%s', msg, cat)
end

local function formatExtLink(url)
    local protocols = { ftp = true, http = true, https = true }

    local success, uri = pcall(function() return mw.uri.new(url) end)
    if success and uri.protocol and protocols[uri.protocol] then
        local dest = tostring(uri)
        return string.format('[%s %s]', dest, dest:gsub(uri.protocol .. '://', ''))
    else
        return url
    end
end

local function formatEntityId(entityId)
    local label = mw.wikibase.label(entityId)
    local link = mw.wikibase.sitelink(entityId)
    if link then
        if label then
            return '[[' .. link .. '|' .. label .. ']]'
        else
            return '[[' .. link .. ']]'
        end
    else
        return label or ''
    end
end

local function formatTime(value, args)
    local year, month, day
    local ret = ''
 
    year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
    if value.precision == 9 then
        ret = tonumber(year)
    elseif value.precision == 10 then
        ret = mw.getLanguage('it'):formatDate('F Y', tonumber(year) .. '-' .. month)
    elseif value.precision == 11 then
        ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
        ret = ret:gsub('^1%s', '1º ')
    end
    if value.precision >= 9 and value.precision <= 11 then
        ret = ret .. (value.time:sub(1, 1) == '-' and ' a.C.' or '')
    end

    return ret
end

local function formatGlobecoordinate(value, args)
    local ret
    if args.formatting == 'latitude' then
        ret = value.latitude
    elseif args.formatting == 'longitude' then
        ret = value.longitude
    else
        ret = value.latitude .. ', ' .. value.longitude
    end
    return ret
end

local function formatFromPattern(str, args)
    local pattern = args.pattern
    pattern = mw.ustring.gsub(pattern, '\\{', '{')
    pattern = mw.ustring.gsub(pattern, '\\}', '}')
    return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
end

local function getEntityIdFromValue(value)
    local prefix = ''
    if value['entity-type'] == 'item' then
        prefix = 'Q'
    elseif value['entity-type'] == 'property' then
        prefix = 'P'
    else
        error(i18n.errors['unknown-entity-type'])
    end
    return prefix .. value['numeric-id']
end

local function formatDatavalue(datavalue, args)
    local ret

    --Default formatters
    if datavalue.type == 'wikibase-entityid' then
        if args.formatting == 'raw' then
            ret = getEntityIdFromValue(datavalue.value)
        else
            ret = formatEntityId(getEntityIdFromValue(datavalue.value))
        end
    elseif datavalue.type == 'string' then
        ret = datavalue.value
        if args.formatting == 'extlink' then
            ret = formatExtLink(ret)
        end
    elseif datavalue.type == 'monolingualtext' then
        ret = datavalue.value.text
    elseif datavalue.type == 'time' then
        if args.formatting == 'raw' then
            ret = datavalue.value.time
        else
            ret = formatTime(datavalue.value, args)
        end
    elseif datavalue.type == 'globecoordinate' then
        ret = formatGlobecoordinate(datavalue.value, args)
    elseif datavalue.type == 'quantity' then
        ret = tonumber(datavalue.value.amount)
    else
        error(i18n.errors['unknown-datavalue-type'])
    end

    return ret
end

local function formatSnak(snak, args)
    if snak.snaktype == 'somevalue' then
        return i18n['somevalue']
    elseif snak.snaktype == 'novalue' then
        return i18n['novalue']
    elseif snak.snaktype == 'value' then
        return formatDatavalue(snak.datavalue, args)
    else
        error(i18n.errors['unknown-snak-type'])
    end
end

-- =============================================================
-- Fine Funzioni copiate da Modulo:Wikidata
-- =============================================================


local function read_array(raw_data)
    if not(raw_data) then return {} end
    local list = mw.text.split(raw_data, ",")
    local data = {}
    for _,s in ipairs(list) do
        data[#data+1] = s
    end
    return data
end

local function read_wikidata(from)
    local P585 = 'P585'
    local P1082 = 'P1082'
    local entity = mw.wikibase.getEntityObject(from)
    local claims
    if entity.claims and entity.claims.P1082 and #entity.claims.P1082 > 0 then
        claims = entity.claims.P1082
    else
        return nil
    end
    --if true then return mw.text.jsonEncode(claims[1],mw.text.JSON_PRETTY) end
    local years = {}
    local populations = {}
    for _,claim in ipairs(claims) do
        if claim.qualifiers and claim.qualifiers.P585 and (claim.rank == 'preferred' or  claim.rank == 'normal') then
            --if true then return claim end
            years[#years+1] = formatSnak(claim.qualifiers.P585[1] , {})
            populations[#populations+1] = formatSnak(claim.mainsnak, {})
        end
    end
    return populations, years
end


function p.demograph(frame)
    local args = getArgs(frame)
    local populations, years = read_wikidata(args[1])
    for i = 1, math.floor(#populations/2) do
        local j=#populations-i+1
        years[i], years[j] = years[j], years[i]
        populations[i], populations[j] = populations[j], populations[i]
    end
    --if true then return mw.text.jsonEncode(years, mw.text.JSON_PRETTY) end    
    local graph_args = {
        ygrid = true,
        xtitle = 'anni',
        ytitle = 'popolazione',
        y = { populations },
        x =  years,
        graph_type = 'rect',
        seriesTitles = {'Popolazione'},
        colors = {'#4682B4'}
    }
    local graph_json = mChart.chart_json(graph_args)
    --if true then return  graph_json end
    return  frame:extensionTag('graph', graph_json)
end

    return p