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

48版 をインポートしました
template>K-iczn
(en:Module:Wd 2017年8月29日 (火) 11:01(UTC)より)
(48版 をインポートしました)
 
(7人の利用者による、間の22版が非表示)
5行目: 5行目:
local i18n
local i18n


function loadSubmodules(frame)
local function loadI18n(aliasesP, frame)
-- internationalization
local title
 
if frame then
-- current module invoked by page/template, get its title from frame
title = frame:getTitle()
else
-- current module included by other module, get its title from ...
title = arg
end
 
if not i18n then
if not i18n then
if frame then
i18n = require(title .. "/i18n").init(aliasesP)
-- module invoked by page/template, get its title from frame
i18n = require(frame:getTitle().."/i18n")
else
-- module included by other module, get its title from ...
i18n = require(arg.."/i18n")
end
end
end
end
end


local aliasesP = {
p.claimCommands = {
coord          = "P625",
property  = "property",
---------------
properties = "properties",
author          = "P50",
qualifier  = "qualifier",
publisher      = "P123",
qualifiers = "qualifiers",
importedFrom    = "P143",
reference  = "reference",
statedIn        = "P248",
references = "references"
pages          = "P304",
publicationDate = "P577",
startTime      = "P580",
endTime        = "P582",
chapter        = "P792",
retrieved      = "P813",
referenceURL    = "P854",
archiveURL      = "P1065",
title          = "P1476",
quote          = "P1683",
shortName      = "P1813",
language        = "P2439",
archiveDate    = "P2960"
}
}


local aliasesQ = {
p.generalCommands = {
percentage              = "Q11229",
label      = "label",
prolepticJulianCalendar = "Q1985786"
title      = "title",
description = "description",
alias      = "alias",
aliases    = "aliases",
badge      = "badge",
badges      = "badges"
}
}


local flags = {
p.flags = {
linked        = "linked",
linked        = "linked",
short        = "short",
raw          = "raw",
raw          = "raw",
short        = "short",
multilanguage = "multilanguage",
multilanguage = "multilanguage",
unit          = "unit",
unit          = "unit",
mdy          = "mdy",
-------------
single        = "single",
sourced      = "sourced",
edit          = "edit",
editAtEnd    = "edit@end",
best          = "best",
preferred    = "preferred",
preferred    = "preferred",
normal        = "normal",
normal        = "normal",
deprecated    = "deprecated",
deprecated    = "deprecated",
best          = "best",
future        = "future",
future        = "future",
current      = "current",
current      = "current",
former        = "former"
former        = "former",
edit          = "edit",
editAtEnd    = "edit@end",
mdy          = "mdy",
single        = "single",
sourced      = "sourced"
}
}


local parameters = {
p.args = {
property  = "%p",
eid  = "eid",
qualifier = "%q",
page = "page",
reference = "%r",
date = "date"
separator = "%s",
}
general  = "%x"
 
local aliasesP = {
coord                  = "P625",
-----------------------
image                  = "P18",
author                  = "P50",
publisher              = "P123",
importedFrom            = "P143",
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"
}
 
local aliasesQ = {
percentage              = "Q11229",
prolepticJulianCalendar = "Q1985786",
citeWeb                = "Q5637226",
citeQ                  = "Q22321052"
}
 
local parameters = {
property  = "%p",
qualifier = "%q",
reference = "%r",
alias    = "%a",
badge    = "%b",
separator = "%s",
general  = "%x"
}
}


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


84行目: 127行目:
[parameters.reference]        = {"getReferences", "getReference"},
[parameters.reference]        = {"getReferences", "getReference"},
[parameters.qualifier]        = {"getAllQualifiers"},
[parameters.qualifier]        = {"getAllQualifiers"},
[parameters.qualifier.."\\d"] = {"getQualifiers", "getQualifier"}
[parameters.qualifier.."\\d"] = {"getQualifiers", "getQualifier"},
[parameters.alias]            = {"getAlias"},
[parameters.badge]            = {"getBadge"}
}
}


95行目: 140行目:
["sep%r"]    = nil,  -- none
["sep%r"]    = nil,  -- none
["punc"]    = nil  -- none
["punc"]    = nil  -- none
}
local rankTable = {
["preferred"]  = 1,
["normal"]    = 2,
["deprecated"] = 3
}
}


local Config = {}
local Config = {}
Config.__index = Config


-- allows for recursive calls
-- allows for recursive calls
function Config.new()
function Config:new()
local cfg = {}
local cfg = {}
setmetatable(cfg, Config)
setmetatable(cfg, self)
self.__index = self
 
cfg.separators = {
cfg.separators = {
-- single value objects wrapped in arrays so that we can pass by reference
-- single value objects wrapped in arrays so that we can pass by reference
113行目: 164行目:
["punc"]  = {copyTable(defaultSeparators["punc"])}
["punc"]  = {copyTable(defaultSeparators["punc"])}
}
}
 
cfg.entity = nil
cfg.entity = nil
cfg.entityID = nil
cfg.entityID = nil
120行目: 171行目:
cfg.qualifierIDs = {}
cfg.qualifierIDs = {}
cfg.qualifierIDsAndValues = {}
cfg.qualifierIDsAndValues = {}
 
cfg.bestRank = true
cfg.bestRank = true
cfg.ranks = {true, true, false}  -- preferred = true, normal = true, deprecated = false
cfg.ranks = {true, true, false}  -- preferred = true, normal = true, deprecated = false
126行目: 177行目:
cfg.flagBest = false
cfg.flagBest = false
cfg.flagRank = false
cfg.flagRank = false
 
cfg.periods = {true, true, true}  -- future = true, current = true, former = true
cfg.periods = {true, true, true}  -- future = true, current = true, former = true
cfg.flagPeriod = false
cfg.flagPeriod = false
cfg.atDate = {parseDate(os.date('!%Y-%m-%d'))}  -- today as {year, month, day}
 
cfg.mdyDate = false
cfg.mdyDate = false
cfg.singleClaim = false
cfg.singleClaim = false
135行目: 187行目:
cfg.editable = false
cfg.editable = false
cfg.editAtEnd = false
cfg.editAtEnd = false
 
cfg.pageTitle = false
cfg.inSitelinks = false
 
cfg.langCode = mw.language.getContentLanguage().code
cfg.langCode = mw.language.getContentLanguage().code
cfg.langName = mw.language.fetchLanguageName(cfg.langCode, cfg.langCode)
cfg.langName = mw.language.fetchLanguageName(cfg.langCode, cfg.langCode)
cfg.langObj = mw.language.new(cfg.langCode)
cfg.langObj = mw.language.new(cfg.langCode)
 
cfg.siteID = mw.wikibase.getGlobalSiteId()
 
cfg.states = {}
cfg.states = {}
cfg.states.qualifiersCount = 0
cfg.states.qualifiersCount = 0
cfg.curState = nil
cfg.curState = nil
 
cfg.prefetchedRefs = nil
cfg.prefetchedRefs = nil
 
return cfg
return cfg
end
end


local State = {}
local State = {}
State.__index = State


function State.new(cfg)
function State:new(cfg, type)
local stt = {}
local stt = {}
setmetatable(stt, State)
setmetatable(stt, self)
self.__index = self
 
stt.conf = cfg
stt.conf = cfg
stt.type = type
 
stt.results = {}
stt.results = {}
 
stt.parsedFormat = {}
stt.parsedFormat = {}
stt.separator = {}
stt.separator = {}
stt.movSeparator = {}
stt.movSeparator = {}
stt.puncMark = {}
stt.puncMark = {}
 
stt.linked = false
stt.linked = false
stt.rawValue = false
stt.rawValue = false
173行目: 228行目:
stt.unitOnly = false
stt.unitOnly = false
stt.singleValue = false
stt.singleValue = false
 
return stt
return stt
end
end


function replaceAlias(ID)
local function replaceAlias(id)
if aliasesP[ID] then
if aliasesP[id] then
ID = aliasesP[ID]
id = aliasesP[id]
end
end
 
return ID
return id
end
end


function applyStringParams(str, ...)
local function errorText(code, param)
for i, v in ipairs(arg) do
local text = i18n["errors"][code]
str = mw.ustring.gsub(str, "$"..i, v)
if param then text = mw.ustring.gsub(text, "$1", param) end
end
return text
return str
end
end


function unknownDataTypeError(dataType)
local function throwError(errorMessage, param)
return applyStringParams(i18n['errors']['unknown-data-type'], dataType)
error(errorText(errorMessage, param))
end
end


function missingRequiredParameterError()
local function replaceDecimalMark(num)
return i18n['errors']['missing-required-parameter']
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
end
end


function extraRequiredParameterError(param)
local function padZeros(num, numDigits)
return applyStringParams(i18n['errors']['extra-required-parameter'], param)
local numZeros
end
local negative = false
 
if num < 0 then
negative = true
num = num * -1
end
 
num = tostring(num)
numZeros = numDigits - num:len()


function getOrdinalSuffix(num)
for _ = 1, numZeros do
return i18n.getOrdinalSuffix(num)
num = "0"..num
end
end


function addDelimiters(num)
if negative then
return i18n.addDelimiters(num)
num = "-"..num
end
end


function replaceDecimalMark(num)
return num
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
end
end


function replaceSpecialChar(chr)
local function replaceSpecialChar(chr)
if chr == '_' then
if chr == '_' then
-- replace underscores with spaces
-- replace underscores with spaces
226行目: 286行目:
end
end


function replaceSpecialChars(str)
local function replaceSpecialChars(str)
local chr
local chr
local esc = false
local esc = false
local strOut = ""
local strOut = ""
 
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
245行目: 305行目:
end
end
end
end
 
return strOut
return strOut
end
end


function buildWikilink(target, label)
local function buildWikilink(target, label)
if target == label then
if not label or target == label then
return "[[" .. target .. "]]"
return "[[" .. target .. "]]"
else
else
263行目: 323行目:
return nil
return nil
end
end
 
local tOut = {}
local tOut = {}
 
for i, v in pairs(tIn) do
for i, v in pairs(tIn) do
tOut[i] = v
tOut[i] = v
end
end
 
return tOut
return tOut
end
end
275行目: 335行目:
-- used to merge output arrays together;
-- used to merge output arrays together;
-- note that it currently mutates the first input array
-- note that it currently mutates the first input array
function mergeArrays(a1, a2)
local function mergeArrays(a1, a2)
for i = 1, #a2 do
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
a1[#a1 + 1] = a2[i]
end
end
 
return a1
return a1
end
end


function parseWikidataURL(url)
local function split(str, del)
local i, j
local out = {}
local i, j = str:find(del)
if url:match('^http[s]?://') then
 
i, j = url:find("Q")
if i and j then
out[1] = str:sub(1, i - 1)
if i then
out[2] = str:sub(j + 1)
return url:sub(i)
else
end
out[1] = str
end
end
 
return out
end
 
local function parseWikidataURL(url)
local id
 
if url:match('^http[s]?://') then
id = split(url, "Q")
 
if id[2] then
return "Q" .. id[2]
end
end
 
return nil
return nil
end
end
299行目: 373行目:
function parseDate(dateStr, precision)
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(mw.ustring.gsub(dateStr:sub(ptr, i-1), "^\+(.+)$", "%1"), 10)  -- remove '+' sign (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
373行目: 448行目:
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]
407行目: 482行目:
end
end


function alwaysTrue()
local function alwaysTrue()
return true
return true
end
end
456行目: 531行目:
-- ]
-- ]
--
--
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
483行目: 558行目:
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
532行目: 607行目:
end
end
end
end
 
