「モジュール:Wd」の版間の差分

remove unused local "refHash" and narrow lifetime/scope of "valuesArray"
(1版)
 
bsd>Uzume
(remove unused local "refHash" and narrow lifetime/scope of "valuesArray")
1行目: 1行目:
-- Original module located at [[:en:Module:Wd]], [[:en:Module:Wd/i18n]] and [[:en:Module:Wd/aliasesP]].
-- Original module located at [[:en:Module:Wd]] and [[:en:Module:Wd/i18n]].


require("strict")
local p = {}
local p = {}
local arg = ...
local module_arg = ...
local i18n
local i18n
local i18nPath


function loadSubmodules(frame)
local function loadI18n(aliasesP, frame)
local title
local title
 
if frame then
if frame then
-- current module invoked by page/template, get its title from frame
-- current module invoked by page/template, get its title from frame
13行目: 15行目:
else
else
-- current module included by other module, get its title from ...
-- current module included by other module, get its title from ...
title = arg
title = module_arg
end
 
if not i18n then
i18nPath = title .. "/i18n"
i18n = require(i18nPath).init(aliasesP)
end
end
i18n = i18n or require(title .. "/i18n")
p.aliasesP = p.aliasesP or mw.loadData(title .. "/aliasesP")
end
end


30行目: 34行目:


p.generalCommands = {
p.generalCommands = {
label     = "label",
label       = "label",
title     = "title",
title       = "title",
alias     = "alias",
description = "description",
aliases   = "aliases",
alias       = "alias",
badge     = "badge",
aliases     = "aliases",
badges     = "badges"
badge       = "badge",
badges     = "badges"
}
}


60行目: 65行目:


p.args = {
p.args = {
eid = "eid"
eid = "eid",
page = "page",
date = "date",
globalSiteId = "globalSiteId"
}
 
local aliasesP = {
coord                  = "P625",
-----------------------
image                  = "P18",
author                  = "P50",
authorNameString        = "P2093",
publisher              = "P123",
importedFrom            = "P143",
wikimediaImportURL      = "P4656",
statedIn                = "P248",
pages                  = "P304",
language                = "P407",
hasPart                = "P527",
publicationDate        = "P577",
startTime              = "P580",
endTime                = "P582",
chapter                = "P792",
retrieved              = "P813",
referenceURL            = "P854",
sectionVerseOrParagraph = "P958",
archiveURL              = "P1065",
title                  = "P1476",
formatterURL            = "P1630",
quote                  = "P1683",
shortName              = "P1813",
definingFormula        = "P2534",
archiveDate            = "P2960",
inferredFrom            = "P3452",
typeOfReference        = "P3865",
column                  = "P3903",
subjectNamedAs          = "P1810",
wikidataProperty        = "P1687",
publishedIn            = "P1433"
}
}


84行目: 127行目:
qualifier            = "%q[%s][%r]",
qualifier            = "%q[%s][%r]",
reference            = "%r",
reference            = "%r",
propertyWithQualifier = "%p[ <span style=\"font-size:85%\">(%q)</span>][%s][%r]",
propertyWithQualifier = "%p[ <span style=\"font-size:85\\%\">(%q)</span>][%s][%r]",
alias                = "%a[%s]",
alias                = "%a[%s]",
badge                = "%b[%s]"
badge                = "%b[%s]"
114行目: 157行目:
}
}


local Config = {}
local function replaceAlias(id)
Config.__index = Config
if aliasesP[id] then
id = aliasesP[id]
end
 
return id
end
 
local function errorText(code, ...)
local text = i18n["errors"][code]
if arg then text = mw.ustring.format(text, unpack(arg)) end
return text
end
 
local function throwError(errorMessage, ...)
error(errorText(errorMessage, unpack(arg)))
end


-- allows for recursive calls
local function replaceDecimalMark(num)
function Config.new()
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
local cfg = {}
end
setmetatable(cfg, Config)
 
local function padZeros(num, numDigits)
cfg.separators = {
local numZeros
-- single value objects wrapped in arrays so that we can pass by reference
local negative = false
["sep"]  = {copyTable(defaultSeparators["sep"])},
 
["sep%s"] = {copyTable(defaultSeparators["sep%s"])},
if num < 0 then
["sep%q"] = {copyTable(defaultSeparators["sep%q"])},
negative = true
["sep%r"] = {copyTable(defaultSeparators["sep%r"])},
num = num * -1
["punc"]  = {copyTable(defaultSeparators["punc"])}
end
}
 
num = tostring(num)
cfg.entity = nil
numZeros = numDigits - num:len()
cfg.entityID = nil
 
cfg.propertyID = nil
for _ = 1, numZeros do
cfg.propertyValue = nil
num = "0"..num
cfg.qualifierIDs = {}
end
cfg.qualifierIDsAndValues = {}
 
if negative then
cfg.bestRank = true
num = "-"..num
cfg.ranks = {true, true, false}  -- preferred = true, normal = true, deprecated = false
end
cfg.foundRank = #cfg.ranks
 
cfg.flagBest = false
return num
cfg.flagRank = false
cfg.periods = {true, true, true}  -- future = true, current = true, former = true
cfg.flagPeriod = false
cfg.mdyDate = false
cfg.singleClaim = false
cfg.sourcedOnly = false
cfg.editable = false
cfg.editAtEnd = false
cfg.inSitelinks = false
cfg.langCode = mw.language.getContentLanguage().code
cfg.langName = mw.language.fetchLanguageName(cfg.langCode, cfg.langCode)
cfg.langObj = mw.language.new(cfg.langCode)
-- somewhat reliable way of determining global site ID in the absence of a library function, targeting the Wikipedia project (i.e. appending "wiki")
cfg.siteID = (function() for i,v in pairs(mw.site.interwikiMap("local")) do if v.isCurrentWiki and i~="w" then return mw.ustring.gsub(i,"-","_").."wiki" end end end)()
cfg.states = {}
cfg.states.qualifiersCount = 0
cfg.curState = nil
cfg.prefetchedRefs = nil
return cfg
end
end


local State = {}
local function replaceSpecialChar(chr)
State.__index = State
if chr == '_' then
 
-- replace underscores with spaces
function State.new(cfg)
return ' '
local stt = {}
else
setmetatable(stt, State)
return chr
stt.conf = cfg
stt.results = {}
stt.parsedFormat = {}
stt.separator = {}
stt.movSeparator = {}
stt.puncMark = {}
stt.linked = false
stt.rawValue = false
stt.shortName = false
stt.anyLanguage = false
stt.unitOnly = false
stt.singleValue = false
return stt
end
 
function replaceAlias(id)
if p.aliasesP[id] then
id = p.aliasesP[id]
end
end
return id
end
end


function errorText(code, param)
local function replaceSpecialChars(str)
local text = i18n["errors"][code]
local chr
if param then text = mw.ustring.gsub(text, "$1", param) end
local esc = false
return text
local strOut = ""
end
 
for i = 1, #str do
chr = str:sub(i,i)
 
if not esc then
if chr == '\\' then
esc = true
else
strOut = strOut .. replaceSpecialChar(chr)
end
else
strOut = strOut .. chr
esc = false
end
end


function throwError(errorMessage, param)
return strOut
error(errorText(errorMessage, param))
end
end


function replaceDecimalMark(num)
local function buildWikilink(target, label)
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
if not label or target == label then
return "[[" .. target .. "]]"
else
return "[[" .. target .. "|" .. label .. "]]"
end
end
end


function padZeros(num, numDigits)
-- used to make frame.args mutable, to replace #frame.args (which is always 0)
local numZeros
-- with the actual amount and to simply copy tables
local negative = false
local function copyTable(tIn)
if not tIn then
if num < 0 then
return nil
negative = true
num = num * -1
end
end
 
num = tostring(num)
local tOut = {}
numZeros = numDigits - num:len()
 
for i, v in pairs(tIn) do
for i = 1, numZeros do
tOut[i] = v
num = "0"..num
end
if negative then
num = "-"..num
end
end
return num
end


function replaceSpecialChar(chr)
return tOut
if chr == '_' then
-- replace underscores with spaces
return ' '
else
return chr
end
end
end


function replaceSpecialChars(str)
-- used to merge output arrays together;
local chr
-- note that it currently mutates the first input array
local esc = false
local function mergeArrays(a1, a2)
local strOut = ""
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
for i = 1, #str do
chr = str:sub(i,i)
if not esc then
if chr == '\\' then
esc = true
else
strOut = strOut .. replaceSpecialChar(chr)
end
else
strOut = strOut .. chr
esc = false
end
end
end
return strOut
end


function buildWikilink(target, label)
return a1
if not label or target == label then
return "[[" .. target .. "]]"
else
return "[[" .. target .. "|" .. label .. "]]"
end
end
end


-- used to make frame.args mutable, to replace #frame.args (which is always 0)
local function split(str, del)
-- with the actual amount and to simply copy tables
function copyTable(tIn)
if not tIn then
return nil
end
local tOut = {}
for i, v in pairs(tIn) do
tOut[i] = v
end
return tOut
end
 
-- used to merge output arrays together;
-- note that it currently mutates the first input array
function mergeArrays(a1, a2)
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
end
return a1
end
 
function split(str, del)
local out = {}
local out = {}
local i, j = str:find(del)
local i, j = str:find(del)
 
if i and j then
if i and j then
out[1] = str:sub(1, i - 1)
out[1] = str:sub(1, i - 1)
318行目: 278行目:
out[1] = str
out[1] = str
end
end
 
return out
return out
end
end


function parseWikidataURL(url)
local function parseWikidataURL(url)
local id
local id
 
if url:match('^http[s]?://') then
if url:match('^http[s]?://') then
id = split(url, "Q")
id = split(url, "Q")
 
if id[2] then
if id[2] then
return "Q" .. id[2]
return "Q" .. id[2]
end
end
end
end
 
return nil
return nil
end
end


function parseDate(dateStr, precision)
local function parseDate(dateStr, precision)
precision = precision or "d"
precision = precision or "d"
 
local i, j, index, ptr
local i, j, index, ptr
local parts = {nil, nil, nil}
local parts = {nil, nil, nil}
 
if dateStr == nil then
if dateStr == nil then
return parts[1], parts[2], parts[3]  -- year, month, day
return parts[1], parts[2], parts[3]  -- year, month, day
end
end
 
-- 'T' for snak values, '/' for outputs with '/Julian' attached
-- 'T' for snak values, '/' for outputs with '/Julian' attached
i, j = dateStr:find("[T/]")
i, j = dateStr:find("[T/]")
 
if i then
if i then
dateStr = dateStr:sub(1, i-1)
dateStr = dateStr:sub(1, i-1)
end
end
 
local from = 1
local from = 1
 
if dateStr:sub(1,1) == "-" then
if dateStr:sub(1,1) == "-" then
-- this is a negative number, look further ahead
-- this is a negative number, look further ahead
from = 2
from = 2
end
end
 
index = 1
index = 1
ptr = 1
ptr = 1
 
i, j = dateStr:find("-", from)
i, j = dateStr:find("-", from)
 
if i then
if i then
-- year
-- year
parts[index] = tonumber(mw.ustring.gsub(dateStr:sub(ptr, i-1), "^\+(.+)$", "%1"), 10)  -- remove '+' sign (explicitly give base 10 to prevent error)
parts[index] = tonumber(dateStr:sub(ptr, i-1), 10)  -- explicitly give base 10 to prevent error
 
if parts[index] == -0 then
if parts[index] == -0 then
parts[index] = tonumber("0")  -- for some reason, 'parts[index] = 0' may actually store '-0', so parse from string instead
parts[index] = tonumber("0")  -- for some reason, 'parts[index] = 0' may actually store '-0', so parse from string instead
end
end
 
if precision == "y" then
if precision == "y" then
-- we're done
-- we're done
return parts[1], parts[2], parts[3]  -- year, month, day
return parts[1], parts[2], parts[3]  -- year, month, day
end
end
 
index = index + 1
index = index + 1
ptr = i + 1
ptr = i + 1
 
i, j = dateStr:find("-", ptr)
i, j = dateStr:find("-", ptr)
 
if i then
if i then
-- month
-- month
parts[index] = tonumber(dateStr:sub(ptr, i-1), 10)
parts[index] = tonumber(dateStr:sub(ptr, i-1), 10)
 
if precision == "m" then
if precision == "m" then
-- we're done
-- we're done
return parts[1], parts[2], parts[3]  -- year, month, day
return parts[1], parts[2], parts[3]  -- year, month, day
end
end
 
index = index + 1
index = index + 1
ptr = i + 1
ptr = i + 1
end
end
end
end
 
if dateStr:sub(ptr) ~= "" then
if dateStr:sub(ptr) ~= "" then
-- day if we have month, month if we have year, or year
-- day if we have month, month if we have year, or year
parts[index] = tonumber(dateStr:sub(ptr), 10)
parts[index] = tonumber(dateStr:sub(ptr), 10)
end
end
 
return parts[1], parts[2], parts[3]  -- year, month, day
return parts[1], parts[2], parts[3]  -- year, month, day
end
end


function datePrecedesDate(aY, aM, aD, bY, bM, bD)
local function datePrecedesDate(aY, aM, aD, bY, bM, bD)
if aY == nil or bY == nil then
if aY == nil or bY == nil then
return nil
return nil
413行目: 373行目:
bM = bM or 1
bM = bM or 1
bD = bD or 1
bD = bD or 1
 
if aY < bY then
if aY < bY then
return true
return true
end
end
 
if aY > bY then
if aY > bY then
return false
return false
end
end
 
if aM < bM then
if aM < bM then
return true
return true
end
end
 
if aM > bM then
if aM > bM then
return false
return false
end
end
 
if aD < bD then
if aD < bD then
return true
return true
end
end
 
return false
return false
end
end


function getHookName(param, index)
local function getHookName(param, index)
if hookNames[param] then
if hookNames[param] then
return hookNames[param][index]
return hookNames[param][index]
447行目: 407行目:
end
end


function alwaysTrue()
local function alwaysTrue()
return true
return true
end
end
496行目: 456行目:
-- ]
-- ]
--
--
function parseFormat(str)
local function parseFormat(str)
local chr, esc, param, root, cur, prev, new
local chr, esc, param, root, cur, prev, new
local params = {}
local params = {}
 
local function newObject(array)
local function newObject(array)
local obj = {}  -- new object
local obj = {}  -- new object
obj.str = ""
obj.str = ""
 
