Modul:Benutzer:Herzi Pinki/ByDistrict

Die Dokumentation für dieses Modul kann unter Modul:Benutzer:Herzi Pinki/ByDistrict/Doku erstellt werden

-- Denkmalgeschützte Objekte in Österreich nach Bezirk 2015-08-16 by Herzi Pinki
-- replaces the manual and redundant list of municipalities per district (in Austria: Bezirk) where ever needed.
-- this is done based on WD entries for the district / municipality
--  and on naming conventions in the project
-- the following usages will be supported (in main namespace only):
-- * [[Denkmalgeschützte Objekte im Bezirk Schärding]] replace pseudo navi with single template call
-- * [[Vorlage:Navigationsleiste Denkmalgeschützte Objekte im Bezirk Schärding]] replace navi with single template call
-- * [[Bezirk Schärding#Verwaltungsgliederung]] replace list of municipalities
-- * [[Vorlage:Navigationsleiste Denkmalgeschützte Objekte in Wien]] replace navi with single template call
-- 
-- * DenkmalschutzNachBezirk: return the Wiki Code for 

--[[
# Vorlage <nowiki>{{Denkmalgeschützte Objekte in Österreich nach Bezirk|<Bezirk>}}</nowiki> wäre die Minimalschnittstelle. Oder Schlüssel?  Steyr-Land District ([https://www.wikidata.org/wiki/Q854074 Q854074]) 
# mir wäre der Name lieber, d.h. gibt es einen Lookup von Bezirk Steyr-Land auf Q854074?
# Kann WD zu einem Bezirk das Lemma auf WP:de bestimmen?
# Vom Bezirk zum Bundesland? (Property:P131)
# Daraus Einleitung, Karte und Kopf der Tabelle erzeugen.
# Unter jedem Bezirk gibt es eine Liste der Gemeinden.Property:P150
## über diese iterieren, sortiert nach Alphabet
## ich brauche nicht nur den Namen, sondern auch das Lemma in der WP:de, krieg ich das?
## aus dem Lemma den Namen der Denkmalliste bestimmen
## diese ist Schlüssel für die Metadatenvorlage :de:Vorlage:Metadaten Denkmalliste Österreich, die botgeneriert die Anzahlen enthält.
#Tabellenende und Navi automatisch erzeugen.

# Liste von (P360) von Denkmalliste (Q15097084) von (P642) -> Bezirk

# hoo: only 15 objects are cached!!

# mw.log(mw.wikibase.getEntityObject('Q853690'))
--]]

local config = {
    -- reference date to see the municipality structure at
    -- this allows to prepare changes in municipality structure before they really happen (using now)
    -- this allows to use outdated municipality structure on WP as long as other changes (e.g. necessary moves) are not in place
    -- either one of the following two lines
    -- format yyyymmdd
    refDate = tonumber(os.date('%Y%m%d')), --now
    -- refDate = 20141231, -- arbitrary date
    
    -- do show monument counters as collected by krdbot in Vorlage:Metadaten_Denkmalliste_Österreich
    -- as this can break parser limits, you can switch it off here in case of failure
    -- the critical point here is Vom Präprozessor besuchte Knoten, creating counts will consume 8-10% of the max nodes of 1000000
    showCounts = true
}
-- some things are done by naming conventions other by WD navigation

-- the data that is used to generate the template -- should be included from
-- a data page
local data = {
    pidIsA                      = 'P31',
    pidBundesland               = 'P131',
    pidListOfMunips             = 'P150',
    pidHauptkategorieZumArtikel = 'P910',
    pidListeDerDenkmale         = 'P1456',
    pidStartzeitpunkt           = 'P580',
    pidEndzeitpunkt             = 'P582',
    pidOrdnungsnummer           = 'P1545',
    
    qBezirkInOesterreich        = 871419, -- id is int
    
    --naviSep = '&nbsp;&#124;',  -- seperator for Navigationsleiste
    naviSep = '&nbsp;•',
    naviSepSplit = ', ', -- for split lists

    imagemaps = { -- not matching naming conventions and to be flexible, could be a property in WD?
        Tirol     = 'Imagemap Bezirke von Tirol (Bundesland)',
        Salzburg  = 'Imagemap Bezirke von Salzburg (Bundesland)',
        Wien      = 'Imagemap Wiener Gemeindebezirke',
        },
        
    districtCategories = { -- not matching naming conventions and to be flexible
        -- ['Bezirk Innsbruck-Land']     = 'Bezirk Innsbruck Land', -- already fixed
        ['Bezirk St. Pölten-Land']     = 'Bezirk Sankt Pölten-Land',
        },
        
    listCategoriesPerFedState = { -- not matching naming conventions and to be flexible
        Burgenland  = 'Liste (Kulturdenkmale im Burgenland)',
        Salzburg    = 'Liste (Kulturdenkmale im Land Salzburg)',
        Steiermark  = 'Liste (Kulturdenkmale in der Steiermark)',
        },
        
    wherePerFedState = { -- not matching naming conventions and to be flexible
        Burgenland  = 'im Burgenland',
        Salzburg    = 'im Land Salzburg',
        Steiermark  = 'in der Steiermark',
        Tirol       = 'im Land Tirol',
        },

    -- static text
    protectedObjectsOverview = {
        ['hd1'] = "Im \'\'\'%s\'\'\' gibt es \'\'\'%s denkmalgeschützte Objekte\'\'\'. Die unten angeführte Liste führt zu den Denkmallisten der Gemeinden und gibt die jeweilige Anzahl der Objekte an.\n\n"
        },
        
    -- for testing resions, additional output generated when true
    verbose = false
    
}

-- internationalisation
local i18n = {
    ["errors"] = {
        ["not-a-district"] = "Der Aufrufparameter ist kein gültiger Bezirk in Österreich.",
        ["empty-district"] = "Der Bezirk hat keine aktuellen Gemeinden.",
    }
    }

local p = {}

local function printError(code)
	return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
end

local function throwError(code)
	error (i18n.errors[code] or code, 2)
end

-- debug
local function print (x, level)
    local s = ''
    local l = level or 0;
    if x then
        if type(x) == "table" then
            local sep = false
            s = '{'
            for key, val in pairs(x) do  -- Table iteration.
                if sep 
                    then s = s .. ', '
                    else sep = true
                end
                s = s .. '[' .. key .. '] = '
                if key == 'sitelinks' or key == 'aliases' or key == 'labels'
                then s = s .. '{…}'
                else s = s .. print (val, l+1)
                end
            end
            s = s .. '}'
            elseif type(x) == "string"
                then s = s .. '"' .. x .. '"'
            elseif type(x) == "number" or type(x) == "boolean" 
                then s = s .. x
            else s = s .. '(' .. type(x) .. ')' 
            end
    else s = 'nil'
    end
    if l == 0 then s = s .. "\n\n" end -- need two as output is rendered by the wiki parser
    return s
end

-- map districts not matching naming conventions
local function mapDistrict(d)
    return data.districtCategories[d] or d
end

-- creates a wiki link to an item
local function createLink(item)
    local name = item:getLabel()
    local link = item:getSitelink()
    
    if name == link
    then return '[[' .. name .. ']]'
    else return '[[' .. link .. '|' .. name .. ']]'
    end
end

-- check if municipality still exists
-- claim: a single statement (claim) of a municipality of a district
local function isExistentMunip(claim)
    if claim.qualifiers then
        --compare P580 and P582 qualifiers with refDate
        local from, to
        -- string.gsub(mw.wikibase.getEntityObject('Q853690')['claims']['P150'][1]['qualifiers']["P582"][1].datavalue.value.time, '.(%d*)\-(%d*)\-(%d*)T.*','%1%2%3')
        if claim.qualifiers[data.pidStartzeitpunkt] then
        	-- convert to yyyymmdd
        	from = tonumber(string.gsub(claim.qualifiers[data.pidStartzeitpunkt][1].datavalue.value.time, '([%-+]%d*)\-(%d*)\-(%d*)T.*','%1%2%3'),10)
        else
        	from = -99999999
        end
        if claim.qualifiers[data.pidEndzeitpunkt] then
        	to = tonumber(string.gsub(claim.qualifiers[data.pidEndzeitpunkt][1].datavalue.value.time, '([%-+]%d*)\-(%d*)\-(%d*)T.*','%1%2%3'),10)
        else
        	to = 99999999 -- 8 digits max
        end
        return from <= config.refDate and config.refDate <= to
    end
    return true
end

-- check if item is a Bezirk in Österreich
local function isValidDistrict (qid)
    local district = mw.wikibase.getEntityObject(qid)
    if district then
        allIsA = district['claims'][data.pidIsA]
        for i = 1, #allIsA do
        	-- check for correct class
            --     there could be subclasses of qBezirkInOesterreich, could be already implemented somewhere in WP:de, expensive
            --     risk considered low
            if allIsA[i].mainsnak.datavalue.value['numeric-id'] == data.qBezirkInOesterreich then
	    		-- TODO check for valid date
                return true
            end
        end
    end
    return false
end

--[[
    frame?
    qid: wd id of the district.
         Pre: It has been checked that the district exists in WD
         Pre: district still exists as an adminstrative unit in reality
    return: sorted table with all current munips in district with 
         ref      : WD entity ref
         name     : localized name of munip
         sitelink : localized sitelink to munip
--]]
local function getCurrentMunips(frame, qid)
    local district     = mw.wikibase.getEntityObject(qid)
    local munips       = district['claims'][data.pidListOfMunips]
    if not munips then
    	throwError("empty-district")
	end
	
    local munipsByName = {} -- collect all munips with their data and sort them by name / label
    
    -- collect munips currently part of the district
    for i = 1, #munips do
        if isExistentMunip(munips[i]) then
            local munipRef   = munips[i].mainsnak.datavalue.value['numeric-id']
            local munip      = mw.wikibase.getEntityObject('Q' .. munipRef)

		local nr = 0
	    if munips[i].qualifiers and munips[i].qualifiers[data.pidOrdnungsnummer] then
	    	nr = tonumber(munips[i].qualifiers[data.pidOrdnungsnummer][1].datavalue.value)
	    end
	
            munipsByName[#munipsByName+1] = { ref = munip, name = munip:getLabel(), sitelink = munip:getSitelink(), nr = nr}
        end
    end
    
    -- sort list of munips by name
    local comp = function(a, b)
    	if a['nr'] == b['nr'] 
	        then return a['name'] < b['name']
	        else return a['nr'] < b['nr']
    	end
    end
    table.sort(munipsByName, comp)
    
    return munipsByName
end

-- extracts the count of protected objects from corresponding metadata 
-- ignores errors to not bloat the generated code
-- in munipDLLink: the name of the list of protected monuments
-- remark: TODO - need the frame argument to be able to call object functions?
local function protectedObjectsCount(frame, munipDLLink)
	local wikiCode = '{{#iferror:' .. 
					 frame:expandTemplate({
                                          title = 'Metadaten Denkmalliste Österreich',
                                          args = { munipDLLink, 'Summe'}
                                         })
                     .. '|<span class="error" title="Fehlende Metadaten">?</span>}}'
    return frame:preprocess(wikiCode)
end

-- performs the loop on municipalities of district and embeds them in suitable wiki code
local function protectedObjectsOverview(frame, qid)
    local wikiCode     = ''
    local district     = mw.wikibase.getEntityObject(qid)
    local fedStateRef  = district:getBestStatements(data.pidBundesland)[1].mainsnak.datavalue.value['numeric-id']
    local fedState     = mw.wikibase.getEntityObject('Q' .. fedStateRef)
    
    -- collect all munips with their data and sort them by name / label
    local munipsByName = getCurrentMunips(frame, qid)

    --local districtCatRef  = district['claims'][data.pidHauptkategorieZumArtikel][1].mainsnak.datavalue.value['numeric-id']
    --local districtCat     = mw.wikibase.getEntityObject('Q' .. districtCatRef)
    --local districtCatName = districtCat:getLabel()

    local fedStateName = fedState:getLabel()
    local fedStateLink = fedState:getSitelink()
    local districtLink = district:getSitelink()
    -- skip leading 'Bezirk ', but keeping trailing disambig, per naming conventions
    local districtBaseWDA  = string.gsub (districtLink, "Bezirk ", "")
    -- skip leading 'Bezirk ' and trailing disambig, per naming conventions
    local districtBaseWODA = string.gsub (district:getLabel(), "Bezirk ", "")
    
    -- Image map Bezirke
    wikiCode = wikiCode .. frame:expandTemplate({
        title = data.imagemaps[fedStateName] or 'Imagemap Bezirke von ' .. fedStateName, --  naming conventions
        args = { districtBaseWDA, Appl = 'Denkmal', Einbindung = 'miniatur|rechts'}
        })
    -- Header
    wikiCode = wikiCode .. string.format (data.protectedObjectsOverview['hd1'],
                                          createLink(district) .. (data.verbose and ' ([[d:' .. qid ..'|WD]])' or ''),
                                          protectedObjectsCount(frame, districtBaseWODA)
                                         )
    -- table header
    wikiCode = wikiCode .. '{| class="wikitable sortable zebra"\n'
    wikiCode = wikiCode .. '! Denkmalliste\n'
    wikiCode = wikiCode .. '! data-sort-type="number" | Objektanzahl\n'
    
    local munipsWithoutList = 0 -- do not have an entry in Metadata
    
    -- generate table entries
    for i = 1, #munipsByName do

        local protectedObjectLists = munipsByName[i]['ref']['claims'][data.pidListeDerDenkmale]
        -- number of lists of protected monuments in WD
        -- can be 0: missing, 1: single list, >1 split lists (due to size restrictions)
        local nrProtectedObjectLists = 0
        if protectedObjectLists then nrProtectedObjectLists = #protectedObjectLists end
        if nrProtectedObjectLists == 1 then
            -- get the munip specific list of cultural heritage monuments or none
            local munipDLRef   = protectedObjectLists[1].mainsnak.datavalue.value['numeric-id']
            local munipDL      = mw.wikibase.getEntityObject('Q' .. munipDLRef)
            local munipDLLink  = munipDL:getSitelink()
            
            wikiCode = wikiCode .. '|-\n'
            wikiCode = wikiCode .. '| <span class="wikidata-content">[[' .. munipDLLink .. '|' .. munipsByName[i]['name'] .. ']]</span>'
            if data.verbose then
                wikiCode = wikiCode .. ' ([[d:' .. munipsByName[i]['ref']['id'] ..'|WD]])'
            end
            wikiCode = wikiCode .. '\n'
            wikiCode = wikiCode .. '| style="text-align:right" | ' .. protectedObjectsCount(frame, munipDLLink) .. '\n'
        elseif nrProtectedObjectLists > 1 then
        	-- multiple split lists
            wikiCode = wikiCode .. '|-\n'
            wikiCode = wikiCode .. '| <span class="wikidata-content">' .. munipsByName[i]['name'] .. '</span>'
            if data.verbose then
                wikiCode = wikiCode .. ' ([[d:' .. munipsByName[i]['ref']['id'] ..'|WD]])'
            end
            wikiCode = wikiCode .. '\n'
            wikiCode = wikiCode .. '|\n'
            -- wikiCode = wikiCode .. '| style="text-align:right" | ' .. protectedObjectsCount(frame, munipDLLink) .. '\n'

        	for j = 1, #protectedObjectLists do

	            local munipDLRef   = protectedObjectLists[j].mainsnak.datavalue.value['numeric-id'] -- partial list ref
	            local munipDL      = mw.wikibase.getEntityObject('Q' .. munipDLRef) -- partial list name: Liste der denkmalgeschützten Objekte in Hall in Tirol/A–L
	            local munipDLLink  = munipDL:getSitelink()
	            local splitMunipDL = mw.text.split(munipDL:getLabel(), '/')
	            local lastPartOfMunipDL = splitMunipDL[#splitMunipDL]
	            
	            wikiCode = wikiCode .. '|-\n'
	            wikiCode = wikiCode .. '| data-sort-value="' .. munipsByName[i]['name'] .. '/' .. lastPartOfMunipDL .. '" | <span class="wikidata-content">[[' .. munipDLLink .. '|' ..lastPartOfMunipDL .. ']]</span>'
	            if data.verbose then
	                wikiCode = wikiCode .. ' ([[d:' .. munipsByName[i]['ref']['id'] ..'|WD]])'
	            end
	            wikiCode = wikiCode .. '\n'
	            wikiCode = wikiCode .. '| style="text-align:right" | ' .. protectedObjectsCount(frame, munipDLLink) .. '\n'
        	end
        else
            -- no associated list of cultural heritage monuments
            munipsWithoutList = munipsWithoutList + 1
            wikiCode = wikiCode .. '|-\n'
            wikiCode = wikiCode .. '| <span class="wikidata-content">' .. munipsByName[i]['name'] .. '</span>&nbsp;* '
            if data.verbose then
                wikiCode = wikiCode .. ' ([[d:' .. munipsByName[i]['ref']['id'] ..'|WD]])'
            end
            wikiCode = wikiCode .. '\n'
            wikiCode = wikiCode .. '| style="text-align:right" | 0' ..'\n'
        end
    end
    
    -- close table
    wikiCode = wikiCode .. '|}\n\n'
    
    -- footnote
    if munipsWithoutList > 0 then
        wikiCode = wikiCode .. '<small>* für '
        if munipsWithoutList == 1 then
            wikiCode = wikiCode .. ' diese Gemeinde'
        else
            wikiCode = wikiCode .. munipsWithoutList .. ' Gemeinden'
        end
        wikiCode = wikiCode .. ' sind keine denkmalgeschützten Objekte ausgewiesen</small>\n'
    end

    local navi
    if fedStateName == "Steiermark"
    then navi = 'Navigationsleiste Denkmalgeschützte Objekte in den Bezirken in der Steiermark'
    else navi = 'Navigationsleiste Denkmalgeschützte Objekte in den Bezirken in ' .. fedStateName
    end
    wikiCode = wikiCode .. frame:expandTemplate({
        title = navi,
        args = {}
        })

    -- TODO re-activate categories
    wikiCode = wikiCode .. '[[:Kategorie:' .. mapDistrict(districtLink) .. ']]\n\n'
    wikiCode = wikiCode .. '[[:Kategorie:' .. (data.listCategoriesPerFedState[fedStateName] or 'Liste (Kulturdenkmale in ' .. fedStateName .. ')') .. '|*]]\n\n'
    
    return wikiCode
end

-- performs the loop on municipalities of district and embeds them in suitable wiki code
local function protectedObjectsNaviContent(frame, qid)
    -- collect all munips with their data and sort them by name / label
    local munipsByName = getCurrentMunips(frame, qid)

    local munipsWithoutList = 0 -- do not have an entry in Metadata
    
    -- generate list entries
    local first = true
    local wikiCode = '\n'
    for i = 1, #munipsByName do
    -- [[Liste der denkmalgeschützten Objekte in Aflenz|Aflenz]] (nn)&nbsp;&#124;
        if first
        then first  = false
        else wikiCode   = wikiCode .. data.naviSep ..'\n'
        end
        
        local protectedObjectLists = munipsByName[i]['ref']['claims'][data.pidListeDerDenkmale]
        -- number of lists of protected monuments in WD
        -- can be 0: missing, 1: single list, >1 split lists (due to size restrictions)
        local nrProtectedObjectLists = 0
        if protectedObjectLists then nrProtectedObjectLists = #protectedObjectLists end
        if nrProtectedObjectLists == 1 then
            -- get the munip specific list of cultural heritage monuments or none
            local munipDLRef   = protectedObjectLists[1].mainsnak.datavalue.value['numeric-id']
            local munipDL      = mw.wikibase.getEntityObject('Q' .. munipDLRef)
            local munipDLLink  = munipDL:getSitelink()
            
            wikiCode = wikiCode .. '<span class="wikidata-content">[[' .. munipDLLink .. '|' .. munipsByName[i]['name'] .. ']]</span>'
            if config.showCounts then
            	wikiCode = wikiCode .. '&nbsp;(<span title="Anzahl geschützter Objekte in der Gemeinde">' .. protectedObjectsCount(frame, munipDLLink) .. '</span>)'
            end
        elseif nrProtectedObjectLists > 1 then
        	-- multiple split lists
        	wikiCode = wikiCode .. '<span class="wikidata-content">' .. munipsByName[i]['name'] .. '</span> <span style="font-size:smaller;">('
        	local first = true
        	for j = 1, #protectedObjectLists do
		        if first
		        then first  = false
		        else wikiCode   = wikiCode .. data.naviSepSplit ..'\n'
		        end
		        
	            local munipDLRef   = protectedObjectLists[j].mainsnak.datavalue.value['numeric-id'] -- partial list ref
	            local munipDL      = mw.wikibase.getEntityObject('Q' .. munipDLRef) -- partial list name: Liste der denkmalgeschützten Objekte in Hall in Tirol/A–L
	            local munipDLLink  = munipDL:getSitelink()
	            local splitMunipDL = mw.text.split(munipDL:getLabel(), '/')
	            local lastPartOfMunipDL = splitMunipDL[#splitMunipDL]
	            
	            wikiCode = wikiCode .. '<span class="wikidata-content">[[' .. munipDLLink .. '|' .. lastPartOfMunipDL .. ']]</span>'
            if config.showCounts then
	            wikiCode = wikiCode .. '&nbsp;(<span title="Anzahl geschützter Objekte in der Gemeinde">' .. protectedObjectsCount(frame, munipDLLink) .. '</span>)'
	            end
        	end
        	wikiCode = wikiCode .. ')</span>'
        else
            -- no associated list of cultural heritage monuments
            munipsWithoutList = munipsWithoutList + 1
            wikiCode = wikiCode .. '<span class="wikidata-content">' .. munipsByName[i]['name'] .. '</span>'
            if config.showCounts then
             	wikiCode = wikiCode .. '&nbsp;(0)'
             end
             wikiCode = wikiCode .. '&nbsp;*'
        end
    end

    -- footnote
    if munipsWithoutList > 0 then
        wikiCode = wikiCode .. '\n\n<small>* für '
        if munipsWithoutList == 1 then
            wikiCode = wikiCode .. ' diese Gemeinde'
        else
            wikiCode = wikiCode .. munipsWithoutList .. ' Gemeinden'
        end
        wikiCode = wikiCode .. ' sind keine denkmalgeschützten Objekte ausgewiesen</small>\n'
    end
    
    return wikiCode
end

-- performs the loop on municipalities of district and embeds them in suitable wiki code
-- replaces the bones of navi [[Vorlage:Navigationsleiste Denkmalgeschützte Objekte im Bezirk Bruck-Mürzzuschlag]] etc.
local function protectedObjectsNavi(frame, qid, image)
    local wikiCode     = ''
    local district     = mw.wikibase.getEntityObject(qid)
    local fedStateRef  = district:getBestStatements(data.pidBundesland)[1].mainsnak.datavalue.value['numeric-id']
    local fedState     = mw.wikibase.getEntityObject('Q' .. fedStateRef)
    
    local fedStateName = fedState:getLabel()
    local fedStateLink = fedState:getSitelink()
    local districtLink = district:getSitelink()
    -- skip leading 'Bezirk ', but keeping trailing disambig, per naming conventions
    local districtBaseWDA  = string.gsub (districtLink, "Bezirk ", "")
    -- skip leading 'Bezirk ' and trailing disambig, per naming conventions
    local districtBaseWODA = string.gsub (district:getLabel(), "Bezirk ", "")

    -- Navigationsleiste Bezirke
    wikiCode = wikiCode .. frame:expandTemplate({
        title = 'Navigationsleiste', --  naming conventions
        args = { 
            TITEL  = '[[Denkmalgeschützte Objekte im ' .. districtLink .. ']]',
            BILD   = image and ('[[Datei:' .. image .. '|85x85px|Karte des Bezirks ' .. districtBaseWDA .. (data.wherePerFedState[fedStateName] or 'in ' .. fedStateName) ..']]'),
            INHALT = protectedObjectsNaviContent (frame, qid)
            }
        })

    wikiCode = wikiCode .. frame:preprocess('<noinclude>\\n\\n')
    --TODO activate category
    wikiCode = wikiCode .. '[[:Kategorie:Vorlage:Navigationsleiste Denkmalgeschützte Objekte in Österreich|' .. districtBaseWODA .. ']]'
    wikiCode = wikiCode .. frame:preprocess('\n\n</noinclude>')

    --TODO activate category
    local cat = '[[:Kategorie:Vorlage:Navigationsleiste Denkmalgeschützte Objekte in Österreich|' .. districtBaseWODA .. ']]'
    wikiCode = wikiCode .. frame:extensionTag ('noinclude', cat)
    
    wikiCode = wikiCode .. mw.text.tag ('noinclude', {}, 'try 2')
    wikiCode = wikiCode .. frame:preprocess(mw.text.tag ('noinclude', {}, 'try 3'))
    wikiCode = wikiCode .. frame:preprocess('<noinclude>' .. 'try 4' .. '</noinclude>')

    return wikiCode
end

-- * [[Denkmalgeschützte Objekte im Bezirk Schärding]] replace pseudo navi with single template call
-- p.protectedObjectsOverview (frame)
function p.protectedObjectsOverview(frame)
    local qid = frame.args.qid -- qid of Bezirk
    if frame.args.name then
    	qid = mw.wikibase.getEntityIdForTitle(frame.args.name)
    	end
    -- TODO replace by mapping name of Bezirk to qid of Bezirk
    --[[
    the API allows to get the qid for an arbitrary article using:
    https://de.wikipedia.org/wiki/Spezial:API-Spielwiese#action=query&prop=pageprops&format=json&ppprop=wikibase_item&titles=Bezirk%20Eferding
    arbitrary API calls from Lua are not supported
    --]]
    
    -- TODO checks
    if qid then
        if isValidDistrict(qid)
        then return protectedObjectsOverview(frame, qid)
        else return printError("not-a-district")
        end
    end
end

-- * [[Vorlage:Navigationsleiste Denkmalgeschützte Objekte im Bezirk Schärding]] replace navi with single template call
-- p.protectedObjectsNavi (frame)
function p.protectedObjectsNavi(frame, image)
    local qid = frame.args.qid -- qid of Bezirk
    if frame.args.name then
    	qid = mw.wikibase.getEntityIdForTitle(frame.args.name)
    	end
    -- TODO replace by mapping name of Bezirk to qid of Bezirk
    -- TODO checks
    if qid then
        if isValidDistrict(qid)
        then return protectedObjectsNavi(frame, qid, image)
        else return printError("not-a-district")
        end
    end
end

-- * [[Vorlage:Navigationsleiste Denkmalgeschützte Objekte im Bezirk Schärding]] replace content of navi with single template call
-- p.protectedObjectsNavi (frame)
function p.protectedObjectsNaviContent(frame)
    local qid = frame.args.qid -- qid of Bezirk
    if frame.args.name then
    	qid = mw.wikibase.getEntityIdForTitle(frame.args.name)
    	end
    -- TODO replace by mapping name of Bezirk to qid of Bezirk
    -- TODO checks
    if qid then
        if isValidDistrict(qid)
        then return protectedObjectsNaviContent(frame, qid)
        else return printError("not-a-district")
        end
    end
end

-- * [[Bezirk Schärding#Verwaltungsgliederung]] replace list of municipalities
function p.VerwaltungsgliederungNachBezirk(frame)
end

return p