cur.str = cur.str .. replaceSpecialChar(chr)
cur.str = cur.str .. replaceSpecialChar(chr)
end
end
539行目: 614行目:
esc = false
esc = false
end
end
 
prev = nil
prev = nil
end
end
 
endParam()
endParam()
return root, params
end


function convertRank(rank)
-- make sure that at least one required parameter has been defined
if rank == "preferred" then
if not next(root.req) then
return 1
throwError("missing-required-parameter")
elseif rank == "normal" then
end
return 2
 
elseif rank == "deprecated" then
-- make sure that the separator parameter "%s" is not amongst the required parameters
return 3
if root.req[parameters.separator] then
else
throwError("extra-required-parameter", parameters.separator)
return 4  -- default (in its literal sense)
end
end
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 = convertRank(v.rank)
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


function getShortName(ID)
-- if id == nil then item connected to current page is used
if ID then
function Config:getLabel(id, raw, link, short)
return p._property({ID, aliasesP.shortName}) -- "property" is single
local label = nil
else
local title = nil
return p._property({aliasesP.shortName})  -- "property" is single
local prefix= ""
 
if not id then
id = mw.wikibase.getEntityIdForCurrentPage()
 
if not id then
return ""
end
end
end
end


function getLabel(ID, args)
id = id:upper() -- just to be sure
args = args or {}
 
if raw then
if ID then
-- check if given id actually exists
args[#args + 1] = ID
if mw.wikibase.isValidEntityId(id) and mw.wikibase.entityExists(id) then
end
label = id
return p._label(args)
end


function Config:getEditIcon()
if id:sub(1,1) == "P" then
local value = ""
prefix = "Property:"
local prefix = ""
end
local front = " "
end
local back = ""
 
prefix = "d:" .. prefix
if self.entityID:sub(1,1) == "P" then
 
prefix = "Property:"
title = label  -- may be nil
end
else
-- try short name first if requested
if self.editAtEnd then
if short then
front = '<span style="float:'
label = p._property{aliasesP.shortName, [p.args.eid] = id}  -- get short name
 
if self.langObj:isRTL() then
if label == "" then
front = front .. 'left'
label = nil
else
end
front = front .. 'right'
end
 
-- get label
if not label then
label = mw.wikibase.getLabelByLang(id, self.langCode)
end
end
front = front .. '">'
back = '</span>'
end
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 not label then
label = ""
if self.propertyID then
elseif link then
value = value .. "#" .. self.propertyID
-- build a link if requested
if not title then
if id:sub(1,1) == "Q" then
title = mw.wikibase.getSitelink(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
end
 
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
return label
return front .. value .. back
end
end


-- used to create the final output string when it's all done, so that for references the
function Config:getEditIcon()
-- function extensionTag("ref", ...) is only called when they really ended up in the final output
local value = ""
function Config:concatValues(valuesArray)
local prefix = ""
local outString = ""
local front = "&nbsp;"
local j, skip
local back = ""
 
for i = 1, #valuesArray do
if self.entityID:sub(1,1) == "P" then
-- check if this is a reference
prefix = "Property:"
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
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})
end
else
outString = outString .. valuesArray[i][1]
end
end
end
 
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if self.editAtEnd then
if self.editable and outString ~= "" then
front = '<span style="float:'
outString = outString .. self:getEditIcon()
 
if self.langObj:isRTL() then
front = front .. 'left'
else
front = front .. 'right'
end
 
front = front .. '">'
back = '</span>'
end
 
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
 
if self.propertyID then
value = value .. "#" .. self.propertyID
elseif self.inSitelinks then
value = value .. "#sitelinks-wikipedia"
end
end
 
return outString
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
 
return front .. value .. back
end
end


