Modul:Wd/peskovnik: Razlika med redakcijama

Izbrisana vsebina Dodana vsebina
mBrez povzetka urejanja
mBrez povzetka urejanja
Vrstica 1:
-- Original module located at [[:en:Module:Wd]], [[:en:Module:Wd/i18n]] and [[:en:Module:Wd/i18naliasesP]].
 
local p = {}
Vrstica 5:
local i18n
 
local function loadI18nloadSubmodules(aliasesP, frame)
local title
 
if frame then
-- current module invoked by page/template, get its title from frame
Vrstica 15:
title = arg
end
 
i18n = i18n or require(title .. "/i18n")
if not i18n then
i18n p.aliasesP = requirep.aliasesP or mw.loadData(title .. "/i18n").init(aliasesP")
end
end
 
Vrstica 31 ⟶ 30:
 
p.generalCommands = {
label = "label",
title = "title",
descriptionalias = "descriptionalias",
alias aliases = "aliasaliases",
aliasesbadge = "aliasesbadge",
badge badges = "badgebadges",
badges = "badges"
}
 
Vrstica 62 ⟶ 60:
 
p.args = {
eid = "eid",
page = "page",
date = "date"
}
 
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"
}
 
Vrstica 118 ⟶ 84:
qualifier = "%q[%s][%r]",
reference = "%r",
propertyWithQualifier = "%p[ <span style=\"font-size:85\\%\">(%q)</span>][%s][%r]",
alias = "%a[%s]",
badge = "%b[%s]"
Vrstica 149 ⟶ 115:
 
local Config = {}
Config.__index = Config
 
-- allows for recursive calls
function Config:.new()
local cfg = {}
setmetatable(cfg, selfConfig)
self.__index = self
 
cfg.separators = {
-- single value objects wrapped in arrays so that we can pass by reference
Vrstica 164 ⟶ 130:
["punc"] = {copyTable(defaultSeparators["punc"])}
}
 
cfg.entity = nil
cfg.entityID = nil
Vrstica 171 ⟶ 137:
cfg.qualifierIDs = {}
cfg.qualifierIDsAndValues = {}
 
cfg.bestRank = true
cfg.ranks = {true, true, false} -- preferred = true, normal = true, deprecated = false
Vrstica 177 ⟶ 143:
cfg.flagBest = false
cfg.flagRank = false
 
cfg.periods = {true, true, true} -- future = true, current = true, former = true
cfg.flagPeriod = false
cfg.atDate = {parseDate(os.date('!%Y-%m-%d'))} -- today as {year, month, day}
 
cfg.mdyDate = false
cfg.singleClaim = false
Vrstica 187 ⟶ 152:
cfg.editable = false
cfg.editAtEnd = false
 
cfg.inSitelinks = false
 
cfg.langCode = mw.language.getContentLanguage().code
cfg.langName = mw.language.fetchLanguageName(cfg.langCode, cfg.langCode)
cfg.langObj = mw.language.new(cfg.langCode)
 
-- somewhat reliable way of determining global site ID in the absence of a library function, targeting the Wikipedia project (i.e. appending "wiki")
cfg.siteID = mw.wikibase.getGlobalSiteId()
cfg.siteID = (function() for i,v in pairs(mw.site.interwikiMap("local")) do if v.isCurrentWiki and i~="w" then return mw.ustring.gsub(i,"-","_").."wiki" end end end)()
 
cfg.states = {}
cfg.states.qualifiersCount = 0
cfg.curState = nil
 
cfg.prefetchedRefs = nil
 
return cfg
end
 
local State = {}
State.__index = State
 
function State:.new(cfg, type)
local stt = {}
setmetatable(stt, selfState)
self.__index = self
 
stt.conf = cfg
stt.type = type
 
stt.results = {}
 
stt.parsedFormat = {}
stt.separator = {}
stt.movSeparator = {}
stt.puncMark = {}
 
stt.linked = false
stt.rawValue = false
Vrstica 228 ⟶ 193:
stt.unitOnly = false
stt.singleValue = false
 
return stt
end
 
local function replaceAlias(id)
if p.aliasesP[id] then
id = p.aliasesP[id]
end
 
return id
end
 
local function errorText(code, param)
local text = i18n["errors"][code]
if param then text = mw.ustring.gsub(text, "$1", param) end
Vrstica 246 ⟶ 211:
end
 
local function throwError(errorMessage, param)
error(errorText(errorMessage, param))
end
 
local function replaceDecimalMark(num)
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
end
 
local function padZeros(num, numDigits)
local numZeros
local negative = false
 
if num < 0 then
negative = true
num = num * -1
end
 
num = tostring(num)
numZeros = numDigits - num:len()
 
for _i = 1, numZeros do
num = "0"..num
end
 
if negative then
num = "-"..num
end
 
return num
end
 
local function replaceSpecialChar(chr)
if chr == '_' then
-- replace underscores with spaces
Vrstica 286 ⟶ 251:
end
 
local function replaceSpecialChars(str)
local chr
local esc = false
local strOut = ""
 
for i = 1, #str do
chr = str:sub(i,i)
 
if not esc then
if chr == '\\' then
Vrstica 305 ⟶ 270:
end
end
 
return strOut
end
 
local function buildWikilink(target, label)
if not label or target == label then
return "[[" .. target .. "]]"
Vrstica 323 ⟶ 288:
return nil
end
 
local tOut = {}
 
for i, v in pairs(tIn) do
tOut[i] = v
end
 
return tOut
end
Vrstica 335 ⟶ 300:
-- used to merge output arrays together;
-- note that it currently mutates the first input array
local function mergeArrays(a1, a2)
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
end
 
return a1
end
 
local function split(str, del)
local out = {}
local i, j = str:find(del)
 
