Jump to content

Module:DynamicCapiunto

Documentation for this module may be created at Module:DynamicCapiunto/doc

local capiunto = require 'capiunto'
local p = {}

-- TemplateStyles stylesheet holding the infobox's look (pc-infobox classes).
local STYLESHEET = 'Template:DynamicInfobox/styles.css'

-- Category for pages whose infobox could not be rendered, e.g. because the
-- entity is not (yet) in UnlinkedWikibase's cache.
local ERROR_CATEGORY = 'Pages with Infobox Errors'

-- Category for pages showing a bare Q-ID instead of a label, because the
-- entity is not (yet) cached or has no English/"mul" label on Wikidata.
local MISSING_LABEL_CATEGORY = 'Pages with Missing Wikidata Labels'

-- Error message plus the error tracking category.
local function errorOutput(message)
    return '<span class="error">Error: ' .. message .. '</span>' ..
        '[[Category:' .. ERROR_CATEGORY .. ']]'
end

function p.main(frame)
    local args = frame:getParent().args
    local qid = args.qid or args[1]

    if not qid then
        return errorOutput('No Wikidata QID provided')
    end

    -- Register the entity association
    frame:callParserFunction('#unlinkedwikibase', 'id=' .. qid)

    -- Get entity data from UnlinkedWikibase
    local entity = mw.ext.UnlinkedWikibase.getEntity(qid)

    if not entity then
        return errorOutput('Entity ' .. qid .. ' not found')
    end

    local lang = mw.language.getContentLanguage()

    -- Label of an entity: English, then the language-independent default
    -- label ("mul"), otherwise nil.
    local function getLabel(ent)
        if not ent or not ent.labels then return nil end
        for _, l in ipairs({ 'en', 'mul' }) do
            local label = ent.labels[l]
            if label and label.value and label.value ~= '' then
                return label.value
            end
        end
        return nil
    end

    -- Wikipedia article of an entity, from its Wikidata sitelinks: English
    -- first, German as fallback. Returns the URL and a link label, or nil.
    -- Entities cached by the UpdateEntities maintenance script
    -- (wbgetentities) carry sitelink titles but no URLs, so the URL is built
    -- from the title.
    local wikipediaSites = {
        { site = 'enwiki', lang = 'en', label = 'Wikipedia' },
        { site = 'dewiki', lang = 'de', label = 'Wikipedia (de)' }
    }

    local function getWikipediaUrl(ent)
        if not ent or not ent.sitelinks then return nil end
        for _, w in ipairs(wikipediaSites) do
            local link = ent.sitelinks[w.site]
            if link and link.title and link.title ~= '' then
                -- WIKI encoding also turns spaces into underscores
                return 'https://' .. w.lang .. '.wikipedia.org/wiki/' ..
                    mw.uri.encode(link.title, 'WIKI'), w.label
            end
        end
        return nil
    end

    -- Categories collected while the infobox is built and appended to the
    -- output at the end, e.g. "Pages with Image" or the country.
    local categories = {}
    local function addCategory(name)
        if not categories[name] then
            categories[name] = true
            table.insert(categories, name)
        end
    end

    -- Wikidata country items mapped to the wiki's country categories. Add an
    -- entry here to categorise pages by another country.
    local countryCategories = {
        Q183 = 'Germany'
    }

    -- Add the country categories for every non-deprecated value of pid
    -- (P17 country for organisations, P27 citizenship for people).
    local function addCountryCategories(pid)
        if not entity.claims or not entity.claims[pid] then return end
        for _, claim in ipairs(entity.claims[pid]) do
            local snak = claim.mainsnak
            local v = snak and snak.datavalue and snak.datavalue.value
            if claim.rank ~= 'deprecated' and type(v) == 'table' and v.id and
                countryCategories[v.id] then
                addCategory(countryCategories[v.id])
            end
        end
    end

    -- Add a "Member of <label>" category for every non-deprecated umbrella
    -- organisation (P463). Values whose entity or label is not cached yet are
    -- skipped; formatValue already flags those as missing labels.
    local function addMemberOfCategories()
        if not entity.claims or not entity.claims.P463 then return end
        for _, claim in ipairs(entity.claims.P463) do
            local snak = claim.mainsnak
            local v = snak and snak.datavalue and snak.datavalue.value
            if claim.rank ~= 'deprecated' and type(v) == 'table' and v.id then
                local label = getLabel(mw.ext.UnlinkedWikibase.getEntity(v.id))
                -- Drop characters that are not allowed in page titles
                label = label and mw.text.trim((label:gsub('[%[%]{}|#<>]', '')))
                if label and label ~= '' then
                    addCategory('Member of ' .. label)
                end
            end
        end
    end

    -- Render the stylesheet and infobox followed by its base category and all
    -- collected categories.
    local function render(box, baseCategory)
        local out = {
            frame:extensionTag('templatestyles', '', { src = STYLESHEET }) ..
            tostring(box),
            '[[Category:' .. baseCategory .. ']]'
        }
        for _, name in ipairs(categories) do
            table.insert(out, '[[Category:' .. name .. ']]')
        end
        return table.concat(out, '\n')
    end

    -- Helper function to get property value from entity
    local function getPropertyValue(pid)
        if not entity.claims or not entity.claims[pid] then return nil end

        local claims = entity.claims[pid]
        if not claims or #claims == 0 then return nil end

        local claim = claims[1]
        if not claim.mainsnak or not claim.mainsnak.datavalue then
            return nil
        end

        return claim.mainsnak.datavalue.value
    end

    -- Format a Wikidata time value according to its precision, e.g.
    -- "15 January 2023", "January 2023" or "2023".
    local function formatTime(value)
        local sign, year, month, day =
            value.time:match('^([+-]?)(%d+)-(%d+)-(%d+)')
        if not year then return value.time end
        local y, m, d = tonumber(year), tonumber(month), tonumber(day)
        local precision = value.precision or 11
        if sign == '-' then return tostring(y) .. ' BC' end
        local format, date
        if precision >= 11 and m > 0 and d > 0 then
            format, date = 'j F Y', string.format('%04d-%02d-%02d', y, m, d)
        elseif precision == 10 and m > 0 then
            format, date = 'F Y', string.format('%04d-%02d-01', y, m)
        else
            return tostring(y)
        end
        local ok, text = pcall(lang.formatDate, lang, format, date)
        if ok then return text end
        return date
    end

    -- Helper function to format different value types
    local function formatValue(value)
        if not value then return nil end

        if type(value) == 'table' then
            -- Handle time values
            if value.time then
                return formatTime(value)
                -- Handle entity references (Q-IDs)
            elseif value.id then
                -- Register a parser cache dependency so the page is invalidated
                -- when UnlinkedWikibase populates or updates this entity's data.
                mw.ext.UnlinkedWikibase.getLocalTitle(value.id)
                local linkedEntity = mw.ext.UnlinkedWikibase.getEntity(value.id)
                local label = getLabel(linkedEntity)
                if not label then addCategory(MISSING_LABEL_CATEGORY) end
                if linkedEntity then
                    -- Then prefer a Wikipedia article (external link)
                    local url = getWikipediaUrl(linkedEntity)
                    if url then
                        return '[' .. url .. ' ' .. (label or value.id) .. ']'
                    end
                    -- Fallback to the plain label if available
                    if label then return label end
                end
                return value.id
                -- Handle monolingual text
            elseif value.text then
                return value.text
            end
        end

        return tostring(value)
    end

    -- Formatted value of a property, or nil.
    local function getFormatted(pid)
        return formatValue(getPropertyValue(pid))
    end

    -- All non-deprecated values of a property, formatted and separated by
    -- line breaks, or nil. Used for properties with several values, e.g.
    -- several umbrella associations (P463).
    local function getAllFormatted(pid)
        if not entity.claims or not entity.claims[pid] then return nil end
        local values = {}
        for _, claim in ipairs(entity.claims[pid]) do
            local snak = claim.mainsnak
            if claim.rank ~= 'deprecated' and snak and snak.datavalue then
                local text = formatValue(snak.datavalue.value)
                if text then table.insert(values, text) end
            end
        end
        if #values == 0 then return nil end
        return table.concat(values, '<br>')
    end

    -- Helper to get claim entity id (if the claim is an entity)
    local function getClaimEntityId(pid)
        local v = getPropertyValue(pid)
        if type(v) == 'table' and v.id then return v.id end
        return nil
    end

    -- Helper to get the first claim object for a property
    local function getFirstClaimObject(pid)
        if not entity.claims or not entity.claims[pid] then return nil end
        local claims = entity.claims[pid]
        if not claims or #claims == 0 then return nil end
        return claims[1]
    end

    -- Helper to get a qualifier value (prefer English monolingual text for P2096)
    local function getQualifierValue(claim, qualPid)
        if not claim or not claim.qualifiers or not claim.qualifiers[qualPid] then
            return nil
        end
        local qsnaks = claim.qualifiers[qualPid]
        if not qsnaks or #qsnaks == 0 then return nil end
        for _, q in ipairs(qsnaks) do
            -- Check for valid snak with datavalue
            if q and q.snaktype == 'value' and q.datavalue and q.datavalue.value then
                local v = q.datavalue.value
                if type(v) == 'table' then
                    -- For monolingual text, prefer English
                    if v.language and v.language == 'en' and v.text then
                        return v.text
                    end
                else
                    return tostring(v)
                end
            end
        end
        return nil
    end

    -- Add the main image (P18) with its media legend (P2096) as caption.
    -- Capiunto always renders images directly below the title.
    local function addMainImage(box)
        local claim = getFirstClaimObject('P18')
        local v = claim and claim.mainsnak and claim.mainsnak.datavalue and
            claim.mainsnak.datavalue.value
        if not v then return end
        addCategory('Pages with Image')
        local caption = getQualifierValue(claim, 'P2096')
        if caption == '' then caption = nil end
        box:addImage('[[File:' .. tostring(v) .. '|280px]]', caption)
    end

    -- Extract a {latitude, longitude} coordinate (P625) from an entity object.
    local function getCoordFromEntity(ent)
        if not ent or not ent.claims or not ent.claims.P625 then return nil end
        local claims = ent.claims.P625
        if not claims or #claims == 0 then return nil end
        local snak = claims[1].mainsnak
        if not snak or not snak.datavalue then return nil end
        local v = snak.datavalue.value
        if type(v) == 'table' and v.latitude and v.longitude then return v end
        return nil
    end

    -- Leaflet/OpenStreetMap map for this entity, as HTML, or nil.
    -- Prefer the entity's own coordinate location (P625). If it has none, fall
    -- back to the coordinates of the entity referenced as its headquarters
    -- location (P159), fetched via UnlinkedWikibase.
    -- Rendered via the Maps extension's #display_map parser function. A module's
    -- return value goes through the main parse pass but NOT the preprocessor, so
    -- parser-function syntax would otherwise be emitted literally. We expand it
    -- here with frame:preprocess().
    local function getMap()
        local coord = getCoordFromEntity(entity)
        if not coord then
            local hqId = getClaimEntityId('P159')
            if hqId then
                -- Register a parser cache dependency on the HQ entity so the
                -- page is invalidated when its data is populated/updated.
                mw.ext.UnlinkedWikibase.getLocalTitle(hqId)
                coord = getCoordFromEntity(
                    mw.ext.UnlinkedWikibase.getEntity(hqId))
            end
        end
        if not coord then return nil end
        addCategory('Pages with Map')
        return frame:preprocess(string.format(
            '{{#display_map:%s,%s|width=100%%|height=200|zoom=13|service=leaflet}}',
            tostring(coord.latitude), tostring(coord.longitude)))
    end

    -- Social media accounts, in display order. Each entry lists one or more
    -- Wikidata properties (first one with a value wins) and a function that
    -- turns the stored identifier into a profile URL.
    ---@type {label: string, pids: string[], url: fun(v: string, pid: string): string?}[]
    local socialMedia = {
        {
            label = 'Facebook',
            pids = { 'P2013' },
            url = function(v)
                return 'https://www.facebook.com/' .. v
            end
        },
        {
            label = 'Instagram',
            pids = { 'P2003' },
            url = function(v)
                return 'https://www.instagram.com/' .. v .. '/'
            end
        },
        {
            label = 'YouTube',
            pids = { 'P2397', 'P11245' },
            url = function(v, pid)
                if pid == 'P11245' then
                    return 'https://www.youtube.com/@' .. v
                end
                return 'https://www.youtube.com/channel/' .. v
            end
        },
        {
            label = 'TikTok',
            pids = { 'P7085' },
            url = function(v)
                return 'https://www.tiktok.com/@' .. v
            end
        },
        {
            label = 'X',
            pids = { 'P2002' },
            url = function(v)
                return 'https://x.com/' .. v
            end
        },
        {
            label = 'Threads',
            pids = { 'P11892' },
            url = function(v)
                return 'https://www.threads.com/@' .. v
            end
        },
        {
            label = 'Bluesky',
            pids = { 'P12361' },
            url = function(v)
                return 'https://bsky.app/profile/' .. v
            end
        },
        {
            label = 'Mastodon',
            pids = { 'P4033' },
            url = function(v)
                -- Stored as user@server.domain
                local user, server = v:match('^@?([^@]+)@(.+)$')
                if not user then return nil end
                return 'https://' .. server .. '/@' .. user
            end
        },
        {
            label = 'LinkedIn',
            pids = { 'P4264', 'P6634' },
            url = function(v, pid)
                if pid == 'P6634' then
                    return 'https://www.linkedin.com/in/' .. v
                end
                return 'https://www.linkedin.com/company/' .. v
            end
        }
    }

    -- Get the best string value for a property: preferred rank first, then
    -- the first normal-rank claim. Deprecated claims (e.g. abandoned
    -- accounts) are skipped.
    local function getBestStringValue(pid)
        if not entity.claims or not entity.claims[pid] then return nil end
        local fallback
        for _, claim in ipairs(entity.claims[pid]) do
            local snak = claim.mainsnak
            local v = snak and snak.datavalue and snak.datavalue.value
            if type(v) == 'string' and v ~= '' then
                if claim.rank == 'preferred' then return v end
                if claim.rank ~= 'deprecated' and not fallback then
                    fallback = v
                end
            end
        end
        return fallback
    end

    -- Links to the entity's social media profiles, e.g.
    -- "Facebook · Instagram · YouTube", or nil.
    local function getSocialMedia()
        local links = {}
        for _, site in ipairs(socialMedia) do
            for _, pid in ipairs(site.pids) do
                local v = getBestStringValue(pid)
                local url = v and site.url(mw.text.trim(v), pid)
                if url then
                    -- Spaces would end the external link target early
                    url = url:gsub(' ', '%%20')
                    table.insert(links, '[' .. url .. ' ' .. site.label .. ']')
                    break
                end
            end
        end
        if #links == 0 then return nil end
        addCategory('Pages with Social Media')
        return table.concat(links, ' · ')
    end

    -- Official website (P856) as a link showing just the host and path.
    local function getWebsite()
        local url = getPropertyValue('P856')
        if type(url) ~= 'string' or url == '' then return nil end
        addCategory('Pages with Official Website')
        local display = url:gsub('^https?://', ''):gsub('^www%.', '')
            :gsub('/$', '')
        return '[' .. url .. ' ' .. display .. ']'
    end

    -- Footer line with links to the entity's Wikipedia article (if any) and
    -- its Wikidata item.
    local function getFooter()
        local links = {}
        local wikipediaUrl, wikipediaLabel = getWikipediaUrl(entity)
        if wikipediaUrl then
            addCategory('Pages with Wikipedia Article')
            table.insert(links,
                '[' .. wikipediaUrl .. ' ' .. wikipediaLabel .. ']')
        end
        table.insert(links,
            '[https://www.wikidata.org/wiki/' .. qid .. ' View on Wikidata]')
        return '<div class="pc-infobox-footer">' ..
            table.concat(links, ' · ') .. '</div>'
    end

    -- Add a section: an optional header followed by its rows. Each row is
    -- either { label, data } or { wikitext = ... }; rows without data are
    -- dropped, and the header is only shown if at least one row remains.
    local function addSection(box, header, rows)
        local present = {}
        for _, row in ipairs(rows) do
            if row.wikitext or row[2] then table.insert(present, row) end
        end
        if #present == 0 then return end
        if header then box:addHeader(header) end
        for _, row in ipairs(present) do
            if row.wikitext then
                box:addWikitext(row.wikitext)
            else
                box:addRow(row[1], row[2])
            end
        end
    end

    -- Date and place combined into one cell, e.g. "1 May 1950<br>Munich".
    local function datePlace(datePid, placePid)
        local date, place = getFormatted(datePid), getFormatted(placePid)
        if date and place then return date .. '<br>' .. place end
        return date or place
    end

    -- Add the links section shared by both infobox types.
    local function addLinks(box)
        addSection(box, 'Links', {
            { 'Website',      getWebsite() },
            { 'Social media', getSocialMedia() }
        })
        box:addWikitext(getFooter())
    end

    local title = getLabel(entity)
    if not title then
        title = qid
        addCategory(MISSING_LABEL_CATEGORY)
    end
    local infobox = capiunto.create({
        title = title,
        bodyClass = 'infobox vcard pc-infobox'
    })

    -- Decide which infobox to render based on instance (P31)
    if getClaimEntityId('P31') == 'Q5' then
        -- Person infobox
        addMainImage(infobox)

        addSection(infobox, nil, {
            { 'Born',       datePlace('P569', 'P19') },
            { 'Died',       datePlace('P570', 'P20') },
            { 'Occupation', getFormatted('P106') }
        })
        addCountryCategories('P27')

        local map = getMap()
        if map then infobox:addWikitext(map) end

        addLinks(infobox)
        return render(infobox, 'People')
    end

    -- Default: organisation/troupe infobox

    -- Official name (P1448) as a subtitle, unless it just repeats the title
    local officialName = getFormatted('P1448')
    if officialName and officialName ~= title then
        infobox:addSubHeader(officialName, 'pc-infobox-subtitle')
    end

    -- Logo (P154), then the main image
    local logo = getPropertyValue('P154')
    if type(logo) == 'string' and logo ~= '' then
        addCategory('Pages with Logo')
        -- Row class gives transparent logos a light backing in dark mode
        infobox:addImage('[[File:' .. logo .. '|150px]]', nil,
            'pc-infobox-logo')
    end
    addMainImage(infobox)

    -- Member count (P2124): the most recent value by its point in time
    -- (P585) qualifier, shown as e.g. "120 (as of 1 May 2023)". Undated
    -- values are only used when no dated one exists, preferring preferred
    -- rank.
    local function getMemberCount()
        if not entity.claims or not entity.claims.P2124 then return nil end
        local best, bestKey, bestTime, undated
        for _, claim in ipairs(entity.claims.P2124) do
            local snak = claim.mainsnak
            local v = snak and snak.datavalue and snak.datavalue.value
            if claim.rank ~= 'deprecated' and type(v) == 'table' and v.amount then
                local q = claim.qualifiers and claim.qualifiers.P585 and
                    claim.qualifiers.P585[1]
                local t = q and q.datavalue and q.datavalue.value
                local sign, y, m, d
                if type(t) == 'table' and t.time then
                    sign, y, m, d = t.time:match('^([+-]?)(%d+)-(%d+)-(%d+)')
                end
                if y then
                    local key = (tonumber(y) * 10000 + tonumber(m) * 100 +
                        tonumber(d)) * (sign == '-' and -1 or 1)
                    if not bestKey or key > bestKey then
                        best, bestKey, bestTime = v, key, t
                    end
                elseif not undated or claim.rank == 'preferred' then
                    undated = v
                end
            end
        end
        local value = best or undated
        if not value then return nil end
        local amount = tonumber((value.amount:gsub('^%+', '')))
        if not amount then return nil end
        local text = lang:formatNum(amount)
        if bestTime and best == value then
            text = text .. ' <span class="pc-infobox-note">(as of ' ..
                formatTime(bestTime) .. ')</span>'
        end
        return text
    end

    -- Registered address: the street address (P6375) qualifier of the
    -- headquarters (P159) statement, otherwise a P6375 statement on the
    -- entity itself. Addresses are monolingual text in any language.
    local function getAddress()
        local claim = getFirstClaimObject('P159')
        local qsnaks = claim and claim.qualifiers and claim.qualifiers.P6375
        for _, q in ipairs(qsnaks or {}) do
            local v = q.snaktype == 'value' and q.datavalue and q.datavalue.value
            if type(v) == 'table' and v.text and v.text ~= '' then
                return v.text
            end
        end
        local v = getPropertyValue('P6375')
        if type(v) == 'table' and v.text and v.text ~= '' then return v.text end
        return nil
    end

    local dissolved = getFormatted('P576')
    if dissolved then addCategory('Dissolved') end

    addSection(infobox, nil, {
        { 'Founded',             getFormatted('P571') },
        { 'Dissolved',           dissolved },
        { 'Members',             getMemberCount() },
        { 'Legal form',          getFormatted('P1454') },
        { 'Parent organization', getFormatted('P749') },
        { 'Member of',           getAllFormatted('P463') }
    })
    addMemberOfCategories()

    addSection(infobox, 'Location', {
        { 'Headquarters',     getFormatted('P159') },
        { 'Address',          getAddress() },
        { 'Country',          getFormatted('P17') },
        { wikitext = getMap() }
    })
    addCountryCategories('P17')

    addLinks(infobox)
    return render(infobox, 'Clubs, Societies and Institutions')
end

return p