Modiwl:Wd: Gwahaniaeth rhwng fersiynau
Cynnwys wedi'i ddileu Cynnwys wedi'i ychwanegu
Dafyddt (sgwrs | cyfraniadau) Diweddaru o en (datrys dyddiadau geni/marw) |
Diweddaru o en Tagiau: Gwrthdröwyd |
||
Llinell 1:
-- Original module located at [[:en:Module:Wd
local p = {}
Llinell 5:
local i18n
local function
local title
if frame then
-- current module invoked by page/template, get its title from frame
Llinell 15:
title = arg
end
if not i18n then
end
end
Llinell 30 ⟶ 31:
p.generalCommands = {
label = "label",
title = "title",
badges = "badges"
}
Llinell 60 ⟶ 62:
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 84 ⟶ 118:
qualifier = "%q[%s][%r]",
reference = "%r",
propertyWithQualifier = "%p[ <span style=\"font-size:
alias = "%a[%s]",
badge = "%b[%s]"
Llinell 115 ⟶ 149:
local Config = {}
-- allows for recursive calls
function Config
local cfg = {}
setmetatable(cfg,
self.__index = self
cfg.separators = {
-- single value objects wrapped in arrays so that we can pass by reference
Llinell 130 ⟶ 164:
["punc"] = {copyTable(defaultSeparators["punc"])}
}
cfg.entity = nil
cfg.entityID = nil
Llinell 137 ⟶ 171:
cfg.qualifierIDs = {}
cfg.qualifierIDsAndValues = {}
cfg.bestRank = true
cfg.ranks = {true, true, false} -- preferred = true, normal = true, deprecated = false
Llinell 143 ⟶ 177:
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 152 ⟶ 187:
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)
cfg.siteID = mw.wikibase.getGlobalSiteId()
cfg.states = {}
cfg.states.qualifiersCount = 0
cfg.curState = nil
cfg.prefetchedRefs = nil
return cfg
end
local State = {}
function State
local stt = {}
setmetatable(stt,
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 193 ⟶ 228:
stt.unitOnly = false
stt.singleValue = false
return stt
end
local function replaceAlias(id)
if
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 211 ⟶ 246:
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
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 251 ⟶ 286:
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 270 ⟶ 305:
end
end
return strOut
end
local function buildWikilink(target, label)
if not label or target == label then
return "[[" .. target .. "]]"
Llinell 288 ⟶ 323:
return nil
end
local tOut = {}
for i, v in pairs(tIn) do
tOut[i] = v
end
return tOut
end
Llinell 300 ⟶ 335:
-- 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 318 ⟶ 353:
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 338 ⟶ 373:
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 413 ⟶ 448:
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 447 ⟶ 482:
end
local function alwaysTrue()
return true
end
Llinell 496 ⟶ 531:
-- ]
--
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 523 ⟶ 558:
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 572 ⟶ 607:
end
end
cur.str = cur.str .. replaceSpecialChar(chr)
end
Llinell 579 ⟶ 614:
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
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 620 ⟶ 655:
local title = nil
local prefix= ""
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.
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
if label == "" then
label = nil
end
end
-- get label
if not label then
label
end
end
if not label then
label = ""
Llinell 672 ⟶ 701:
if not title then
if id:sub(1,1) == "Q" then
title = mw.wikibase.
elseif id:sub(1,1) == "P" then
-- properties have no sitelink, link to Wikidata instead
Llinell 679 ⟶ 708:
end
end
if title then
label = buildWikilink(prefix .. title, label)
end
end
return label
end
Llinell 691 ⟶ 720:
local value = ""
local prefix = ""
local front = "
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 706 ⟶ 735:
front = front .. 'right'
end
front = front .. '">'
back = '</span>'
end
value = "[[File:
if self.propertyID then
value = value .. "#" .. self.propertyID
Llinell 718 ⟶ 747:
value = value .. "#sitelinks-wikipedia"
end
value = value .. "|" .. i18n['info']['edit-on-wikidata'] .. "]]"
return front .. value .. back
end
Llinell 729 ⟶ 758:
local outString = ""
local j, skip
for i = 1, #valuesArray do
-- check if this is a reference
Llinell 735 ⟶ 764:
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 744 ⟶ 773:
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 =
end
else
Llinell 753 ⟶ 782:
end
end
return outString
end
Llinell 760 ⟶ 789:
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 776 ⟶ 806:
else
label = self:getLabel(itemID, raw, link, short)
if label ~= "" then
return space .. label
Llinell 782 ⟶ 812:
end
end
return ""
end
function
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 812 ⟶ 846:
return buildWikilink("c:" .. datavalue, datavalue)
elseif subtype == 'math' and not raw then
local attribute = nil
if (type == parameters.property or (type == parameters.qualifier and self.propertyID == aliasesP.hasPart)) and snak.property == aliasesP.definingFormula then
attribute = {qid = self.entityID}
end
return mw.getCurrentFrame():extensionTag("math", datavalue, attribute)
elseif subtype == 'external-id' and link then
local url = p._property
if url ~= "" then
url = mw.ustring.gsub(url, "$1", datavalue)
Llinell 826 ⟶ 866:
end
elseif datatype == 'monolingualtext' then
if anyLang or datavalue['language'] == self.langCode then
return datavalue['text']
else
Llinell 836 ⟶ 874:
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 868 ⟶ 906:
local calendar = ""
local precision = datavalue['precision']
if precision == 11 then
p = "d"
Llinell 877 ⟶ 915:
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 903 ⟶ 941:
suffix = i18n['datetime']['suffixes']['century']
end
suffix = i18n.getOrdinalSuffix(yRound) .. suffix
else
Llinell 914 ⟶ 952:
-- round decades down (e.g. 2010s)
yRound = math.floor(yDiv) * yFactor
if not raw then
prefix = i18n['datetime']['prefixes']['decade-period']
Llinell 920 ⟶ 958:
end
end
if raw and sign < 0 then
-- if BCE then compensate for "counting backwards"
Llinell 928 ⟶ 966:
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 937 ⟶ 975:
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 945 ⟶ 983:
end
end
if yRound == 0 then
-- otherwise, take the unrounded (original) number of years
Llinell 954 ⟶ 992:
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 971 ⟶ 1,009:
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 980 ⟶ 1,018:
end
end
if not raw then
if precision == 3 then
Llinell 1,002 ⟶ 1,040:
mayAddCalendar = true
end
if mayAddCalendar then
calendarID = parseWikidataURL(datavalue['calendarmodel'])
if calendarID and calendarID == aliasesQ.prolepticJulianCalendar then
if not raw then
Llinell 1,018 ⟶ 1,056:
end
end
if not raw then
local ce = nil
if sign < 0 then
ce = i18n['datetime']['BCE']
Llinell 1,027 ⟶ 1,065:
ce = i18n['datetime']['CE']
end
if ce then
if link then
Llinell 1,034 ⟶ 1,072:
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,047 ⟶ 1,085:
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
local
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,086 ⟶ 1,139:
lonDirectionE = i18n['coord']['longitude-east']
lonDirectionW = i18n['coord']['longitude-west']
degSymbol = i18n['coord']['degrees']
minSymbol = i18n['coord']['minutes']
Llinell 1,096 ⟶ 1,149:
lonDirectionE = lonDirectionEN_E
lonDirectionW = lonDirectionEN_W
degSymbol = "/"
minSymbol = "/"
Llinell 1,102 ⟶ 1,155:
separator = "/"
end
latitude = datavalue['latitude']
longitude = datavalue['longitude']
if latitude < 0 then
latDirection = latDirectionS
Llinell 1,114 ⟶ 1,167:
latDirectionEN = latDirectionEN_N
end
if longitude < 0 then
lonDirection = lonDirectionW
Llinell 1,123 ⟶ 1,176:
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
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"
if precision >= 1 then
if not raw then
latDegSym = replaceDecimalMark(latDegrees) .. degSymbol
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
end
latValue =
lonValue =
value = latValue .. separator .. lonValue
if link then
globe = parseWikidataURL(datavalue['globe'])
if globe then
globe = mw.wikibase.
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.."¶ms="..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,204 ⟶ 1,304:
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,234 ⟶ 1,334:
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,246 ⟶ 1,346:
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,254 ⟶ 1,354:
function Config:setRank(rank)
local rankPos
if rank == p.flags.best then
self.bestRank = true
Llinell 1,260 ⟶ 1,360:
return
end
if rank:sub(1,9) == p.flags.preferred then
rankPos = 1
Llinell 1,270 ⟶ 1,370:
return
end
-- one of the rank flags was given, check if another one was given before
if not self.flagRank then
Llinell 1,277 ⟶ 1,377:
self.flagRank = true -- mark that a rank flag was given
end
if rank:sub(-1) == "+" then
for i = rankPos, 1, -1 do
Llinell 1,293 ⟶ 1,393:
function Config:setPeriod(period)
local periodPos
if period == p.flags.future then
periodPos = 1
Llinell 1,303 ⟶ 1,403:
return
end
-- one of the period flags was given, check if another one was given before
if not self.flagPeriod then
Llinell 1,309 ⟶ 1,409:
self.flagPeriod = true -- mark that a period flag was given
end
self.periods[periodPos] = true
end
Llinell 1,315 ⟶ 1,415:
function Config:qualifierMatches(claim, id, value)
local qualifiers
if claim.qualifiers then qualifiers = claim.qualifiers[id] end
if qualifiers then
for
if self:snakEqualsValue(v, value) then
return true
Llinell 1,327 ⟶ 1,427:
return true
end
return false
end
Llinell 1,348 ⟶ 1,448:
local endTimeM = nil
local endTimeD = nil
if self.periods[1] and self.periods[2] and self.periods[3] then
-- any time
return true
end
startTime = self:getSingleRawQualifier(claim, aliasesP.startTime)
if startTime and startTime ~= "" and startTime ~= " " then
startTimeY, startTimeM, startTimeD = parseDate(startTime)
end
endTime = self:getSingleRawQualifier(claim,
if endTime and endTime ~= "" and endTime ~= " " then
endTimeY, endTimeM, endTimeD = parseDate(endTime)
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,378 ⟶ 1,470:
endTimeD = nil
end
if self.periods[1] then
-- future
if startTimeY and datePrecedesDate(
return true
end
end
if self.periods[2] then
-- current
if (startTimeY == nil or not datePrecedesDate(
(endTimeY == nil or datePrecedesDate(
return true
end
end
if self.periods[3] then
-- former
if endTimeY and not datePrecedesDate(
return true
end
end
return false
end
Llinell 1,407 ⟶ 1,499:
if not flag then
return false
end
if flag == p.flags.linked then
self.curState.linked = true
Llinell 1,416 ⟶ 1,506:
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,464 ⟶ 1,554:
function Config:processFlagOrCommand(flag)
local param = ""
if not flag then
return false
end
if flag == p.claimCommands.property or flag == p.claimCommands.properties then
param = parameters.property
Llinell 1,482 ⟶ 1,570:
return self:processFlag(flag)
end
if self.states[param] then
return false
end
-- create a new state for each command
self.states[param] = State
-- use "%x" as the general parameter name
self.states[param].parsedFormat = parseFormat(parameters.general) -- will be overwritten for param=="%p"
-- set the separator
self.states[param].separator = self.separators["sep"..param] -- will be nil for param=="%p", which will be set separately
if flag == p.claimCommands.property or flag == p.claimCommands.qualifier or flag == p.claimCommands.reference then
self.states[param].singleValue = true
end
self.curState = self.states[param]
return true
end
Llinell 1,507 ⟶ 1,595:
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,543 ⟶ 1,631:
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,553 ⟶ 1,641:
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,576 ⟶ 1,664:
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,587 ⟶ 1,675:
end
end
for
if v.param then
valuesArray = mergeArrays(valuesArray, result[v.str])
Llinell 1,594 ⟶ 1,682:
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,615 ⟶ 1,703:
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,635 ⟶ 1,723:
-- level 1 hook
function State:getProperty(claim)
local value = {self
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Llinell 1,647 ⟶ 1,735:
function State:getQualifiers(claim, param)
local qualifiers
if claim.qualifiers then qualifiers = claim.qualifiers[self.conf.qualifierIDs[param]] end
if qualifiers then
Llinell 1,660 ⟶ 1,748:
-- level 2 hook
function State:getQualifier(snak)
local value = {self
if #value > 0 then
return {value} -- wrap the value object in an array and return it
Llinell 1,673 ⟶ 1,761:
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,703 ⟶ 1,791:
return self.conf.prefetchedRefs
end
if claim.references then
-- iterate through claim's reference statements to collect their values;
Llinell 1,723 ⟶ 1,811:
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[
statement.snaks[
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,
statement.snaks[
end
-- retrieve all the parameters
for i in pairs(statement.snaks) do
label = ""
-- multiple authors may be given
if i ==
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 ==
end
if #params[i] == 0 then
params[i] = nil
Llinell 1,752 ⟶ 1,857:
key = "external-id"
label = self.conf:getLabel(i)
if label ~= "" then
label = label .. " "
Llinell 1,759 ⟶ 1,864:
key = i
end
-- add the parameter to each matching type of citation
for j in pairs(citeParams) do
Llinell 1,769 ⟶ 1,874:
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,782 ⟶ 1,887:
end
end
-- get title of general template for citing web references
citeWeb = split(mw.wikibase.
-- get title of template that expands stated-in references into citations
citeQ = split(mw.wikibase.
-- (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'][
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'][
-- we need the raw "stated in" Q-identifier for the this template
citeParams['q'][i18n['cite']['q'][
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,809 ⟶ 1,914:
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[
citeParams['default'] = {}
-- start by adding authors up front
if params[
citeParams['default'][#citeParams['default'] + 1] = table.concat(params[
end
-- combine "reference URL" and "title" into one link if both are present
if params[
citeParams['default'][#citeParams['default'] + 1] = '[' .. params[
elseif params[
citeParams['default'][#citeParams['default'] + 1] = params[
elseif params[
citeParams['default'][#citeParams['default'] + 1] = '"' .. params[
end
-- then add "stated in"
if params[
citeParams['default'][#citeParams['default'] + 1] = "''" .. params[
end
-- remove previously added parameters so that they won't be added a second time
params[
params[
params[
params[
-- 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
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,879 ⟶ 1,984:
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
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 1,907 ⟶ 2,012:
function State:getReferenceDetails(snaks, dType, raw, link, anyLang)
local values = {}
if not snaks[dType] then
return {}
end
for
-- 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 1,924 ⟶ 2,029:
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.
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 1,949 ⟶ 2,054:
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 1,965 ⟶ 2,070:
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 1,979 ⟶ 2,084:
end
end
return false
end
Llinell 1,986 ⟶ 2,091:
function State:iterate(statements, hooks, matchHook)
matchHook = matchHook or alwaysTrue
local matches = false
local rankPos = nil
local result, gotRequired
for
-- 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,016 ⟶ 2,121:
end
end
for
if result.count == hooks.count then
-- we're done if all hooks have been called;
Llinell 2,023 ⟶ 2,128:
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,039 ⟶ 2,144:
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,050 ⟶ 2,155:
end
end
return self:out()
end
local function
local id = nil
local prop = nil
if arg then
page = arg
eid = nil
elseif arg:sub(1,1):upper() == "Q" or arg:sub(1,9):lower() == "property:" or allowOmitPropPrefix then
eid = arg
page = nil
else
prop = arg
end
end
if eid then
if eid:sub(1,9):lower() == "property:" then
id = replaceAlias(mw.text.trim(eid:sub(10)))
if id:sub(1,1):upper() ~= "P" then
id = ""
end
else
id = replaceAlias(eid)
end
elseif page then
if page:sub(1,1) == ":" then
page = mw.text.trim(page:sub(2))
end
id = mw.wikibase.getEntityIdForTitle(page) 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
local
if
args
return mw.text.trim(arg)
else
return nil
end
end
local function claimCommand(args, funcName)
local
local lastArg, parsedFormat, formatParams, claims, value
local hooks = {count = 0}
-- set the date if given;
-- must come BEFORE processing the flags
if args[p.args.date] then
cfg.atDate = {parseDate(args[p.args.date])}
cfg.periods = {false, true, false} -- change default time constraint to 'current'
end
-- process flags and commands
repeat
lastArg = nextArg(args)
until not cfg:processFlagOrCommand(lastArg)
-- get the entity ID from either the positional argument, the eid argument or the page argument
cfg.entityID, cfg.propertyID = getEntityId(lastArg, args[p.args.eid], args[p.args.page])
if cfg.entityID == "" then
return "" -- we cannot continue without a valid entity ID
end
cfg.entity = mw.wikibase.getEntity(cfg.entityID)
if not cfg.propertyID then
cfg.propertyID = nextArg(args)
end
cfg.propertyID = replaceAlias(cfg.propertyID)
if not cfg.entity or not cfg.propertyID then
return "" -- we cannot continue without an entity or a property ID
end
cfg.propertyID = cfg.propertyID:upper()
if not cfg.entity.claims or not cfg.entity.claims[cfg.propertyID] then
return "" -- there is no use to continue without any claims
end
claims = cfg.entity.claims[cfg.propertyID]
if cfg.states.qualifiersCount > 0 then
-- do further processing if "qualifier(s)" command was given
if #args -
-- claim ID or literal value has been given
end
for i = 1,
-- check if given qualifier ID is an alias and add it
end
elseif
-- do further processing if "reference(s)" command was given
cfg.propertyValue = nextArg(args)
end
-- check for special property value 'somevalue' or 'novalue'
if
if
else
end
end
-- parse the desired format, or choose an appropriate format
if args["format"] then
parsedFormat, formatParams = parseFormat(args["format"])
elseif
if
parsedFormat, formatParams = parseFormat(formats.propertyWithQualifier)
else
parsedFormat, formatParams = parseFormat(formats.qualifier)
end
elseif
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
end
-- if only "reference(s)" has been given, set the default separator to none (except when raw)
if
and not
end
-- if exactly one "qualifier(s)" command has been given, make "sep%q" point to "sep%q1" to make them equivalent
if
end
-- process overridden separator values;
-- must come AFTER tweaking the default separators
-- 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(
-- 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,191 ⟶ 2,337:
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
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
-- if the "single" flag has been given then this state should be equivalent to "property" (singular)
if
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
end
-- set the parsed format and the separators (and optional punctuation mark);
-- must come AFTER creating the additonal states
-- process qualifier matching values, analogous to
for i, v in pairs(args) do
i = tostring(i)
if i:match('^[Pp]%d+$') or
v = replaceSpecialChars(v)
-- check for special qualifier value 'somevalue'
if v ~= "" and mw.text.trim(v) == "" then
v = " " -- single space represents 'somevalue'
end
end
end
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
-- then iterate through the claims to collect values
value = cfg:concatValues(cfg.states[parameters.property]:iterate(claims, hooks, State.claimMatches)) -- pass property state with level 1 hooks and matchHook
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if cfg.editable and value ~= "" then
value = value .. cfg:getEditIcon()
end
return value
end
local function generalCommand(args, funcName)
local
local lastArg
local value = nil
repeat
lastArg = nextArg(args)
until not cfg:processFlag(lastArg)
-- get the entity ID from either the positional argument, the eid argument or the page argument
cfg.entityID = getEntityId(lastArg, args[p.args.eid], args[p.args.page], true)
if cfg.entityID == "" or not mw.wikibase.entityExists(cfg.entityID) then
return "" -- we cannot continue without an entity
end
-- serve according to the given command
if funcName == p.generalCommands.label then
value =
elseif funcName == p.generalCommands.title then
if
value = mw.wikibase.
end
if
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
end
if funcName == p.generalCommands.alias or funcName == p.generalCommands.aliases then
if not cfg.entity.aliases or not cfg.entity.aliases[cfg.langCode] then
return "" -- there is no use to continue without any aliasses
end
local aliases = cfg.entity.aliases[cfg.langCode]
-- parse the desired format, or parse the default aliases format
if args["format"] then
Llinell 2,306 ⟶ 2,453:
parsedFormat, formatParams = parseFormat(formats.alias)
end
-- process overridden separator values;
-- must come AFTER tweaking the default separators
-- define the hook that should be called (getAlias);
-- only define the hook if the parameter ("%a") has been given
Llinell 2,317 ⟶ 2,464:
hooks.count = hooks.count + 1
end
-- set the parsed format and the separators (and optional punctuation mark)
-- iterate to collect values
value = cfg:concatValues(cfg.curState:iterate(aliases, hooks))
elseif funcName == p.generalCommands.badge or funcName == p.generalCommands.badges then
if not cfg.entity.sitelinks or not cfg.entity.sitelinks[cfg.siteID] or not cfg.entity.sitelinks[cfg.siteID].badges then
return "" -- there is no use to continue without any badges
end
local badges = cfg.entity.sitelinks[cfg.siteID].badges
cfg.inSitelinks = true
-- parse the desired format, or parse the default aliases format
if args["format"] then
Llinell 2,336 ⟶ 2,485:
parsedFormat, formatParams = parseFormat(formats.badge)
end
-- process overridden separator values;
-- must come AFTER tweaking the default separators
-- define the hook that should be called (getBadge);
-- only define the hook if the parameter ("%b") has been given
Llinell 2,347 ⟶ 2,496:
hooks.count = hooks.count + 1
end
-- set the parsed format and the separators (and optional punctuation mark)
-- iterate to collect values
value = cfg:concatValues(cfg.curState:iterate(badges, hooks))
end
end
value = value or ""
if
-- if desired, add a clickable icon that may be used to edit the returned value on Wikidata
value = value ..
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
local function wikitextWrapper(frame)
args.pointer = 1
loadI18n(aliasesP, frame)
return commandFunc(args, commandName)
end
p[commandName] = wikitextWrapper
local function luaWrapper(args)
args = copyTable(args)
args.pointer = 1
loadI18n(aliasesP)
return commandFunc(args, commandName)
end
p["_" .. commandName] = luaWrapper
end
end
Llinell 2,390 ⟶ 2,541:
-- main function that is supposed to be used by wrapper templates
function p.main(frame)
if not mw.wikibase then return nil end
local f, args
loadI18n(aliasesP, frame)
-- get the parent frame to take the arguments that were passed to the wrapper template
frame = frame:getParent() or frame
if not frame.args[1] then
throwError("no-function-specified")
end
f = mw.text.trim(frame.args[1])
if f == "main" then
throwError("main-called-twice")
end
assert(p["_"..f], errorText('no-such-function', f))
-- copy arguments from immutable to mutable table
args = copyTable(frame.args)
-- remove the function name from the list
table.remove(args, 1)
return p["_"..f](args)
end
|