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/
local p = {}
Llinell 5:
local i18n
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")
end
Llinell 31 ⟶ 30:
p.generalCommands = {
label
title
}
Llinell 62 ⟶ 60:
p.args = {
eid
}
Llinell 118 ⟶ 84:
qualifier = "%q[%s][%r]",
reference = "%r",
propertyWithQualifier = "%p[ <span style=\"font-size:
alias = "%a[%s]",
badge = "%b[%s]"
Llinell 149 ⟶ 115:
local Config = {}
Config.__index = Config
-- allows for recursive calls
function Config
local cfg = {}
setmetatable(cfg,
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.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 = (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
local stt = {}
setmetatable(stt,
stt.conf = cfg
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
if p.aliasesP[id] then
id = p.aliasesP[id]
end
return id
end
local text = i18n["errors"][code]
if param then text = mw.ustring.gsub(text, "$1", param) end
Llinell 246 ⟶ 211:
end
error(errorText(errorMessage, param))
end
return mw.ustring.gsub(num, "[.]", i18n['numeric']['decimal-mark'], 1)
end
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
if chr == '_' then
-- replace underscores with spaces
Llinell 286 ⟶ 251:
end
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
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
for i = 1, #a2 do
a1[#a1 + 1] = a2[i]
end
return a1
end
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 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
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
if hookNames[param] then
return hookNames[param][index]
Llinell 482 ⟶ 447:
end
return true
end
Llinell 531 ⟶ 496:
-- ]
--
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 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 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.
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.
-- 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.
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 = "
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:
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 = ""
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
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)
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
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
local precision
local latValue, latitude,
local lonValue, longitude,
local latDirection, latDirectionN, latDirectionS, latDirectionEN
local lonDirection, lonDirectionE, lonDirectionW, lonDirectionEN
local latDirectionEN_N = "N"
local latDirectionEN_S = "S"
local lonDirectionEN_E = "E"
local lonDirectionEN_W = "W"
if not raw then
latDirectionN = i18n['coord']['latitude-north']
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
latitude = math.floor(latitude / precision + 0.5) * precision
longitude = math.floor(longitude / precision + 0.5) * precision
numDigits = math.ceil(-math.log10(3600 * precision))
if numDigits < 0 or numDigits == -0 then
numDigits = tonumber("0") -- for some reason, 'numDigits = 0' may actually store '-0', so parse from string instead
end
strFormat = "%." .. numDigits .. "f"
-- use string.format() to strip decimal point followed by a zero (.0) for whole numbers
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
lonSeconds = replaceDecimalMark(lonSeconds)
end
latValue = latValue .. latSeconds .. secSymbol
lonValue = lonValue .. lonSeconds .. secSymbol
end
latValue =
lonValue =
value = latValue .. separator .. lonValue
if link then
globe = parseWikidataURL(datavalue['globe'])
if globe then
globe = mw.wikibase.
else
globe = "earth"
end
value = "[https://tools.wmflabs.org/geohack/geohack.php?language="..self.langCode.."¶ms="..latitude.."_"..latDirectionEN.."_"..longitude.."_"..lonDirectionEN.."_globe:"..globe.." "..value.."]"
end
return value
elseif datatype == 'wikibase-entityid' then
local label
local itemID = datavalue['numeric-id']
if subtype == 'wikibase-item' then
itemID = "Q" .. itemID
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
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, 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(
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,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
-- 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
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
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 = {}
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 "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.
-- 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'][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
value.refHash =
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
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
-- 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.
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
-- 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
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
if id:sub(1,1):upper() == "Q" then
return id:upper() -- entity ID of an item was given
elseif id:sub(1,9):lower() == "property:" then
return replaceAlias(mw.text.trim(id:sub(10))):upper() -- entity ID of a property was given
return replaceAlias(id):upper() -- could be an entity ID of a property without "Property:" prefix
else
return nil
end
end
local
if
args
else
args[nextIndex] = ""
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
local
local hooks = {count = 0}
local nextIndex = 1
-- process flags and commands
while _:processFlagOrCommand(args[nextIndex]) do
nextIndex = nextIndex + 1
end
_.entityID, nextIndex = extractEntityFromArgs(args, nextIndex, false)
-- if eid was explicitly set to empty, then this returns an empty string
if _.entityID == nil then
return ""
end
_.entity = mw.wikibase.getEntity(_.entityID)
_.propertyID = replaceAlias(args[nextIndex]):upper()
nextIndex = nextIndex + 1
if _.states.qualifiersCount > 0 then
-- do further processing if "qualifier(s)" command was given
if #args -
-- claim ID or literal value has been given
nextIndex = nextIndex + 1
end
for i = 1,
-- check if given qualifier ID is an alias and add it
nextIndex = nextIndex + 1
end
elseif
-- do further processing if "reference(s)" command was given
if args[nextIndex] then
_.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
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,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
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 p.aliasesP[i] then
v = replaceSpecialChars(v)
-- check for special qualifier value 'somevalue'
if v ~= "" and mw.text.trim(v) == "" then
v = " " -- single space represents 'somevalue'
end
end
end
if _.entity and _.entity.claims then claims = _.entity.claims[_.propertyID] end
if claims
-- first sort the claims on rank to pre-define the order of output (preferred first, then normal, then deprecated)
claims = sortOnRank(claims)
-- then iterate through the claims to collect values
value = _:concatValues(_.states[parameters.property]:iterate(claims, hooks, State.claimMatches)) -- pass property state with level 1 hooks and matchHook
-- if desired, add a clickable icon that may be used to edit the returned values on Wikidata
if _.editable and value ~= "" then
value = value .. _:getEditIcon()
end
return value
else
return ""
end
end
local
local value = nil
local nextIndex = 1
while _:processFlag(args[nextIndex]) do
nextIndex = nextIndex + 1
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 =
elseif funcName == p.generalCommands.title then
if
value = mw.wikibase.
end
if
value = buildWikilink(value)
end
else
local parsedFormat, formatParams
local hooks = {count = 0}
if funcName == p.generalCommands.alias or funcName == p.generalCommands.badge then
end
_.entity = mw.wikibase.getEntity(_.entityID)
if funcName == p.generalCommands.alias or funcName == p.generalCommands.aliases then
local aliases
-- 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
-- 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)
if _.entity and _.entity.aliases then aliases = _.entity.aliases[_.langCode] end
if aliases then
value = end
elseif funcName == p.generalCommands.badge or funcName == p.generalCommands.badges then
_.inSitelinks = true
local badges
-- 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
-- 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)
if _.entity and _.entity.sitelinks and _.entity.sitelinks[_.siteID] then badges = _.entity.sitelinks[_.siteID].badges end
if badges then
value = end
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)
for
local function wikitextWrapper(frame)
return commandFunc(copyTable(frame.args), commandName)
end
p[commandName] = wikitextWrapper
local function luaWrapper(args)
loadSubmodules()
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
loadSubmodules(frame)
-- get the parent frame to take the arguments that were passed to the wrapper template
frame = frame:getParent() or frame
if not frame.args[1] then
throwError("no-function-specified")
end
f = mw.text.trim(frame.args[1])
if f == "main" then
throwError("main-called-twice")
end
assert(p["_"..f], errorText('no-such-function', f))
-- copy arguments from immutable to mutable table
args = copyTable(frame.args)
-- remove the function name from the list
table.remove(args, 1)
return p["_"..f](args)
end
|