if i and j then
out[1] = str:sub(1, i - 1)
Vrstica 353 ⟶ 318:
out[1] = str
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
end
Vrstica 373 ⟶ 338:
function parseDate(dateStr, precision)
precision = precision or "d"
 
local i, j, index, ptr
local parts = {nil, nil, nil}
 
if dateStr == nil then
return parts[1], parts[2], parts[3] -- year, month, day
end
 
-- 'T' for snak values, '/' for outputs with '/Julian' attached
i, j = dateStr:find("[T/]")
 
if i then
dateStr = dateStr:sub(1, i-1)
end
 
local from = 1
 
if dateStr:sub(1,1) == "-" then
-- this is a negative number, look further ahead
from = 2
end
 
index = 1
ptr = 1
 
i, j = dateStr:find("-", from)
 
if i then
-- year
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
parts[index] = tonumber("0") -- for some reason, 'parts[index] = 0' may actually store '-0', so parse from string instead
end
 
if precision == "y" then
-- we're done
return parts[1], parts[2], parts[3] -- year, month, day
end
 
index = index + 1
ptr = i + 1
 
i, j = dateStr:find("-", ptr)
 
if i then
-- month
parts[index] = tonumber(dateStr:sub(ptr, i-1), 10)
 
if precision == "m" then
-- we're done
return parts[1], parts[2], parts[3] -- year, month, day
end
 
index = index + 1
ptr = i + 1
end
end
 
if dateStr:sub(ptr) ~= "" then
-- day if we have month, month if we have year, or year
parts[index] = tonumber(dateStr:sub(ptr), 10)
end
 
return parts[1], parts[2], parts[3] -- year, month, day
end
 
local function datePrecedesDate(aY, aM, aD, bY, bM, bD)
if aY == nil or bY == nil then
return nil
Vrstica 448 ⟶ 413:
bM = bM or 1
bD = bD or 1
 
if aY < bY then
return true
end
 
if aY > bY then
return false
end
 
if aM < bM then
return true
end
 
if aM > bM then
return false
end
 
if aD < bD then
return true
end
 
return false
end
 
local function getHookName(param, index)
if hookNames[param] then
return hookNames[param][index]
Vrstica 482 ⟶ 447:
end
 
local function alwaysTrue()
return true
end
Vrstica 531 ⟶ 496:
-- ]
--
local function parseFormat(str)
local chr, esc, param, root, cur, prev, new
local params = {}
 
local function newObject(array)
local obj = {} -- new object
obj.str = ""
 