array[#array + 1] = obj  -- array{object}
array[#array + 1] = obj  -- array{object}
obj.parent = array
obj.parent = array
 
return obj
return obj
end
end
 
local function endParam()
local function endParam()
if param > 0 then
if param > 0 then
523行目: 483行目:
end
end
end
end
 
root = {}  -- array
root = {}  -- array
root.req = {}
root.req = {}
cur = newObject(root)
cur = newObject(root)
prev = nil
prev = nil
 
esc = false
esc = false
param = 0
param = 0
 
for i = 1, #str do
for i = 1, #str do
chr = str:sub(i,i)
chr = str:sub(i,i)
 
if not esc then
if not esc then
if chr == '\\' then
if chr == '\\' then
572行目: 532行目:
end
end
end
end
 
cur.str = cur.str .. replaceSpecialChar(chr)
cur.str = cur.str .. replaceSpecialChar(chr)
end
end
579行目: 539行目:
esc = false
esc = false
end
end
 
prev = nil
prev = nil
end
end
 
endParam()
endParam()
 
-- make sure that at least one required parameter has been defined
-- make sure that at least one required parameter has been defined
if not next(root.req) then
if not next(root.req) then
throwError("missing-required-parameter")
throwError("missing-required-parameter")
end
end
 
-- make sure that the separator parameter "%s" is not amongst the required parameters
-- make sure that the separator parameter "%s" is not amongst the required parameters
if root.req[parameters.separator] then
if root.req[parameters.separator] then
throwError("extra-required-parameter", parameters.separator)
throwError("extra-required-parameter", parameters.separator)
end
end
 
return root, params
return root, params
end
end


function sortOnRank(claims)
local function sortOnRank(claims)
local rankPos
local rankPos
local ranks = {{}, {}, {}, {}}  -- preferred, normal, deprecated, (default)
local ranks = {{}, {}, {}, {}}  -- preferred, normal, deprecated, (default)
local sorted = {}
local sorted = {}
 
for i, v in ipairs(claims) do
for _, v in ipairs(claims) do
rankPos = rankTable[v.rank] or 4
rankPos = rankTable[v.rank] or 4
ranks[rankPos][#ranks[rankPos] + 1] = v
ranks[rankPos][#ranks[rankPos] + 1] = v
end
end
 
sorted = ranks[1]
sorted = ranks[1]
sorted = mergeArrays(sorted, ranks[2])
sorted = mergeArrays(sorted, ranks[2])
sorted = mergeArrays(sorted, ranks[3])
sorted = mergeArrays(sorted, ranks[3])
 
return sorted
return sorted
end
end


-- if id == nil then item connected to current page is used
local function isValueInTable(searchedItem, inputTable)
function Config:getLabel(id, raw, link, short)
for _, item in pairs(inputTable) do
local label = nil
if item == searchedItem then
local title = nil
return true
local prefix= ""
end
local lang
end
return false
if not id then
end
id = mw.wikibase.getEntityIdForCurrentPage()
 
local Config = {}
if not id then
 
return ""
-- allows for recursive calls
end
function Config:new()
end
local cfg = {}
setmetatable(cfg, self)
id = id:upper()  -- just to be sure
self.__index = self
 
if raw then
cfg.separators = {
-- check if given id actually exists
-- single value objects wrapped in arrays so that we can pass by reference
if mw.wikibase.getEntity(id) then
["sep"]  = {copyTable(defaultSeparators["sep"])},
label = id
["sep%s"] = {copyTable(defaultSeparators["sep%s"])},
["sep%q"] = {copyTable(defaultSeparators["sep%q"])},
if id:sub(1,1) == "P" then
["sep%r"] = {copyTable(defaultSeparators["sep%r"])},
prefix = "Property:"
["punc"]  = {copyTable(defaultSeparators["punc"])}
end
}
end
 
cfg.entity = nil
prefix = "d:" .. prefix
cfg.entityID = nil
cfg.propertyID = nil
title = label  -- may be nil
cfg.propertyValue = nil
else
cfg.qualifierIDs = {}
-- try short name first if requested
cfg.qualifierIDsAndValues = {}
if short then
 
label = p._property({p.aliasesP.shortName, [p.args.eid] = id})  -- get short name
cfg.bestRank = true
cfg.ranks = {true, true, false}  -- preferred = true, normal = true, deprecated = false
if label == "" then
cfg.foundRank = #cfg.ranks
label = nil
cfg.flagBest = false
end
cfg.flagRank = false
end
 
cfg.periods = {true, true, true}  -- future = true, current = true, former = true
-- get label
cfg.flagPeriod = false
if not label then
cfg.atDate = {parseDate(os.date('!%Y-%m-%d'))}  -- today as {year, month, day}
label, lang = mw.wikibase.getLabelWithLang(id)
-- don't allow language fallback
if lang ~= self.langCode then
label = nil
end
end
end
if not label then
label = ""
elseif link then
-- build a link if requested
if not title then
if id:sub(1,1) == "Q" then
title = mw.wikibase.sitelink(id)
elseif id:sub(1,1) == "P" then
-- properties have no sitelink, link to Wikidata instead
title = id
prefix = "d:Property:"
end
end
if title then
label = buildWikilink(prefix .. title, label)
end
end
return label
end


function Config:getEditIcon()
cfg.mdyDate = false
local value = ""
cfg.singleClaim = false
local prefix = ""
cfg.sourcedOnly = false
local front = " "
cfg.editable = false
local back = ""
cfg.editAtEnd = false
 
if self.entityID:sub(1,1) == "P" then
cfg.inSitelinks = false
prefix = "Property:"
 
end
cfg.langCode = mw.language.getContentLanguage().code
cfg.langName = mw.language.fetchLanguageName(cfg.langCode, cfg.langCode)
if self.editAtEnd then
cfg.langObj = mw.language.new(cfg.langCode)
front = '<span style="float:'
 
cfg.siteID = mw.wikibase.getGlobalSiteId()
if self.langObj:isRTL() then
 
front = front .. 'left'
cfg.states = {}
else
cfg.states.qualifiersCount = 0
front = front .. 'right'
cfg.curState = nil
end
 
cfg.prefetchedRefs = nil
front = front .. '">'
 
back = '</span>'
return cfg
end
value = "[[File:Blue pencil.svg|frameless|text-top|10px|alt=" .. i18n['info']['edit-on-wikidata'] .. "|link=https://www.wikidata.org/wiki/" .. prefix .. self.entityID .. "?uselang=" .. self.langCode
if self.propertyID then
value = value .. "#" .. self.propertyID
elseif self.inSitelinks then
value = value .. "#sitelinks-wikipedia"
end
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
return front .. value .. back
end
end


-- used to create the final output string when it's all done, so that for references the
local State = {}
-- function extensionTag("ref", ...) is only called when they really ended up in the final output
 
function Config:concatValues(valuesArray)
function State:new(cfg, type)
local outString = ""
local stt = {}
local j, skip
setmetatable(stt, self)
self.__index = self
for i = 1, #valuesArray do
 
-- check if this is a reference
stt.conf = cfg
if valuesArray[i].refHash then
stt.type = type
j = i - 1
 
skip = false
stt.results = {}
-- skip this reference if it is part of a continuous row of references that already contains the exact same reference
while valuesArray[j] and valuesArray[j].refHash do
if valuesArray[i].refHash == valuesArray[j].refHash then
skip = true
break
end
j = j - 1
end
if not skip then
-- add <ref> tag with the reference's hash as its name (to deduplicate references)
outString = outString .. mw.getCurrentFrame():extensionTag("ref", valuesArray[i][1], {name = "wikidata-" .. valuesArray[i].refHash .. "-v" .. i18n['cite']['version']})
end
else
outString = outString .. valuesArray[i][1]
end
end
return outString
end


function Config:convertUnit(unit, raw, link, short, unitOnly)
stt.parsedFormat = {}
local space = " "
stt.separator = {}
local label = ""
stt.movSeparator = {}
stt.puncMark = {}
if unit == "" or unit == "1" then
 
return nil
stt.linked = false
stt.rawValue = false
stt.shortName = false
stt.anyLanguage = false
stt.unitOnly = false
stt.singleValue = false
 
return stt
end
 
-- if id == nil then item connected to current page is used
function Config:getLabel(id, raw, link, short)
local label = nil
local prefix, title= "", nil
 
if not id then
id = mw.wikibase.getEntityIdForCurrentPage()
 
if not id then
return ""
end
end
end
 
if unitOnly then
id = id:upper()  -- just to be sure
space = ""
 
end
if raw then
-- check if given id actually exists
itemID = parseWikidataURL(unit)
if mw.wikibase.isValidEntityId(id) and mw.wikibase.entityExists(id) then
label = id
if itemID then
end
if itemID == aliasesQ.percentage then
 
return "%"
prefix, title = "d:Special:EntityPage/", label -- may be nil
else
else
label = self:getLabel(itemID, raw, link, short)
-- try short name first if requested
if short then
if label ~= "" then
label = p._property{aliasesP.shortName, [p.args.eid] = id}  -- get short name
return space .. label
 
if label == "" then
label = nil
end
end
end
-- get label
if not label then
label = mw.wikibase.getLabel(id)
end
end
end
end
return ""
end


function Config:getValue(snak, raw, link, short, anyLang, unitOnly, noSpecial)
if not label then
if snak.snaktype == 'value' then
label = ""
local datatype = snak.datavalue.type
elseif link then
local subtype = snak.datatype
-- build a link if requested
local datavalue = snak.datavalue.value
if not title then
if id:sub(1,1) == "Q" then
if datatype == 'string' then
title = mw.wikibase.getSitelink(id)
if subtype == 'url' and link then
elseif id:sub(1,1) == "P" then
-- create link explicitly
-- properties have no sitelink, link to Wikidata instead
if raw then
prefix, title = "d:Special:EntityPage/", id
-- will render as a linked number like [1]
end
return "[" .. datavalue .. "]"
end
else
 
return "[" .. datavalue .. " " .. datavalue .. "]"
label = mw.text.nowiki(label) -- escape raw label text so it cannot be wikitext markup
end
if title then
elseif subtype == 'commonsMedia' then
label = buildWikilink(prefix .. title, label)
if link then
end
return buildWikilink("c:File:" .. datavalue, datavalue)
end
elseif not raw then
 
return "[[File:" .. datavalue .. "]]"
return label
else
end
return datavalue
 
end
function Config:getEditIcon()
elseif subtype == 'geo-shape' and link then
local value = ""
return buildWikilink("c:" .. datavalue, datavalue)
local prefix = ""
elseif subtype == 'math' and not raw then
local front = "&nbsp;"
return mw.getCurrentFrame():extensionTag("math", datavalue)
local back = ""
elseif subtype == 'external-id' and link then
 
local url = p._property({p.aliasesP.formatterURL, [p.args.eid] = snak.property})  -- get formatter URL
if self.entityID:sub(1,1) == "P" then
prefix = "Property:"
if url ~= "" then
end
url = mw.ustring.gsub(url, "$1", datavalue)
 
return "[" .. url .. " " .. datavalue .. "]"
if self.editAtEnd then
else
front = '<span style="float:'
return datavalue
 
end
if self.langObj:isRTL() then
else
front = front .. 'left'
return datavalue
else
end
front = front .. 'right'
elseif datatype == 'monolingualtext' then
end
if anyLang then
 
return datavalue['text'], datavalue['language']
front = front .. '">'
elseif datavalue['language'] == self.langCode then
back = '</span>'
return datavalue['text']
end
else
 
return nil
value = "[[File:OOjs UI icon edit-ltr-progressive.svg|frameless|text-top|10px|alt=" .. i18n['info']['edit-on-wikidata'] .. "|link=https://www.wikidata.org/wiki/" .. prefix .. self.entityID .. "?uselang=" .. self.langCode
end
 
elseif datatype == 'quantity' then
if self.propertyID then
local value = ""
value = value .. "#" .. self.propertyID
local unit
elseif self.inSitelinks then
value = value .. "#sitelinks-wikipedia"
if not unitOnly then
end
-- get value and strip + signs from front
 
value = mw.ustring.gsub(datavalue['amount'], "^\+(.+)$", "%1")
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
 
if raw then
return front .. value .. back
return value
end
 
-- used to create the final output string when it's all done, so that for references the
-- function extensionTag("ref", ...) is only called when they really ended up in the final output
function Config:concatValues(valuesArray)
local outString = ""
local j, skip
 
for i = 1, #valuesArray do
-- check if this is a reference
if valuesArray[i].refHash then
j = i - 1
skip = false
 
-- skip this reference if it is part of a continuous row of references that already contains the exact same reference
while valuesArray[j] and valuesArray[j].refHash do
if valuesArray[i].refHash == valuesArray[j].refHash then
skip = true
break
end
end
j = j - 1
-- replace decimal mark based on locale
end
value = replaceDecimalMark(value)
 
if not skip then
-- add delimiters for readability
-- add <ref> tag with the reference's hash as its name (to deduplicate references)
value = i18n.addDelimiters(value)
outString = outString .. mw.getCurrentFrame():extensionTag("ref", valuesArray[i][1], {name = valuesArray[i].refHash})
end
end
else
unit = self:convertUnit(datavalue['unit'], raw, link, short, unitOnly)
outString = outString .. valuesArray[i][1]
end
if unit then
end
value = value .. unit
 
end
return outString
end
return value
 
elseif datatype == 'time' then
function Config:convertUnit(unit, raw, link, short, unitOnly)
local y, m, d, p, yDiv, yRound, yFull, value, calendarID, dateStr
local space = " "
local yFactor = 1
local label = ""
local sign = 1
local itemID
local prefix = ""
 
local suffix = ""
if unit == "" or unit == "1" then
local mayAddCalendar = false
return nil
local calendar = ""
end
local precision = datavalue['precision']
 
if unitOnly then
if precision == 11 then
space = ""
p = "d"
end
elseif precision == 10 then
 
p = "m"
itemID = parseWikidataURL(unit)
else
 
p = "y"
if itemID then
yFactor = 10^(9-precision)
if itemID == aliasesQ.percentage then
return "%"
else
label = self:getLabel(itemID, raw, link, short)
 
if label ~= "" then
return space .. label
end
end
end
y, m, d = parseDate(datavalue['time'], p)
end
 
if y < 0 then
return ""
sign = -1
end
y = y * sign
 
end
function State:getValue(snak)
return self.conf:getValue(snak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly, false, self.type:sub(1,2))
-- if precision is tens/hundreds/thousands/millions/billions of years
end
if precision <= 8 then
 
yDiv = y / yFactor
function Config:getValue(snak, raw, link, short, anyLang, unitOnly, noSpecial, type)
if snak.snaktype == 'value' then
-- if precision is tens/hundreds/thousands of years
local datatype = snak.datavalue.type
if precision >= 6 then
local subtype = snak.datatype
mayAddCalendar = true
local datavalue = snak.datavalue.value
 
if precision <= 7 then
if datatype == 'string' then
-- round centuries/millenniums up (e.g. 20th century or 3rd millennium)
if subtype == 'url' and link then
yRound = math.ceil(yDiv)
-- create link explicitly
if raw then
if not raw then
-- will render as a linked number like [1]
if precision == 6 then
return "[" .. datavalue .. "]"
suffix = i18n['datetime']['suffixes']['millennium']
else
suffix = i18n['datetime']['suffixes']['century']
end
suffix = i18n.getOrdinalSuffix(yRound) .. suffix
else
-- if not verbose, take the first year of the century/millennium
-- (e.g. 1901 for 20th century or 2001 for 3rd millennium)
yRound = (yRound - 1) * yFactor + 1
end
else
-- precision == 8
-- round decades down (e.g. 2010s)
yRound = math.floor(yDiv) * yFactor
if not raw then
prefix = i18n['datetime']['prefixes']['decade-period']
suffix = i18n['datetime']['suffixes']['decade-period']
end
end
if raw and sign < 0 then
-- if BCE then compensate for "counting backwards"
-- (e.g. -2019 for 2010s BCE, -2000 for 20th century BCE or -3000 for 3rd millennium BCE)
yRound = yRound + yFactor - 1
end
else
else
local yReFactor, yReDiv, yReRound
return "[" .. datavalue .. " " .. datavalue .. "]"
end
-- round to nearest for tens of thousands of years or more
elseif subtype == 'commonsMedia' then
yRound = math.floor(yDiv + 0.5)
if link then
return buildWikilink("c:File:" .. datavalue, datavalue)
if yRound == 0 then
elseif not raw then
if precision <= 2 and y ~= 0 then
return "[[File:" .. datavalue .. "]]"
yReFactor = 1e6
else
yReDiv = y / yReFactor
return datavalue
yReRound = math.floor(yReDiv + 0.5)
end
elseif subtype == 'geo-shape' and link then
if yReDiv == yReRound then
return buildWikilink("c:" .. datavalue, datavalue)
-- change precision to millions of years only if we have a whole number of them
elseif subtype == 'math' and not raw then
precision = 3
local attribute = nil
yFactor = yReFactor
 
yRound = yReRound
if (type == parameters.property or (type == parameters.qualifier and self.propertyID == aliasesP.hasPart)) and snak.property == aliasesP.definingFormula then
end
attribute = {qid = self.entityID}
end
end
 
if yRound == 0 then
return mw.getCurrentFrame():extensionTag("math", datavalue, attribute)
-- otherwise, take the unrounded (original) number of years
elseif subtype == 'external-id' and link then
precision = 5
local url = p._property{aliasesP.formatterURL, [p.args.eid] = snak.property}  -- get formatter URL
yFactor = 1
 
yRound = y
if url ~= "" then
mayAddCalendar = true
url = mw.ustring.gsub(url, "$1", datavalue)
end
return "[" .. url .. " " .. datavalue .. "]"
end
else
return datavalue
if precision >= 1 and y ~= 0 then
end
yFull = yRound * yFactor
else
return datavalue
yReFactor = 1e9
end
yReDiv = yFull / yReFactor
elseif datatype == 'monolingualtext' then
yReRound = math.floor(yReDiv + 0.5)
if anyLang or datavalue['language'] == self.langCode then
return datavalue['text']
if yReDiv == yReRound then
else
-- change precision to billions of years if we're in that range
return nil
precision = 0
end
yFactor = yReFactor
elseif datatype == 'quantity' then
yRound = yReRound
local value = ""
else
local unit
yReFactor = 1e6
 
yReDiv = yFull / yReFactor
if not unitOnly then
yReRound = math.floor(yReDiv + 0.5)
-- get value and strip + signs from front
value = mw.ustring.gsub(datavalue['amount'], "^%+(.+)$", "%1")
if yReDiv == yReRound then
 
-- change precision to millions of years if we're in that range
if raw then
precision = 3
return value
yFactor = yReFactor
end
yRound = yReRound
 
end
-- replace decimal mark based on locale
end
value = replaceDecimalMark(value)
end
 
-- add delimiters for readability
if not raw then
value = i18n.addDelimiters(value)
if precision == 3 then
suffix = i18n['datetime']['suffixes']['million-years']
elseif precision == 0 then
suffix = i18n['datetime']['suffixes']['billion-years']
else
yRound = yRound * yFactor
if yRound == 1 then
suffix = i18n['datetime']['suffixes']['year']
else
suffix = i18n['datetime']['suffixes']['years']
end
end
else
yRound = yRound * yFactor
end
end
else
yRound = y
mayAddCalendar = true
end
end
 
if mayAddCalendar then
unit = self:convertUnit(datavalue['unit'], raw, link, short, unitOnly)
calendarID = parseWikidataURL(datavalue['calendarmodel'])
 
if unit then
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
value = value .. unit
if not raw then
if link then
calendar = " ("..buildWikilink(i18n['datetime']['julian-calendar'], i18n['datetime']['julian'])..")"
else
calendar = " ("..i18n['datetime']['julian']..")"
end
else
calendar = "/"..i18n['datetime']['julian']
end
end
end
end
 
if not raw then
return value
local ce = nil
elseif datatype == 'time' then
local y, m, d, p, yDiv, yRound, yFull, value, calendarID, dateStr
if sign < 0 then
local yFactor = 1
ce = i18n['datetime']['BCE']
local sign = 1
elseif precision <= 5 then
local prefix = ""
ce = i18n['datetime']['CE']
local suffix = ""
end
local mayAddCalendar = false
local calendar = ""
if ce then
local precision = datavalue['precision']
if link then
 
ce = buildWikilink(i18n['datetime']['common-era'], ce)
if precision == 11 then
end
p = "d"
suffix = suffix .. " " .. ce
elseif precision == 10 then
end
p = "m"
value = tostring(yRound)
if m then
dateStr = self.langObj:formatDate("F", "1-"..m.."-1")
if d then
if self.mdyDate then
dateStr = dateStr .. " " .. d .. ","
else
dateStr = d .. " " .. dateStr
end
end
value = dateStr .. " " .. value
end
value = prefix .. value .. suffix .. calendar
else
else
value = padZeros(yRound * sign, 4)
p = "y"
yFactor = 10^(9-precision)
if m then
end
value = value .. "-" .. padZeros(m, 2)
 
y, m, d = parseDate(datavalue['time'], p)
if d then
 
value = value .. "-" .. padZeros(d, 2)
if y < 0 then
end
sign = -1
end
y = y * sign
value = value .. calendar
end
end
return value
elseif datatype == 'globecoordinate' then
-- logic from https://github.com/DataValues/Geo
local precision, numDigits, strFormat, value, globe
local latValue, latitude, latDegrees, latMinutes, latSeconds
local lonValue, longitude, lonDegrees, lonMinutes, lonSeconds
local latDirection, latDirectionN, latDirectionS, latDirectionEN
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
local latDirectionEN_N = "N"
local latDirectionEN_S = "S"
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
if not raw then
latDirectionN = i18n['coord']['latitude-north']
latDirectionS = i18n['coord']['latitude-south']
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionW = i18n['coord']['longitude-west']
degSymbol = i18n['coord']['degrees']
minSymbol = i18n['coord']['minutes']
secSymbol = i18n['coord']['seconds']
separator = i18n['coord']['separator']
else
latDirectionN = latDirectionEN_N
latDirectionS = latDirectionEN_S
lonDirectionE = lonDirectionEN_E
lonDirectionW = lonDirectionEN_W
degSymbol = "/"
minSymbol = "/"
secSymbol = "/"
separator = "/"
end
latitude = datavalue['latitude']
longitude = datavalue['longitude']
if latitude < 0 then
latDirection = latDirectionS
latDirectionEN = latDirectionEN_S
latitude = math.abs(latitude)
else
latDirection = latDirectionN
latDirectionEN = latDirectionEN_N
end
if longitude < 0 then
lonDirection = lonDirectionW
lonDirectionEN = lonDirectionEN_W
longitude = math.abs(longitude)
else
lonDirection = lonDirectionE
lonDirectionEN = lonDirectionEN_E
end
precision = datavalue['precision']
if not precision or precision == 0 then
precision = 1 / 3600  -- precision unspecified, set to arcsecond
end
latitude = math.floor(latitude / precision + 0.5) * precision
longitude = math.floor(longitude / precision + 0.5) * precision
numDigits = math.ceil(-math.log10(3600 * precision))
if numDigits < 0 or numDigits == -0 then
numDigits = tonumber("0")  -- for some reason, 'numDigits = 0' may actually store '-0', so parse from string instead
end
strFormat = "%." .. numDigits .. "f"
-- use string.format() to strip decimal point followed by a zero (.0) for whole numbers
latSeconds = tonumber(strFormat:format(math.floor(latitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
lonSeconds = tonumber(strFormat:format(math.floor(longitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
latMinutes = math.floor(latSeconds / 60)
lonMinutes = math.floor(lonSeconds / 60)
latSeconds = latSeconds - (latMinutes * 60)
lonSeconds = lonSeconds - (lonMinutes * 60)
latDegrees = math.floor(latMinutes / 60)
lonDegrees = math.floor(lonMinutes / 60)
latMinutes = latMinutes - (latDegrees * 60)
lonMinutes = lonMinutes - (lonDegrees * 60)
latValue = latDegrees .. degSymbol
lonValue = lonDegrees .. degSymbol
if precision < 1 then
latValue = latValue .. latMinutes .. minSymbol
lonValue = lonValue .. lonMinutes .. minSymbol
end
if precision < (1 / 60) then
latSeconds = strFormat:format(latSeconds)
lonSeconds = strFormat:format(lonSeconds)
if not raw then
-- replace decimal marks based on locale
latSeconds = replaceDecimalMark(latSeconds)
lonSeconds = replaceDecimalMark(lonSeconds)
end
latValue = latValue .. latSeconds .. secSymbol
lonValue = lonValue .. lonSeconds .. secSymbol
end
latValue = latValue .. latDirection
lonValue = lonValue .. lonDirection
value = latValue .. separator .. lonValue
if link then
globe = parseWikidataURL(datavalue['globe'])
if globe then
globe = mw.wikibase.getEntity(globe):getLabel("en"):lower()
else
globe = "earth"
end
value = "[https://tools.wmflabs.org/geohack/geohack.php?language="..self.langCode.."&params="..latitude.."_"..latDirectionEN.."_"..longitude.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
end
return value
elseif datatype == 'wikibase-entityid' then
local label
local itemID = datavalue['numeric-id']
if subtype == 'wikibase-item' then
itemID = "Q" .. itemID
elseif subtype == 'wikibase-property' then
itemID = "P" .. itemID
else
return '<strong class="error">' .. errorText('unknown-data-type', subtype) .. '</strong>'
end
label = self:getLabel(itemID, raw, link, short)
if label == "" then
label = nil
end
return label
else
return '<strong class="error">' .. errorText('unknown-data-type', datatype) .. '</strong>'
end
elseif snak.snaktype == 'somevalue' and not noSpecial then
if raw then
return " "  -- single space represents 'somevalue'
else
return i18n['values']['unknown']
end
elseif snak.snaktype == 'novalue' and not noSpecial then
if raw then
return ""  -- empty string represents 'novalue'
else
return i18n['values']['none']
end
else
return nil
end
end


function Config:getSingleRawQualifier(claim, qualifierID)
-- if precision is tens/hundreds/thousands/millions/billions of years
local qualifiers
if precision <= 8 then
yDiv = y / yFactor
if claim.qualifiers then qualifiers = claim.qualifiers[qualifierID] end
 
-- if precision is tens/hundreds/thousands of years
if qualifiers and qualifiers[1] then
if precision >= 6 then
return self:getValue(qualifiers[1], true) -- raw = true
mayAddCalendar = true
else
 
return nil
if precision <= 7 then
end
-- round centuries/millenniums up (e.g. 20th century or 3rd millennium)
end
yRound = math.ceil(yDiv)
 
if not raw then
if precision == 6 then
suffix = i18n['datetime']['suffixes']['millennium']
else
suffix = i18n['datetime']['suffixes']['century']
end
 
suffix = i18n.getOrdinalSuffix(yRound) .. suffix
else
-- if not verbose, take the first year of the century/millennium
-- (e.g. 1901 for 20th century or 2001 for 3rd millennium)
yRound = (yRound - 1) * yFactor + 1
end
else
-- precision == 8
-- round decades down (e.g. 2010s)
yRound = math.floor(yDiv) * yFactor
 
if not raw then
prefix = i18n['datetime']['prefixes']['decade-period']
suffix = i18n['datetime']['suffixes']['decade-period']
end
end
 
if raw and sign < 0 then
-- if BCE then compensate for "counting backwards"
-- (e.g. -2019 for 2010s BCE, -2000 for 20th century BCE or -3000 for 3rd millennium BCE)
yRound = yRound + yFactor - 1
end
else
local yReFactor, yReDiv, yReRound
 
-- round to nearest for tens of thousands of years or more
yRound = math.floor(yDiv + 0.5)
 
if yRound == 0 then
if precision <= 2 and y ~= 0 then
yReFactor = 1e6
yReDiv = y / yReFactor
yReRound = math.floor(yReDiv + 0.5)
 
if yReDiv == yReRound then
-- change precision to millions of years only if we have a whole number of them
precision = 3
yFactor = yReFactor
yRound = yReRound
end
end
 
if yRound == 0 then
-- otherwise, take the unrounded (original) number of years
precision = 5
yFactor = 1
yRound = y
mayAddCalendar = true
end
end
 
if precision >= 1 and y ~= 0 then
yFull = yRound * yFactor
 
yReFactor = 1e9
yReDiv = yFull / yReFactor
yReRound = math.floor(yReDiv + 0.5)
 
if yReDiv == yReRound then
-- change precision to billions of years if we're in that range
precision = 0
yFactor = yReFactor
yRound = yReRound
else
yReFactor = 1e6
yReDiv = yFull / yReFactor
yReRound = math.floor(yReDiv + 0.5)
 
if yReDiv == yReRound then
-- change precision to millions of years if we're in that range
precision = 3
yFactor = yReFactor
yRound = yReRound
end
end
end


function Config:snakEqualsValue(snak, value)
if not raw then
local snakValue = self:getValue(snak, true)  -- raw = true
if precision == 3 then
suffix = i18n['datetime']['suffixes']['million-years']
if snakValue and snak.snaktype == 'value' and snak.datavalue.type == 'wikibase-entityid' then value = value:upper() end
elseif precision == 0 then
suffix = i18n['datetime']['suffixes']['billion-years']
return snakValue == value
else
end
yRound = yRound * yFactor
if yRound == 1 then
suffix = i18n['datetime']['suffixes']['year']
else
suffix = i18n['datetime']['suffixes']['years']
end
end
else
yRound = yRound * yFactor
end
end
else
yRound = y
mayAddCalendar = true
end
 
if mayAddCalendar then
calendarID = parseWikidataURL(datavalue['calendarmodel'])


function Config:setRank(rank)
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
local rankPos
if not raw then
if link then
if rank == p.flags.best then
calendar = " ("..buildWikilink(i18n['datetime']['julian-calendar'], i18n['datetime']['julian'])..")"
self.bestRank = true
else
self.flagBest = true  -- mark that 'best' flag was given
calendar = " ("..i18n['datetime']['julian']..")"
return
end
end
else
calendar = "/"..i18n['datetime']['julian']
if rank:sub(1,9) == p.flags.preferred then
end
rankPos = 1
end
elseif rank:sub(1,6) == p.flags.normal then
end
rankPos = 2
 
elseif rank:sub(1,10) == p.flags.deprecated then
if not raw then
rankPos = 3
local ce = nil
else
 
return
if sign < 0 then
end
ce = i18n['datetime']['BCE']
elseif precision <= 5 then
-- one of the rank flags was given, check if another one was given before
ce = i18n['datetime']['CE']
if not self.flagRank then
end
self.ranks = {false, false, false}  -- no other rank flag given before, so unset ranks
self.bestRank = self.flagBest      -- unsets bestRank only if 'best' flag was not given before
self.flagRank = true                -- mark that a rank flag was given
end
if rank:sub(-1) == "+" then
for i = rankPos, 1, -1 do
self.ranks[i] = true
end
elseif rank:sub(-1) == "-" then
for i = rankPos, #self.ranks do
self.ranks[i] = true
end
else
self.ranks[rankPos] = true
end
end


function Config:setPeriod(period)
if ce then
local periodPos
if link then
ce = buildWikilink(i18n['datetime']['common-era'], ce)
if period == p.flags.future then
end
periodPos = 1
suffix = suffix .. " " .. ce
elseif period == p.flags.current then
end
periodPos = 2
 
elseif period == p.flags.former then
value = tostring(yRound)
periodPos = 3
 
else
if m then
return
dateStr = self.langObj:formatDate("F", "1-"..m.."-1")
end
-- one of the period flags was given, check if another one was given before
if not self.flagPeriod then
self.periods = {false, false, false}  -- no other period flag given before, so unset periods
self.flagPeriod = true                -- mark that a period flag was given
end
self.periods[periodPos] = true
end


function Config:qualifierMatches(claim, id, value)
if d then
local qualifiers
if self.mdyDate then
dateStr = dateStr .. " " .. d .. ","
if claim.qualifiers then qualifiers = claim.qualifiers[id] end
else
if qualifiers then
dateStr = d .. " " .. dateStr
for i, v in pairs(qualifiers) do
end
if self:snakEqualsValue(v, value) then
end
return true
 
end
value = dateStr .. " " .. value
end
end
elseif value == "" then
-- if the qualifier is not present then treat it the same as the special value 'novalue'
return true
end
return false
end


function Config:rankMatches(rankPos)
value = prefix .. value .. suffix .. calendar
if self.bestRank then
else
return (self.ranks[rankPos] and self.foundRank >= rankPos)
value = padZeros(yRound * sign, 4)
else
return self.ranks[rankPos]
end
end


function Config:timeMatches(claim)
if m then
local startTime = nil
value = value .. "-" .. padZeros(m, 2)
local startTimeY = nil
 
local startTimeM = nil
if d then
local startTimeD = nil
value = value .. "-" .. padZeros(d, 2)
local endTime = nil
end
local endTimeY = nil
end
local endTimeM = nil
 
local endTimeD = nil
value = value .. calendar
end
if self.periods[1] and self.periods[2] and self.periods[3] then
 
-- any time
return value
return true
elseif datatype == 'globecoordinate' then
end
-- logic from https://github.com/DataValues/Geo (v4.0.1)
 
local now = os.date('!*t')
local precision, unitsPerDegree, numDigits, strFormat, value, globe
local latitude, latConv, latValue, latLink
startTime = self:getSingleRawQualifier(claim, p.aliasesP.startTime)
local longitude, lonConv, lonValue, lonLink
if startTime and startTime ~= "" and startTime ~= " " then
local latDirection, latDirectionN, latDirectionS, latDirectionEN
startTimeY, startTimeM, startTimeD = parseDate(startTime)
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
end
local degSymbol, minSymbol, secSymbol, separator
 
endTime = self:getSingleRawQualifier(claim, p.aliasesP.endTime)
local latDegrees = nil
if endTime and endTime ~= "" and endTime ~= " " then
local latMinutes = nil
endTimeY, endTimeM, endTimeD = parseDate(endTime)
local latSeconds = nil
elseif endTime == " " then
local lonDegrees = nil
-- end time is 'unknown', assume it is somewhere in the past;
local lonMinutes = nil
-- we can do this by taking the current date as a placeholder for the end time
local lonSeconds = nil
endTimeY = now['year']
 
endTimeM = now['month']
local latDegSym = ""
endTimeD = now['day']
local latMinSym = ""
end
local latSecSym = ""
local lonDegSym = ""
if startTimeY ~= nil and endTimeY ~= nil and datePrecedesDate(endTimeY, endTimeM, endTimeD, startTimeY, startTimeM, startTimeD) then
local lonMinSym = ""
-- invalidate end time if it precedes start time
local lonSecSym = ""
endTimeY = nil
 
endTimeM = nil
local latDirectionEN_N = "N"
endTimeD = nil
local latDirectionEN_S = "S"
end
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
if self.periods[1] then
 
-- future
if not raw then
if startTimeY and datePrecedesDate(now['year'], now['month'], now['day'], startTimeY, startTimeM, startTimeD) then
latDirectionN = i18n['coord']['latitude-north']
return true
latDirectionS = i18n['coord']['latitude-south']
end
lonDirectionE = i18n['coord']['longitude-east']
end
lonDirectionW = i18n['coord']['longitude-west']
 
if self.periods[2] then
degSymbol = i18n['coord']['degrees']
-- current
minSymbol = i18n['coord']['minutes']
if (startTimeY == nil or not datePrecedesDate(now['year'], now['month'], now['day'], startTimeY, startTimeM, startTimeD)) and
secSymbol = i18n['coord']['seconds']
  (endTimeY == nil or datePrecedesDate(now['year'], now['month'], now['day'], endTimeY, endTimeM, endTimeD)) then
separator = i18n['coord']['separator']
return true
else
end
latDirectionN = latDirectionEN_N
end
latDirectionS = latDirectionEN_S
lonDirectionE = lonDirectionEN_E
if self.periods[3] then
lonDirectionW = lonDirectionEN_W
-- former
if endTimeY and not datePrecedesDate(now['year'], now['month'], now['day'], endTimeY, endTimeM, endTimeD) then
return true
end
end
return false
end


function Config:processFlag(flag)
degSymbol = "/"
if not flag then
minSymbol = "/"
return false
secSymbol = "/"
else
separator = "/"
flag = mw.text.trim(flag)
end
end
 
latitude = datavalue['latitude']
if flag == p.flags.linked then
longitude = datavalue['longitude']
self.curState.linked = true
 
return true
if latitude < 0 then
elseif flag == p.flags.raw then
latDirection = latDirectionS
self.curState.rawValue = true
latDirectionEN = latDirectionEN_S
latitude = math.abs(latitude)
if self.curState == self.states[parameters.reference] then
else
-- raw reference values end with periods and require a separator (other than none)
latDirection = latDirectionN
self.separators["sep%r"][1] = {" "}
latDirectionEN = latDirectionEN_N
end
end
 
return true
if longitude < 0 then
elseif flag == p.flags.short then
lonDirection = lonDirectionW
self.curState.shortName = true
lonDirectionEN = lonDirectionEN_W
return true
longitude = math.abs(longitude)
elseif flag == p.flags.multilanguage then
else
self.curState.anyLanguage = true
lonDirection = lonDirectionE
return true
lonDirectionEN = lonDirectionEN_E
elseif flag == p.flags.unit then
end
self.curState.unitOnly = true
 
return true
precision = datavalue['precision']
elseif flag == p.flags.mdy then
 
self.mdyDate = true
if not precision or precision <= 0 then
return true
precision = 1 / 3600  -- precision not set (correctly), set to arcsecond
elseif flag == p.flags.single then
end
self.singleClaim = true
 
return true
-- remove insignificant detail
elseif flag == p.flags.sourced then
latitude = math.floor(latitude / precision + 0.5) * precision
self.sourcedOnly = true
longitude = math.floor(longitude / precision + 0.5) * precision
return true
 
elseif flag == p.flags.edit then
if precision >= 1 - (1 / 60) and precision < 1 then
self.editable = true
precision = 1
return true
elseif precision >= (1 / 60) - (1 / 3600) and precision < (1 / 60) then
elseif flag == p.flags.editAtEnd then
precision = 1 / 60
self.editable = true
end
self.editAtEnd = true
return true
elseif flag == p.flags.best or flag:match('^'..p.flags.preferred..'[+-]?$') or flag:match('^'..p.flags.normal..'[+-]?$') or flag:match('^'..p.flags.deprecated..'[+-]?$') then
self:setRank(flag)
return true
elseif flag == p.flags.future or flag == p.flags.current or flag == p.flags.former then
self:setPeriod(flag)
return true
elseif flag == "" then
-- ignore empty flags and carry on
return true
else
return false
end
end


function Config:processFlagOrCommand(flag)
if precision >= 1 then
local param = ""
unitsPerDegree = 1
elseif precision >= (1 / 60) then
if not flag then
unitsPerDegree = 60
return false
else
else
unitsPerDegree = 3600
flag = mw.text.trim(flag)
end
end
 
numDigits = math.ceil(-math.log10(unitsPerDegree * precision))
if flag == p.claimCommands.property or flag == p.claimCommands.properties then
 
param = parameters.property
if numDigits <= 0 then
elseif flag == p.claimCommands.qualifier or flag == p.claimCommands.qualifiers then
numDigits = tonumber("0")  -- for some reason, 'numDigits = 0' may actually store '-0', so parse from string instead
self.states.qualifiersCount = self.states.qualifiersCount + 1
end
param = parameters.qualifier .. self.states.qualifiersCount
 
self.separators["sep"..param] = {copyTable(defaultSeparators["sep%q\\d"])}
strFormat = "%." .. numDigits .. "f"
elseif flag == p.claimCommands.reference or flag == p.claimCommands.references then
 
param = parameters.reference
if precision >= 1 then
else
latDegrees = strFormat:format(latitude)
return self:processFlag(flag)
lonDegrees = strFormat:format(longitude)
end
 
if not raw then
if self.states[param] then
latDegSym = replaceDecimalMark(latDegrees) .. degSymbol
return false
lonDegSym = replaceDecimalMark(lonDegrees) .. degSymbol
end
else
latDegSym = latDegrees .. degSymbol
-- create a new state for each command
lonDegSym = lonDegrees .. degSymbol
self.states[param] = State.new(self)
end
else
-- use "%x" as the general parameter name
latConv = math.floor(latitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
self.states[param].parsedFormat = parseFormat(parameters.general)  -- will be overwritten for param=="%p"
lonConv = math.floor(longitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
 
-- set the separator
if precision >= (1 / 60) then
self.states[param].separator = self.separators["sep"..param]  -- will be nil for param=="%p", which will be set separately
latMinutes = latConv
lonMinutes = lonConv
if flag:sub(-1) ~= 's' then
else
self.states[param].singleValue = true
latSeconds = latConv
end
lonSeconds = lonConv
 
self.curState = self.states[param]
latMinutes = math.floor(latSeconds / 60)
lonMinutes = math.floor(lonSeconds / 60)
return true
 
end
latSeconds = strFormat:format(latSeconds - (latMinutes * 60))
lonSeconds = strFormat:format(lonSeconds - (lonMinutes * 60))


function Config:processSeparators(args)
if not raw then
local sep
latSecSym = replaceDecimalMark(latSeconds) .. secSymbol
lonSecSym = replaceDecimalMark(lonSeconds) .. secSymbol
for i, v in pairs(self.separators) do
else
if args[i] then
latSecSym = latSeconds .. secSymbol
sep = replaceSpecialChars(args[i])
lonSecSym = lonSeconds .. secSymbol
end
if sep ~= "" then
end
self.separators[i][1] = {sep}
 
else
latDegrees = math.floor(latMinutes / 60)
self.separators[i][1] = nil
lonDegrees = math.floor(lonMinutes / 60)
end
end
end
end


function Config:setFormatAndSeparators(state, parsedFormat)
latDegSym = latDegrees .. degSymbol
state.parsedFormat = parsedFormat
lonDegSym = lonDegrees .. degSymbol
state.separator = self.separators["sep"]
state.movSeparator = self.separators["sep"..parameters.separator]
state.puncMark = self.separators["punc"]
end


-- determines if a claim has references by prefetching them from the claim using getReferences,
latMinutes = latMinutes - (latDegrees * 60)
-- which applies some filtering that determines if a reference is actually returned,
lonMinutes = lonMinutes - (lonDegrees * 60)
-- and caches the references for later use
function State:isSourced(claim)
self.conf.prefetchedRefs = self:getReferences(claim)
return (#self.conf.prefetchedRefs > 0)
end


function State:resetCaches()
if precision >= (1 / 60) then
-- any prefetched references of the previous claim must not be used
latMinutes = strFormat:format(latMinutes)
self.conf.prefetchedRefs = nil
lonMinutes = strFormat:format(lonMinutes)
end


function State:claimMatches(claim)
if not raw then
local matches, rankPos
latMinSym = replaceDecimalMark(latMinutes) .. minSymbol
lonMinSym = replaceDecimalMark(lonMinutes) .. minSymbol
-- first of all, reset any cached values used for the previous claim
else
self:resetCaches()
latMinSym = latMinutes .. minSymbol
lonMinSym = lonMinutes .. minSymbol
-- if a property value was given, check if it matches the claim's property value
end
if self.conf.propertyValue then
else
matches = self.conf:snakEqualsValue(claim.mainsnak, self.conf.propertyValue)
latMinSym = latMinutes .. minSymbol
else
lonMinSym = lonMinutes .. minSymbol
matches = true
end
end
end
 
-- if any qualifier values were given, check if each matches one of the claim's qualifier values
latValue = latDegSym .. latMinSym .. latSecSym .. latDirection
for i, v in pairs(self.conf.qualifierIDsAndValues) do
lonValue = lonDegSym .. lonMinSym .. lonSecSym .. lonDirection
matches = (matches and self.conf:qualifierMatches(claim, i, v))
 
end
value = latValue .. separator .. lonValue
 
-- check if the claim's rank and time period match
if link then
rankPos = rankTable[claim.rank] or 4
globe = parseWikidataURL(datavalue['globe'])
matches = (matches and self.conf:rankMatches(rankPos) and self.conf:timeMatches(claim))
 
if globe then
-- if only claims with references must be returned, check if this one has any
globe = mw.wikibase.getLabelByLang(globe, "en"):lower()
if self.conf.sourcedOnly then
else
matches = (matches and self:isSourced(claim))  -- prefetches and caches references
globe = "earth"
end
end
 
return matches, rankPos
latLink = table.concat({latDegrees, latMinutes, latSeconds}, "_")
end
lonLink = table.concat({lonDegrees, lonMinutes, lonSeconds}, "_")
 
value = "[https://geohack.toolforge.org/geohack.php?language="..self.langCode.."&params="..latLink.."_"..latDirectionEN.."_"..lonLink.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
end


function State:out()
return value
local result  -- collection of arrays with value objects
elseif datatype == 'wikibase-entityid' then
local valuesArray  -- array with value objects
local label
local sep = nil  -- value object
local itemID = datavalue['numeric-id']
local out = {}  -- array with value objects
 
if subtype == 'wikibase-item' then
local function walk(formatTable, result)
itemID = "Q" .. itemID
local valuesArray = {}  -- array with value objects
elseif subtype == 'wikibase-property' then
itemID = "P" .. itemID
for i, v in pairs(formatTable.req) do
else
if not result[i] or not result[i][1] then
return '<strong class="error">' .. errorText('unknown-data-type', subtype) .. '</strong>'
-- we've got no result for a parameter that is required on this level,
end
-- so skip this level (and its children) by returning an empty result
 
return {}
label = self:getLabel(itemID, raw, link, short)
 
if label == "" then
label = nil
end
end
return label
else
return '<strong class="error">' .. errorText('unknown-data-type', datatype) .. '</strong>'
end
end
elseif snak.snaktype == 'somevalue' and not noSpecial then
for i, v in ipairs(formatTable) do
if raw then
if v.param then
return " " -- single space represents 'somevalue'
valuesArray = mergeArrays(valuesArray, result[v.str])
else
elseif v.str ~= "" then
return i18n['values']['unknown']
valuesArray[#valuesArray + 1] = {v.str}
end
if v.child then
valuesArray = mergeArrays(valuesArray, walk(v.child, result))
end
end
end
elseif snak.snaktype == 'novalue' and not noSpecial then
return valuesArray
if raw then
end
return "" -- empty string represents 'novalue'
-- iterate through the results from back to front, so that we know when to add separators
for i = #self.results, 1, -1 do
result = self.results[i]
-- if there is already some output, then add the separators
if #out > 0 then
sep = self.separator[1]  -- fixed separator
result[parameters.separator] = {self.movSeparator[1]} -- movable separator
else
else
sep = nil
return i18n['values']['none']
result[parameters.separator] = {self.puncMark[1]}  -- optional punctuation mark
end
valuesArray = walk(self.parsedFormat, result)
if #valuesArray > 0 then
if sep then
valuesArray[#valuesArray + 1] = sep
end
out = mergeArrays(valuesArray, out)
end
end
else
return nil
end
end
-- reset state before next iteration
self.results = {}
return out
end
end


-- level 1 hook
function Config:getSingleRawQualifier(claim, qualifierID)
function State:getProperty(claim)
local qualifiers
local value = {self.conf:getValue(claim.mainsnak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly)}  -- create one value object
 
if claim.qualifiers then qualifiers = claim.qualifiers[qualifierID] end
if #value > 0 then
 
return {value} -- wrap the value object in an array and return it
if qualifiers and qualifiers[1] then
return self:getValue(qualifiers[1], true) -- raw = true
else
else
return {}  -- return empty array if there was no value
return nil
end
end
end
end


-- level 1 hook
function Config:snakEqualsValue(snak, value)
function State:getQualifiers(claim, param)
local snakValue = self:getValue(snak, true)  -- raw = true
local qualifiers
 
if snakValue and snak.snaktype == 'value' and snak.datavalue.type == 'wikibase-entityid' then value = value:upper() end
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
 
if qualifiers then
return snakValue == value
-- iterate through claim's qualifier statements to collect their values;
-- return array with multiple value objects
return self.conf.states[param]:iterate(qualifiers, {[parameters.general] = hookNames[parameters.qualifier.."\\d"][2], count = 1}) -- pass qualifier state with level 2 hook
else
return {}  -- return empty array
end
end
end


-- level 2 hook
function Config:setRank(rank)
function State:getQualifier(snak)
local rankPos
local value = {self.conf:getValue(snak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly)} -- create one value object
 
if rank == p.flags.best then
if #value > 0 then
self.bestRank = true
return {value}  -- wrap the value object in an array and return it
self.flagBest = true -- mark that 'best' flag was given
else
return
return {}  -- return empty array if there was no value
end
end
end


-- level 1 hook
if rank:sub(1,9) == p.flags.preferred then
function State:getAllQualifiers(claim, param, result, hooks)
rankPos = 1
local out = {}  -- array with value objects
elseif rank:sub(1,6) == p.flags.normal then
local sep = self.conf.separators["sep"..parameters.qualifier][1]  -- value object
rankPos = 2
elseif rank:sub(1,10) == p.flags.deprecated then
-- iterate through the output of the separate "qualifier(s)" commands
rankPos = 3
for i = 1, self.conf.states.qualifiersCount do
else
return
-- if a hook has not been called yet, call it now
end
if not result[parameters.qualifier..i] then
 
self:callHook(parameters.qualifier..i, hooks, claim, result)
-- one of the rank flags was given, check if another one was given before
end
if not self.flagRank then
self.ranks = {false, false, false}  -- no other rank flag given before, so unset ranks
-- if there is output for this particular "qualifier(s)" command, then add it
self.bestRank = self.flagBest      -- unsets bestRank only if 'best' flag was not given before
if result[parameters.qualifier..i] and result[parameters.qualifier..i][1] then
self.flagRank = true                -- mark that a rank flag was given
-- if there is already some output, then add the separator
if #out > 0 and sep then
out[#out + 1] = sep
end
out = mergeArrays(out, result[parameters.qualifier..i])
end
end
end
return out
end


-- level 1 hook
if rank:sub(-1) == "+" then
function State:getReferences(claim)
for i = rankPos, 1, -1 do
if self.conf.prefetchedRefs then
self.ranks[i] = true
-- return references that have been prefetched by isSourced
end
return self.conf.prefetchedRefs
elseif rank:sub(-1) == "-" then
end
for i = rankPos, #self.ranks do
self.ranks[i] = true
if claim.references then
end
-- iterate through claim's reference statements to collect their values;
-- return array with multiple value objects
return self.conf.states[parameters.reference]:iterate(claim.references, {[parameters.general] = hookNames[parameters.reference][2], count = 1})  -- pass reference state with level 2 hook
else
else
return {}  -- return empty array
self.ranks[rankPos] = true
end
end
end
end


-- level 2 hook
function Config:setPeriod(period)
function State:getReference(statement)
local periodPos
local key, citeWeb, citeQ, label
 
local params = {}
if period == p.flags.future then
local citeParams = {['web'] = {}, ['q'] = {}}
periodPos = 1
local citeMismatch = {}
elseif period == p.flags.current then
local useCite = nil
periodPos = 2
local useParams = nil
elseif period == p.flags.former then
local value = ""
periodPos = 3
local ref = {}
else
return
if statement.snaks then
end
-- don't include "imported from", which is added by a bot
 
if statement.snaks[p.aliasesP.importedFrom] then
-- one of the period flags was given, check if another one was given before
statement.snaks[p.aliasesP.importedFrom] = nil
if not self.flagPeriod then
end
self.periods = {false, false, false} -- no other period flag given before, so unset periods
self.flagPeriod = true               -- mark that a period flag was given
-- don't include "language" if it is equal to the local one
end
if self:getReferenceDetail(statement.snaks, p.aliasesP.language) == self.conf.langName then
 
statement.snaks[p.aliasesP.language] = nil
self.periods[periodPos] = true
end
end
 
-- retrieve all the parameters
function Config:qualifierMatches(claim, id, value)
for i in pairs(statement.snaks) do
local qualifiers
label = ""
 
if claim.qualifiers then qualifiers = claim.qualifiers[id] end
-- multiple authors may be given
if qualifiers then
if i == p.aliasesP.author then
for _, v in pairs(qualifiers) do
params[i] = self:getReferenceDetails(statement.snaks, i, false, self.linked, true) -- link = true/false, anyLang = true
if self:snakEqualsValue(v, value) then
else
return true
params[i] = {self:getReferenceDetail(statement.snaks, i, false, (self.linked or (i == p.aliasesP.statedIn)) and (statement.snaks[i][1].datatype ~= 'url'), true)}  -- link = true/false, anyLang = true
end
if #params[i] == 0 then
params[i] = nil
else
if statement.snaks[i][1].datatype == 'external-id' then
key = "external-id"
label = self.conf:getLabel(i)
if label ~= "" then
label = label .. " "
end
else
key = i
end
-- add the parameter to each matching type of citation
for j in pairs(citeParams) do
-- do so if there was no mismatch with a previous parameter
if not citeMismatch[j] then
-- check if this parameter is not mismatching itself
if i18n['cite'][j][key] then
-- continue if an option is available in the corresponding cite template
if i18n['cite'][j][key] ~= "" then
citeParams[j][i18n['cite'][j][key]] = label .. params[i][1]
-- if there are multiple parameter values (authors), add those too
for k=2, #params[i] do
citeParams[j][i18n['cite'][j][key]..k] = label .. params[i][k]
end
end
else
citeMismatch[j] = true
end
end
end
end
end
end
end
elseif value == "" then
-- get title of general template for citing web references
-- if the qualifier is not present then treat it the same as the special value 'novalue'
citeWeb = split(mw.wikibase.sitelink(aliasesQ.citeWeb) or "", ":")[2]  -- split off namespace from front
return true
end
-- get title of template that expands stated-in references into citations
 
citeQ = split(mw.wikibase.sitelink(aliasesQ.citeQ) or "", ":")[2]  -- split off namespace from front
return false
end
-- (1) use the general template for citing web references if there is a match and if at least both "reference URL" and "title" are present
 
if citeWeb and not citeMismatch['web'] and citeParams['web'][i18n['cite']['web'][p.aliasesP.referenceURL]] and citeParams['web'][i18n['cite']['web'][p.aliasesP.title]] then
function Config:rankMatches(rankPos)
useCite = citeWeb
if self.bestRank then
useParams = citeParams['web']
return (self.ranks[rankPos] and self.foundRank >= rankPos)
else
-- (2) use the template that expands stated-in references into citations if there is a match and if at least "stated in" is present
return self.ranks[rankPos]
elseif citeQ and not citeMismatch['q'] and citeParams['q'][i18n['cite']['q'][p.aliasesP.statedIn]] then
-- we need the raw "stated in" Q-identifier for the this template
citeParams['q'][i18n['cite']['q'][p.aliasesP.statedIn]] = self:getReferenceDetail(statement.snaks, p.aliasesP.statedIn, true)  -- raw = true
useCite = citeQ
useParams = citeParams['q']
end
if useCite and useParams then
-- if this module is being substituted then build a regular template call, otherwise expand the template
if mw.isSubsting() then
for i, v in pairs(useParams) do
value = value .. "|" .. i .. "=" .. v
end
value = "{{" .. useCite .. value .. "}}"
else
value = mw.getCurrentFrame():expandTemplate{title=useCite, args=useParams}
end
-- (3) else, do some default rendering of name-value pairs, but only if at least "stated in", "reference URL" or "title" is present
elseif params[p.aliasesP.statedIn] or params[p.aliasesP.referenceURL] or params[p.aliasesP.title] then
citeParams['default'] = {}
-- start by adding authors up front
if params[p.aliasesP.author] and #params[p.aliasesP.author] > 0 then
citeParams['default'][#citeParams['default'] + 1] = table.concat(params[p.aliasesP.author], " & ")
end
-- combine "reference URL" and "title" into one link if both are present
if params[p.aliasesP.referenceURL] and params[p.aliasesP.title] then
citeParams['default'][#citeParams['default'] + 1] = '[' .. params[p.aliasesP.referenceURL][1] .. ' "' .. params[p.aliasesP.title][1] .. '"]'
elseif params[p.aliasesP.referenceURL] then
citeParams['default'][#citeParams['default'] + 1] = params[p.aliasesP.referenceURL][1]
elseif params[p.aliasesP.title] then
citeParams['default'][#citeParams['default'] + 1] = '"' .. params[p.aliasesP.title][1] .. '"'
end
-- then add "stated in"
if params[p.aliasesP.statedIn] then
citeParams['default'][#citeParams['default'] + 1] = "''" .. params[p.aliasesP.statedIn][1] .. "''"
end
-- remove previously added parameters so that they won't be added a second time
params[p.aliasesP.author] = nil
params[p.aliasesP.referenceURL] = nil
params[p.aliasesP.title] = nil
params[p.aliasesP.statedIn] = nil
-- add the rest of the parameters
for i, v in pairs(params) do
i = self.conf:getLabel(i)
if i ~= "" then
citeParams['default'][#citeParams['default'] + 1] = i .. ": " .. v[1]
end
end
value = table.concat(citeParams['default'], "; ")
if value ~= "" then
value = value .. "."
end
end
if value ~= "" then
value = {value}  -- create one value object
if not self.rawValue then
-- this should become a <ref> tag, so safe the reference's hash for later
value.refHash = statement.hash
end
ref = {value}  -- wrap the value object in an array
end
end
end
return ref
end
end


-- gets a detail of one particular type for a reference
function Config:timeMatches(claim)
function State:getReferenceDetail(snaks, dType, raw, link, anyLang)
local startTime = nil
local switchLang = anyLang
local startTimeY = nil
local value = nil
local startTimeM = nil
local startTimeD = nil
if not snaks[dType] then
local endTime = nil
return nil
local endTimeY = nil
local endTimeM = nil
local endTimeD = nil
 
if self.periods[1] and self.periods[2] and self.periods[3] then
-- any time
return true
end
 
startTime = self:getSingleRawQualifier(claim, aliasesP.startTime)
if startTime and startTime ~= "" and startTime ~= " " then
startTimeY, startTimeM, startTimeD = parseDate(startTime)
end
 
endTime = self:getSingleRawQualifier(claim, aliasesP.endTime)
if endTime and endTime ~= "" and endTime ~= " " then
endTimeY, endTimeM, endTimeD = parseDate(endTime)
end
end
-- if anyLang, first try the local language and otherwise any language
repeat
for i, v in ipairs(snaks[dType]) do
value = self.conf:getValue(v, raw, link, false, anyLang and not switchLang, false, true)  -- noSpecial = true
if value then
break
end
end
if value or not anyLang then
break
end
switchLang = not switchLang
until anyLang and switchLang
return value
end


-- gets the details of one particular type for a reference
if startTimeY ~= nil and endTimeY ~= nil and datePrecedesDate(endTimeY, endTimeM, endTimeD, startTimeY, startTimeM, startTimeD) then
function State:getReferenceDetails(snaks, dType, raw, link, anyLang)
-- invalidate end time if it precedes start time
local values = {}
endTimeY = nil
endTimeM = nil
if not snaks[dType] then
endTimeD = nil
return {}
end
end
for i, v in ipairs(snaks[dType]) do
-- if nil is returned then it will not be added to the table
values[#values + 1] = self.conf:getValue(v, raw, link, false, anyLang, false, true)  -- noSpecial = true
end
return values
end


-- level 1 hook
if self.periods[1] then
function State:getAlias(object)
-- future
local value = object.value
if startTimeY and datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], startTimeY, startTimeM, startTimeD) then
local title = nil
return true
if value and self.linked then
if self.conf.entityID:sub(1,1) == "Q" then
title = mw.wikibase.sitelink(self.conf.entityID)
elseif self.conf.entityID:sub(1,1) == "P" then
title = "d:Property:" .. self.conf.entityID
end
end
end
if title then
 
value = buildWikilink(title, value)
if self.periods[2] then
-- current
if (startTimeY == nil or not datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], startTimeY, startTimeM, startTimeD)) and
  (endTimeY == nil or datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], endTimeY, endTimeM, endTimeD)) then
return true
end
end
end
end
value = {value}  -- create one value object
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
else
return {}  -- return empty array if there was no value
end
end


-- level 1 hook
if self.periods[3] then
function State:getBadge(value)
-- former
value = self.conf:getLabel(value, self.rawValue, self.linked, self.shortName)
if endTimeY and not datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], endTimeY, endTimeM, endTimeD) then
return true
if value == "" then
end
value = nil
end
end
 
value = {value}  -- create one value object
return false
end
if #value > 0 then
 
return {value}  -- wrap the value object in an array and return it
function Config:processFlag(flag)
else
if not flag then
return {}  -- return empty array if there was no value
return false
end
end
end


function State:callHook(param, hooks, statement, result)
if flag == p.flags.linked then
local valuesArray, refHash
self.curState.linked = true
return true
-- call a parameter's hook if it has been defined and if it has not been called before
elseif flag == p.flags.raw then
if not result[param] and hooks[param] then
self.curState.rawValue = true
valuesArray = self[hooks[param]](self, statement, param, result, hooks)  -- array with value objects
 
if self.curState == self.states[parameters.reference] then
-- add to the result
-- raw reference values end with periods and require a separator (other than none)
if #valuesArray > 0 then
self.separators["sep%r"][1] = {" "}
result[param] = valuesArray
result.count = result.count + 1
else
result[param] = {} -- an empty array to indicate that we've tried this hook already
return true  -- miss == true
end
end
end
return false
end


-- iterate through claims, claim's qualifiers or claim's references to collect values
return true
function State:iterate(statements, hooks, matchHook)
elseif flag == p.flags.short then
matchHook = matchHook or alwaysTrue
self.curState.shortName = true
return true
local matches = false
elseif flag == p.flags.multilanguage then
local rankPos = nil
self.curState.anyLanguage = true
local result, gotRequired
return true
elseif flag == p.flags.unit then
for i, v in ipairs(statements) do
self.curState.unitOnly = true
-- rankPos will be nil for non-claim statements (e.g. qualifiers, references, etc.)
return true
matches, rankPos = matchHook(self, v)
elseif flag == p.flags.mdy then
self.mdyDate = true
if matches then
return true
result = {count = 0}  -- collection of arrays with value objects
elseif flag == p.flags.single then
self.singleClaim = true
local function walk(formatTable)
return true
local miss
elseif flag == p.flags.sourced then
self.sourcedOnly = true
for i2, v2 in pairs(formatTable.req) do
return true
-- call a hook, adding its return value to the result
elseif flag == p.flags.edit then
miss = self:callHook(i2, hooks, v, result)
self.editable = true
return true
if miss then
elseif flag == p.flags.editAtEnd then
-- we miss a required value for this level, so return false
self.editable = true
return false
self.editAtEnd = true
end
return true
elseif flag == p.flags.best or flag:match('^'..p.flags.preferred..'[+-]?$') or flag:match('^'..p.flags.normal..'[+-]?$') or flag:match('^'..p.flags.deprecated..'[+-]?$') then
if result.count == hooks.count then
self:setRank(flag)
-- we're done if all hooks have been called;
return true
-- returning at this point breaks the loop
elseif flag == p.flags.future or flag == p.flags.current or flag == p.flags.former then
return true
self:setPeriod(flag)
end
return true
end
elseif flag == "" then
-- ignore empty flags and carry on
for i2, v2 in ipairs(formatTable) do
return true
if result.count == hooks.count then
else
-- we're done if all hooks have been called;
return false
-- returning at this point prevents further childs from being processed
return true
end
if v2.child then
walk(v2.child)
end
end
return true
end
gotRequired = walk(self.parsedFormat)
-- only append the result if we got values for all required parameters on the root level
if gotRequired then
-- if we have a rankPos (only with matchHook() for complete claims), then update the foundRank
if rankPos and self.conf.foundRank > rankPos then
self.conf.foundRank = rankPos
end
-- append the result
self.results[#self.results + 1] = result
-- break if we only need a single value
if self.singleValue then
break
end
end
end
end
end
return self:out()
end
end


function extractEntityFromInput(id, allowOmitPropPrefix)
function Config:processFlagOrCommand(flag)
if id:sub(1,1):upper() == "Q" then
local param = ""
return id:upper()  -- entity ID of an item was given
 
elseif id:sub(1,9):lower() == "property:" then
if not flag then
return replaceAlias(mw.text.trim(id:sub(10))):upper()  -- entity ID of a property was given
return false
elseif allowOmitPropPrefix and id ~= "" then
return replaceAlias(id):upper()  -- could be an entity ID of a property without "Property:" prefix
else
return nil
end
end
end


function extractEntityFromArgs(args, nextIndex, allowOmitPropPrefix)
if flag == p.claimCommands.property or flag == p.claimCommands.properties then
local id, eidArg
param = parameters.property
elseif flag == p.claimCommands.qualifier or flag == p.claimCommands.qualifiers then
if args[nextIndex] then
self.states.qualifiersCount = self.states.qualifiersCount + 1
args[nextIndex] = mw.text.trim(args[nextIndex])
param = parameters.qualifier .. self.states.qualifiersCount
self.separators["sep"..param] = {copyTable(defaultSeparators["sep%q\\d"])}
elseif flag == p.claimCommands.reference or flag == p.claimCommands.references then
param = parameters.reference
else
else
args[nextIndex] = ""
return self:processFlag(flag)
end
end
 
id = extractEntityFromInput(args[nextIndex], allowOmitPropPrefix)
if self.states[param] then
eidArg = args[p.args.eid]
return false
if id then
return id, nextIndex + 1
elseif eidArg then
return extractEntityFromInput(eidArg, true), nextIndex  -- if no positional id was found but eid was given, use eid without a default
else
return mw.wikibase.getEntityIdForCurrentPage(), nextIndex  -- by default, use item-entity connected to current page
end
end
end


function claimCommand(args, funcName)
-- create a new state for each command
local _ = Config.new()
self.states[param] = State:new(self, param)
_:processFlagOrCommand(funcName)  -- process first command (== function name)
 
-- use "%x" as the general parameter name
local parsedFormat, formatParams, claims, value
self.states[param].parsedFormat = parseFormat(parameters.general)  -- will be overwritten for param=="%p"
local hooks = {count = 0}
 
-- set the separator
local nextIndex = 1
self.states[param].separator = self.separators["sep"..param]  -- will be nil for param=="%p", which will be set separately
 
-- process flags and commands
if flag == p.claimCommands.property or flag == p.claimCommands.qualifier or flag == p.claimCommands.reference then
while _:processFlagOrCommand(args[nextIndex]) do
self.states[param].singleValue = true
nextIndex = nextIndex + 1
end
end
 
_.entityID, nextIndex = extractEntityFromArgs(args, nextIndex, false)
self.curState = self.states[param]
 
-- if eid was explicitly set to empty, then this returns an empty string
return true
if _.entityID == nil then
end
return ""
 
function Config:processSeparators(args)
local sep
 
for i, v in pairs(self.separators) do
if args[i] then
sep = replaceSpecialChars(args[i])
 
if sep ~= "" then
self.separators[i][1] = {sep}
else
self.separators[i][1] = nil
end
end
end
end
end
_.entity = mw.wikibase.getEntity(_.entityID)
 
_.propertyID = replaceAlias(args[nextIndex]):upper()
function Config:setFormatAndSeparators(state, parsedFormat)
nextIndex = nextIndex + 1
state.parsedFormat = parsedFormat
state.separator = self.separators["sep"]
if _.states.qualifiersCount > 0 then
state.movSeparator = self.separators["sep"..parameters.separator]
-- do further processing if "qualifier(s)" command was given
state.puncMark = self.separators["punc"]
end
if #args - nextIndex + 1 > _.states.qualifiersCount then
 
-- claim ID or literal value has been given
-- determines if a claim has references by prefetching them from the claim using getReferences,
-- which applies some filtering that determines if a reference is actually returned,
_.propertyValue = mw.text.trim(args[nextIndex])
-- and caches the references for later use
nextIndex = nextIndex + 1
function State:isSourced(claim)
end
self.conf.prefetchedRefs = self:getReferences(claim)
return (#self.conf.prefetchedRefs > 0)
for i = 1, _.states.qualifiersCount do
end
-- check if given qualifier ID is an alias and add it
 
_.qualifierIDs[parameters.qualifier..i] = replaceAlias(mw.text.trim(args[nextIndex] or "")):upper()
function State:resetCaches()
nextIndex = nextIndex + 1
-- any prefetched references of the previous claim must not be used
end
self.conf.prefetchedRefs = nil
elseif _.states[parameters.reference] then
end
-- do further processing if "reference(s)" command was given
 
function State:claimMatches(claim)
if args[nextIndex] then
local matches, rankPos
_.propertyValue = mw.text.trim(args[nextIndex])
 
end
-- first of all, reset any cached values used for the previous claim
-- not incrementing nextIndex because it is never used after this
self:resetCaches()
end
 
-- if a property value was given, check if it matches the claim's property value
-- check for special property value 'somevalue' or 'novalue'
if self.conf.propertyValue then
if _.propertyValue then
matches = self.conf:snakEqualsValue(claim.mainsnak, self.conf.propertyValue)
_.propertyValue = replaceSpecialChars(_.propertyValue)
else
matches = true
if _.propertyValue ~= "" and mw.text.trim(_.propertyValue) == "" then
end
_.propertyValue = " "  -- single space represents 'somevalue', whereas empty string represents 'novalue'
 
else
-- if any qualifier values were given, check if each matches one of the claim's qualifier values
_.propertyValue = mw.text.trim(_.propertyValue)
for i, v in pairs(self.conf.qualifierIDsAndValues) do
end
matches = (matches and self.conf:qualifierMatches(claim, i, v))
end
end
 
-- parse the desired format, or choose an appropriate format
-- check if the claim's rank and time period match
if args["format"] then
rankPos = rankTable[claim.rank] or 4
parsedFormat, formatParams = parseFormat(args["format"])
matches = (matches and self.conf:rankMatches(rankPos) and self.conf:timeMatches(claim))
elseif _.states.qualifiersCount > 0 then  -- "qualifier(s)" command given
 
if _.states[parameters.property] then  -- "propert(y|ies)" command given
-- if only claims with references must be returned, check if this one has any
parsedFormat, formatParams = parseFormat(formats.propertyWithQualifier)
if self.conf.sourcedOnly then
else
matches = (matches and self:isSourced(claim))  -- prefetches and caches references
parsedFormat, formatParams = parseFormat(formats.qualifier)
end
elseif _.states[parameters.property] then -- "propert(y|ies)" command given
parsedFormat, formatParams = parseFormat(formats.property)
else -- "reference(s)" command given
parsedFormat, formatParams = parseFormat(formats.reference)
end
end
 
-- if a "qualifier(s)" command and no "propert(y|ies)" command has been given, make the movable separator a semicolon
return matches, rankPos
if _.states.qualifiersCount > 0 and not _.states[parameters.property] then
end
_.separators["sep"..parameters.separator][1] = {";"}
 
end
function State:out()
local result  -- collection of arrays with value objects
-- if only "reference(s)" has been given, set the default separator to none (except when raw)
local valuesArray  -- array with value objects
if _.states[parameters.reference] and not _.states[parameters.property] and _.states.qualifiersCount == 0
local sep = nil -- value object
  and not _.states[parameters.reference].rawValue then
local out = {}  -- array with value objects
_.separators["sep"][1] = nil
 
end
local function walk(formatTable, result)
local valuesArray = {}  -- array with value objects
-- if exactly one "qualifier(s)" command has been given, make "sep%q" point to "sep%q1" to make them equivalent
 
if _.states.qualifiersCount == 1 then
for i, v in pairs(formatTable.req) do
_.separators["sep"..parameters.qualifier] = _.separators["sep"..parameters.qualifier.."1"]
if not result[i] or not result[i][1] then
end
-- we've got no result for a parameter that is required on this level,
-- so skip this level (and its children) by returning an empty result
-- process overridden separator values;
return {}
-- must come AFTER tweaking the default separators
end
_:processSeparators(args)
end
 
-- define the hooks that should be called (getProperty, getQualifiers, getReferences);
for _, v in ipairs(formatTable) do
-- only define a hook if both its command ("propert(y|ies)", "reference(s)", "qualifier(s)") and its parameter ("%p", "%r", "%q1", "%q2", "%q3") have been given
if v.param then
for i, v in pairs(_.states) do
valuesArray = mergeArrays(valuesArray, result[v.str])
-- e.g. 'formatParams["%q1"] or formatParams["%q"]' to define hook even if "%q1" was not defined to be able to build a complete value for "%q"
elseif v.str ~= "" then
if formatParams[i] or formatParams[i:sub(1, 2)] then
valuesArray[#valuesArray + 1] = {v.str}
hooks[i] = getHookName(i, 1)
end
hooks.count = hooks.count + 1
 
if v.child then
valuesArray = mergeArrays(valuesArray, walk(v.child, result))
end
end
end
return valuesArray
end
end
 
-- the "%q" parameter is not attached to a state, but is a collection of the results of multiple states (attached to "%q1", "%q2", "%q3", ...);
-- iterate through the results from back to front, so that we know when to add separators
-- so if this parameter is given then this hook must be defined separately, but only if at least one "qualifier(s)" command has been given
for i = #self.results, 1, -1 do
if formatParams[parameters.qualifier] and _.states.qualifiersCount > 0 then
result = self.results[i]
hooks[parameters.qualifier] = getHookName(parameters.qualifier, 1)
 
hooks.count = hooks.count + 1
-- if there is already some output, then add the separators
end
if #out > 0 then
sep = self.separator[1] -- fixed separator
-- create a state for "properties" if it doesn't exist yet, which will be used as a base configuration for each claim iteration;
result[parameters.separator] = {self.movSeparator[1]}  -- movable separator
-- must come AFTER defining the hooks
else
if not _.states[parameters.property] then
sep = nil
_.states[parameters.property] = State.new(_)
result[parameters.separator] = {self.puncMark[1]}  -- optional punctuation mark
-- if the "single" flag has been given then this state should be equivalent to "property" (singular)
if _.singleClaim then
_.states[parameters.property].singleValue = true
end
end
end
 
valuesArray = walk(self.parsedFormat, result)
-- if the "sourced" flag has been given then create a state for "reference" if it doesn't exist yet, using default values,
 
-- which must exist in order to be able to determine if a claim has any references;
if #valuesArray > 0 then
-- must come AFTER defining the hooks
if sep then
if _.sourcedOnly and not _.states[parameters.reference] then
valuesArray[#valuesArray + 1] = sep
_:processFlagOrCommand(p.claimCommands.reference)  -- use singular "reference" to minimize overhead
end
-- set the parsed format and the separators (and optional punctuation mark);
-- must come AFTER creating the additonal states
_:setFormatAndSeparators(_.states[parameters.property], parsedFormat)
-- process qualifier matching values, analogous to _.propertyValue
for i, v in pairs(args) do
i = tostring(i)
if i:match('^[Pp]%d+$') or p.aliasesP[i] then
v = replaceSpecialChars(v)
-- check for special qualifier value 'somevalue'
if v ~= "" and mw.text.trim(v) == "" then
v = " "  -- single space represents 'somevalue'
end
end
 
_.qualifierIDsAndValues[replaceAlias(i):upper()] = v
out = mergeArrays(valuesArray, out)
end
end
end
end
if _.entity and _.entity.claims then claims = _.entity.claims[_.propertyID] end
if claims then
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
claims = sortOnRank(claims)
-- then iterate through the claims to collect values
value = _:concatValues(_.states[parameters.property]:iterate(claims, hooks, State.claimMatches))  -- pass property state with level 1 hooks and matchHook
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if _.editable and value ~= "" then
value = value .. _:getEditIcon()
end
return value
else
return ""
end
end


function generalCommand(args, funcName)
-- reset state before next iteration
local _ = Config.new()
self.results = {}
_.curState = State.new(_)
 
return out
local value = nil
end
local nextIndex = 1
 
-- level 1 hook
while _:processFlag(args[nextIndex]) do
function State:getProperty(claim)
nextIndex = nextIndex + 1
local value = {self:getValue(claim.mainsnak)}  -- create one value object
 
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
else
return {}  -- return empty array if there was no value
end
end
end
_.entityID, nextIndex = extractEntityFromArgs(args, nextIndex, true)
 
-- level 1 hook
-- if eid was explicitly set to empty, then this returns an empty string
function State:getQualifiers(claim, param)
if _.entityID == nil then
local qualifiers
return ""
 
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if qualifiers then
-- iterate through claim's qualifier statements to collect their values;
-- return array with multiple value objects
return self.conf.states[param]:iterate(qualifiers, {[parameters.general] = hookNames[parameters.qualifier.."\\d"][2], count = 1})  -- pass qualifier state with level 2 hook
else
return {}  -- return empty array
end
end
end
-- serve according to the given command
 
if funcName == p.generalCommands.label then
-- level 2 hook
value = _:getLabel(_.entityID, _.curState.rawValue, _.curState.linked, _.curState.shortName)
function State:getQualifier(snak)
elseif funcName == p.generalCommands.title then
local value = {self:getValue(snak)}  -- create one value object
_.inSitelinks = true
 
if #value > 0 then
if _.entityID:sub(1,1) == "Q" then
return {value}  -- wrap the value object in an array and return it
value = mw.wikibase.sitelink(_.entityID)
end
if _.curState.linked and value then
value = buildWikilink(value)
end
else
else
local parsedFormat, formatParams
return {}  -- return empty array if there was no value
local hooks = {count = 0}
end
end
if funcName == p.generalCommands.alias or funcName == p.generalCommands.badge then
 
_.curState.singleValue = true
-- level 1 hook
end
function State:getAllQualifiers(claim, param, result, hooks)
local out = {} -- array with value objects
_.entity = mw.wikibase.getEntity(_.entityID)
local sep = self.conf.separators["sep"..parameters.qualifier][1]  -- value object
 
if funcName == p.generalCommands.alias or funcName == p.generalCommands.aliases then
-- iterate through the output of the separate "qualifier(s)" commands
local aliases
for i = 1, self.conf.states.qualifiersCount do
 
-- parse the desired format, or parse the default aliases format
-- if a hook has not been called yet, call it now
if args["format"] then
if not result[parameters.qualifier..i] then
parsedFormat, formatParams = parseFormat(args["format"])
self:callHook(parameters.qualifier..i, hooks, claim, result)
else
end
parsedFormat, formatParams = parseFormat(formats.alias)
 
-- if there is output for this particular "qualifier(s)" command, then add it
if result[parameters.qualifier..i] and result[parameters.qualifier..i][1] then
 
-- if there is already some output, then add the separator
if #out > 0 and sep then
out[#out + 1] = sep
end
end
 
-- process overridden separator values;
out = mergeArrays(out, result[parameters.qualifier..i])
-- must come AFTER tweaking the default separators
end
_:processSeparators(args)
end
 
-- define the hook that should be called (getAlias);
return out
-- only define the hook if the parameter ("%a") has been given
end
if formatParams[parameters.alias] then
 
hooks[parameters.alias] = getHookName(parameters.alias, 1)
-- level 1 hook
hooks.count = hooks.count + 1
function State:getReferences(claim)
end
if self.conf.prefetchedRefs then
-- return references that have been prefetched by isSourced
-- set the parsed format and the separators (and optional punctuation mark)
return self.conf.prefetchedRefs
_:setFormatAndSeparators(_.curState, parsedFormat)
end
 
if _.entity and _.entity.aliases then aliases = _.entity.aliases[_.langCode] end
if claim.references then
if aliases then
-- iterate through claim's reference statements to collect their values;
value = _:concatValues(_.curState:iterate(aliases, hooks))
-- return array with multiple value objects
end
return self.conf.states[parameters.reference]:iterate(claim.references, {[parameters.general] = hookNames[parameters.reference][2], count = 1}) -- pass reference state with level 2 hook
elseif funcName == p.generalCommands.badge or funcName == p.generalCommands.badges then
else
_.inSitelinks = true
return {}  -- return empty array
local badges
-- parse the desired format, or parse the default aliases format
if args["format"] then
parsedFormat, formatParams = parseFormat(args["format"])
else
parsedFormat, formatParams = parseFormat(formats.badge)
end
-- process overridden separator values;
-- must come AFTER tweaking the default separators
_:processSeparators(args)
-- define the hook that should be called (getBadge);
-- only define the hook if the parameter ("%b") has been given
if formatParams[parameters.badge] then
hooks[parameters.badge] = getHookName(parameters.badge, 1)
hooks.count = hooks.count + 1
end
-- set the parsed format and the separators (and optional punctuation mark)
_:setFormatAndSeparators(_.curState, parsedFormat)
if _.entity and _.entity.sitelinks and _.entity.sitelinks[_.siteID] then badges = _.entity.sitelinks[_.siteID].badges end
if badges then
value = _:concatValues(_.curState:iterate(badges, hooks))
end
end
end
end
end
-- level 2 hook
function State:getReference(statement)
local citeParamMapping = i18n['cite']['param-mapping']
local citeConfig = i18n['cite']['config']
local citeTypes = i18n['cite']['output-types']
value = value or ""
-- will hold rendered properties of the reference which are not directly from statement.snaks,
-- Namely, these are a backup title from "subject named as" and a URL generated from an external ID.
    local additionalProcessedProperties = {}
    -- for each citation type, there will be an associative array that associates lists of rendered properties
    -- to citation-template parameters
    local groupedProcessedProperties = {}
    -- like above, but only associates one rendered property to each parameter; if the above variable
    -- contains more strings for a parameter, the strings will be assigned to numbered params (e.g. "author1")
local citeParams = {}
 
local citeErrors = {}
local referenceEmpty = true  -- will be set to false if at least one parameter is left unremoved
 
local version = 11  -- increment this each time the below logic is changed to avoid conflict errors
 
if not statement.snaks then
return {}
end
 
-- don't use bot-added references referencing Wikimedia projects or containing "inferred from" (such references are not usable on Wikipedia)
if statement.snaks[aliasesP.importedFrom] or statement.snaks[aliasesP.wikimediaImportURL] or statement.snaks[aliasesP.inferredFrom] then
return {}
end
if _.editable and value ~= "" then
-- don't include "type of reference"
-- if desired, add a clickable icon that may be used to edit the returned value on Wikidata
if statement.snaks[aliasesP.typeOfReference] then
value = value .. _:getEditIcon()
statement.snaks[aliasesP.typeOfReference] = nil
end
 
-- don't include "image" to prevent littering
if statement.snaks[aliasesP.image] then
statement.snaks[aliasesP.image] = nil
end
end
return value
end


-- modules that include this module should call the functions with an underscore prepended, e.g.: p._property(args)
-- don't include "language" if it is equal to the local one
function establishCommands(commandList, commandFunc)
if self:getReferenceDetail(statement.snaks, aliasesP.language) == self.conf.langName then
for commandIndex, commandName in pairs(commandList) do
statement.snaks[aliasesP.language] = nil
local function wikitextWrapper(frame)
end
loadSubmodules(frame)
   
return commandFunc(copyTable(frame.args), commandName)
    if statement.snaks[aliasesP.statedIn] and not statement.snaks[aliasesP.referenceURL] then
end
    -- "stated in" was given but "reference URL" was not.
p[commandName] = wikitextWrapper
    -- get "Wikidata property" properties from the item in "stated in"
    -- if any of the returned properties of the external-id datatype is in statement.snaks, generate a link from it and use the link in the reference
   
    -- find the "Wikidata property" properties in the item from "stated in"
    local wikidataPropertiesOfSource = mw.text.split(p._properties{p.flags.raw, aliasesP.wikidataProperty, [p.args.eid] = self.conf:getValue(statement.snaks[aliasesP.statedIn][1], true, false)}, ", ", true)
    for i, wikidataPropertyOfSource in pairs(wikidataPropertiesOfSource) do
    if statement.snaks[wikidataPropertyOfSource] and statement.snaks[wikidataPropertyOfSource][1].datatype == "external-id" then
    local tempLink = self:getReferenceDetail(statement.snaks, wikidataPropertyOfSource, false, true)  -- not raw, linked
    if mw.ustring.match(tempLink, "^%[%Z- %Z+%]$") then  -- getValue returned a URL in square brackets.
    -- the link is in wiki markup, so strip the square brackets and the display text
    -- gsub also returns another, discarted value, therefore the result is assigned to tempLink first
    tempLink = mw.ustring.gsub(tempLink, "^%[(%Z-) %Z+%]$", "%1")
        additionalProcessedProperties[aliasesP.referenceURL] = {tempLink}
        statement.snaks[wikidataPropertyOfSource] = nil
        break
    end
    end
    end
    end
   
    -- don't include "subject named as", but use it as the title when "title" is not present but a URL is
    if statement.snaks[aliasesP.subjectNamedAs] then
    if not statement.snaks[aliasesP.title] and (statement.snaks[aliasesP.referenceURL] or additionalProcessedProperties[aliasesP.referenceURL]) then
    additionalProcessedProperties[aliasesP.title] = {self:getReferenceDetail(statement.snaks, aliasesP.subjectNamedAs, false, false, true)}  -- not raw, not linked, anyLang
    end
    statement.snaks[aliasesP.subjectNamedAs] = nil
    end
   
    -- initialize groupedProcessedProperties and citeParams
    for _, citeType in ipairs(citeTypes) do
    groupedProcessedProperties[citeType] = {}
    citeParams[citeType] = {}
    end
 
-- fill groupedProcessedProperties
for refProperty in pairs(statement.snaks) do
-- add the parameter to each matching type of citation
for _, citeType in ipairs(citeTypes) do
repeat  -- just a simple wrapper to emulate "continue"
-- skip if there already have been errors
if citeErrors[citeType] then
break
end
-- set mappingKey and prefix
local mappingKey
local prefix = ""
if statement.snaks[refProperty][1].datatype == 'external-id' then
mappingKey = "external-id"
prefix = self.conf:getLabel(refProperty)
if prefix ~= "" then
prefix = prefix .. " "
end
else
mappingKey = refProperty
end
local paramName = citeParamMapping[citeType][mappingKey]
-- skip properties with empty parameter name
if paramName == "" then
break
end
referenceEmpty = false
 
-- handle unknown properties in the reference
if not paramName then
local error_message = errorText("unknown-property-in-ref", refProperty)
assert(error_message) -- Should not be nil
citeErrors[citeType] = error_message
break
end
-- set processedProperty
local processedProperty
local raw = false  -- if the value is wanted raw
if isValueInTable(paramName, citeConfig[citeType]["raw-value-params"] or {}) then
raw = true
end
if isValueInTable(paramName, citeConfig[citeType]["numbered-params"] or {}) then
-- Multiple values may be given.
processedProperty = self:getReferenceDetails(statement.snaks, refProperty, raw, self.linked, true)  -- anyLang = true
else
-- If multiple values are given, all but the first suitable one are discarted.
processedProperty = {self:getReferenceDetail(statement.snaks, refProperty, raw, self.linked and (statement.snaks[refProperty][1].datatype ~= 'url'), true)}  -- link = true/false, anyLang = true
end
local function luaWrapper(args)
if #processedProperty == 0 then
loadSubmodules()
break
return commandFunc(args, commandName)
end
               
                -- add an entry to groupedProcessedProperties
                if not groupedProcessedProperties[citeType][paramName] then
                groupedProcessedProperties[citeType][paramName] = {}
                end
                for _, propertyValue in pairs(processedProperty) do
                table.insert(groupedProcessedProperties[citeType][paramName], prefix .. propertyValue)
                end
            until true
end
end
p["_" .. commandName] = luaWrapper
end
end
end
-- handle additional properties
 
for refProperty in pairs(additionalProcessedProperties) do
establishCommands(p.claimCommands, claimCommand)
for _, citeType in ipairs(citeTypes) do
establishCommands(p.generalCommands, generalCommand)
repeat
-- skip if there already have been errors
if citeErrors[citeType] then
break
end
                local paramName = citeParamMapping[citeType][refProperty]
-- handle unknown properties in the reference
if not paramName then
-- Skip this additional property, but do not cause an error.
break
end
if paramName == "" then
break
end
referenceEmpty = false
               
                if not groupedProcessedProperties[citeType][paramName] then
                groupedProcessedProperties[citeType][paramName] = {}
                end
                for _, propertyValue in pairs(additionalProcessedProperties[refProperty]) do
                table.insert(groupedProcessedProperties[citeType][paramName], propertyValue)
                end
until true
end
end
-- fill citeParams
for _, citeType in ipairs(citeTypes) do
for paramName, paramValues in pairs(groupedProcessedProperties[citeType]) do
if #paramValues == 1 or not isValueInTable(paramName, citeConfig[citeType]["numbered-params"] or {}) then
citeParams[citeType][paramName] = paramValues[1]
else
-- There is more than one value for this parameter - the values will
-- go into separate numbered parameters (e.g. "author1", "author2")
for paramNum, paramValue in pairs(paramValues) do
citeParams[citeType][paramName .. paramNum] = paramValue
end
end
end
end
-- handle missing mandatory parameters for the templates
for _, citeType in ipairs(citeTypes) do
for _, requiredCiteParam in pairs(citeConfig[citeType]["mandatory-params"] or {}) do
if not citeParams[citeType][requiredCiteParam] then  -- The required param is not present.
if citeErrors[citeType] then  -- Do not override the previous error, if it exists.
break
end
local error_message = errorText("missing-mandatory-param", requiredCiteParam)
assert(error_message)  -- Should not be nil
citeErrors[citeType] = error_message
end
end
end
local citeTypeToUse = nil
 
    -- choose the output template
    for _, citeType in ipairs(citeTypes) do
    if not citeErrors[citeType] then
    citeTypeToUse = citeType
    break
    end
    end
 
-- set refContent
local refContent = ""
if citeTypeToUse then
local templateToUse = citeConfig[citeTypeToUse]["template"]
local paramsToUse = citeParams[citeTypeToUse]
if not templateToUse or templateToUse == "" then
throwError("no-such-reference-template", tostring(templateToUse), i18nPath, citeTypeToUse)
end
-- if this module is being substituted then build a regular template call, otherwise expand the template
if mw.isSubsting() then
for i, v in pairs(paramsToUse) do
refContent = refContent .. "|" .. i .. "=" .. v
end
 
refContent = "{{" .. templateToUse .. refContent .. "}}"
else
xpcall(
function () refContent = mw.getCurrentFrame():expandTemplate{title=templateToUse, args=paramsToUse} end,
function () throwError("no-such-reference-template", templateToUse, i18nPath, citeTypeToUse) end
)
end
 
-- If the citation couldn't be displayed using any template, but is not empty (barring ignored propeties), throw an error.
elseif not referenceEmpty then
refContent = errorText("malformed-reference-header")
    for _, citeType in ipairs(citeTypes) do
    refContent = refContent .. errorText("template-failure-reason", citeConfig[citeType]["template"], citeErrors[citeType])
    end
refContent = refContent .. errorText("malformed-reference-footer")
end
 
    -- wrap refContent
local ref = {}
if refContent ~= "" then
ref = {refContent}
 
if not self.rawValue then
-- this should become a <ref> tag, so save the reference's hash for later
ref.refHash = "wikidata-" .. statement.hash .. "-v" .. (tonumber(i18n['version']) + version)
end
return {ref}
else
return {}
end
end
 
-- gets a detail of one particular type for a reference
function State:getReferenceDetail(snaks, dType, raw, link, anyLang)
local switchLang = anyLang
local value = nil
 
if not snaks[dType] then
return nil
end
 
-- if anyLang, first try the local language and otherwise any language
repeat
for _, v in ipairs(snaks[dType]) do
value = self.conf:getValue(v, raw, link, false, anyLang and not switchLang, false, true)  -- noSpecial = true
 
if value then
break
end
end
 
if value or not anyLang then
break
end
 
switchLang = not switchLang
until anyLang and switchLang
 
return value
end
 
-- gets the details of one particular type for a reference
function State:getReferenceDetails(snaks, dType, raw, link, anyLang)
local values = {}
 
if not snaks[dType] then
return {}
end
 
for _, v in ipairs(snaks[dType]) do
-- if nil is returned then it will not be added to the table
values[#values + 1] = self.conf:getValue(v, raw, link, false, anyLang, false, true)  -- noSpecial = true
end
 
return values
end
 
-- level 1 hook
function State:getAlias(object)
local value = object.value
local title = nil
 
if value and self.linked then
if self.conf.entityID:sub(1,1) == "Q" then
title = mw.wikibase.getSitelink(self.conf.entityID)
elseif self.conf.entityID:sub(1,1) == "P" then
title = "d:Property:" .. self.conf.entityID
end
 
if title then
value = buildWikilink(title, value)
end
end
 
value = {value}  -- create one value object
 
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
else
return {}  -- return empty array if there was no value
end
end
 
-- level 1 hook
function State:getBadge(value)
value = self.conf:getLabel(value, self.rawValue, self.linked, self.shortName)
 
if value == "" then
value = nil
end
 
value = {value}  -- create one value object
 
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
else
return {}  -- return empty array if there was no value
end
end
 
function State:callHook(param, hooks, statement, result)
-- call a parameter's hook if it has been defined and if it has not been called before
if not result[param] and hooks[param] then
local valuesArray = self[hooks[param]](self, statement, param, result, hooks)  -- array with value objects
 
-- add to the result
if #valuesArray > 0 then
result[param] = valuesArray
result.count = result.count + 1
else
result[param] = {}  -- an empty array to indicate that we've tried this hook already
return true  -- miss == true
end
end
 
return false
end
 
-- iterate through claims, claim's qualifiers or claim's references to collect values
function State:iterate(statements, hooks, matchHook)
matchHook = matchHook or alwaysTrue
 
local matches = false
local rankPos = nil
local result, gotRequired
 
for _, v in ipairs(statements) do
-- rankPos will be nil for non-claim statements (e.g. qualifiers, references, etc.)
matches, rankPos = matchHook(self, v)
 
if matches then
result = {count = 0}  -- collection of arrays with value objects
 
local function walk(formatTable)
local miss
 
for i2, v2 in pairs(formatTable.req) do
-- call a hook, adding its return value to the result
miss = self:callHook(i2, hooks, v, result)
 
if miss then
-- we miss a required value for this level, so return false
return false
end
 
if result.count == hooks.count then
-- we're done if all hooks have been called;
-- returning at this point breaks the loop
return true
end
end
 
for _, v2 in ipairs(formatTable) do
if result.count == hooks.count then
-- we're done if all hooks have been called;
-- returning at this point prevents further childs from being processed
return true
end
 
if v2.child then
walk(v2.child)
end
end
 
return true
end
gotRequired = walk(self.parsedFormat)
 
-- only append the result if we got values for all required parameters on the root level
if gotRequired then
-- if we have a rankPos (only with matchHook() for complete claims), then update the foundRank
if rankPos and self.conf.foundRank > rankPos then
self.conf.foundRank = rankPos
end
 
-- append the result
self.results[#self.results + 1] = result
 
-- break if we only need a single value
if self.singleValue then
break
end
end
end
end
 
return self:out()
end
 
local function getEntityId(arg, eid, page, allowOmitPropPrefix, globalSiteId)
local id = nil
local prop = nil
 
if arg then
if arg:sub(1,1) == ":" then
page = arg
eid = nil
elseif arg:sub(1,1):upper() == "Q" or arg:sub(1,9):lower() == "property:" or allowOmitPropPrefix then
eid = arg
page = nil
else
prop = arg
end
end
 
if eid then
if eid:sub(1,9):lower() == "property:" then
id = replaceAlias(mw.text.trim(eid:sub(10)))
 
if id:sub(1,1):upper() ~= "P" then
id = ""
end
else
id = replaceAlias(eid)
end
elseif page then
if page:sub(1,1) == ":" then
page = mw.text.trim(page:sub(2))
end
 
id = mw.wikibase.getEntityIdForTitle(page, globalSiteId) or ""
end
 
if not id then
id = mw.wikibase.getEntityIdForCurrentPage() or ""
end
 
id = id:upper()
 
if not mw.wikibase.isValidEntityId(id) then
id = ""
end
 
return id, prop
end
 
local function nextArg(args)
local arg = args[args.pointer]
 
if arg then
args.pointer = args.pointer + 1
return mw.text.trim(arg)
else
return nil
end
end
 
local function claimCommand(args, funcName)
local cfg = Config:new()
cfg:processFlagOrCommand(funcName)  -- process first command (== function name)
 
local lastArg, parsedFormat, formatParams, claims, value
local hooks = {count = 0}
 
-- set the date if given;
-- must come BEFORE processing the flags
if args[p.args.date] then
cfg.atDate = {parseDate(args[p.args.date])}
cfg.periods = {false, true, false}  -- change default time constraint to 'current'
end
 
-- process flags and commands
repeat
lastArg = nextArg(args)
until not cfg:processFlagOrCommand(lastArg)
 
-- get the entity ID from either the positional argument, the eid argument or the page argument
cfg.entityID, cfg.propertyID = getEntityId(lastArg, args[p.args.eid], args[p.args.page], false, args[p.args.globalSiteId])
 
if cfg.entityID == "" then
return ""  -- we cannot continue without a valid entity ID
end
 
cfg.entity = mw.wikibase.getEntity(cfg.entityID)
 
if not cfg.propertyID then
cfg.propertyID = nextArg(args)
end
 
cfg.propertyID = replaceAlias(cfg.propertyID)
 
if not cfg.entity or not cfg.propertyID then
return ""  -- we cannot continue without an entity or a property ID
end
 
cfg.propertyID = cfg.propertyID:upper()
 
if not cfg.entity.claims or not cfg.entity.claims[cfg.propertyID] then
return ""  -- there is no use to continue without any claims
end
 
claims = cfg.entity.claims[cfg.propertyID]
 
if cfg.states.qualifiersCount > 0 then
-- do further processing if "qualifier(s)" command was given
 
if #args - args.pointer + 1 > cfg.states.qualifiersCount then
-- claim ID or literal value has been given
 
cfg.propertyValue = nextArg(args)
end
 
for i = 1, cfg.states.qualifiersCount do
-- check if given qualifier ID is an alias and add it
cfg.qualifierIDs[parameters.qualifier..i] = replaceAlias(nextArg(args) or ""):upper()
end
elseif cfg.states[parameters.reference] then
-- do further processing if "reference(s)" command was given
 
cfg.propertyValue = nextArg(args)
end
 
-- check for special property value 'somevalue' or 'novalue'
if cfg.propertyValue then
cfg.propertyValue = replaceSpecialChars(cfg.propertyValue)
 
if cfg.propertyValue ~= "" and mw.text.trim(cfg.propertyValue) == "" then
cfg.propertyValue = " "  -- single space represents 'somevalue', whereas empty string represents 'novalue'
else
cfg.propertyValue = mw.text.trim(cfg.propertyValue)
end
end
 
-- parse the desired format, or choose an appropriate format
if args["format"] then
parsedFormat, formatParams = parseFormat(args["format"])
elseif cfg.states.qualifiersCount > 0 then  -- "qualifier(s)" command given
if cfg.states[parameters.property] then  -- "propert(y|ies)" command given
parsedFormat, formatParams = parseFormat(formats.propertyWithQualifier)
else
parsedFormat, formatParams = parseFormat(formats.qualifier)
end
elseif cfg.states[parameters.property] then  -- "propert(y|ies)" command given
parsedFormat, formatParams = parseFormat(formats.property)
else  -- "reference(s)" command given
parsedFormat, formatParams = parseFormat(formats.reference)
end
 
-- if a "qualifier(s)" command and no "propert(y|ies)" command has been given, make the movable separator a semicolon
if cfg.states.qualifiersCount > 0 and not cfg.states[parameters.property] then
cfg.separators["sep"..parameters.separator][1] = {";"}
end
 
-- if only "reference(s)" has been given, set the default separator to none (except when raw)
if cfg.states[parameters.reference] and not cfg.states[parameters.property] and cfg.states.qualifiersCount == 0
  and not cfg.states[parameters.reference].rawValue then
cfg.separators["sep"][1] = nil
end
 
-- if exactly one "qualifier(s)" command has been given, make "sep%q" point to "sep%q1" to make them equivalent
if cfg.states.qualifiersCount == 1 then
cfg.separators["sep"..parameters.qualifier] = cfg.separators["sep"..parameters.qualifier.."1"]
end
 
-- process overridden separator values;
-- must come AFTER tweaking the default separators
cfg:processSeparators(args)
 
-- define the hooks that should be called (getProperty, getQualifiers, getReferences);
-- only define a hook if both its command ("propert(y|ies)", "reference(s)", "qualifier(s)") and its parameter ("%p", "%r", "%q1", "%q2", "%q3") have been given
for i, v in pairs(cfg.states) do
-- e.g. 'formatParams["%q1"] or formatParams["%q"]' to define hook even if "%q1" was not defined to be able to build a complete value for "%q"
if formatParams[i] or formatParams[i:sub(1, 2)] then
hooks[i] = getHookName(i, 1)
hooks.count = hooks.count + 1
end
end
 
-- the "%q" parameter is not attached to a state, but is a collection of the results of multiple states (attached to "%q1", "%q2", "%q3", ...);
-- so if this parameter is given then this hook must be defined separately, but only if at least one "qualifier(s)" command has been given
if formatParams[parameters.qualifier] and cfg.states.qualifiersCount > 0 then
hooks[parameters.qualifier] = getHookName(parameters.qualifier, 1)
hooks.count = hooks.count + 1
end
 
-- create a state for "properties" if it doesn't exist yet, which will be used as a base configuration for each claim iteration;
-- must come AFTER defining the hooks
if not cfg.states[parameters.property] then
cfg.states[parameters.property] = State:new(cfg, parameters.property)
 
-- if the "single" flag has been given then this state should be equivalent to "property" (singular)
if cfg.singleClaim then
cfg.states[parameters.property].singleValue = true
end
end
 
-- if the "sourced" flag has been given then create a state for "reference" if it doesn't exist yet, using default values,
-- which must exist in order to be able to determine if a claim has any references;
-- must come AFTER defining the hooks
if cfg.sourcedOnly and not cfg.states[parameters.reference] then
cfg:processFlagOrCommand(p.claimCommands.reference)  -- use singular "reference" to minimize overhead
end
 
-- set the parsed format and the separators (and optional punctuation mark);
-- must come AFTER creating the additonal states
cfg:setFormatAndSeparators(cfg.states[parameters.property], parsedFormat)
 
-- process qualifier matching values, analogous to cfg.propertyValue
for i, v in pairs(args) do
i = tostring(i)
 
if i:match('^[Pp]%d+$') or aliasesP[i] then
v = replaceSpecialChars(v)
 
-- check for special qualifier value 'somevalue'
if v ~= "" and mw.text.trim(v) == "" then
v = " "  -- single space represents 'somevalue'
end
 
cfg.qualifierIDsAndValues[replaceAlias(i):upper()] = v
end
end
 
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
claims = sortOnRank(claims)
 
-- then iterate through the claims to collect values
value = cfg:concatValues(cfg.states[parameters.property]:iterate(claims, hooks, State.claimMatches))  -- pass property state with level 1 hooks and matchHook
 
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if cfg.editable and value ~= "" then
value = value .. cfg:getEditIcon()
end
 
return value
end
 
local function generalCommand(args, funcName)
local cfg = Config:new()
cfg.curState = State:new(cfg)
 
local lastArg
local value = nil
 
repeat
lastArg = nextArg(args)
until not cfg:processFlag(lastArg)
 
-- get the entity ID from either the positional argument, the eid argument or the page argument
cfg.entityID = getEntityId(lastArg, args[p.args.eid], args[p.args.page], true, args[p.args.globalSiteId])
 
if cfg.entityID == "" or not mw.wikibase.entityExists(cfg.entityID) then
return ""  -- we cannot continue without an entity
end
 
-- serve according to the given command
if funcName == p.generalCommands.label then
value = cfg:getLabel(cfg.entityID, cfg.curState.rawValue, cfg.curState.linked, cfg.curState.shortName)
elseif funcName == p.generalCommands.title then
cfg.inSitelinks = true
 
if cfg.entityID:sub(1,1) == "Q" then
value = mw.wikibase.getSitelink(cfg.entityID)
end
 
if cfg.curState.linked and value then
value = buildWikilink(value)
end
elseif funcName == p.generalCommands.description then
value = mw.wikibase.getDescription(cfg.entityID)
else
local parsedFormat, formatParams
local hooks = {count = 0}
 
cfg.entity = mw.wikibase.getEntity(cfg.entityID)
 
if funcName == p.generalCommands.alias or funcName == p.generalCommands.badge then
cfg.curState.singleValue = true
end
 
if funcName == p.generalCommands.alias or funcName == p.generalCommands.aliases then
if not cfg.entity.aliases or not cfg.entity.aliases[cfg.langCode] then
return ""  -- there is no use to continue without any aliasses
end
 
local aliases = cfg.entity.aliases[cfg.langCode]
 
-- parse the desired format, or parse the default aliases format
if args["format"] then
parsedFormat, formatParams = parseFormat(args["format"])
else
parsedFormat, formatParams = parseFormat(formats.alias)
end
 
-- process overridden separator values;
-- must come AFTER tweaking the default separators
cfg:processSeparators(args)
 
-- define the hook that should be called (getAlias);
-- only define the hook if the parameter ("%a") has been given
if formatParams[parameters.alias] then
hooks[parameters.alias] = getHookName(parameters.alias, 1)
hooks.count = hooks.count + 1
end
 
-- set the parsed format and the separators (and optional punctuation mark)
cfg:setFormatAndSeparators(cfg.curState, parsedFormat)
 
-- iterate to collect values
value = cfg:concatValues(cfg.curState:iterate(aliases, hooks))
elseif funcName == p.generalCommands.badge or funcName == p.generalCommands.badges then
if not cfg.entity.sitelinks or not cfg.entity.sitelinks[cfg.siteID] or not cfg.entity.sitelinks[cfg.siteID].badges then
return ""  -- there is no use to continue without any badges
end
 
local badges = cfg.entity.sitelinks[cfg.siteID].badges
 
cfg.inSitelinks = true
 
-- parse the desired format, or parse the default aliases format
if args["format"] then
parsedFormat, formatParams = parseFormat(args["format"])
else
parsedFormat, formatParams = parseFormat(formats.badge)
end
 
-- process overridden separator values;
-- must come AFTER tweaking the default separators
cfg:processSeparators(args)
 
-- define the hook that should be called (getBadge);
-- only define the hook if the parameter ("%b") has been given
if formatParams[parameters.badge] then
hooks[parameters.badge] = getHookName(parameters.badge, 1)
hooks.count = hooks.count + 1
end
 
-- set the parsed format and the separators (and optional punctuation mark)
cfg:setFormatAndSeparators(cfg.curState, parsedFormat)
 
-- iterate to collect values
value = cfg:concatValues(cfg.curState:iterate(badges, hooks))
end
end
 
value = value or ""
 
if cfg.editable and value ~= "" then
-- if desired, add a clickable icon that may be used to edit the returned value on Wikidata
value = value .. cfg:getEditIcon()
end
 
return value
end
 
-- modules that include this module should call the functions with an underscore prepended, e.g.: p._property(args)
local function establishCommands(commandList, commandFunc)
for _, commandName in pairs(commandList) do
local function wikitextWrapper(frame)
local args = copyTable(frame.args)
args.pointer = 1
loadI18n(aliasesP, frame)
return commandFunc(args, commandName)
end
p[commandName] = wikitextWrapper
 
local function luaWrapper(args)
args = copyTable(args)
args.pointer = 1
loadI18n(aliasesP)
return commandFunc(args, commandName)
end
p["_" .. commandName] = luaWrapper
end
end
 
establishCommands(p.claimCommands, claimCommand)
establishCommands(p.generalCommands, generalCommand)
 
-- main function that is supposed to be used by wrapper templates
function p.main(frame)
if not mw.wikibase then return nil end
 
local f, args
 
loadI18n(aliasesP, frame)
 
-- get the parent frame to take the arguments that were passed to the wrapper template
frame = frame:getParent() or frame
 
if not frame.args[1] then
throwError("no-function-specified")
end
 
f = mw.text.trim(frame.args[1])
 
if f == "main" then
throwError("main-called-twice")
end
 
assert(p["_"..f], errorText('no-such-function', f))
 
-- copy arguments from immutable to mutable table
args = copyTable(frame.args)
 
-- remove the function name from the list
table.remove(args, 1)


-- main function that is supposed to be used by wrapper templates
function p.main(frame)
local f, args, i, v
loadSubmodules(frame)
-- get the parent frame to take the arguments that were passed to the wrapper template
frame = frame:getParent() or frame
if not frame.args[1] then
throwError("no-function-specified")
end
f = mw.text.trim(frame.args[1])
if f == "main" then
throwError("main-called-twice")
end
assert(p["_"..f], errorText('no-such-function', f))
-- copy arguments from immutable to mutable table
args = copyTable(frame.args)
-- remove the function name from the list
table.remove(args, 1)
return p["_"..f](args)
return p["_"..f](args)
end
end


return p
return p
匿名利用者