Modiwl:Wd: Gwahaniaeth rhwng fersiynau

Cynnwys wedi'i ddileu Cynnwys wedi'i ychwanegu
Diweddaru o en
Tagiau: Gwrthdröwyd
B Wedi gwrthdroi golygiadau gan Llywelyn2000 (Sgwrs); wedi adfer y golygiad diweddaraf gan Dafyddt.
Tagiau: Gwrthdroi
Llinell 1:
-- Original module located at [[:en:Module:Wd]], [[:en:Module:Wd/i18n]] and [[:en:Module:Wd/i18naliasesP]].
 
local p = {}
Llinell 5:
local i18n
 
local function loadI18nloadSubmodules(aliasesP, frame)
local title
 
if frame then
-- current module invoked by page/template, get its title from frame
Llinell 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
 
Llinell 31 ⟶ 30:
 
p.generalCommands = {
label = "label",
title = "title",
descriptionalias = "descriptionalias",
alias aliases = "aliasaliases",
aliasesbadge = "aliasesbadge",
badge badges = "badgebadges",
badges = "badges"
}
 
Llinell 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"
}
 
Llinell 118 ⟶ 84:
qualifier = "%q[%s][%r]",
reference = "%r",
propertyWithQualifier = "%p[ <span style=\"font-size:85\\%smaller\">(%q)</span>][%s][%r]",
alias = "%a[%s]",
badge = "%b[%s]"
Llinell 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
Llinell 164 ⟶ 130:
["punc"] = {copyTable(defaultSeparators["punc"])}
}
 
cfg.entity = nil
cfg.entityID = nil
Llinell 171 ⟶ 137:
cfg.qualifierIDs = {}
cfg.qualifierIDsAndValues = {}
 
cfg.bestRank = true
cfg.ranks = {true, true, false} -- preferred = true, normal = true, deprecated = false
Llinell 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
Llinell 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 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
Llinell 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
Llinell 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
Llinell 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
Llinell 305 ⟶ 270:
end
end
 
return strOut
end
 
local function buildWikilink(target, label)
if not label or target == label then
return "[[" .. target .. "]]"
Llinell 323 ⟶ 288:
return nil
end
 
local tOut = {}
 
for i, v in pairs(tIn) do
tOut[i] = v
end
 
return tOut
end
Llinell 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)
Llinell 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
Llinell 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
Llinell 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]
Llinell 482 ⟶ 447:
end
 
local function alwaysTrue()
return true
end
Llinell 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
Llinell 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
Llinell 607 ⟶ 572:
end
end
 
cur.str = cur.str .. replaceSpecialChar(chr)
end
Llinell 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
Llinell 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 = ""
Llinell 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
Llinell 708 ⟶ 679:
end
end
 
if title then
label = buildWikilink(prefix .. title, label)
end
end
 
return label
end
Llinell 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'
Llinell 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
Llinell 747 ⟶ 718:
value = value .. "#sitelinks-wikipedia"
end
 
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
 
return front .. value .. back
end
Llinell 758 ⟶ 729:
local outString = ""
local j, skip
 
for i = 1, #valuesArray do
-- check if this is a reference
Llinell 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
Llinell 773 ⟶ 744:
j = j - 1
end
 
if not skip then
-- add <ref> tag with the reference's hash as its name (to deduplicate references)
outString = outString .. mw.getCurrentFrame():extensionTag("ref", valuesArray[i][1], {name = "wikidata-" .. valuesArray[i].refHash .. "-v" .. i18n['cite']['version']})
end
else
Llinell 782 ⟶ 753:
end
end
 
return outString
end
Llinell 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
Llinell 806 ⟶ 776:
else
label = self:getLabel(itemID, raw, link, short)
 
if label ~= "" then
return space .. label
Llinell 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
Llinell 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)
Llinell 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
Llinell 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
Llinell 906 ⟶ 868:
local calendar = ""
local precision = datavalue['precision']
 
if precision == 11 then
p = "d"
Llinell 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
Llinell 941 ⟶ 903:
suffix = i18n['datetime']['suffixes']['century']
end
 
suffix = i18n.getOrdinalSuffix(yRound) .. suffix
else
Llinell 952 ⟶ 914:
-- round decades down (e.g. 2010s)
yRound = math.floor(yDiv) * yFactor
 
if not raw then
prefix = i18n['datetime']['prefixes']['decade-period']
Llinell 958 ⟶ 920:
end
end
 
if raw and sign < 0 then
-- if BCE then compensate for "counting backwards"
Llinell 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
Llinell 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
Llinell 983 ⟶ 945:
end
end
 