array[#array + 1] = obj -- array{object}
obj.parent = array
 
return obj
end
 
local function endParam()
if param > 0 then
Vrstica 558 ⟶ 523:
end
end
 
root = {} -- array
root.req = {}
cur = newObject(root)
prev = nil
 
esc = false
param = 0
 
for i = 1, #str do
chr = str:sub(i,i)
 
if not esc then
if chr == '\\' then
Vrstica 607 ⟶ 572:
end
end
 
cur.str = cur.str .. replaceSpecialChar(chr)
end
Vrstica 614 ⟶ 579:
esc = false
end
 
prev = nil
end
 
endParam()
 
-- make sure that at least one required parameter has been defined
if not next(root.req) then
throwError("missing-required-parameter")
end
 
-- make sure that the separator parameter "%s" is not amongst the required parameters
if root.req[parameters.separator] then
throwError("extra-required-parameter", parameters.separator)
end
 
return root, params
end
 
local function sortOnRank(claims)
local rankPos
local ranks = {{}, {}, {}, {}} -- preferred, normal, deprecated, (default)
local sorted = {}
 
for _i, v in ipairs(claims) do
rankPos = rankTable[v.rank] or 4
ranks[rankPos][#ranks[rankPos] + 1] = v
end
 
sorted = ranks[1]
sorted = mergeArrays(sorted, ranks[2])
sorted = mergeArrays(sorted, ranks[3])
 
return sorted
end
Vrstica 655 ⟶ 620:
local title = nil
local prefix= ""
local lang
 
if not id then
id = mw.wikibase.getEntityIdForCurrentPage()
 
if not id then
return ""
end
end
 
id = id:upper() -- just to be sure
 
if raw then
-- check if given id actually exists
if mw.wikibase.isValidEntityId(id) and mw.wikibase.entityExistsgetEntity(id) then
label = id
 
if id:sub(1,1) == "P" then
prefix = "Property:"
end
end
 
prefix = "d:" .. prefix
 
title = label -- may be nil
else
-- try short name first if requested
if short then
label = p._property({p.aliasesP.shortName, [p.args.eid] = id}) -- get short name
 
if label == "" then
label = nil
end
end
 
-- get label
if not label then
label, lang = mw.wikibase.getLabelByLanggetLabelWithLang(id, self.langCode)
-- don't allow language fallback
if lang ~= self.langCode then
label = nil
end
end
end
 
if not label then
label = ""
Vrstica 701 ⟶ 672:
if not title then
if id:sub(1,1) == "Q" then
title = mw.wikibase.getSitelinksitelink(id)
elseif id:sub(1,1) == "P" then
-- properties have no sitelink, link to Wikidata instead
Vrstica 708 ⟶ 679:
end
end
 
if title then
label = buildWikilink(prefix .. title, label)
end
end
 
return label
end
Vrstica 720 ⟶ 691:
local value = ""
local prefix = ""
local front = "&nbsp; "
local back = ""
 
if self.entityID:sub(1,1) == "P" then
prefix = "Property:"
end
 
if self.editAtEnd then
front = '<span style="float:'
 
if self.langObj:isRTL() then
front = front .. 'left'
Vrstica 735 ⟶ 706:
front = front .. 'right'
end
 
front = front .. '">'
back = '</span>'
end
 
value = "[[File:OOjsBlue UI icon edit-ltr-progressivepencil.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
Vrstica 747 ⟶ 718:
value = value .. "#sitelinks-wikipedia"
end
 
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
 
return front .. value .. back
end
Vrstica 758 ⟶ 729:
local outString = ""
local j, skip
 
for i = 1, #valuesArray do
-- check if this is a reference
Vrstica 764 ⟶ 735:
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
Vrstica 773 ⟶ 744:
j = j - 1
end
 
if not skip then
-- add <ref> tag with the reference's hash as its name (to deduplicate references)
Vrstica 782 ⟶ 753:
end
end
 
return outString
end
Vrstica 789 ⟶ 760:
local space = " "
local label = ""
local itemID
 
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
Vrstica 806 ⟶ 776:
else
label = self:getLabel(itemID, raw, link, short)
 
if label ~= "" then
return space .. label
Vrstica 812 ⟶ 782:
end
end
 
return ""
end
 
function StateConfig:getValue(snak, raw, link, short, anyLang, unitOnly, noSpecial)
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
Vrstica 846 ⟶ 812:
return buildWikilink("c:" .. datavalue, datavalue)
elseif subtype == 'math' and not raw then
return mw.getCurrentFrame():extensionTag("math", datavalue)
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({p.aliasesP.formatterURL, [p.args.eid] = snak.property}) -- get formatter URL
 
if url ~= "" then
url = mw.ustring.gsub(url, "$1", datavalue)
Vrstica 866 ⟶ 826:
end
elseif datatype == 'monolingualtext' then
if anyLang or datavalue['language'] == self.langCode then
return datavalue['text'], datavalue['language']
elseif datavalue['language'] == self.langCode then
return datavalue['text']
else
Vrstica 874 ⟶ 836:
local value = ""
local unit
 
if not unitOnly then
-- get value and strip + signs from front
value = mw.ustring.gsub(datavalue['amount'], "^\+(.+)$", "%1")
 
if raw then
return value
end
 
-- replace decimal mark based on locale
value = replaceDecimalMark(value)
 
-- add delimiters for readability
value = i18n.addDelimiters(value)
end
 
unit = self:convertUnit(datavalue['unit'], raw, link, short, unitOnly)
 
if unit then
value = value .. unit
end
 
return value
elseif datatype == 'time' then
Vrstica 906 ⟶ 868:
local calendar = ""
local precision = datavalue['precision']
 
if precision == 11 then
p = "d"
Vrstica 915 ⟶ 877:
yFactor = 10^(9-precision)
end
 
y, m, d = parseDate(datavalue['time'], p)
 
if y < 0 then
sign = -1
y = y * sign
end
 
-- 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
Vrstica 941 ⟶ 903:
suffix = i18n['datetime']['suffixes']['century']
end
 
suffix = i18n.getOrdinalSuffix(yRound) .. suffix
else
Vrstica 952 ⟶ 914:
-- round decades down (e.g. 2010s)
yRound = math.floor(yDiv) * yFactor
 
if not raw then
prefix = i18n['datetime']['prefixes']['decade-period']
Vrstica 958 ⟶ 920:
end
end
 
if raw and sign < 0 then
-- if BCE then compensate for "counting backwards"
Vrstica 966 ⟶ 928:
else
local yReFactor, yReDiv, yReRound
 
-- round to nearest for tens of thousands of years or more
yRound = math.floor(yDiv + 0.5)
 
if yRound == 0 then
if precision <= 2 and y ~= 0 then
Vrstica 975 ⟶ 937:
yReDiv = y / yReFactor
yReRound = math.floor(yReDiv + 0.5)
 
if yReDiv == yReRound then
-- change precision to millions of years only if we have a whole number of them
Vrstica 983 ⟶ 945:
end
end
 
if yRound == 0 then
-- otherwise, take the unrounded (original) number of years
Vrstica 992 ⟶ 954:
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
Vrstica 1.009 ⟶ 971:
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
Vrstica 1.018 ⟶ 980:
end
end
 
if not raw then
if precision == 3 then
Vrstica 1.040 ⟶ 1.002:
mayAddCalendar = true
end
 
if mayAddCalendar then
calendarID = parseWikidataURL(datavalue['calendarmodel'])
 
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
if not raw then
Vrstica 1.056 ⟶ 1.018:
end
end
 
if not raw then
local ce = nil
 
if sign < 0 then
ce = i18n['datetime']['BCE']
Vrstica 1.065 ⟶ 1.027:
ce = i18n['datetime']['CE']
end
 
if ce then
if link then
Vrstica 1.072 ⟶ 1.034:
suffix = suffix .. " " .. ce
end
 
value = tostring(yRound)
 
if m then
dateStr = self.langObj:formatDate("F", "1-"..m.."-1")
 
if d then
if self.mdyDate then
dateStr = dateStr .. " " .. d .. ","
else
dateStr = d .. ". " .. dateStr
end
end
 
value = dateStr .. " " .. value
end
 
value = prefix .. value .. suffix .. calendar
else
value = padZeros(yRound * sign, 4)
 
if m then
value = value .. "-" .. padZeros(m, 2)
 
if d then
value = value .. "-" .. padZeros(d, 2)
end
end
 
value = value .. calendar
end
 
return value
elseif datatype == 'globecoordinate' then
-- logic from https://github.com/DataValues/Geo (v4.0.1)
 
local precision, unitsPerDegree, numDigits, strFormat, value, globe
local latitude, latConv, latValue, latLink
Vrstica 1.113 ⟶ 1.075:
local latDirection, latDirectionN, latDirectionS, latDirectionEN
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
local degSymbol, minSymbol, secSymbol, separator
 
local latDegrees = nil
local latMinutes = nil
Vrstica 1.121 ⟶ 1.082:
local lonMinutes = nil
local lonSeconds = nil
 
local latDegSym = ""
local latMinSym = ""
Vrstica 1.128 ⟶ 1.089:
local lonMinSym = ""
local lonSecSym = ""
 
local latDirectionEN_N = "N"
local latDirectionEN_S = "S"
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
 
if not raw then
latDirectionN = i18n['coord']['latitude-north']
Vrstica 1.139 ⟶ 1.100:
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionW = i18n['coord']['longitude-west']
 
degSymbol = i18n['coord']['degrees']
minSymbol = i18n['coord']['minutes']
Vrstica 1.149 ⟶ 1.110:
lonDirectionE = lonDirectionEN_E
lonDirectionW = lonDirectionEN_W
 
degSymbol = "/"
minSymbol = "/"
Vrstica 1.155 ⟶ 1.116:
separator = "/"
end
 
latitude = datavalue['latitude']
longitude = datavalue['longitude']
 
if latitude < 0 then
latDirection = latDirectionS
Vrstica 1.167 ⟶ 1.128:
latDirectionEN = latDirectionEN_N
end
 
if longitude < 0 then
lonDirection = lonDirectionW
Vrstica 1.176 ⟶ 1.137:
lonDirectionEN = lonDirectionEN_E
end
 
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
longitude = math.floor(longitude / precision + 0.5) * precision
 
if precision >= 1 - (1 / 60) and precision < 1 then
precision = 1
Vrstica 1.192 ⟶ 1.153:
precision = 1 / 60
end
 
if precision >= 1 then
unitsPerDegree = 1
Vrstica 1.200 ⟶ 1.161:
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
end
 
strFormat = "%." .. numDigits .. "f"
 
if precision >= 1 then
latDegrees = strFormat:format(latitude)
lonDegrees = strFormat:format(longitude)
 
if not raw then
latDegSym = replaceDecimalMark(latDegrees) .. degSymbol
Vrstica 1.223 ⟶ 1.184:
latConv = math.floor(latitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
lonConv = math.floor(longitude * unitsPerDegree * 10^numDigits + 0.5) / 10^numDigits
 
if precision >= (1 / 60) then
latMinutes = latConv
Vrstica 1.230 ⟶ 1.191:
latSeconds = latConv
lonSeconds = lonConv
 
latMinutes = math.floor(latSeconds / 60)
lonMinutes = math.floor(lonSeconds / 60)
 
latSeconds = strFormat:format(latSeconds - (latMinutes * 60))
lonSeconds = strFormat:format(lonSeconds - (lonMinutes * 60))
 
if not raw then
latSecSym = replaceDecimalMark(latSeconds) .. secSymbol
Vrstica 1.245 ⟶ 1.206:
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
Vrstica 1.271 ⟶ 1.232:
end
end
 
latValue = latDegSym .. latMinSym .. latSecSym .. latDirection
lonValue = lonDegSym .. lonMinSym .. lonSecSym .. lonDirection
 
value = latValue .. separator .. lonValue
 
if link then
globe = parseWikidataURL(datavalue['globe'])
 
if globe then
globe = mw.wikibase.getLabelByLanggetEntity(globe, ):getLabel("en"):lower()
else
globe = "earth"
end
 
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
 
return value
elseif datatype == 'wikibase-entityid' then
local label
local itemID = datavalue['numeric-id']
 
if subtype == 'wikibase-item' then
itemID = "Q" .. itemID
Vrstica 1.304 ⟶ 1.265:
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
Vrstica 1.334 ⟶ 1.295:
function Config:getSingleRawQualifier(claim, qualifierID)
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[qualifierID] end
 
if qualifiers and qualifiers[1] then
return self:getValue(qualifiers[1], true) -- raw = true
Vrstica 1.346 ⟶ 1.307:
function Config:snakEqualsValue(snak, value)
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
 
return snakValue == value
end
Vrstica 1.354 ⟶ 1.315:
function Config:setRank(rank)
local rankPos
 
if rank == p.flags.best then
self.bestRank = true
Vrstica 1.360 ⟶ 1.321:
return
end
 
if rank:sub(1,9) == p.flags.preferred then
rankPos = 1
Vrstica 1.370 ⟶ 1.331:
return
end
 
-- one of the rank flags was given, check if another one was given before
if not self.flagRank then
Vrstica 1.377 ⟶ 1.338:
self.flagRank = true -- mark that a rank flag was given
end
 
if rank:sub(-1) == "+" then
for i = rankPos, 1, -1 do
Vrstica 1.393 ⟶ 1.354:
function Config:setPeriod(period)
local periodPos
 
if period == p.flags.future then
periodPos = 1
Vrstica 1.403 ⟶ 1.364:
return
end
 
-- one of the period flags was given, check if another one was given before
if not self.flagPeriod then
Vrstica 1.409 ⟶ 1.370:
self.flagPeriod = true -- mark that a period flag was given
end
 
self.periods[periodPos] = true
end
Vrstica 1.415 ⟶ 1.376:
function Config:qualifierMatches(claim, id, value)
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[id] end
if qualifiers then
for _i, v in pairs(qualifiers) do
if self:snakEqualsValue(v, value) then
return true
Vrstica 1.427 ⟶ 1.388:
return true
end
 
return false
end
Vrstica 1.448 ⟶ 1.409:
local endTimeM = nil
local endTimeD = nil
 
if self.periods[1] and self.periods[2] and self.periods[3] then
-- any time
return true
end
 
local now = os.date('!*t')
startTime = self:getSingleRawQualifier(claim, aliasesP.startTime)
startTime = self:getSingleRawQualifier(claim, p.aliasesP.startTime)
if startTime and startTime ~= "" and startTime ~= " " then
startTimeY, startTimeM, startTimeD = parseDate(startTime)
end
 
endTime = self:getSingleRawQualifier(claim, p.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
Vrstica 1.470 ⟶ 1.439:
endTimeD = nil
end
 
if self.periods[1] then
-- future
if startTimeY and datePrecedesDate(self.atDatenow[1'year'], self.atDatenow[2'month'], self.atDatenow[3'day'], startTimeY, startTimeM, startTimeD) then
return true
end
end
 
if self.periods[2] then
-- current
if (startTimeY == nil or not datePrecedesDate(self.atDatenow[1'year'], self.atDatenow[2'month'], self.atDatenow[3'day'], startTimeY, startTimeM, startTimeD)) and
(endTimeY == nil or datePrecedesDate(self.atDatenow[1'year'], self.atDatenow[2'month'], self.atDatenow[3'day'], endTimeY, endTimeM, endTimeD)) then
return true
end
end
 
if self.periods[3] then
-- former
if endTimeY and not datePrecedesDate(self.atDatenow[1'year'], self.atDatenow[2'month'], self.atDatenow[3'day'], endTimeY, endTimeM, endTimeD) then
return true
end
end
 
return false
end
Vrstica 1.499 ⟶ 1.468:
if not flag then
return false
else
flag = mw.text.trim(flag)
end
 
if flag == p.flags.linked then
self.curState.linked = true
Vrstica 1.506 ⟶ 1.477:
elseif flag == p.flags.raw then
self.curState.rawValue = true
 
if self.curState == self.states[parameters.reference] then
-- raw reference values end with periods and require a separator (other than none)
self.separators["sep%r"][1] = {" "}
end
 
return true
elseif flag == p.flags.short then
Vrstica 1.554 ⟶ 1.525:
function Config:processFlagOrCommand(flag)
local param = ""
 
if not flag then
return false
else
flag = mw.text.trim(flag)
end
 
if flag == p.claimCommands.property or flag == p.claimCommands.properties then
param = parameters.property
Vrstica 1.570 ⟶ 1.543:
return self:processFlag(flag)
end
 
if self.states[param] then
return false
end
 
-- create a new state for each command
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:sub(-1) ~= 's' then
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
Vrstica 1.595 ⟶ 1.568:
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}
Vrstica 1.631 ⟶ 1.604:
function State:claimMatches(claim)
local matches, rankPos
 
-- first of all, reset any cached values used for the previous claim
self:resetCaches()
 
-- if a property value was given, check if it matches the claim's property value
if self.conf.propertyValue then
Vrstica 1.641 ⟶ 1.614:
matches = true
end
 
-- 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
matches = (matches and self.conf:qualifierMatches(claim, i, v))
end
 
-- check if the claim's rank and time period match
rankPos = rankTable[claim.rank] or 4
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 self.conf.sourcedOnly then
matches = (matches and self:isSourced(claim)) -- prefetches and caches references
end
 
return matches, rankPos
end
Vrstica 1.664 ⟶ 1.637:
local sep = nil -- value object
local out = {} -- array with value objects
 
local function walk(formatTable, result)
local valuesArray = {} -- array with value objects
 
for i, v in pairs(formatTable.req) do
if not result[i] or not result[i][1] then
Vrstica 1.675 ⟶ 1.648:
end
end
 
for _i, v in ipairs(formatTable) do
if v.param then
valuesArray = mergeArrays(valuesArray, result[v.str])
Vrstica 1.682 ⟶ 1.655:
valuesArray[#valuesArray + 1] = {v.str}
end
 
if v.child then
valuesArray = mergeArrays(valuesArray, walk(v.child, result))
end
end
 
return valuesArray
end
 
-- iterate through the results from back to front, so that we know when to add separators
for i = #self.results, 1, -1 do
result = self.results[i]
 
-- if there is already some output, then add the separators
if #out > 0 then
Vrstica 1.703 ⟶ 1.676:
result[parameters.separator] = {self.puncMark[1]} -- optional punctuation mark
end
 
valuesArray = walk(self.parsedFormat, result)
 
if #valuesArray > 0 then
if sep then
valuesArray[#valuesArray + 1] = sep
end
 
out = mergeArrays(valuesArray, out)
end
end
 
-- reset state before next iteration
self.results = {}
 
return out
end
Vrstica 1.723 ⟶ 1.696:
-- level 1 hook
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
 
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Vrstica 1.735 ⟶ 1.708:
function State:getQualifiers(claim, param)
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if qualifiers then
Vrstica 1.748 ⟶ 1.721:
-- level 2 hook
function State:getQualifier(snak)
local value = {self.conf:getValue(snak, self.rawValue, self.linked, self.shortName, self.anyLanguage, self.unitOnly)} -- create one value object
 
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Vrstica 1.761 ⟶ 1.734:
local out = {} -- array with value objects
local sep = self.conf.separators["sep"..parameters.qualifier][1] -- value object
 
-- iterate through the output of the separate "qualifier(s)" commands
for i = 1, self.conf.states.qualifiersCount do
 
-- if a hook has not been called yet, call it now
if not result[parameters.qualifier..i] then
self:callHook(parameters.qualifier..i, hooks, claim, result)
end
 
-- if there is output for this particular "qualifier(s)" command, then add it
if result[parameters.qualifier..i] and result[parameters.qualifier..i][1] then
 
-- if there is already some output, then add the separator
if #out > 0 and sep then
out[#out + 1] = sep
end
 
out = mergeArrays(out, result[parameters.qualifier..i])
end
end
 
return out
end
Vrstica 1.791 ⟶ 1.764:
return self.conf.prefetchedRefs
end
 
if claim.references then
-- iterate through claim's reference statements to collect their values;
Vrstica 1.811 ⟶ 1.784:
local value = ""
local ref = {}
 
local version = 1 -- incrementincrease this each time the below logic is changed to avoid conflict errors
 
if statement.snaks then
-- don't include "imported from", which is added by a bot
if statement.snaks[p.aliasesP.importedFrom] then
statement.snaks[p.aliasesP.importedFrom] = nil
end
 
-- don't include "inferred from", which is added by a bot
if statement.snaks[p.aliasesP.inferredFrom] then
statement.snaks[p.aliasesP.inferredFrom] = nil
end
 
-- don't include "type of reference"
if statement.snaks[p.aliasesP.typeOfReference] then
statement.snaks[p.aliasesP.typeOfReference] = nil
end
 
-- don't include "image" to prevent littering
if statement.snaks[p.aliasesP.image] then
statement.snaks[p.aliasesP.image] = nil
end
 
-- don't include "language" if it is equal to the local one
if self:getReferenceDetail(statement.snaks, p.aliasesP.language) == self.conf.langName then
statement.snaks[p.aliasesP.language] = nil
end
 
-- retrieve all the parameters
for i in pairs(statement.snaks) do
label = ""
 
-- multiple authors may be given
if i == p.aliasesP.author then
params[i] = self:getReferenceDetails(statement.snaks, i, false, self.linked, true) -- link = true/false, anyLang = true
else
params[i] = {self:getReferenceDetail(statement.snaks, i, false, (self.linked or (i == p.aliasesP.statedIn)) and (statement.snaks[i][1].datatype ~= 'url'), true)} -- link = true/false, anyLang = true
end
 
if #params[i] == 0 then
params[i] = nil
Vrstica 1.857 ⟶ 1.830:
key = "external-id"
label = self.conf:getLabel(i)
 
if label ~= "" then
label = label .. " "
Vrstica 1.864 ⟶ 1.837:
key = i
end
 
-- add the parameter to each matching type of citation
for j in pairs(citeParams) do
Vrstica 1.874 ⟶ 1.847:
if i18n['cite'][j][key] ~= "" then
citeParams[j][i18n['cite'][j][key]] = label .. params[i][1]
 
-- if there are multiple parameter values (authors), add those too
for k=2, #params[i] do
Vrstica 1.887 ⟶ 1.860:
end
end
 
-- get title of general template for citing web references
citeWeb = split(mw.wikibase.getSitelinksitelink(aliasesQ.citeWeb) or "", ":")[2] -- split off namespace from front
 
-- get title of template that expands stated-in references into citations
citeQ = split(mw.wikibase.getSitelinksitelink(aliasesQ.citeQ) or "", ":")[2] -- split off namespace from front
 
-- (1) use the general template for citing web references if there is a match and if at least both "reference URL" and "title" are present
if citeWeb and not citeMismatch['web'] and citeParams['web'][i18n['cite']['web'][p.aliasesP.referenceURL]] and citeParams['web'][i18n['cite']['web'][p.aliasesP.title]] then
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'][p.aliasesP.statedIn]] then
-- we need the raw "stated in" Q-identifier for the this template
citeParams['q'][i18n['cite']['q'][p.aliasesP.statedIn]] = self:getReferenceDetail(statement.snaks, p.aliasesP.statedIn, true) -- raw = true
 
useCite = citeQ
useParams = citeParams['q']
end
 
if useCite and useParams then
-- if this module is being substituted then build a regular template call, otherwise expand the template
Vrstica 1.914 ⟶ 1.887:
value = value .. "|" .. i .. "=" .. v
end
 
value = "{{" .. useCite .. value .. "}}"
else
value = mw.getCurrentFrame():expandTemplate{title=useCite, args=useParams}
end
 
-- (3) else, do some default rendering of name-value pairs, but only if at least "stated in", "reference URL" or "title" is present
elseif params[p.aliasesP.statedIn] or params[p.aliasesP.referenceURL] or params[p.aliasesP.title] then
citeParams['default'] = {}
 
-- start by adding authors up front
if params[p.aliasesP.author] and #params[p.aliasesP.author] > 0 then
citeParams['default'][#citeParams['default'] + 1] = table.concat(params[p.aliasesP.author], " & ")
end
 
-- combine "reference URL" and "title" into one link if both are present
if params[p.aliasesP.referenceURL] and params[p.aliasesP.title] then
citeParams['default'][#citeParams['default'] + 1] = '[' .. params[p.aliasesP.referenceURL][1] .. ' "' .. params[p.aliasesP.title][1] .. '"]'
elseif params[p.aliasesP.referenceURL] then
citeParams['default'][#citeParams['default'] + 1] = params[p.aliasesP.referenceURL][1]
elseif params[p.aliasesP.title] then
citeParams['default'][#citeParams['default'] + 1] = '"' .. params[p.aliasesP.title][1] .. '"'
end
 
-- then add "stated in"
if params[p.aliasesP.statedIn] then
citeParams['default'][#citeParams['default'] + 1] = "''" .. params[p.aliasesP.statedIn][1] .. "''"
end
 
-- remove previously added parameters so that they won't be added a second time
params[p.aliasesP.author] = nil
params[p.aliasesP.referenceURL] = nil
params[p.aliasesP.title] = nil
params[p.aliasesP.statedIn] = nil
 
-- add the rest of the parameters
for i, v in pairs(params) do
i = self.conf:getLabel(i)
 
if i ~= "" then
citeParams['default'][#citeParams['default'] + 1] = i .. ": " .. v[1]
end
end
 
value = table.concat(citeParams['default'], "; ")
 
if value ~= "" then
value = value .. "."
end
end
 
if value ~= "" then
value = {value} -- create one value object
 
if not self.rawValue then
-- this should become a <ref> tag, so savesafe the reference's hash for later
value.refHash = "wikidata-" .. statement.hash .. "-v" .. (tonumber(i18n['cite']['version']) + version)
end
 
ref = {value} -- wrap the value object in an array
end
end
 
return ref
end
Vrstica 1.984 ⟶ 1.957:
local switchLang = anyLang
local value = nil
 
if not snaks[dType] then
return nil
end
 
-- if anyLang, first try the local language and otherwise any language
repeat
for _i, v in ipairs(snaks[dType]) do
value = self.conf:getValue(v, raw, link, false, anyLang and not switchLang, false, true) -- noSpecial = true
 
if value then
break
end
end
 
if value or not anyLang then
break
end
 
switchLang = not switchLang
until anyLang and switchLang
 
return value
end
Vrstica 2.012 ⟶ 1.985:
function State:getReferenceDetails(snaks, dType, raw, link, anyLang)
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
 
return values
end
Vrstica 2.029 ⟶ 2.002:
local value = object.value
local title = nil
 
if value and self.linked then
if self.conf.entityID:sub(1,1) == "Q" then
title = mw.wikibase.getSitelinksitelink(self.conf.entityID)
elseif self.conf.entityID:sub(1,1) == "P" then
title = "d:Property:" .. self.conf.entityID
end
 
if title then
value = buildWikilink(title, value)
end
end
 
value = {value} -- create one value object
 
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Vrstica 2.054 ⟶ 2.027:
function State:getBadge(value)
value = self.conf:getLabel(value, self.rawValue, self.linked, self.shortName)
 
if value == "" then
value = nil
end
 
value = {value} -- create one value object
 
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Vrstica 2.070 ⟶ 2.043:
function State:callHook(param, hooks, statement, result)
local valuesArray, refHash
 
-- call a parameter's hook if it has been defined and if it has not been called before
if not result[param] and hooks[param] then
valuesArray = self[hooks[param]](self, statement, param, result, hooks) -- array with value objects
 
-- add to the result
if #valuesArray > 0 then
Vrstica 2.084 ⟶ 2.057:
end
end
 
return false
end
Vrstica 2.091 ⟶ 2.064:
function State:iterate(statements, hooks, matchHook)
matchHook = matchHook or alwaysTrue
 
local matches = false
local rankPos = nil
local result, gotRequired
 
for _i, v in ipairs(statements) do
-- rankPos will be nil for non-claim statements (e.g. qualifiers, references, etc.)
matches, rankPos = matchHook(self, v)
 
if matches then
result = {count = 0} -- collection of arrays with value objects
 
local function walk(formatTable)
local miss
 
for i2, v2 in pairs(formatTable.req) do
-- call a hook, adding its return value to the result
miss = self:callHook(i2, hooks, v, result)
 
if miss then
-- we miss a required value for this level, so return false
return false
end
 
if result.count == hooks.count then
-- we're done if all hooks have been called;
Vrstica 2.121 ⟶ 2.094:
end
end
 
for _i2, v2 in ipairs(formatTable) do
if result.count == hooks.count then
-- we're done if all hooks have been called;
Vrstica 2.128 ⟶ 2.101:
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
Vrstica 2.144 ⟶ 2.117:
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
Vrstica 2.155 ⟶ 2.128:
end
end
 
return self:out()
end
 
local function getEntityIdextractEntityFromInput(arg, eid, pageid, allowOmitPropPrefix)
if id:sub(1,1):upper() == "Q" then
local id = nil
return id:upper() -- entity ID of an item was given
local prop = nil
elseif id:sub(1,9):lower() == "property:" then
 
return replaceAlias(mw.text.trim(id:sub(10))):upper() -- entity ID of a property was given
if arg then
if elseif arg:sub(1,1)allowOmitPropPrefix =and id ~= ":" then
return replaceAlias(id):upper() -- could be an entity ID of a property without "Property:" prefix
page = arg
else
eid = nil
return nil
elseif arg:sub(1,1):upper() == "Q" or arg:sub(1,9):lower() == "property:" or allowOmitPropPrefix then
eid = arg
page = nil
else
prop = arg
end
end
 
if eid then
if eid:sub(1,9):lower() == "property:" then
id = replaceAlias(mw.text.trim(eid:sub(10)))
 
if id:sub(1,1):upper() ~= "P" then
id = ""
end
else
id = replaceAlias(eid)
end
elseif page then
if page:sub(1,1) == ":" then
page = mw.text.trim(page:sub(2))
end
 
id = mw.wikibase.getEntityIdForTitle(page) 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 nextArgextractEntityFromArgs(args, nextIndex, allowOmitPropPrefix)
local argid, = args[args.pointer]eidArg
 
if argargs[nextIndex] then
args.pointer[nextIndex] = mw.text.trim(args.pointer + 1[nextIndex])
return mw.text.trim(arg)
else
args[nextIndex] = ""
return nil
end
id = extractEntityFromInput(args[nextIndex], allowOmitPropPrefix)
eidArg = args[p.args.eid]
if id then
return id, nextIndex + 1
elseif eidArg then
return extractEntityFromInput(eidArg, true), nextIndex -- if no positional id was found but eid was given, use eid without a default
else
return mw.wikibase.getEntityIdForCurrentPage(), nextIndex -- by default, use item-entity connected to current page
end
end
 
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}
 
local nextIndex = 1
-- set the date if given;
-- must come BEFORE processing the flags
if args[p.args.date] then
cfg.atDate = {parseDate(args[p.args.date])}
cfg.periods = {false, true, false} -- change default time constraint to 'current'
end
 
-- process flags and commands
while _:processFlagOrCommand(args[nextIndex]) do
repeat
nextIndex = nextIndex + 1
lastArg = nextArg(args)
until not cfg:processFlagOrCommand(lastArg)
 
-- get the entity ID from either the positional argument, the eid argument or the page argument
cfg.entityID, cfg.propertyID = getEntityId(lastArg, args[p.args.eid], args[p.args.page])
 
if cfg.entityID == "" then
return "" -- we cannot continue without a valid entity ID
end
 
_.entityID, nextIndex = extractEntityFromArgs(args, nextIndex, false)
cfg.entity = mw.wikibase.getEntity(cfg.entityID)
 
-- if eid was explicitly set to empty, then this returns an empty string
if not cfg.propertyID then
if _.entityID == nil then
cfg.propertyID = nextArg(args)
return ""
end
 
_.entity = mw.wikibase.getEntity(_.entityID)
cfg.propertyID = replaceAlias(cfg.propertyID)
_.propertyID = replaceAlias(args[nextIndex]):upper()
 
nextIndex = nextIndex + 1
if not cfg.entity or not cfg.propertyID then
return "" -- we cannot continue without an entity or a property ID
if _.states.qualifiersCount > 0 then
end
 
cfg.propertyID = cfg.propertyID:upper()
 
if not cfg.entity.claims or not cfg.entity.claims[cfg.propertyID] then
return "" -- there is no use to continue without any claims
end
 
claims = cfg.entity.claims[cfg.propertyID]
 
if cfg.states.qualifiersCount > 0 then
-- do further processing if "qualifier(s)" command was given
 
if #args - args.pointernextIndex + 1 > cfg_.states.qualifiersCount then
-- claim ID or literal value has been given
 
cfg_.propertyValue = nextArgmw.text.trim(args[nextIndex])
nextIndex = nextIndex + 1
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(nextArgmw.text.trim(args)[nextIndex] or "")):upper()
nextIndex = nextIndex + 1
end
elseif cfg_.states[parameters.reference] then
-- do further processing if "reference(s)" command was given
 
if args[nextIndex] then
cfg.propertyValue = nextArg(args)
_.propertyValue = mw.text.trim(args[nextIndex])
end
-- not incrementing nextIndex because it is never used after this
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
Vrstica 2.337 ⟶ 2.269:
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 p.aliasesP[i] then
v = replaceSpecialChars(v)
 
-- check for special qualifier value 'somevalue'
if v ~= "" and mw.text.trim(v) == "" then
v = " " -- single space represents 'somevalue'
end
 
cfg_.qualifierIDsAndValues[replaceAlias(i):upper()] = v
end
end
 
if _.entity and _.entity.claims then claims = _.entity.claims[_.propertyID] end
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
if claims = sortOnRank(claims)then
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
 
claims = sortOnRank(claims)
-- then iterate through the claims to collect values
value = cfg:concatValues(cfg.states[parameters.property]:iterate(claims, hooks, State.claimMatches)) -- pass property state with level 1 hooks and matchHook
-- then iterate through the claims to collect values
 
value = _:concatValues(_.states[parameters.property]:iterate(claims, hooks, State.claimMatches)) -- pass property state with level 1 hooks and matchHook
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if cfg.editable and value ~= "" then
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
value = value .. cfg:getEditIcon()
if _.editable and value ~= "" then
value = value .. _:getEditIcon()
end
return value
else
return ""
end
 
return value
end
 
local function generalCommand(args, funcName)
local cfg_ = Config:.new()
cfg_.curState = State:.new(cfg_)
 
local lastArg
local value = nil
local nextIndex = 1
 
repeat
while _:processFlag(args[nextIndex]) do
lastArg = nextArg(args)
nextIndex = nextIndex + 1
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
 
_.entityID, nextIndex = extractEntityFromArgs(args, nextIndex, true)
-- if eid was explicitly set to empty, then this returns an empty string
if _.entityID == nil then
return ""
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.getSitelinksitelink(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
 
_.entity = mw.wikibase.getEntity(_.entityID)
if funcName == p.generalCommands.alias or funcName == p.generalCommands.aliases then
local aliases
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
Vrstica 2.453 ⟶ 2.384:
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
Vrstica 2.464 ⟶ 2.395:
hooks.count = hooks.count + 1
end
 
-- set the parsed format and the separators (and optional punctuation mark)
cfg_:setFormatAndSeparators(cfg_.curState, parsedFormat)
 
if _.entity and _.entity.aliases then aliases = _.entity.aliases[_.langCode] end
-- iterate to collect values
if aliases then
value = cfg_:concatValues(cfg_.curState:iterate(aliases, hooks))
end
elseif funcName == p.generalCommands.badge or funcName == p.generalCommands.badges then
_.inSitelinks = true
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
local 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
Vrstica 2.485 ⟶ 2.414:
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
Vrstica 2.496 ⟶ 2.425:
hooks.count = hooks.count + 1
end
 
-- set the parsed format and the separators (and optional punctuation mark)
cfg_:setFormatAndSeparators(cfg_.curState, parsedFormat)
 
if _.entity and _.entity.sitelinks and _.entity.sitelinks[_.siteID] then badges = _.entity.sitelinks[_.siteID].badges end
-- iterate to collect values
if badges then
value = cfg_:concatValues(cfg_.curState:iterate(badges, hooks))
end
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 _commandIndex, commandName in pairs(commandList) do
local function wikitextWrapper(frame)
local args = copyTableloadSubmodules(frame.args)
return commandFunc(copyTable(frame.args), commandName)
args.pointer = 1
loadI18n(aliasesP, frame)
return commandFunc(args, commandName)
end
p[commandName] = wikitextWrapper
 
local function luaWrapper(args)
loadSubmodules()
args = copyTable(args)
args.pointer = 1
loadI18n(aliasesP)
return commandFunc(args, commandName)
end
p["_" .. commandName] = luaWrapper
end
end
Vrstica 2.541 ⟶ 2.468:
-- main function that is supposed to be used by wrapper templates
function p.main(frame)
local f, args, i, v
 
loadI18nloadSubmodules(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)
end
 
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.pageId(frame)
local entity = mw.wikibase.getEntityObject()
if not entity then return nil else return entity.id end
end