function Config:convertUnit(unit, raw, link, short, unitOnly)
-- used to create the final output string when it's all done, so that for references the
raw = raw or false
-- function extensionTag("ref", ...) is only called when they really ended up in the final output
link = link or false
function Config:concatValues(valuesArray)
short = short or false
local outString = ""
unitOnly = unitOnly or false
local j, skip
local args = {}
local space = " "
local label = ""
if unit == "" or unit == "1" then
return nil
end
if unitOnly then
space = ""
end
itemID = parseWikidataURL(unit)
if itemID then
if itemID == aliasesQ.percentage then
return "%"
else
if raw then
args[#args + 1] = flags.raw
end
if link then
args[#args + 1] = flags.linked
end
if short then
args[#args + 1] = flags.short
end
label = getLabel(itemID, args)
if label ~= "" then
return space .. label
end
end
end
return ""
end


function Config:getValue(snak, raw, link, short, anyLang, unitOnly, noSpecial)
for i = 1, #valuesArray do
raw = raw or false
-- check if this is a reference
link = link or false
if valuesArray[i].refHash then
short = short or false
j = i - 1
anyLang = anyLang or false
skip = false
unitOnly = unitOnly or false
 
noSpecial = noSpecial or 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 snak.snaktype == 'value' then
if valuesArray[i].refHash == valuesArray[j].refHash then
if snak.datavalue.type == 'string' then
skip = true
if snak.datatype == 'url' and link then
break
-- create link explicitly
if raw then
-- will render as a linked number like [1]
return "[" .. snak.datavalue.value .. "]"
else
return "[" .. snak.datavalue.value .. " " .. snak.datavalue.value .. "]"
end
end
elseif snak.datatype == 'commonsMedia' then
j = j - 1
if link then
return buildWikilink("c:File:" .. snak.datavalue.value, snak.datavalue.value)
elseif not raw then
return "[[File:" .. snak.datavalue.value .. "]]"
else
return snak.datavalue.value
end
elseif snak.datatype == 'geo-shape' and link then
return buildWikilink("c:" .. snak.datavalue.value, snak.datavalue.value)
elseif snak.datatype == 'math' and not raw then
return mw.getCurrentFrame():extensionTag("math", snak.datavalue.value)
else
return snak.datavalue.value
end
end
elseif snak.datavalue.type == 'monolingualtext' then
 
if anyLang then
if not skip then
return snak.datavalue.value['text'], snak.datavalue.value['language']
-- add <ref> tag with the reference's hash as its name (to deduplicate references)
elseif snak.datavalue.value['language'] == self.langCode then
outString = outString .. mw.getCurrentFrame():extensionTag("ref", valuesArray[i][1], {name = valuesArray[i].refHash})
return snak.datavalue.value['text']
else
return nil
end
end
elseif snak.datavalue.type == 'quantity' then
else
local value = ""
outString = outString .. valuesArray[i][1]
local unit
end
end
if not unitOnly then
 
-- get value and strip + signs from front
return outString
value = mw.ustring.gsub(snak.datavalue.value['amount'], "^\+(.+)$", "%1")
end
 
if raw then
function Config:convertUnit(unit, raw, link, short, unitOnly)
return value
local space = " "
end
local label = ""
local itemID
-- replace decimal mark based on locale
 
value = replaceDecimalMark(value)
if unit == "" or unit == "1" then
return nil
-- add delimiters for readability
end
value = addDelimiters(value)
 
end
if unitOnly then
space = ""
unit = self:convertUnit(snak.datavalue.value['unit'], raw, link, short, unitOnly)
end
 
if unit then
itemID = parseWikidataURL(unit)
value = value .. unit
 
end
if itemID then
if itemID == aliasesQ.percentage then
return value
return "%"
elseif snak.datavalue.type == 'time' then
else
local y, m, d, p, yDiv, yRound, yFull, value, calendarID, dateStr
label = self:getLabel(itemID, raw, link, short)
local yFactor = 1
 
local sign = 1
if label ~= "" then
local prefix = ""
return space .. label
local suffix = ""
local mayAddCalendar = false
local calendar = ""
local precision = snak.datavalue.value['precision']
if precision == 11 then
p = "d"
elseif precision == 10 then
p = "m"
else
p = "y"
yFactor = 10^(9-precision)
end
end
end
y, m, d = parseDate(snak.datavalue.value['time'], p)
end
 
if y < 0 then
return ""
sign = -1
end
y = y * sign
 
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))
end
 
function Config:getValue(snak, raw, link, short, anyLang, unitOnly, noSpecial, type)
if snak.snaktype == 'value' then
local datatype = snak.datavalue.type
local subtype = snak.datatype
local datavalue = snak.datavalue.value
 
if datatype == 'string' then
if subtype == 'url' and link then
-- create link explicitly
if raw then
-- will render as a linked number like [1]
return "[" .. datavalue .. "]"
else
return "[" .. datavalue .. " " .. datavalue .. "]"
end
elseif subtype == 'commonsMedia' then
if link then
return buildWikilink("c:File:" .. datavalue, datavalue)
elseif not raw then
return "[[File:" .. datavalue .. "]]"
else
return datavalue
end
elseif subtype == 'geo-shape' and link then
return buildWikilink("c:" .. datavalue, datavalue)
elseif subtype == 'math' and not raw then
local attribute = nil
 
if (type == parameters.property or (type == parameters.qualifier and self.propertyID == aliasesP.hasPart)) and snak.property == aliasesP.definingFormula then
attribute = {qid = self.entityID}
end
 
return mw.getCurrentFrame():extensionTag("math", datavalue, attribute)
elseif subtype == 'external-id' and link then
local url = p._property{aliasesP.formatterURL, [p.args.eid] = snak.property}  -- get formatter URL
 
if url ~= "" then
url = mw.ustring.gsub(url, "$1", datavalue)
return "[" .. url .. " " .. datavalue .. "]"
else
return datavalue
end
else
return datavalue
end
end
elseif datatype == 'monolingualtext' then
-- if precision is tens/hundreds/thousands/millions/billions of years
if anyLang or datavalue['language'] == self.langCode then
if precision <= 8 then
return datavalue['text']
yDiv = y / yFactor
else
return nil
-- if precision is tens/hundreds/thousands of years
end
if precision >= 6 then
elseif datatype == 'quantity' then
mayAddCalendar = true
local value = ""
local unit
if precision <= 7 then
 
-- round centuries/millenniums up (e.g. 20th century or 3rd millennium)
if not unitOnly then
yRound = math.ceil(yDiv)
-- get value and strip + signs from front
value = mw.ustring.gsub(datavalue['amount'], "^\+(.+)$", "%1")
if not raw then
 
if precision == 6 then
if raw then
suffix = i18n['datetime']['suffixes']['millennium']
return value
else
end
suffix = i18n['datetime']['suffixes']['century']
 
end
-- replace decimal mark based on locale
value = replaceDecimalMark(value)
suffix = getOrdinalSuffix(yRound) .. suffix
 
else
-- add delimiters for readability
-- if not verbose, take the first year of the century/millennium
value = i18n.addDelimiters(value)
-- (e.g. 1901 for 20th century or 2001 for 3rd millennium)
end
yRound = (yRound - 1) * yFactor + 1
 
end
unit = self:convertUnit(datavalue['unit'], raw, link, short, unitOnly)
else
 
-- precision == 8
if unit then
-- round decades down (e.g. 2010s)
value = value .. unit
yRound = math.floor(yDiv) * yFactor
end
 
if not raw then
return value
prefix = i18n['datetime']['prefixes']['decade-period']
elseif datatype == 'time' then
suffix = i18n['datetime']['suffixes']['decade-period']
local y, m, d, p, yDiv, yRound, yFull, value, calendarID, dateStr
end
local yFactor = 1
end
local sign = 1
local prefix = ""
if raw and sign < 0 then
local suffix = ""
-- if BCE then compensate for "counting backwards"
local mayAddCalendar = false
-- (e.g. -2019 for 2010s BCE, -2000 for 20th century BCE or -3000 for 3rd millennium BCE)
local calendar = ""
yRound = yRound + yFactor - 1
local precision = datavalue['precision']
end
 
else
if precision == 11 then
local yReFactor, yReDiv, yReRound
p = "d"
elseif precision == 10 then
-- round to nearest for tens of thousands of years or more
p = "m"
yRound = math.floor(yDiv + 0.5)
else
p = "y"
if yRound == 0 then
yFactor = 10^(9-precision)
if precision <= 2 and y ~= 0 then
end
yReFactor = 1e6
 
yReDiv = y / yReFactor
y, m, d = parseDate(datavalue['time'], p)
yReRound = math.floor(yReDiv + 0.5)
 
if y < 0 then
if yReDiv == yReRound then
sign = -1
-- change precision to millions of years only if we have a whole number of them
y = y * sign
precision = 3
end
yFactor = yReFactor
 
yRound = yReRound
-- if precision is tens/hundreds/thousands/millions/billions of years
if precision <= 8 then
yDiv = y / yFactor
 
-- if precision is tens/hundreds/thousands of years
if precision >= 6 then
mayAddCalendar = true
 
if precision <= 7 then
-- round centuries/millenniums up (e.g. 20th century or 3rd millennium)
yRound = math.ceil(yDiv)
 
if not raw then
if precision == 6 then
suffix = i18n['datetime']['suffixes']['millennium']
else
suffix = i18n['datetime']['suffixes']['century']
end
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
end
else
if yRound == 0 then
-- precision == 8
-- otherwise, take the unrounded (original) number of years
-- round decades down (e.g. 2010s)
precision = 5
yRound = math.floor(yDiv) * yFactor
yFactor = 1
 
yRound = y
if not raw then
mayAddCalendar = true
prefix = i18n['datetime']['prefixes']['decade-period']
suffix = i18n['datetime']['suffixes']['decade-period']
end
end
end
end
 
if precision >= 1 and y ~= 0 then
if raw and sign < 0 then
yFull = yRound * yFactor
-- if BCE then compensate for "counting backwards"
-- (e.g. -2019 for 2010s BCE, -2000 for 20th century BCE or -3000 for 3rd millennium BCE)
yReFactor = 1e9
yRound = yRound + yFactor - 1
yReDiv = yFull / yReFactor
end
yReRound = math.floor(yReDiv + 0.5)
else
local yReFactor, yReDiv, yReRound
if yReDiv == yReRound then
 
-- change precision to billions of years if we're in that range
-- round to nearest for tens of thousands of years or more
precision = 0
yRound = math.floor(yDiv + 0.5)
yFactor = yReFactor
 
yRound = yReRound
if yRound == 0 then
else
if precision <= 2 and y ~= 0 then
yReFactor = 1e6
yReFactor = 1e6
yReDiv = yFull / yReFactor
yReDiv = y / yReFactor
yReRound = math.floor(yReDiv + 0.5)
yReRound = math.floor(yReDiv + 0.5)
 
if yReDiv == yReRound then
if yReDiv == yReRound then
-- change precision to millions of years if we're in that range
-- change precision to millions of years only if we have a whole number of them
precision = 3
precision = 3
yFactor = yReFactor
yFactor = yReFactor
yRound = yReRound
yRound = yReRound
end
end
end
if yRound == 0 then
-- otherwise, take the unrounded (original) number of years
precision = 5
yFactor = 1
yRound = y
mayAddCalendar = true
end
end
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
 
if not raw then
if not raw then
if precision == 3 then
if precision == 3 then
921行目: 1,040行目:
mayAddCalendar = true
mayAddCalendar = true
end
end
 
if mayAddCalendar then
if mayAddCalendar then
calendarID = parseWikidataURL(snak.datavalue.value['calendarmodel'])
calendarID = parseWikidataURL(datavalue['calendarmodel'])
 
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
if not raw then
if not raw then
937行目: 1,056行目:
end
end
end
end
 
if not raw then
if not raw then
local ce = nil
local ce = nil
 
if sign < 0 then
if sign < 0 then
ce = i18n['datetime']['BCE']
ce = i18n['datetime']['BCE']
946行目: 1,065行目:
ce = i18n['datetime']['CE']
ce = i18n['datetime']['CE']
end
end
 
if ce then
if ce then
if link then
if link then
953行目: 1,072行目:
suffix = suffix .. " " .. ce
suffix = suffix .. " " .. ce
end
end
 
value = tostring(yRound)
value = tostring(yRound)
 
if m then
if m then
dateStr = self.langObj:formatDate("F", "1-"..m.."-1")
dateStr = self.langObj:formatDate("F", "1-"..m.."-1")
 
if d then
if d then
if self.mdyDate then
if self.mdyDate then
966行目: 1,085行目:
end
end
end
end
 
value = dateStr .. " " .. value
value = dateStr .. " " .. value
end
end
 
value = prefix .. value .. suffix .. calendar
value = prefix .. value .. suffix .. calendar
else
else
value = tostring(yRound * sign)
value = padZeros(yRound * sign, 4)
 
if m then
if m then
value = value .. "-" .. m
value = value .. "-" .. padZeros(m, 2)
 
if d then
if d then
value = value .. "-" .. d
value = value .. "-" .. padZeros(d, 2)
end
end
end
end
 
value = value .. calendar
value = value .. calendar
end
end
 
return value
return value
elseif snak.datavalue.type == 'globecoordinate' then
elseif datatype == 'globecoordinate' then
-- logic from https://github.com/DataValues/Geo
-- logic from https://github.com/DataValues/Geo (v4.0.1)
 
local precision, numDigits, strFormat, value, globe
local precision, unitsPerDegree, numDigits, strFormat, value, globe
local latValue, latitude, latDegrees, latMinutes, latSeconds
local latitude, latConv, latValue, latLink
local lonValue, longitude, lonDegrees, lonMinutes, lonSeconds
local longitude, lonConv, lonValue, lonLink
local latDirection, latDirectionN, latDirectionS, latDirectionEN
local latDirection, latDirectionN, latDirectionS, latDirectionEN
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
local degSymbol, minSymbol, secSymbol, separator
 
local latDegrees = nil
local latMinutes = nil
local latSeconds = nil
local lonDegrees = nil
local lonMinutes = nil
local lonSeconds = nil
 
local latDegSym = ""
local latMinSym = ""
local latSecSym = ""
local lonDegSym = ""
local lonMinSym = ""
local lonSecSym = ""
 
local latDirectionEN_N = "N"
local latDirectionEN_N = "N"
local latDirectionEN_S = "S"
local latDirectionEN_S = "S"
local lonDirectionEN_E = "E"
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
local lonDirectionEN_W = "W"
 
if not raw then
if not raw then
latDirectionN = i18n['coord']['latitude-north']
latDirectionN = i18n['coord']['latitude-north']
1,005行目: 1,139行目:
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionW = i18n['coord']['longitude-west']
lonDirectionW = i18n['coord']['longitude-west']
 
degSymbol = i18n['coord']['degrees']
degSymbol = i18n['coord']['degrees']
minSymbol = i18n['coord']['minutes']
minSymbol = i18n['coord']['minutes']
1,015行目: 1,149行目:
lonDirectionE = lonDirectionEN_E
lonDirectionE = lonDirectionEN_E
lonDirectionW = lonDirectionEN_W
lonDirectionW = lonDirectionEN_W
 
degSymbol = "/"
degSymbol = "/"
minSymbol = "/"
minSymbol = "/"
1,021行目: 1,155行目:
separator = "/"
separator = "/"
end
end
 
latitude = snak.datavalue.value['latitude']
latitude = datavalue['latitude']
longitude = snak.datavalue.value['longitude']
longitude = datavalue['longitude']
 
if latitude < 0 then
if latitude < 0 then
latDirection = latDirectionS
latDirection = latDirectionS
1,033行目: 1,167行目:
latDirectionEN = latDirectionEN_N
latDirectionEN = latDirectionEN_N
end
end
 
if longitude < 0 then
if longitude < 0 then
lonDirection = lonDirectionW
lonDirection = lonDirectionW
1,042行目: 1,176行目:
lonDirectionEN = lonDirectionEN_E
lonDirectionEN = lonDirectionEN_E
end
end
 
precision = snak.datavalue.value['precision']
precision = datavalue['precision']
 
if not precision or precision <= 0 then
precision = 1 / 3600  -- precision not set (correctly), set to arcsecond
end
 
-- remove insignificant detail
latitude = math.floor(latitude / precision + 0.5) * precision
latitude = math.floor(latitude / precision + 0.5) * precision
longitude = math.floor(longitude / precision + 0.5) * precision
longitude = math.floor(longitude / precision + 0.5) * precision
 
numDigits = math.ceil(-math.log10(3600 * precision))
if precision >= 1 - (1 / 60) and precision < 1 then
precision = 1
if numDigits < 0 or numDigits == -0 then
elseif precision >= (1 / 60) - (1 / 3600) and precision < (1 / 60) then
precision = 1 / 60
end
 
if precision >= 1 then
unitsPerDegree = 1
elseif precision >= (1 / 60)  then
unitsPerDegree = 60
else
unitsPerDegree = 3600
end
 
numDigits = math.ceil(-math.log10(unitsPerDegree * precision))
 
if numDigits <= 0 then
numDigits = tonumber("0")  -- for some reason, 'numDigits = 0' may actually store '-0', so parse from string instead
numDigits = tonumber("0")  -- for some reason, 'numDigits = 0' may actually store '-0', so parse from string instead
end
end
 
strFormat = "%." .. numDigits .. "f"
strFormat = "%." .. numDigits .. "f"
 
-- use string.format() to strip decimal point followed by a zero (.0) for whole numbers
if precision >= 1 then
latSeconds = tonumber(strFormat:format(math.floor(latitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
latDegrees = strFormat:format(latitude)
lonSeconds = tonumber(strFormat:format(math.floor(longitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
lonDegrees = strFormat:format(longitude)
 
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
if not raw then
-- replace decimal marks based on locale
latDegSym = replaceDecimalMark(latDegrees) .. degSymbol
latSeconds = replaceDecimalMark(latSeconds)
lonDegSym = replaceDecimalMark(lonDegrees) .. degSymbol
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(snak.datavalue.value['globe'])
if globe then
globe = mw.wikibase.getEntity(globe):getLabel("en"):lower()
else
else
globe = "earth"
latDegSym = latDegrees .. degSymbol
lonDegSym = lonDegrees .. degSymbol
end
end
value = "[https://tools.wmflabs.org/geohack/geohack.php?language="..self.langCode.."&params="..latitude.."_"..latDirectionEN.."_"..longitude.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
end
return value
elseif snak.datavalue.type == 'wikibase-entityid' then
local lang
local value = ""
local title = nil
local prefix = ""
local itemID = snak.datavalue.value['numeric-id']
if snak.datatype == 'wikibase-item' then
itemID = "Q" .. itemID
elseif snak.datatype == 'wikibase-property' then
itemID = "P" .. itemID
prefix = "Property:"
else
else
return '<strong class="error">' .. unknownDataTypeError(snak.datatype) .. '</strong>'
latConv = math.floor(latitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
end
lonConv = math.floor(longitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
 
if raw then
if precision >= (1 / 60) then
if link then
latMinutes = latConv
return buildWikilink("d:" .. prefix .. itemID, itemID)
lonMinutes = lonConv
else
else
return itemID
latSeconds = latConv
end
lonSeconds = lonConv
end
 
latMinutes = math.floor(latSeconds / 60)
if short then
lonMinutes = math.floor(lonSeconds / 60)
value = getShortName(prefix .. itemID)
 
end
latSeconds = strFormat:format(latSeconds - (latMinutes * 60))
lonSeconds = strFormat:format(lonSeconds - (lonMinutes * 60))
if value == "" then
 
value, lang = mw.wikibase.getLabelWithLang(itemID)
if not raw then
latSecSym = replaceDecimalMark(latSeconds) .. secSymbol
-- don't allow language fallback
lonSecSym = replaceDecimalMark(lonSeconds) .. secSymbol
if lang ~= self.langCode then
else
value = nil
latSecSym = latSeconds .. secSymbol
lonSecSym = lonSeconds .. secSymbol
end
end
 
latDegrees = math.floor(latMinutes / 60)
lonDegrees = math.floor(lonMinutes / 60)
 
latDegSym = latDegrees .. degSymbol
lonDegSym = lonDegrees .. degSymbol
 
latMinutes = latMinutes - (latDegrees * 60)
lonMinutes = lonMinutes - (lonDegrees * 60)
 
if precision >= (1 / 60) then
latMinutes = strFormat:format(latMinutes)
lonMinutes = strFormat:format(lonMinutes)
 
if not raw then
latMinSym = replaceDecimalMark(latMinutes) .. minSymbol
lonMinSym = replaceDecimalMark(lonMinutes) .. minSymbol
else
latMinSym = latMinutes .. minSymbol
lonMinSym = lonMinutes .. minSymbol
end
else
latMinSym = latMinutes .. minSymbol
lonMinSym = lonMinutes .. minSymbol
end
end
end
end
 
if (link or value == nil) and snak.datatype == 'wikibase-item' then
latValue = latDegSym .. latMinSym .. latSecSym .. latDirection
title = mw.wikibase.sitelink(itemID)
lonValue = lonDegSym .. lonMinSym .. lonSecSym .. lonDirection
end
 
value = latValue .. separator .. lonValue
 
if link then
if link then
if title then
globe = parseWikidataURL(datavalue['globe'])
value = buildWikilink(title, (value or title))
 
elseif not value or snak.datatype == 'wikibase-property' then
if globe then
value = buildWikilink("d:" .. prefix .. itemID, (value or itemID))
globe = mw.wikibase.getLabelByLang(globe, "en"):lower()
else
globe = "earth"
end
end
elseif not value then
 
value = (title or itemID)
latLink = table.concat({latDegrees, latMinutes, latSeconds}, "_")
lonLink = table.concat({lonDegrees, lonMinutes, lonSeconds}, "_")
 
value = "[https://tools.wmflabs.org/geohack/geohack.php?language="..self.langCode.."&params="..latLink.."_"..latDirectionEN.."_"..lonLink.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
end
end
 
return value
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
else
return '<strong class="error">' .. unknownDataTypeError(snak.datavalue.type) .. '</strong>'
return '<strong class="error">' .. errorText('unknown-data-type', datatype) .. '</strong>'
end
end
elseif snak.snaktype == 'somevalue' and not noSpecial then
elseif snak.snaktype == 'somevalue' and not noSpecial then
1,186行目: 1,334行目:
function Config:getSingleRawQualifier(claim, qualifierID)
function Config:getSingleRawQualifier(claim, qualifierID)
local qualifiers
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[qualifierID] end
if claim.qualifiers then qualifiers = claim.qualifiers[qualifierID] end
 
if qualifiers and qualifiers[1] then
if qualifiers and qualifiers[1] then
return self:getValue(qualifiers[1], true)  -- raw = true
return self:getValue(qualifiers[1], true)  -- raw = true
1,198行目: 1,346行目:
function Config:snakEqualsValue(snak, value)
function Config:snakEqualsValue(snak, value)
local snakValue = self:getValue(snak, true)  -- raw = true
local snakValue = self:getValue(snak, true)  -- raw = true
 
if snakValue and snak.snaktype == 'value' and snak.datavalue.type == 'wikibase-entityid' then value = value:upper() end
if snakValue and snak.snaktype == 'value' and snak.datavalue.type == 'wikibase-entityid' then value = value:upper() end
 
return snakValue == value
return snakValue == value
end
end
1,206行目: 1,354行目:
function Config:setRank(rank)
function Config:setRank(rank)
local rankPos
local rankPos
 
if rank == flags.best then
if rank == p.flags.best then
self.bestRank = true
self.bestRank = true
self.flagBest = true  -- mark that 'best' flag was given
self.flagBest = true  -- mark that 'best' flag was given
return
return
end
end
 
if rank:sub(1,9) == flags.preferred then
if rank:sub(1,9) == p.flags.preferred then
rankPos = 1
rankPos = 1
elseif rank:sub(1,6) == flags.normal then
elseif rank:sub(1,6) == p.flags.normal then
rankPos = 2
rankPos = 2
elseif rank:sub(1,10) == flags.deprecated then
elseif rank:sub(1,10) == p.flags.deprecated then
rankPos = 3
rankPos = 3
else
else
return
return
end
end
 
-- one of the rank flags was given, check if another one was given before
-- one of the rank flags was given, check if another one was given before
if not self.flagRank then
if not self.flagRank then
1,229行目: 1,377行目:
self.flagRank = true                -- mark that a rank flag was given
self.flagRank = true                -- mark that a rank flag was given
end
end
 
if rank:sub(-1) == "+" then
if rank:sub(-1) == "+" then
for i = rankPos, 1, -1 do
for i = rankPos, 1, -1 do
1,245行目: 1,393行目:
function Config:setPeriod(period)
function Config:setPeriod(period)
local periodPos
local periodPos
 
if period == flags.future then
if period == p.flags.future then
periodPos = 1
periodPos = 1
elseif period == flags.current then
elseif period == p.flags.current then
periodPos = 2
periodPos = 2
elseif period == flags.former then
elseif period == p.flags.former then
periodPos = 3
periodPos = 3
else
else
return
return
end
end
 
-- one of the period flags was given, check if another one was given before
-- one of the period flags was given, check if another one was given before
if not self.flagPeriod then
if not self.flagPeriod then
1,261行目: 1,409行目:
self.flagPeriod = true                -- mark that a period flag was given
self.flagPeriod = true                -- mark that a period flag was given
end
end
 
self.periods[periodPos] = true
self.periods[periodPos] = true
end
end


function Config:processFlag(flag)
function Config:qualifierMatches(claim, id, value)
if not flag then
local qualifiers
return false
 
if claim.qualifiers then qualifiers = claim.qualifiers[id] end
if qualifiers then
for _, v in pairs(qualifiers) do
if self:snakEqualsValue(v, value) then
return true
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)
if self.bestRank then
return (self.ranks[rankPos] and self.foundRank >= rankPos)
else
else
flag = mw.text.trim(flag)
return self.ranks[rankPos]
end
end
end
if flag == flags.linked then
 
self.curState.linked = true
function Config:timeMatches(claim)
return true
local startTime = nil
elseif flag == flags.raw then
local startTimeY = nil
self.curState.rawValue = true
local startTimeM = nil
local startTimeD = nil
if self.curState == self.states[parameters.reference] then
local endTime = nil
-- raw reference values end with periods and require a separator (other than none)
local endTimeY = nil
self.separators["sep%r"][1] = {" "}
local endTimeM = nil
end
local endTimeD = nil
 
return true
if self.periods[1] and self.periods[2] and self.periods[3] then
elseif flag == flags.short then
-- any time
self.curState.shortName = true
return true
elseif flag == flags.multilanguage then
self.curState.anyLanguage = true
return true
elseif flag == flags.unit then
self.curState.unitOnly = true
return true
return true
elseif flag == flags.mdy then
self.mdyDate = true
return true
elseif flag == flags.single then
self.singleClaim = true
return true
elseif flag == flags.sourced then
self.sourcedOnly = true
return true
elseif flag == flags.edit then
self.editable = true
return true
elseif flag == flags.editAtEnd then
self.editable = true
self.editAtEnd = true
return true
elseif flag == flags.best or flag:match('^'..flags.preferred..'[+-]?$') or flag:match('^'..flags.normal..'[+-]?$') or flag:match('^'..flags.deprecated..'[+-]?$') then
self:setRank(flag)
return true
elseif flag == flags.future or flag == flags.current or flag == flags.former then
self:setPeriod(flag)
return true
elseif flag == "" then
-- ignore empty flags and carry on
return true
else
return false
end
end
end


function Config:processFlagOrCommand(flag)
startTime = self:getSingleRawQualifier(claim, aliasesP.startTime)
local param = ""
if startTime and startTime ~= "" and startTime ~= " " then
startTimeY, startTimeM, startTimeD = parseDate(startTime)
if not flag then
end
return false
 
else
endTime = self:getSingleRawQualifier(claim, aliasesP.endTime)
flag = mw.text.trim(flag)
if endTime and endTime ~= "" and endTime ~= " " then
endTimeY, endTimeM, endTimeD = parseDate(endTime)
end
end
 
if flag == "property" or flag == "properties" then
if startTimeY ~= nil and endTimeY ~= nil and datePrecedesDate(endTimeY, endTimeM, endTimeD, startTimeY, startTimeM, startTimeD) then
param = parameters.property
-- invalidate end time if it precedes start time
elseif flag:match('^qualifier[s]?$') then
endTimeY = nil
self.states.qualifiersCount = self.states.qualifiersCount + 1
endTimeM = nil
param = parameters.qualifier .. self.states.qualifiersCount
endTimeD = nil
self.separators["sep"..param] = {copyTable(defaultSeparators["sep%q\\d"])}
elseif flag:match('^reference[s]?$') then
param = parameters.reference
else
return self:processFlag(flag)
end
end
 
if self.states[param] then
if self.periods[1] then
return false
-- future
if startTimeY and datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], startTimeY, startTimeM, startTimeD) then
return true
end
end
end
 
-- create a new state for each command
if self.periods[2] then
self.states[param] = State.new(self)
-- current
if (startTimeY == nil or not datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], startTimeY, startTimeM, startTimeD)) and
-- use "%x" as the general parameter name
  (endTimeY == nil or datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], endTimeY, endTimeM, endTimeD)) then
self.states[param].parsedFormat = parseFormat(parameters.general) -- will be overwritten for param=="%p"
return true
end
-- set the separator
self.states[param].separator = self.separators["sep"..param] -- will be nil for param=="%p", which will be set separately
if flag:sub(-1) ~= 's' then
self.states[param].singleValue = true
end
end
self.curState = self.states[param]
return true
end


function Config:qualifierMatches(claim, ID, value)
if self.periods[3] then
local qualifiers
-- former
if endTimeY and not datePrecedesDate(self.atDate[1], self.atDate[2], self.atDate[3], endTimeY, endTimeM, endTimeD) then
if claim.qualifiers then qualifiers = claim.qualifiers[ID] end
return true
if qualifiers then
for i, v in pairs(qualifiers) do
if self:snakEqualsValue(v, value) then
return true
end
end
end
elseif value == "" then
-- if the qualifier is not present then treat it the same as the special value 'novalue'
return true
end
end
 
return false
return false
end
end


function Config:rankMatches(rankPos)
function Config:processFlag(flag)
if self.bestRank then
if not flag then
return (self.ranks[rankPos] and self.foundRank >= rankPos)
return false
else
return self.ranks[rankPos]
end
end
end


function Config:timeMatches(claim)
if flag == p.flags.linked then
local startTime = nil
self.curState.linked = true
local startTimeY = nil
return true
local startTimeM = nil
elseif flag == p.flags.raw then
local startTimeD = nil
self.curState.rawValue = true
local endTime = nil
 
local endTimeY = nil
if self.curState == self.states[parameters.reference] then
local endTimeM = nil
-- raw reference values end with periods and require a separator (other than none)
local endTimeD = nil
self.separators["sep%r"][1] = {" "}
end
if self.periods[1] and self.periods[2] and self.periods[3] then
 
-- any time
return true
elseif flag == p.flags.short then
self.curState.shortName = true
return true
elseif flag == p.flags.multilanguage then
self.curState.anyLanguage = true
return true
elseif flag == p.flags.unit then
self.curState.unitOnly = true
return true
elseif flag == p.flags.mdy then
self.mdyDate = true
return true
return true
elseif flag == p.flags.single then
self.singleClaim = true
return true
elseif flag == p.flags.sourced then
self.sourcedOnly = true
return true
elseif flag == p.flags.edit then
self.editable = true
return true
elseif flag == p.flags.editAtEnd then
self.editable = true
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
end
local now = os.date('!*t')
 
function Config:processFlagOrCommand(flag)
startTime = self:getSingleRawQualifier(claim, aliasesP.startTime)
local param = ""
if startTime and startTime ~= "" and startTime ~= " " then
 
startTimeY, startTimeM, startTimeD = parseDate(startTime)
if not flag then
end
return false
endTime = self:getSingleRawQualifier(claim, aliasesP.endTime)
if endTime and endTime ~= "" and endTime ~= " " then
endTimeY, endTimeM, endTimeD = parseDate(endTime)
elseif endTime == " " then
-- end time is 'unknown', assume it is somewhere in the past;
-- we can do this by taking the current date as a placeholder for the end time
endTimeY = now['year']
endTimeM = now['month']
endTimeD = now['day']
end
if startTimeY ~= nil and endTimeY ~= nil and datePrecedesDate(endTimeY, endTimeM, endTimeD, startTimeY, startTimeM, startTimeD) then
-- invalidate end time if it precedes start time
endTimeY = nil
endTimeM = nil
endTimeD = nil
end
if self.periods[1] then
-- future
if startTimeY and datePrecedesDate(now['year'], now['month'], now['day'], startTimeY, startTimeM, startTimeD) then
return true
end
end
end
 
if self.periods[2] then
if flag == p.claimCommands.property or flag == p.claimCommands.properties then
-- current
param = parameters.property
if (startTimeY == nil or not datePrecedesDate(now['year'], now['month'], now['day'], startTimeY, startTimeM, startTimeD)) and
elseif flag == p.claimCommands.qualifier or flag == p.claimCommands.qualifiers then
  (endTimeY == nil or datePrecedesDate(now['year'], now['month'], now['day'], endTimeY, endTimeM, endTimeD)) then
self.states.qualifiersCount = self.states.qualifiersCount + 1
return true
param = parameters.qualifier .. self.states.qualifiersCount
end
self.separators["sep"..param] = {copyTable(defaultSeparators["sep%q\\d"])}
elseif flag == p.claimCommands.reference or flag == p.claimCommands.references then
param = parameters.reference
else
return self:processFlag(flag)
end
end
 
if self.periods[3] then
if self.states[param] then
-- former
return false
if endTimeY and not datePrecedesDate(now['year'], now['month'], now['day'], endTimeY, endTimeM, endTimeD) then
return true
end
end
end
 
return false
-- create a new state for each command
end
self.states[param] = State:new(self, param)
 
-- use "%x" as the general parameter name
self.states[param].parsedFormat = parseFormat(parameters.general)  -- will be overwritten for param=="%p"
 
-- set the separator
self.states[param].separator = self.separators["sep"..param]  -- will be nil for param=="%p", which will be set separately
 
if flag == p.claimCommands.property or flag == p.claimCommands.qualifier or flag == p.claimCommands.reference then
self.states[param].singleValue = true
end
 
self.curState = self.states[param]
 
return true
end
 
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
 
function Config:setFormatAndSeparators(state, parsedFormat)
state.parsedFormat = parsedFormat
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,
-- determines if a claim has references by prefetching them from the claim using getReferences,
1,472行目: 1,631行目:
function State:claimMatches(claim)
function State:claimMatches(claim)
local matches, rankPos
local matches, rankPos
 
-- first of all, reset any cached values used for the previous claim
-- first of all, reset any cached values used for the previous claim
self:resetCaches()
self:resetCaches()
 
-- if a property value was given, check if it matches the claim's property value
-- if a property value was given, check if it matches the claim's property value
if self.conf.propertyValue then
if self.conf.propertyValue then
1,482行目: 1,641行目:
matches = true
matches = true
end
end
 
-- if any qualifier values were given, check if each matches one of the claim's qualifier values
-- if any qualifier values were given, check if each matches one of the claim's qualifier values
for i, v in pairs(self.conf.qualifierIDsAndValues) do
for i, v in pairs(self.conf.qualifierIDsAndValues) do
matches = (matches and self.conf:qualifierMatches(claim, i, v))
matches = (matches and self.conf:qualifierMatches(claim, i, v))
end
end
 
-- check if the claim's rank and time period match
-- check if the claim's rank and time period match
rankPos = convertRank(claim.rank)
rankPos = rankTable[claim.rank] or 4
matches = (matches and self.conf:rankMatches(rankPos) and self.conf:timeMatches(claim))
matches = (matches and self.conf:rankMatches(rankPos) and self.conf:timeMatches(claim))
 
-- if only claims with references must be returned, check if this one has any
-- if only claims with references must be returned, check if this one has any
if self.conf.sourcedOnly then
if self.conf.sourcedOnly then
matches = (matches and self:isSourced(claim))  -- prefetches and caches references
matches = (matches and self:isSourced(claim))  -- prefetches and caches references
end
end
 
return matches, rankPos
return matches, rankPos
end
end
1,505行目: 1,664行目:
local sep = nil  -- value object
local sep = nil  -- value object
local out = {}  -- array with value objects
local out = {}  -- array with value objects
 
local function walk(formatTable, result)
local function walk(formatTable, result)
local valuesArray = {}  -- array with value objects
local valuesArray = {}  -- array with value objects
 
for i, v in pairs(formatTable.req) do
for i, v in pairs(formatTable.req) do
if not result[i] or not result[i][1] then
if not result[i] or not result[i][1] then
1,516行目: 1,675行目:
end
end
end
end
 
for i, v in ipairs(formatTable) do
for _, v in ipairs(formatTable) do
if v.param then
if v.param then
valuesArray = mergeArrays(valuesArray, result[v.str])
valuesArray = mergeArrays(valuesArray, result[v.str])
1,523行目: 1,682行目:
valuesArray[#valuesArray + 1] = {v.str}
valuesArray[#valuesArray + 1] = {v.str}
end
end
 
if v.child then
if v.child then
valuesArray = mergeArrays(valuesArray, walk(v.child, result))
valuesArray = mergeArrays(valuesArray, walk(v.child, result))
end
end
end
end
 
return valuesArray
return valuesArray
end
end
 
-- iterate through the results from back to front, so that we know when to add separators
-- iterate through the results from back to front, so that we know when to add separators
for i = #self.results, 1, -1 do
for i = #self.results, 1, -1 do
result = self.results[i]
result = self.results[i]
 
-- if there is already some output, then add the separators
-- if there is already some output, then add the separators
if #out > 0 then
if #out > 0 then
1,544行目: 1,703行目:
result[parameters.separator] = {self.puncMark[1]}  -- optional punctuation mark
result[parameters.separator] = {self.puncMark[1]}  -- optional punctuation mark
end
end
 
valuesArray = walk(self.parsedFormat, result)
valuesArray = walk(self.parsedFormat, result)
 
if #valuesArray > 0 then
if #valuesArray > 0 then
if sep then
if sep then
valuesArray[#valuesArray + 1] = sep
valuesArray[#valuesArray + 1] = sep
end
end
 
out = mergeArrays(valuesArray, out)
out = mergeArrays(valuesArray, out)
end
end
end
end
 
-- reset state before next iteration
-- reset state before next iteration
self.results = {}
self.results = {}
 
return out
return out
end
end
1,564行目: 1,723行目:
-- level 1 hook
-- level 1 hook
function State:getProperty(claim)
function State:getProperty(claim)
local value = {self.conf:getValue(claim.mainsnak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly)}  -- create one value object
local value = {self:getValue(claim.mainsnak)}  -- create one value object
 
if #value > 0 then
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
return {value}  -- wrap the value object in an array and return it
1,576行目: 1,735行目:
function State:getQualifiers(claim, param)
function State:getQualifiers(claim, param)
local qualifiers
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if qualifiers then
if qualifiers then
1,589行目: 1,748行目:
-- level 2 hook
-- level 2 hook
function State:getQualifier(snak)
function State:getQualifier(snak)
local value = {self.conf:getValue(snak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly)}  -- create one value object
local value = {self:getValue(snak)}  -- create one value object
 
if #value > 0 then
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
return {value}  -- wrap the value object in an array and return it
1,602行目: 1,761行目:
local out = {}  -- array with value objects
local out = {}  -- array with value objects
local sep = self.conf.separators["sep"..parameters.qualifier][1]  -- value object
local sep = self.conf.separators["sep"..parameters.qualifier][1]  -- value object
 
-- iterate through the output of the separate "qualifier(s)" commands
-- iterate through the output of the separate "qualifier(s)" commands
for i = 1, self.conf.states.qualifiersCount do
for i = 1, self.conf.states.qualifiersCount do
 
-- if a hook has not been called yet, call it now
-- if a hook has not been called yet, call it now
if not result[parameters.qualifier..i] then
if not result[parameters.qualifier..i] then
self:callHook(parameters.qualifier..i, hooks, claim, result)
self:callHook(parameters.qualifier..i, hooks, claim, result)
end
end
 
-- if there is output for this particular "qualifier(s)" command, then add it
-- 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 result[parameters.qualifier..i] and result[parameters.qualifier..i][1] then
 
-- if there is already some output, then add the separator
-- if there is already some output, then add the separator
if #out > 0 and sep then
if #out > 0 and sep then
out[#out + 1] = sep
out[#out + 1] = sep
end
end
 
out = mergeArrays(out, result[parameters.qualifier..i])
out = mergeArrays(out, result[parameters.qualifier..i])
end
end
end
end
 
return out
return out
end
end
1,632行目: 1,791行目:
return self.conf.prefetchedRefs
return self.conf.prefetchedRefs
end
end
 
if claim.references then
if claim.references then
-- iterate through claim's reference statements to collect their values;
-- iterate through claim's reference statements to collect their values;
1,643行目: 1,802行目:


-- level 2 hook
-- level 2 hook
-- logic determined based on https://www.wikidata.org/wiki/Help:Sources
function State:getReference(statement)
function State:getReference(statement)
local language, referenceURL, title, statedIn, statedInRaw
local key, citeWeb, citeQ, label
local authors = {}
local params = {}
local params = {}
local citeParams = {}
local citeParams = {['web'] = {}, ['q'] = {}}
local citeMismatch = {}
local useCite = nil
local useParams = nil
local value = ""
local value = ""
local ref = {}
local ref = {}
 
-- number of parameters that do not go along with "stated in"-sources other than web pages as per https://www.wikidata.org/wiki/Help:Sources;
local version = 1  -- increment this each time the below logic is changed to avoid conflict errors
-- these are parameters of properties other than "pages(s)" and "chapter" (for books) and "title" and "publication date" (for databases) and also "stated in"
 
local hasExtraParams = false
if statement.snaks then
if statement.snaks then
-- don't include "imported from", which has been added by a bot
-- don't include "imported from", which is added by a bot
if statement.snaks[aliasesP.importedFrom] then
if statement.snaks[aliasesP.importedFrom] then
statement.snaks[aliasesP.importedFrom] = nil
statement.snaks[aliasesP.importedFrom] = nil
end
end
 
-- not linked yet because we need the plain value for comparison first
-- don't include "inferred from", which is added by a bot
language = self:getReferenceDetail(statement.snaks, aliasesP.language, false, false, false, true)  -- (noUnset = true)
if statement.snaks[aliasesP.inferredFrom] then
if language then
statement.snaks[aliasesP.inferredFrom] = nil
-- not part of a "stated in"-source
end
hasExtraParams = true
 
-- don't include "type of reference"
-- only add language to the reference if it differs from the local one
if statement.snaks[aliasesP.typeOfReference] then
if self.conf.langName ~= language then
statement.snaks[aliasesP.typeOfReference] = nil
if self.linked then
-- retrieve language again, but this time with link
params[aliasesP.language] = self:getReferenceDetail(statement.snaks, aliasesP.language, false, true)  -- link = true
else
params[aliasesP.language] = language
end
end
-- we have to manually unset, since the first call to getReferenceDetail was with noUnset and the second call might not have happened
statement.snaks[aliasesP.language] = nil
end
end
 
authors = self:getReferenceDetails(statement.snaks, aliasesP.author, false, self.linked)  -- link = true/false
-- don't include "image" to prevent littering
if #authors > 0 then
if statement.snaks[aliasesP.image] then
-- not part of a "stated in"-source
statement.snaks[aliasesP.image] = nil
hasExtraParams = true
end
end
 
referenceURL = self:getReferenceDetail(statement.snaks, aliasesP.referenceURL)
-- don't include "language" if it is equal to the local one
if referenceURL then
if self:getReferenceDetail(statement.snaks, aliasesP.language) == self.conf.langName then
-- not part of a "stated in"-source
statement.snaks[aliasesP.language] = nil
hasExtraParams = true
end
end
 
-- the next two may be part of a "stated in"-source, so retrieve them already so that they won't count as hasExtraParams
-- retrieve all the parameters
title    = self:getReferenceDetail(statement.snaks, aliasesP.title, false, false, true) -- anyLang = true
for i in pairs(statement.snaks) do
statedIn = self:getReferenceDetail(statement.snaks, aliasesP.statedIn, false, true, false, true)  -- link = true, (noUnset = true)
label = ""
 
-- (1) if both "reference URL" and "title" are present, then use the general template for citing web references
-- multiple authors may be given
if referenceURL and title and i18n['cite']['cite-web'] and i18n['cite']['cite-web'] ~= "" then
if i == aliasesP.author then
citeParams[i18n['cite']['url']]    = referenceURL
params[i] = self:getReferenceDetails(statement.snaks, i, false, self.linked, true)  -- link = true/false, anyLang = true
citeParams[i18n['cite']['title']]  = title
else
citeParams[i18n['cite']['website']] = statedIn
params[i] = {self:getReferenceDetail(statement.snaks, i, false, (self.linked or (i == aliasesP.statedIn)) and (statement.snaks[i][1].datatype ~= 'url'), true)} -- link = true/false, anyLang = true
citeParams[i18n['cite']['language']] = params[aliasesP.language]
citeParams[i18n['cite']['date']]        = self:getReferenceDetail(statement.snaks, aliasesP.publicationDate)
citeParams[i18n['cite']['access-date']]  = self:getReferenceDetail(statement.snaks, aliasesP.retrieved)
citeParams[i18n['cite']['archive-url']]  = self:getReferenceDetail(statement.snaks, aliasesP.archiveURL)
citeParams[i18n['cite']['archive-date']] = self:getReferenceDetail(statement.snaks, aliasesP.archiveDate)
citeParams[i18n['cite']['publisher']]    = self:getReferenceDetail(statement.snaks, aliasesP.publisher, false, self.linked)  -- link = true/false
citeParams[i18n['cite']['quote']]        = self:getReferenceDetail(statement.snaks, aliasesP.quote, false, false, true)  -- anyLang = true
for i, v in ipairs(authors) do
citeParams[i18n['cite']['author']..i] = v
end
end
 
-- if this module is being substituted then build a regular template call, otherwise expand the template
if #params[i] == 0 then
if mw.isSubsting() then
params[i] = nil
for i, v in pairs(citeParams) do
value = value .. "|" .. i .. "=" .. v
end
value = "{{" .. i18n['cite']['cite-web'] .. value .. "}}"
else
else
value = mw.getCurrentFrame():expandTemplate{title=i18n['cite']['cite-web'], args=citeParams}
if statement.snaks[i][1].datatype == 'external-id' then
end
key = "external-id"
else
label = self.conf:getLabel(i)
-- we need the raw Q-identifier for the next template
 
statedInRaw = self:getReferenceDetail(statement.snaks, aliasesP.statedIn, true)  -- raw = true
if label ~= "" then
label = label .. " "
-- the next three may be part of a "stated in"-source, so retrieve them already so that they won't count as hasExtraParams
params[aliasesP.pages]          = self:getReferenceDetail(statement.snaks, aliasesP.pages)
params[aliasesP.chapter]        = self:getReferenceDetail(statement.snaks, aliasesP.chapter)
params[aliasesP.publicationDate] = self:getReferenceDetail(statement.snaks, aliasesP.publicationDate)
-- retrieve the rest of the parameters and make them count as hasExtraParams
for i in pairs(statement.snaks) do
params[i] = self:getReferenceDetail(statement.snaks, i, false, self.linked, true)  -- link = true/false, anyLang = true
hasExtraParams = true
end
-- (2) if "stated in" is present without any parameters not belonging to a "stated in"-source, then use this template which expands the stated-in item
if statedInRaw and not hasExtraParams and i18n['cite']['cite-q'] and i18n['cite']['cite-q'] ~= "" then
citeParams[i18n['cite']['pages']]  = params[aliasesP.pages]
citeParams[i18n['cite']['chapter']] = params[aliasesP.chapter]
citeParams[i18n['cite']['date']]    = params[aliasesP.publicationDate]
if mw.isSubsting() then
for i, v in pairs(citeParams) do
value = value .. "|" .. i .. "=" .. v
end
end
value = "{{" .. i18n['cite']['cite-q'] .. "|" .. statedInRaw .. value .. "}}"
else
else
citeParams[1] = statedInRaw
key = i
value = mw.getCurrentFrame():expandTemplate{title=i18n['cite']['cite-q'], args=citeParams}
end
end
-- (3) else, do some default rendering of name-value pairs, but only if at least "stated in" or "reference URL" is present
 
elseif statedIn or referenceURL then
-- add the parameter to each matching type of citation
-- authors were already retrieved; start by adding them up front
for j in pairs(citeParams) do
if #authors > 0 then
-- do so if there was no mismatch with a previous parameter
citeParams[#citeParams + 1] = table.concat(authors, " & ")
if not citeMismatch[j] then
end
-- check if this parameter is not mismatching itself
if i18n['cite'][j][key] then
-- combine "reference URL" and "title" into one link if both are present
-- continue if an option is available in the corresponding cite template
if referenceURL and title then
if i18n['cite'][j][key] ~= "" then
citeParams[#citeParams + 1] = "[" .. referenceURL .. " " .. title .. "]"
citeParams[j][i18n['cite'][j][key]] = label .. params[i][1]
elseif referenceURL then
 
citeParams[#citeParams + 1] = referenceURL
-- if there are multiple parameter values (authors), add those too
elseif title then
for k=2, #params[i] do
citeParams[#citeParams + 1] = title
citeParams[j][i18n['cite'][j][key]..k] = label .. params[i][k]
end
end
end
if statedIn then
else
citeParams[#citeParams + 1] = statedIn
citeMismatch[j] = true
end
end
for i, v in pairs(params) do
i = getLabel(i)
if i ~= "" then
citeParams[#citeParams + 1] = i .. ": " .. v
end
end
end
value = table.concat(citeParams, "; ")
if value ~= "" then
value = value .. "."
end
end
end
end
end
end
 
if value ~= "" then
-- get title of general template for citing web references
value = {value} -- create one value object
citeWeb = split(mw.wikibase.getSitelink(aliasesQ.citeWeb) or "", ":")[2]  -- split off namespace from front
 
if not self.rawValue then
-- get title of template that expands stated-in references into citations
-- this should become a <ref> tag, so safe the reference's hash for later
citeQ = split(mw.wikibase.getSitelink(aliasesQ.citeQ) or "", ":")[2] -- split off namespace from front
value.refHash = statement.hash
 
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'][aliasesP.referenceURL]] and citeParams['web'][i18n['cite']['web'][aliasesP.title]] then
ref = {value}  -- wrap the value object in an array
useCite = citeWeb
useParams = citeParams['web']
 
-- (2) use the template that expands stated-in references into citations if there is a match and if at least "stated in" is present
elseif citeQ and not citeMismatch['q'] and citeParams['q'][i18n['cite']['q'][aliasesP.statedIn]] then
-- we need the raw "stated in" Q-identifier for the this template
citeParams['q'][i18n['cite']['q'][aliasesP.statedIn]] = self:getReferenceDetail(statement.snaks, aliasesP.statedIn, true)  -- raw = true
 
useCite = citeQ
useParams = citeParams['q']
end
end
end
return ref
end


-- gets a detail of one particular type for a reference
if useCite and useParams then
function State:getReferenceDetail(snaks, dType, raw, link, anyLang, noUnset)
-- if this module is being substituted then build a regular template call, otherwise expand the template
raw = raw or false
if mw.isSubsting() then
link = link or false
for i, v in pairs(useParams) do
anyLang = anyLang or false
value = value .. "|" .. i .. "=" .. v
noUnset = noUnset or false
end
 
local switchLang = anyLang
value = "{{" .. useCite .. value .. "}}"
local value = nil
else
value = mw.getCurrentFrame():expandTemplate{title=useCite, args=useParams}
if not snaks[dType] then
return nil
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
end
if value or not anyLang then
break
end
switchLang = not switchLang
until anyLang and switchLang
if not noUnset then
-- remove detail(s) to make it possible to get the rest of the details in one loop
snaks[dType] = nil
end
return value
end


-- gets the details of one particular type for a reference
-- (3) else, do some default rendering of name-value pairs, but only if at least "stated in", "reference URL" or "title" is present
function State:getReferenceDetails(snaks, dType, raw, link, anyLang, noUnset)
elseif params[aliasesP.statedIn] or params[aliasesP.referenceURL] or params[aliasesP.title] then
raw = raw or false
citeParams['default'] = {}
link = link or false
anyLang = anyLang or false
noUnset = noUnset or false
local values = {}
if not snaks[dType] then
return {}
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
if not noUnset then
-- remove detail(s) to make it possible to get the rest of the details in one loop
snaks[dType] = nil
end
return values
end


function State:callHook(param, hooks, statement, result)
-- start by adding authors up front
local valuesArray, refHash
if params[aliasesP.author] and #params[aliasesP.author] > 0 then
citeParams['default'][#citeParams['default'] + 1] = table.concat(params[aliasesP.author], " & ")
-- call a parameter's hook if it has been defined and if it has not been called before
end
if not result[param] and hooks[param] then
 
valuesArray = self[hooks[param]](self, statement, param, result, hooks)  -- array with value objects
-- combine "reference URL" and "title" into one link if both are present
if params[aliasesP.referenceURL] and params[aliasesP.title] then
-- add to the result
citeParams['default'][#citeParams['default'] + 1] = '[' .. params[aliasesP.referenceURL][1] .. ' "' .. params[aliasesP.title][1] .. '"]'
if #valuesArray > 0 then
elseif params[aliasesP.referenceURL] then
result[param] = valuesArray
citeParams['default'][#citeParams['default'] + 1] = params[aliasesP.referenceURL][1]
result.count = result.count + 1
elseif params[aliasesP.title] then
else
citeParams['default'][#citeParams['default'] + 1] = '"' .. params[aliasesP.title][1] .. '"'
result[param] = {}  -- an empty array to indicate that we've tried this hook already
end
return true  -- miss == true
 
-- then add "stated in"
if params[aliasesP.statedIn] then
citeParams['default'][#citeParams['default'] + 1] = "''" .. params[aliasesP.statedIn][1] .. "''"
end
 
-- remove previously added parameters so that they won't be added a second time
params[aliasesP.author] = nil
params[aliasesP.referenceURL] = nil
params[aliasesP.title] = nil
params[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
end
end
return false
end


-- iterate through claims, claim's qualifiers or claim's references to collect values
if value ~= "" then
function State:iterate(statements, hooks, matchHook)
value = {value}  -- create one value object
matchHook = matchHook or alwaysTrue
 
if not self.rawValue then
local matches = false
-- this should become a <ref> tag, so save the reference's hash for later
local rankPos = nil
value.refHash = "wikidata-" .. statement.hash .. "-v" .. (tonumber(i18n['cite']['version']) + version)
local result, gotRequired
end
 
for i, v in ipairs(statements) do
ref = {value}  -- wrap the value object in an array
-- rankPos will be nil for non-claim statements (e.g. qualifiers, references, etc.)
end
matches, rankPos = matchHook(self, v)
end
 
if matches then
return ref
result = {count = 0}  -- collection of arrays with value objects
end
 
local function walk(formatTable)
-- gets a detail of one particular type for a reference
local miss
function State:getReferenceDetail(snaks, dType, raw, link, anyLang)
local switchLang = anyLang
for i2, v2 in pairs(formatTable.req) do
local value = nil
-- call a hook, adding its return value to the result
 
miss = self:callHook(i2, hooks, v, result)
if not snaks[dType] then
return nil
if miss then
end
-- we miss a required value for this level, so return false
 
return false
-- if anyLang, first try the local language and otherwise any language
end
repeat
for _, v in ipairs(snaks[dType]) do
if result.count == hooks.count then
value = self.conf:getValue(v, raw, link, false, anyLang and not switchLang, false, true)  -- noSpecial = true
-- we're done if all hooks have been called;
 
-- returning at this point breaks the loop
if value then
return true
break
end
end
end
end
 
for i2, v2 in ipairs(formatTable) do
if value or not anyLang then
if result.count == hooks.count then
break
-- 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
end
return self:out()
end


function p.property(frame)
switchLang = not switchLang
loadSubmodules(frame)
until anyLang and switchLang
return p._property(copyTable(frame.args))
end


function p._property(args)
return value
loadSubmodules()
return execCommand(args, "property")
end
end


function p.properties(frame)
-- gets the details of one particular type for a reference
loadSubmodules(frame)
function State:getReferenceDetails(snaks, dType, raw, link, anyLang)
return p._properties(copyTable(frame.args))
local values = {}
end


function p._properties(args)
if not snaks[dType] then
loadSubmodules()
return {}
return execCommand(args, "properties")
end
end


function p.qualifier(frame)
for _, v in ipairs(snaks[dType]) do
loadSubmodules(frame)
-- if nil is returned then it will not be added to the table
return p._qualifier(copyTable(frame.args))
values[#values + 1] = self.conf:getValue(v, raw, link, false, anyLang, false, true) -- noSpecial = true
end
end


function p._qualifier(args)
return values
loadSubmodules()
return execCommand(args, "qualifier")
end
end


function p.qualifiers(frame)
-- level 1 hook
loadSubmodules(frame)
function State:getAlias(object)
return p._qualifiers(copyTable(frame.args))
local value = object.value
end
local title = nil


function p._qualifiers(args)
if value and self.linked then
loadSubmodules()
if self.conf.entityID:sub(1,1) == "Q" then
return execCommand(args, "qualifiers")
title = mw.wikibase.getSitelink(self.conf.entityID)
end
elseif self.conf.entityID:sub(1,1) == "P" then
title = "d:Property:" .. self.conf.entityID
end


function p.reference(frame)
if title then
loadSubmodules(frame)
value = buildWikilink(title, value)
return p._reference(copyTable(frame.args))
end
end
end


function p._reference(args)
value = {value}  -- create one value object
loadSubmodules()
return execCommand(args, "reference")
end


function p.references(frame)
if #value > 0 then
loadSubmodules(frame)
return {value}  -- wrap the value object in an array and return it
return p._references(copyTable(frame.args))
else
end
return {}  -- return empty array if there was no value
end
end


function p._references(args)
-- level 1 hook
loadSubmodules()
function State:getBadge(value)
return execCommand(args, "references")
value = self.conf:getLabel(value, self.rawValue, self.linked, self.shortName)
end


function execCommand(args, funcName)
if value == "" then
_ = Config.new()
value = nil
_:processFlagOrCommand(funcName)  -- process first command (== function name)
local parsedFormat, formatParams, claims, sep
local hooks = {count = 0}
local nextArg = args[1]
local nextIndex = 2
-- process flags and commands
while _:processFlagOrCommand(nextArg) do
nextArg = args[nextIndex]
nextIndex = nextIndex + 1
end
end
 
if nextArg then
value = {value}  -- create one value object
nextArg = mw.text.trim(nextArg)
 
if #value > 0 then
return {value}  -- wrap the value object in an array and return it
else
else
nextArg = ""
return {}  -- return empty array if there was no value
end
end
end
-- check for optional entity ID of either item or property
 
if nextArg:sub(1,1):upper() == "Q" then
function State:callHook(param, hooks, statement, result)
_.entityID = nextArg:upper()  -- entity ID of an item was given
local valuesArray, refHash
_.entity = mw.wikibase.getEntity(_.entityID)  -- get the item-entity based on the given ID
 
_.propertyID = mw.text.trim(args[nextIndex] or "") -- property ID
-- call a parameter's hook if it has been defined and if it has not been called before
nextIndex = nextIndex + 1
if not result[param] and hooks[param] then
elseif nextArg:sub(1,9):lower() == "property:" then
valuesArray = self[hooks[param]](self, statement, param, result, hooks) -- array with value objects
_.entityID = replaceAlias(mw.text.trim(nextArg:sub(10))):upper()  -- entity ID of a property was given
 
_.entity = mw.wikibase.getEntity(_.entityID)  -- get the property-entity based on the given ID
-- add to the result
_.propertyID = mw.text.trim(args[nextIndex] or "")  -- property ID
if #valuesArray > 0 then
nextIndex = nextIndex + 1
result[param] = valuesArray
else
result.count = result.count + 1
-- no positional entity ID was given, so get entity ID from 'eid' if it was given
if args["eid"] then
if args["eid"]:sub(1,1):upper() == "Q" then
_.entityID = args["eid"]:upper() 
elseif args["eid"]:sub(1,9):lower() == "property:" then
_.entityID = replaceAlias(mw.text.trim(args["eid"]:sub(10))):upper()
else
-- might be entity ID of a property, or a bogus entity ID that will fail later on
_.entityID = replaceAlias(args["eid"]):upper()
if _.entityID == "" then
-- explicitly return if value for 'eid' is empty
return ""
end
end
else
_.entityID = mw.wikibase.getEntityIdForCurrentPage()  -- by default, use item-entity connected to current page
end
_.entity = mw.wikibase.getEntity(_.entityID)
_.propertyID = nextArg  -- property ID
end
-- check if given property ID is an alias
_.propertyID = replaceAlias(_.propertyID):upper()
if _.states.qualifiersCount > 0 then
-- do further processing if "qualifier(s)" command was given
if #args - nextIndex + 1 > _.states.qualifiersCount then
-- claim ID or literal value has been given
_.propertyValue = mw.text.trim(args[nextIndex])
nextIndex = nextIndex + 1
end
for i = 1, _.states.qualifiersCount do
nextArg = mw.text.trim(args[nextIndex] or "")  -- is a qualifierID
nextIndex = nextIndex + 1
-- check if given qualifier ID is an alias and add it
_.qualifierIDs[parameters.qualifier..i] = replaceAlias(nextArg):upper()
end
elseif _.states[parameters.reference] then
-- do further processing if "reference(s)" command was given
nextArg = args[nextIndex]  -- claim ID or literal value (possibly nil)
nextIndex = nextIndex + 1
if nextArg then
_.propertyValue = mw.text.trim(nextArg)
end
end
-- check for special property value 'somevalue' or 'novalue'
if _.propertyValue then
_.propertyValue = replaceSpecialChars(_.propertyValue)
if _.propertyValue ~= "" and mw.text.trim(_.propertyValue) == "" then
_.propertyValue = " "  -- single space represents 'somevalue', whereas empty string represents 'novalue'
else
else
_.propertyValue = mw.text.trim(_.propertyValue)
result[param] = {}  -- an empty array to indicate that we've tried this hook already
return true  -- miss == true
end
end
end
end
 
-- parse the desired format, or choose an appropriate format
return false
if args["format"] then
end
parsedFormat, formatParams = parseFormat(args["format"])
 
elseif _.states.qualifiersCount > 0 then  -- "qualifier(s)" command given
-- iterate through claims, claim's qualifiers or claim's references to collect values
if _.states[parameters.property] then  -- "propert(y|ies)" command given
function State:iterate(statements, hooks, matchHook)
parsedFormat, formatParams = parseFormat(formats.propertyWithQualifier)
matchHook = matchHook or alwaysTrue
else
 
parsedFormat, formatParams = parseFormat(formats.qualifier)
local matches = false
end
local rankPos = nil
elseif _.states[parameters.property] then  -- "propert(y|ies)" command given
local result, gotRequired
parsedFormat, formatParams = parseFormat(formats.property)
 
else  -- "reference(s)" command given
for _, v in ipairs(statements) do
parsedFormat, formatParams = parseFormat(formats.reference)
-- rankPos will be nil for non-claim statements (e.g. qualifiers, references, etc.)
end
matches, rankPos = matchHook(self, v)
 
-- if a "qualifier(s)" command and no "propert(y|ies)" command has been given, make the movable separator a semicolon
if matches then
if _.states.qualifiersCount > 0 and not _.states[parameters.property] then
result = {count = 0} -- collection of arrays with value objects
_.separators["sep"..parameters.separator][1] = {";"}
 
end
local function walk(formatTable)
local miss
-- if only "reference(s)" has been given, set the default separator to none (except when raw)
 
if _.states[parameters.reference] and not _.states[parameters.property] and _.states.qualifiersCount == 0
for i2, v2 in pairs(formatTable.req) do
  and not _.states[parameters.reference].rawValue then
-- call a hook, adding its return value to the result
_.separators["sep"][1] = nil
miss = self:callHook(i2, hooks, v, result)
end
 
if miss then
-- if exactly one "qualifier(s)" command has been given, make "sep%q" point to "sep%q1" to make them equivalent;
-- we miss a required value for this level, so return false
-- must come BEFORE overriding the separator values
return false
if _.states.qualifiersCount == 1 then
end
_.separators["sep"..parameters.qualifier] = _.separators["sep"..parameters.qualifier.."1"]
 
end
if result.count == hooks.count then
-- we're done if all hooks have been called;
-- process overridden separator values;
-- returning at this point breaks the loop
-- must come AFTER parsing the formats
return true
for i, v in pairs(_.separators) do
end
if args[i] then
end
sep = replaceSpecialChars(args[i])
 
for _, v2 in ipairs(formatTable) do
if sep ~= "" then
if result.count == hooks.count then
_.separators[i][1] = {sep}
-- we're done if all hooks have been called;
else
-- returning at this point prevents further childs from being processed
_.separators[i][1] = nil
return true
end
end
end
 
end
if v2.child then
walk(v2.child)
-- make sure that at least one required parameter has been defined
end
if not next(parsedFormat.req) then
end
error(missingRequiredParameterError())
 
end
return true
-- make sure that the separator parameter "%s" is not amongst the required parameters
if parsedFormat.req[parameters.separator] then
error(extraRequiredParameterError(parameters.separator))
end
-- 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(_.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 _.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 _.states[parameters.property] then
_.states[parameters.property] = State.new(_)
-- 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
-- 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 _.sourcedOnly and not _.states[parameters.reference] then
_:processFlagOrCommand("reference")  -- use singular "reference" to minimize overhead
end
-- set the parsed format and the separators (and optional punctuation mark)
_.states[parameters.property].parsedFormat = parsedFormat
_.states[parameters.property].separator = _.separators["sep"]
_.states[parameters.property].movSeparator = _.separators["sep"..parameters.separator]
_.states[parameters.property].puncMark = _.separators["punc"]
-- process qualifier matching values, analogous to _.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
end
gotRequired = walk(self.parsedFormat)
_.qualifierIDsAndValues[replaceAlias(i):upper()] = v
 
end
-- only append the result if we got values for all required parameters on the root level
end
if gotRequired then
-- if we have a rankPos (only with matchHook() for complete claims), then update the foundRank
if _.entity and _.entity.claims then claims = _.entity.claims[_.propertyID] end
if rankPos and self.conf.foundRank > rankPos then
if claims then
self.conf.foundRank = rankPos
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
end
claims = sortOnRank(claims)
-- then iterate through the claims to collect values
return _:concatValues(_.states[parameters.property]:iterate(claims, hooks, State.claimMatches))  -- pass property state with level 1 hooks and matchHook
else
return ""
end
end


function p.label(frame)
-- append the result
loadSubmodules(frame)
self.results[#self.results + 1] = result
return p._label(copyTable(frame.args))
end


function p._label(args, _)
-- break if we only need a single value
_ = _ or Config.new()
if self.singleValue then
_.curState = State.new(_)
break
loadSubmodules()
local ID = nil
local label = nil
local title = nil
local prefix= ""
local lang
local nextArg = args[1]
local nextIndex = 2
while _:processFlag(nextArg) do
nextArg = args[nextIndex]
nextIndex = nextIndex + 1
end
if nextArg then
nextArg = mw.text.trim(nextArg)
else
nextArg = ""
end
-- check for optional entity ID of either item or property
if nextArg:sub(1,1):upper() == "Q" then
ID = nextArg:upper()  -- entity ID of an item was given
elseif nextArg:sub(1,9):lower() == "property:" then
ID = replaceAlias(mw.text.trim(nextArg:sub(10))):upper()  -- entity ID of a property was given
else
-- might be entity ID of a property, or a bogus entity ID that will fail later on
ID = replaceAlias(nextArg):upper()
if ID:sub(1,1) ~= "P" then
if ID == "" then
-- no positional entity ID was given, so get entity ID from 'eid' if it was given
if args["eid"] then
if args["eid"]:sub(1,1):upper() == "Q" then
ID = args["eid"]:upper() 
elseif args["eid"]:sub(1,9):lower() == "property:" then
ID = replaceAlias(mw.text.trim(args["eid"]:sub(10))):upper()
else
-- might be entity ID of a property, or a bogus entity ID that will fail later on
ID = replaceAlias(args["eid"]):upper()
if ID == "" then
-- explicitly return if value for 'eid' is empty
return ""
end
end
else
ID = nil
end
end
end
end
end
end
end
end
 
if ID then
return self:out()
_.entityID = ID
end
else
 
_.entityID = mw.wikibase.getEntityIdForCurrentPage()
local function getEntityId(arg, eid, page, allowOmitPropPrefix)
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
end
 
if not _.curState.rawValue or _.pageTitle then
if eid then
if not _.pageTitle then
if eid:sub(1,9):lower() == "property:" then
-- (1) try short name
id = replaceAlias(mw.text.trim(eid:sub(10)))
if _.curState.shortName then
 
if ID and ID:sub(1,1) == "P" then
if id:sub(1,1):upper() ~= "P" then
label = getShortName("Property:" .. ID)
id = ""
else
label = getShortName(ID)
end
if label == "" then
label = nil
end
end
-- (2) try label
if not label then
label, lang = mw.wikibase.getLabelWithLang(ID)
-- don't allow language fallback
if lang ~= _.langCode then
label = nil
end
end
end
else
id = replaceAlias(eid)
end
end
elseif page then
-- (3) try sitelink/title
if page:sub(1,1) == ":" then
if not label or _.curState.linked then
page = mw.text.trim(page:sub(2))
if not ID then
title = mw.title.getCurrentTitle().prefixedText
elseif ID:sub(1,1) == "Q" then
title = mw.wikibase.sitelink(ID)
elseif label then
-- properties have no sitelink, 'title = ID' should only be set
-- if there is a 'label' already and if it needs to be linked;
-- otherwise, it would be 'label = title == ID' even if '_.pageTitle' is set
title = ID
prefix = "d:Property:"
end
label = label or title
end
end
id = mw.wikibase.getEntityIdForTitle(page) 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
end
-- (4) try entity ID (i.e. raw value)
if not label and not _.pageTitle then
if not ID then
label = _.entityID
elseif mw.wikibase.getEntity(ID) then
label = ID
if ID:sub(1,1) == "P" then
prefix = "Property:"
end
end
prefix = "d:" .. prefix
title = label
end
-- add optional link
if _.curState.linked and title then
label = buildWikilink(prefix .. title, label)  -- label is never nil if title is not nil
end
if not label then
label = ""
elseif _.editable then
-- if desired, add a clickable icon that may be used to edit the returned value on Wikidata
label = label .. _:getEditIcon()
end
return label
end
function p.title(frame)
loadSubmodules(frame)
return p._title(copyTable(frame.args))
end
function p._title(args, _)
_ = _ or Config.new()
_.pageTitle = true
-- loadSubmodules() will already be called by _label()
return p._label(args, _)
end


-- main function that is supposed to be used by wrapper templates
-- process flags and commands
function p.main(frame)
repeat
local f, args, i, v
lastArg = nextArg(args)
until not cfg:processFlagOrCommand(lastArg)
loadSubmodules(frame)
 
-- get the entity ID from either the positional argument, the eid argument or the page argument
-- get the parent frame to take the arguments that were passed to the wrapper template
cfg.entityID, cfg.propertyID = getEntityId(lastArg, args[p.args.eid], args[p.args.page])
frame = frame:getParent() or frame
 
if cfg.entityID == "" then
if not frame.args[1] then
return ""  -- we cannot continue without a valid entity ID
error(i18n["errors"]["no-function-specified"])
end
end
 
cfg.entity = mw.wikibase.getEntity(cfg.entityID)
f = mw.text.trim(frame.args[1])
 
if not cfg.propertyID then
if f == "main" then
cfg.propertyID = nextArg(args)
error(i18n["errors"]["main-called-twice"])
end
end
 
cfg.propertyID = replaceAlias(cfg.propertyID)
assert(p["_"..f], applyStringParams(i18n['errors']['no-such-function'], f))
 
if not cfg.entity or not cfg.propertyID then
-- copy arguments from immutable to mutable table
return ""  -- we cannot continue without an entity or a property ID
args = copyTable(frame.args)
end
 
-- remove the function name from the list
cfg.propertyID = cfg.propertyID:upper()
table.remove(args, 1)
 
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)
 
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)
 
return p["_"..f](args)
return p["_"..f](args)
end
end


return p
return p