if yRound == 0 then
-- otherwise, take the unrounded (original) number of years
Llinell 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
Llinell 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
Llinell 1,018 ⟶ 980:
end
end
 
if not raw then
if precision == 3 then
Llinell 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
Llinell 1,056 ⟶ 1,018:
end
end
 
if not raw then
local ce = nil
 
if sign < 0 then
ce = i18n['datetime']['BCE']
Llinell 1,065 ⟶ 1,027:
ce = i18n['datetime']['CE']
end
 
if ce then
if link then
Llinell 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
Llinell 1,085 ⟶ 1,047:
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 latValue, latitude, latConvlatDegrees, latValuelatMinutes, latLinklatSeconds
local lonValue, longitude, lonConvlonDegrees, lonValuelonMinutes, lonLinklonSeconds
local latDirection, latDirectionN, latDirectionS, latDirectionEN
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_S = "S"
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
 
if not raw then
latDirectionN = i18n['coord']['latitude-north']
Llinell 1,139 ⟶ 1,086:
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionW = i18n['coord']['longitude-west']
 
degSymbol = i18n['coord']['degrees']
minSymbol = i18n['coord']['minutes']
Llinell 1,149 ⟶ 1,096:
lonDirectionE = lonDirectionEN_E
lonDirectionW = lonDirectionEN_W
 
degSymbol = "/"
minSymbol = "/"
Llinell 1,155 ⟶ 1,102:
separator = "/"
end
 
latitude = datavalue['latitude']
longitude = datavalue['longitude']
 
if latitude < 0 then
latDirection = latDirectionS
Llinell 1,167 ⟶ 1,114:
latDirectionEN = latDirectionEN_N
end
 
if longitude < 0 then
lonDirection = lonDirectionW
Llinell 1,176 ⟶ 1,123:
lonDirectionEN = lonDirectionEN_E
end
 
precision = datavalue['precision'] or 1
 
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
 
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
end
 
strFormat = "%." .. numDigits .. "f"
 
-- use string.format() to strip decimal point followed by a zero (.0) for whole numbers
if precision >= 1 then
latDegreeslatSeconds = tonumber(strFormat:format(math.floor(latitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
lonDegreeslonSeconds = tonumber(strFormat:format(math.floor(longitude * 3600 * 10^numDigits + 0.5) / 10^numDigits))
 
latMinutes = math.floor(latSeconds / 60)
lonMinutes = math.floor(lonSeconds / 60)
latSeconds = latSeconds - (latMinutes * 60)
lonSeconds = lonSeconds - (lonMinutes * 60)
latDegrees = math.floor(latMinutes / 60)
lonDegrees = math.floor(lonMinutes / 60)
latMinutes = latMinutes - (latDegrees * 60)
lonMinutes = lonMinutes - (lonDegrees * 60)
latValue = latDegrees .. degSymbol
lonValue = lonDegrees .. degSymbol
if precision < 1 then
latValue = latValue .. latMinutes .. minSymbol
lonValue = lonValue .. lonMinutes .. minSymbol
end
if precision < (1 / 60) then
latSeconds = strFormat:format(latSeconds)
lonSeconds = strFormat:format(lonSeconds)
if not raw then
-- replace decimal marks based on locale
latDegSym = replaceDecimalMark(latDegrees) .. degSymbol
lonDegSymlatSeconds = replaceDecimalMark(lonDegreeslatSeconds) .. degSymbol
lonSeconds = replaceDecimalMark(lonSeconds)
else
latDegSym = latDegrees .. degSymbol
lonDegSym = lonDegrees .. degSymbol
end
else
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
lonMinutes = lonConv
else
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
lonSecSym = replaceDecimalMark(lonSeconds) .. secSymbol
else
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
latValue = latValue .. latSeconds .. secSymbol
lonValue = lonValue .. lonSeconds .. secSymbol
end
 
latValue = latDegSym .. latMinSym .. latSecSymlatValue .. latDirection
lonValue = lonDegSym .. lonMinSym .. lonSecSymlonValue .. 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
 
value = "[https://tools.wmflabs.org/geohack/geohack.php?language="..self.langCode.."&params="..latitude.."_"..latDirectionEN.."_"..longitude.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
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
Llinell 1,304 ⟶ 1,204:
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
Llinell 1,334 ⟶ 1,234:
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
Llinell 1,346 ⟶ 1,246:
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
Llinell 1,354 ⟶ 1,254:
function Config:setRank(rank)
local rankPos
 
if rank == p.flags.best then
self.bestRank = true
Llinell 1,360 ⟶ 1,260:
return
end
 
if rank:sub(1,9) == p.flags.preferred then
rankPos = 1
Llinell 1,370 ⟶ 1,270:
return
end
 
-- one of the rank flags was given, check if another one was given before
if not self.flagRank then
Llinell 1,377 ⟶ 1,277:
self.flagRank = true -- mark that a rank flag was given
end
 
if rank:sub(-1) == "+" then
for i = rankPos, 1, -1 do
Llinell 1,393 ⟶ 1,293:
function Config:setPeriod(period)
local periodPos
 
if period == p.flags.future then
periodPos = 1
Llinell 1,403 ⟶ 1,303:
return
end
 
-- one of the period flags was given, check if another one was given before
if not self.flagPeriod then
Llinell 1,409 ⟶ 1,309:
self.flagPeriod = true -- mark that a period flag was given
end
 
self.periods[periodPos] = true
end
Llinell 1,415 ⟶ 1,315:
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
Llinell 1,427 ⟶ 1,327:
return true
end
 
return false
end
Llinell 1,448 ⟶ 1,348:
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
Llinell 1,470 ⟶ 1,378:
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
Llinell 1,499 ⟶ 1,407:
if not flag then
return false
else
flag = mw.text.trim(flag)
end
 
if flag == p.flags.linked then
self.curState.linked = true
Llinell 1,506 ⟶ 1,416:
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
Llinell 1,554 ⟶ 1,464:
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
Llinell 1,570 ⟶ 1,482:
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
Llinell 1,595 ⟶ 1,507:
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}
Llinell 1,631 ⟶ 1,543:
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
Llinell 1,641 ⟶ 1,553:
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
Llinell 1,664 ⟶ 1,576:
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
Llinell 1,675 ⟶ 1,587:
end
end
 
for _i, v in ipairs(formatTable) do
if v.param then
valuesArray = mergeArrays(valuesArray, result[v.str])
Llinell 1,682 ⟶ 1,594:
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
Llinell 1,703 ⟶ 1,615:
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
Llinell 1,723 ⟶ 1,635:
-- 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
Llinell 1,735 ⟶ 1,647:
function State:getQualifiers(claim, param)
local qualifiers
 
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if qualifiers then
Llinell 1,748 ⟶ 1,660:
-- 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
Llinell 1,761 ⟶ 1,673:
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
Llinell 1,791 ⟶ 1,703:
return self.conf.prefetchedRefs
end
 
if claim.references then
-- iterate through claim's reference statements to collect their values;
Llinell 1,811 ⟶ 1,723:
local value = ""
local ref = {}
 
local version = 1 -- increment 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[aliasesP.inferredFrom] then
statement.snaks[aliasesP.inferredFrom] = nil
end
 
-- don't include "type of reference"
if statement.snaks[aliasesP.typeOfReference] then
statement.snaks[aliasesP.typeOfReference] = nil
end
 
-- don't include "image" to prevent littering
if statement.snaks[aliasesP.image] then
statement.snaks[aliasesP.image] = nil
end
 
-- 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
Llinell 1,857 ⟶ 1,752:
key = "external-id"
label = self.conf:getLabel(i)
 
if label ~= "" then
label = label .. " "
Llinell 1,864 ⟶ 1,759:
key = i
end
 
-- add the parameter to each matching type of citation
for j in pairs(citeParams) do
Llinell 1,874 ⟶ 1,769:
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
Llinell 1,887 ⟶ 1,782:
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
Llinell 1,914 ⟶ 1,809:
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
Llinell 1,984 ⟶ 1,879:
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
Llinell 2,012 ⟶ 1,907:
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
Llinell 2,029 ⟶ 1,924:
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
Llinell 2,054 ⟶ 1,949:
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
Llinell 2,070 ⟶ 1,965:
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
Llinell 2,084 ⟶ 1,979:
end
end
 
return false
end
Llinell 2,091 ⟶ 1,986:
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;
Llinell 2,121 ⟶ 2,016:
end
end
 
for _i2, v2 in ipairs(formatTable) do
if result.count == hooks.count then
-- we're done if all hooks have been called;
Llinell 2,128 ⟶ 2,023:
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
Llinell 2,144 ⟶ 2,039:
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
Llinell 2,155 ⟶ 2,050:
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
Llinell 2,337 ⟶ 2,191:
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
Llinell 2,453 ⟶ 2,306:
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
Llinell 2,464 ⟶ 2,317:
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
Llinell 2,485 ⟶ 2,336:
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
Llinell 2,496 ⟶ 2,347:
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
Llinell 2,541 ⟶ 2,390:
-- main function that is supposed to be used by wrapper templates
function p.main(frame)
local f, args, i, v
if not mw.wikibase then return nil end
 
loadSubmodules(frame)
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)
end