Modul:Wikidata: Unterschied zwischen den Versionen

Aus skandinavien-wiki.net
(ein Zeichen, zehntausende Skriptfehler…)
K (3 Versionen von skanwiki:Modul:Wikidata importiert)
Zeile 1: Zeile 1:
-- module local variables
-- vim: set noexpandtab ft=lua ts=4 sw=4:
require('Module:No globals')
 
local p = {}
local debug = false
 
 
------------------------------------------------------------------------------
-- module local variables and functions
 
local wiki =
local wiki =
{
{
Zeile 10: Zeile 19:
["errors"] =
["errors"] =
{
{
["property-not-found"] = "Eigenschaft nicht gefunden.",
["property-not-found"] = "Property not found.",
["entity-not-found"] = "Wikidata-Eintrag nicht gefunden.",
["entity-not-found"] = "Wikidata entity not found.",
["entity-not-valid"] = "Die an die Wikidata-Schnittstelle übergebene Item-ID ist nicht gültig.",
["unknown-claim-type"] = "Unknown claim type.",
["unknown-claim-type"] = "Unbekannter Aussagentyp.",
["unknown-entity-type"] = "Unknown entity type.",
["unknown-entity-type"] = "Unbekannter Entity-Typ.",
["qualifier-not-found"] = "Qualifier not found.",
["qualifier-not-found"] = "Qualifikator nicht gefunden.",
["site-not-found"] = "Wikimedia project not found.",
["site-not-found"] = "Wikimedia-Projekt nicht gefunden.",
["unknown-datetime-format"] = "Unknown datetime format.",
["invalid-parameters"] = "Ungültige Parameter.",
["local-article-not-found"] = "Article is not yet available in this wiki."
["module-not-loaded"] = "Loading of additional module failed."
},
["maintenance-pages"] =
{
["entity-not-found"] = "Wikidata/Wartung/Fehlendes Datenobjekt",
["entity-not-valid"] = "Wikidata/Wartung/Ungültige Datenobjekt-Identifikationsnummer",
["property-not-existing"] = "Wikidata/Wartung/Eigenschaft existiert nicht"
},
},
["datetime"] =
["datetime"] =
{
{
-- $1 is a placeholder for the actual number
-- $1 is a placeholder for the actual number
[0] = "$1 Mrd. Jahren", -- precision: billion years
[0] = "$1 billion years", -- precision: billion years
[1] = "$100 Mio. Jahren", -- precision: hundred million years
[1] = "$100 million years", -- precision: hundred million years
[2] = "$10 Mio. Jahren", -- precision: ten million years
[2] = "$10 million years", -- precision: ten million years
[3] = "$1 Mio. Jahren", -- precision: million years
[3] = "$1 million years", -- precision: million years
[4] = "$100.000 Jahren", -- precision: hundred thousand years
[4] = "$100,000 years", -- precision: hundred thousand years
[5] = "$10.000 Jahren", -- precision: ten thousand years
[5] = "$10,000 years", -- precision: ten thousand years
[6] = "$1. Jahrtausend", -- precision: millenium
[6] = "$1 millennium", -- precision: millennium
[7] = "$1. Jahrhundert", -- precision: century
[7] = "$1 century", -- precision: century
[8] = "$1er", -- precision: decade
[8] = "$1s", -- precision: decade
-- the following use the format of #time parser function
-- the following use the format of #time parser function
[9]  = "Y", -- precision: year,
[9]  = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[10] = "F Y", -- precision: month
[11] = "j. F Y", -- precision: day
[11] = "F j, Y", -- precision: day
[12] = 'j. F Y, G "Uhr"', -- precision: hour
[12] = "F j, Y ga", -- precision: hour
[13] = "j. F Y G:i", -- precision: minute
[13] = "F j, Y g:ia", -- precision: minute
[14] = "j. F Y G:i:s", -- precision: second
[14] = "F j, Y g:i:sa", -- precision: second
["beforenow"] = "vor $1", -- how to format negative numbers for precisions 0 to 5
["beforenow"] = "$1 BCE", -- how to format negative numbers for precisions 0 to 5
["afternow"] = "in $1", -- how to format positive numbers for precisions 0 to 5
["afternow"] = "$1 CE", -- how to format positive numbers for precisions 0 to 5
["bc"] = '$1 "v.Chr."', -- how print negative years
["bc"] = '$1 "BCE"', -- how print negative years
["ad"] = "$1" -- how print positive years
["ad"] = "$1", -- how print positive years
-- the following are for function getDateValue() and getQualifierDateValue()
["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
-- #4 (getQualifierDateValue) argument
["default-addon"] = "BC", -- default value of the #4 (getDateValue) or
-- #5 (getQualifierDateValue) argument
["prefix-addon"] = false, -- set to true for languages put "BC" in front of the
-- datetime string; or the addon will be suffixed
["addon-sep"] = " ", -- separator between datetime string and addon (or inverse)
["format"] = -- options of the 3rd argument
{
["mdy"] = "F j, Y",
["my"] = "F Y",
["y"] = "Y",
["dmy"] = "j F Y",
["ymd"] = "Y-m-d",
["ym"] = "Y-m"
}
},
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["monolingualtext"] = '<span lang="%language">%text</span>',
["FETCH_WIKIDATA"] = "ABFRAGE_WIKIDATA"
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
["ordinal"] =
{
[1] = "st",
[2] = "nd",
[3] = "rd",
["default"] = "th"
}
}
}


local numberIsParentCalls = 0 -- global value to count calls of expensive function isParent, including recursive calls
if wiki.langcode ~= "en" then
--require("Module:i18n").loadI18n("Module:Wikidata/i18n", i18n)
-- got idea from [[:w:Module:Wd]]
local module_title; if ... == nil then
module_title = mw.getCurrentFrame():getTitle()
else
module_title = ...
end
require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
end


--important properties
-- this function needs to be internationalised along with the above:
local propertyId =
-- takes cardinal numer as a numeric and returns the ordinal as a string
{
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
["starttime"] = "P580",
local function makeOrdinal (cardinal)
["endtime"] = "P582",
local ordsuffix = i18n.ordinal.default
["pointoftime"] = "P585"
if cardinal % 10 == 1 then
}
ordsuffix = i18n.ordinal[1]
 
elseif cardinal % 10 == 2 then
local formatchar =
ordsuffix = i18n.ordinal[2]
{
elseif cardinal % 10 == 3 then
[10] = {"n","m","M","F","xg"}, --precision: month
ordsuffix = i18n.ordinal[3]
[11] = {"W","j","d","z","D","l","N","w"}, --precision: day
end
[12] = {"a","A","g","h","G","H"}, --precision: hour
-- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th'
[13] = {"i"}, --precision: minute
-- similarly for 12 and 13, etc.
[14] = {"s","U"} --precision: second
if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then
}
ordsuffix = i18n.ordinal.default
end
return tostring(cardinal) .. ordsuffix
end


local function printError(code)
local function printError(code)
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
end
end
local function parseDateFormat(f, timestamp, addon, prefix_addon, addon_sep)
local year_suffix
local tstr = ""
local lang_obj = mw.language.new(wiki.langcode)
local f_parts = mw.text.split(f, 'Y', true)
for idx, f_part in pairs(f_parts) do
year_suffix = ''
if string.match(f_part, "x[mijkot]$") then
-- for non-Gregorian year
f_part = f_part .. 'Y'
elseif idx < #f_parts then
-- supress leading zeros in year
year_suffix = lang_obj:formatDate('Y', timestamp)
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
end
if addon ~= "" and prefix_addon then
return addon .. addon_sep .. tstr
elseif addon ~= "" then
return tstr .. addon_sep .. addon
else
return tstr
end
end
local function parseDateValue(timestamp, date_format, date_addon)
local prefix_addon = i18n["datetime"]["prefix-addon"]
local addon_sep = i18n["datetime"]["addon-sep"]
local addon = ""


-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- check for negative date
-- use these as the second parameter and this function instead of the built-in "pairs" function
if string.sub(timestamp, 1, 1) == '-' then
-- to iterate over all qualifiers and snaks in the intended order.
timestamp = '+' .. string.sub(timestamp, 2)
local function orderedpairs(array, order)
addon = date_addon
if not order then return pairs(array) end
end
 
local _date_format = i18n["datetime"]["format"][date_format]
-- return iterator function
if _date_format ~= nil then
local i = 0
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
return function()
else
i = i + 1
return printError("unknown-datetime-format")
if order[i] then
return order[i], array[order[i]]
end
end
end
end
end


-- Function to check whether a certain item is a parent of a given item.
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
-- If pExitItem is reached without finding the searched parent item, the search stops.
-- with the millennium/century/decade handling of formatDate()
-- A parent is connected via P31 or P279.
local function parseDateFull(timestamp, precision, date_format, date_addon)
-- Attention: very intensive function, use carefully!
local prefix_addon = i18n["datetime"]["prefix-addon"]
local function isParent(pItem, pParent, pExitItem, pMaxDepth, pDepth)
local addon_sep = i18n["datetime"]["addon-sep"]
numberIsParentCalls = numberIsParentCalls + 1
local addon = ""
if not pDepth then pDepth = 0 end


if type(pItem) == "number" then pItem = "Q" .. pItem end
-- check for negative date
if string.sub(timestamp, 1, 1) == '-' then
timestamp = '+' .. string.sub(timestamp, 2)
addon = date_addon
end


local entity = mw.wikibase.getEntity(pItem)
-- get the next four characters after the + (should be the year now in all cases)
if not entity then return false end
-- ok, so this is dirty, but let's get it working first
local intyear = tonumber(string.sub(timestamp, 2, 5))
if intyear == 0 and precision <= 9 then
return ""
end


local claims31
-- precision is 10000 years or more
local claims279
if precision <= 5 then
if entity.claims then
local factor = 10 ^ ((5 - precision) + 4)
claims31 = entity.claims[mw.wikibase.resolvePropertyId('P31')]
local y2 = math.ceil(math.abs(intyear) / factor)
claims279 = entity.claims[mw.wikibase.resolvePropertyId('P279')]
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
else
if addon ~= "" then
return false
-- negative date
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end
end
if not claims31 and not claims279 then return false end


local parentIds = {}
-- precision is decades (8), centuries (7) and millennia (6)
if claims31 and #claims31 > 0 then
local era, card
for i, v in ipairs(claims31) do parentIds[#parentIds+1] = getSnakValue(v.mainsnak, "numeric-id") end
if precision == 6 then
card = math.floor((intyear - 1) / 1000) + 1
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
end
end
if claims279 and #claims279 > 0 then
if precision == 7 then
for i, v in ipairs(claims279) do parentIds[#parentIds+1] = getSnakValue(v.mainsnak, "numeric-id") end
card = math.floor((intyear - 1) / 100) + 1
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
end
end
 
if precision == 8 then
-- check if searched parent or exit item is reached or do recursive call
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
if not parentIds[1] or #parentIds == 0 then return false end
end
local itemString = ""
if era then
local result = nil
if addon ~= "" then
for i, v in ipairs(parentIds) do
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
if not v then return false end
itemString = "Q" .. v
 
if itemString == pParent then
-- successful!
return true
elseif itemString == pExitItem or itemString == "Q35120" then
-- exit if either "exit item" or node item (Q35120) is reached
return false
else
else
if pDepth+1 < pMaxDepth then
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
result = isParent(itemString, pParent, pExitItem, pMaxDepth, pDepth+1)
else return false end
 
if result == true then return result end
end
end
return era
end
end
do return false end
end


local function printDatavalueCoordinate(data, parameter)
local _date_format = i18n["datetime"]["format"][date_format]
-- data fields: latitude [double], longitude [double], altitude [double], precision [double], globe [wikidata URI, usually http://www.wikidata.org/entity/Q2 [earth]]
if _date_format ~= nil then
if parameter then
-- check for precision is year and override supplied date_format
if parameter == "globe" then data.globe = mw.ustring.match(data.globe, "Q%d+") end -- extract entity id from the globe URI
if precision == 9 then
return data[parameter]
_date_format = i18n["datetime"][9]
end
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
else
else
return data.latitude .. "/" .. data.longitude -- combine latitude and longitude, which can be decomposed using the #titleparts wiki function
return printError("unknown-datetime-format")
end
end
end
end


local function printDatavalueQuantity(data, parameter)
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- data fields: amount [number], unit [string], upperBound [number], lowerBound [number]
-- use these as the second parameter and this function instead of the built-in "pairs" function
if not parameter or parameter == "amount" then
-- to iterate over all qualifiers and snaks in the intended order.
return tonumber(data.amount)
local function orderedpairs(array, order)
elseif parameter == "unit" then
if not order then return pairs(array) end
return mw.ustring.match(data.unit, "Q%d+")
 
else
-- return iterator function
return data[parameter]
local i = 0
return function()
i = i + 1
if order[i] then
return order[i], array[order[i]]
end
end
end
end
end


-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
local function normalizeDate(date)
local function normalizeDate(date)
date = mw.text.trim(date, "+")
date = mw.text.trim(date, "+")
-- extract year
-- extract year
local yearstr = mw.ustring.match(date, "^-?%d+")
local yearstr = mw.ustring.match(date, "^\-?%d+")
local year = tonumber(yearstr)
local year = tonumber(yearstr)
-- remove leading zeros of year
-- remove leading zeros of year
Zeile 179: Zeile 251:
end
end


-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millenia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
local function formatDate(date, precision, timezone)
function formatDate(date, precision, timezone, formatstr)
precision = precision or 11
precision = precision or 11
date, year = normalizeDate(date)
local date, year = normalizeDate(date)
date = string.gsub(date, "-00%f[%D]", "-01")
if year == 0 and precision <= 9 then return "" end
if year == 0 and precision <= 9 then return "" end


Zeile 199: Zeile 269:
end
end


-- precision is decades, centuries and millenia
-- precision is decades, centuries and millennia
local era
local era
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
Zeile 210: Zeile 280:
end
end


-- precision is years or less
-- precision is year
if precision >= 9 then
if precision == 9 then
return year
end
 
-- precision is less than years
if precision > 9 then
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
timezone = tonumber(timezone)
timezone = tonumber(timezone)
Zeile 221: Zeile 296:
end
end
]]--
]]--
if formatstr then
 
for i=(precision+1), 14 do
local formatstr = i18n.datetime[precision]
for _, ch in pairs(formatchar[i]) do
if formatstr:find(ch) then
formatstr = i18n.datetime[precision]
end
end
end
else
formatstr = i18n.datetime[precision]
end
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
elseif year < 0 then
elseif year < 0 then
Zeile 241: Zeile 307:
end
end
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
end
end
local function printDatavalueTime(data, parameter)
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
--  precision: 0 - billion years, 1 - hundred million years, ..., 6 - millenia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
--  calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
if parameter then
local para, formatstr = parameter:match("([^:]+):([^:]+)")
if parameter == "calendarmodel" then
data.calendarmodel = string.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
elseif para and para == "time" then
return formatDate(data.time, data.precision, data.timezone,formatstr)
elseif parameter == "time" then
data.time = normalizeDate(data.time)
end
return data[parameter]
else
return formatDate(data.time, data.precision, data.timezone)
end
end
end
end
Zeile 274: Zeile 321:
if parameter then
if parameter then
if parameter == "link" then
if parameter == "link" then
local linkTarget = mw.wikibase.sitelink(id)
local linkTarget = mw.wikibase.getSitelink(id)
local linkName = mw.wikibase.label(id)
local linkName = mw.wikibase.getLabel(id)
if linkTarget then
if linkTarget then
local link = linkTarget
-- if there is a local Wikipedia article link to it using the label or the article title
-- if there is a local Wikipedia article linking to it, use the label or the article title
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
if linkName and (linkName ~= linkTarget) then link = link .. "|" .. linkName end
return "[[" .. link .. "]]"
else
else
-- if there is no local Wikipedia article output the label or link to the Wikidata object to input a proper label
-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
end
end
Zeile 289: Zeile 334:
end
end
else
else
return mw.wikibase.label(id) or id
return mw.wikibase.getLabel(id) or id
end
end
 
local function printDatavalueTime(data, parameter)
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
--  precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
--  calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
if parameter then
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
elseif parameter == "time" then data.time = normalizeDate(data.time) end
return data[parameter]
else
return formatDate(data.time, data.precision, data.timezone)
end
end
end
end
Zeile 303: Zeile 361:
end
end


function getSnakValue(snak, parameter)
local function findClaims(entity, property)
-- snaks have three types: "novalue" for null/nil, "somevalue" for not null/not nil, or "value" for actual data
if not property or not entity or not entity.claims then return end
 
if mw.ustring.match(property, "^P%d+$") then
-- if the property is given by an id (P..) access the claim list by this id
return entity.claims[property]
else
property = mw.wikibase.resolvePropertyId(property)
if not property then return end
 
return entity.claims[property]
end
end
 
local function getSnakValue(snak, parameter)
if snak.snaktype == "value" then
if snak.snaktype == "value" then
-- call the respective snak parser
-- call the respective snak parser
Zeile 318: Zeile 389:
end
end


function getQualifierSnak(claim, qualifierId)
local function getQualifierSnak(claim, qualifierId)
-- a "snak" is Wikidata terminology for a typed key/value pair
-- a "snak" is Wikidata terminology for a typed key/value pair
-- a claim consists of a main snak holding the main information of this claim,
-- a claim consists of a main snak holding the main information of this claim,
Zeile 324: Zeile 395:
if qualifierId then
if qualifierId then
-- search the attribute snak with the given qualifier as key
-- search the attribute snak with the given qualifier as key
if claim and claim.qualifiers then
if claim.qualifiers then
local qualifier = claim.qualifiers[qualifierId]
local qualifier = claim.qualifiers[qualifierId]
if qualifier then return qualifier[1] end
if qualifier then return qualifier[1] end
Zeile 335: Zeile 406:
end
end


local function datavalueTimeToDateObject(data)
local function getValueOfClaim(claim, qualifierId, parameter)
local sign, year, month, day, hour, minute, second = string.match(data.time, "(.)(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z")
local result =
{
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
min = tonumber(minute),
sec = tonumber(second),
timezone = data.timezone,
julian = data.calendarmodel and string.match(data.calendarmodel, "Q11184$")
}
if sign == "-" then result.year = -result.year end
return result
end
 
function julianDay(dateObject)
local year = dateObject.year
local month = dateObject.month or 0
local day = dateObject.day or 0
 
if month == 0 then month = 1 end
if day == 0 then day = 1 end
if month <= 2 then
year = year - 1
month = month + 12
end
 
local time = ((((dateObject.sec or 0) / 60 + (dateObject.min or 0) + (dateObject.timezone or 0)) / 60) + (dateObject.hour or 0)) / 24
 
local b
if dateObject.julian then b = 0 else
local century = math.floor(year / 100)
b = 2 - century + math.floor(century / 4)
end
 
return math.floor(365.25 * (year + 4716)) + math.floor(30.6001 * (month + 1)) + day + time + b - 1524.5
end
 
function getQualifierSortValue(claim, qualifierId)
local snak = getQualifierSnak(claim, qualifierId)
if snak and snak.snaktype == "value" then
if snak.datavalue.type == "time" then
return julianDay(datavalueTimeToDateObject(snak.datavalue.value))
else
return getSnakValue(snak)
end
end
end
 
function getValueOfClaim(claim, qualifierId, parameter)
local error
local error
local snak
local snak
Zeile 397: Zeile 417:
end
end


local function getReferences(frame, claim)
local result = ""
-- traverse through all references
for ref in pairs(claim.references or {}) do
local refparts
-- traverse through all parts of the current reference
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
if refparts then refparts = refparts .. ", " else refparts = "" end
-- output the label of the property of the reference part, e.g. "imported from" for P143
refparts = refparts .. tostring(mw.wikibase.getLabel(snakkey)) .. ": "
-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
for snakidx = 1, #snakval do
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts .. getSnakValue(snakval[snakidx])
end
end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
end
return result
end


function formatReference(ref)
local function parseInput(frame)
-- "imported from"-references are useless, skip them:
local qid = frame.args.qid
if ref["P143"] or ref["P4656"] then return nil end
if qid and (#qid == 0) then qid = nil end
local propertyID = mw.text.trim(frame.args[1] or "")
-- load [[Modul:Zitation]]
local input_parm = mw.text.trim(frame.args[2] or "")
local ZitationSuccess, r = pcall(require, "Modul:Zitation")
if input_parm ~= "FETCH_WIKIDATA" then
if type(r) == "table" then
return false, input_parm, nil, nil
Zitation = r.Zitation()
-- clear Zitation state from previous invocations
Zitation.o = nil
end
end
-- assert (ZitationSuccess, i18n["errors"]["module-not-loaded"])
local entity = mw.wikibase.getEntity(qid)
local claims
-- assignments of Wikidata properties to Zitation parameters
if entity and entity.claims then
local wdZmap = {
claims = entity.claims[propertyID]
P1433 = {"bas", "Werk"},
if not claims then
P248  = {"bas", "Werk"},
return false, "", nil, nil
P1476 = {"bas", "Titel"},
P1680 = {"bas", "TitelErg"},
P407  = {"bas", "Sprache"},
P364  = {"bas", "Sprache"},
P2439 = {"bas", "Sprache"},
P123  = {"bas", "Verlag"},
P577  = {"bas", "Datum"},
P98  = {"bas", "Hrsg"},
P2093 = {"bas", "Autor"},
P50  = {"bas", "Autor"},
P1683 = {"bas", "Zitat"},
P854  = {"www", "URL"},
P813  = {"www", "Abruf"},
P1065 = {"www", "ArchivURL"},
P2960 = {"www", "ArchivDatum"},
P2701 = {"www", "Format"},
P393  = {"print", "Auflage"},
P291  = {"print", "Ort"},
P304  = {"fragment", "Seiten"},
P792  = {"fragment", "Kapitel"},
P629  = {"orig", "Titel"}
}
for prop, value in pairs(ref) do
if wdZmap[prop] then
if type(value) == "table" then
-- More snaks with same property, we concatenate using a comma
value = table.concat(value, ", ")
end
-- value should be string now, so we can call Zitation
if type(value) == "string" and string.len(value) > 0 then
Zitation.fill(wdZmap[prop][1], wdZmap[prop][2], value, prop)
end
end
end
else
return false, "", nil, nil
end
end
-- if no title on Wikidata, try to use the URL as title
return true, entity, claims, propertyID
if (not ref["P1476"]) and ref["P854"] then
end
local URLutil = Zitation.fetch("URLutil")
local function isType(claims, type)
Zitation.fill("bas", "Titel", URLutil.getHost(ref["P854"]))
return claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == type
end
local function getValue(entity, claims, propertyID, delim, labelHook)
if labelHook == nil then
labelHook = function (qnumber)
return nil;
end
end
end
return Zitation.format()
if isType(claims, "wikibase-entityid") then
end
local out = {}
 
for k, v in pairs(claims) do
function getReferences(frame, claim)
local qnumber = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
local result = ""
local sitelink = mw.wikibase.getSitelink(qnumber)
-- traverse through all references
local label = labelHook(qnumber) or mw.wikibase.getLabel(qnumber) or qnumber
for ref in pairs(claim.references or {}) do
if sitelink then
local refTable = {}
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
if #snakval == 1 then
refTable[snakkey] = getSnakValue(snakval[1])
else
else
--
out[#out + 1] = "[[:d:" .. qnumber .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
local multival = {}
for snakidx = 1, #snakval do
table.insert(multival, getSnakValue(snakval[snakidx]))
end
refTable[snakkey] = multival
end
end
end
end
return table.concat(out, delim)
local formattedRef, f = formatReference(refTable)
else
-- just return best values
if formattedRef and formattedRef ~= "" then
return entity:formatPropertyValues(propertyID).value
local hash = mw.hash.hashValue('fnv164', formattedRef)
end
result = result .. frame:extensionTag("ref", formattedRef, { name = '_' .. hash })
end
 
------------------------------------------------------------------------------
-- module global functions
 
if debug then
function p.inspectI18n(frame)
local val = i18n
for _, key in pairs(frame.args) do
key = mw.text.trim(key)
val = val[key]
end
end
return val
end
end
return result
end
end


local function hasqualifier(claim, qualifierproperty)
function p.descriptionIn(frame)
local invert
local langcode = frame.args[1]
if string.sub(qualifierproperty, 1, 1) == "!" then invert = true else invert = false end
local id = frame.args[2]
if not claim.qualifiers and not invert then return false end
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
if not claim.qualifiers and invert then return true end
return mw.wikibase.getEntity(id):getDescription(langcode or wiki.langcode)
if qualifierproperty == '' then return true end
end
if not invert and not claim.qualifiers[qualifierproperty] then return false end
 
if invert and claim.qualifiers[string.sub(qualifierproperty, 2)] then return false end
function p.labelIn(frame)
return true
local langcode = frame.args[1]
local id = frame.args[2]
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
return mw.wikibase.getEntity(id):getLabel(langcode or wiki.langcode)
end
 
-- This is used to get a value, or a comma separated list of them if multiple values exist
p.getValue = function(frame)
local delimdefault = ", " -- **internationalise later**
local delim = frame.args.delimiter or ""
delim = string.gsub(delim, '"', '')
if #delim == 0 then
delim = delimdefault
end
local go, errorOrentity, claims, propertyID = parseInput(frame)
if not go then
return errorOrentity
end
return getValue(errorOrentity, claims, propertyID, delim)
end
end


local function qualifierhasvalue(claim, property, value)
-- Same as above, but uses the short name property for label if available.
if not claim.qualifiers then return false end
p.getValueShortName = function(frame)
if not claim.qualifiers[property] then return false end
local go, errorOrentity, claims, propertyID = parseInput(frame)
for key, snak in pairs(claim.qualifiers[property]) do
if not go then
if snak.snaktype == "value" then
return errorOrentity
if snak.datavalue.type == "wikibase-entityid" then
end
if snak.datavalue.value.id == value then
local entity = errorOrentity
return true
-- if wiki-linked value output as link if possible
local function labelHook (qnumber)
local label
local claimEntity = mw.wikibase.getEntity(qnumber)
if claimEntity ~= nil then
if claimEntity.claims.P1813 then
for k2, v2 in pairs(claimEntity.claims.P1813) do
if v2.mainsnak.datavalue.value.language == "en" then
label = v2.mainsnak.datavalue.value.text
end
end
end
--TODO: elseif other types
end
end
end
end
if label == nil or label == "" then return nil end
return label
end
end
return false
return getValue(errorOrentity, claims, propertyID, ", ", labelHook);
end
end


local function hassource(claim, sourceproperty)
-- This is used to get a value, or a comma separated list of them if multiple values exist
if not claim.references then return false end
-- from an arbitrary entry by using its QID.
if sourceproperty == '' or sourceproperty == "true" then return true end
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
if string.sub(sourceproperty,1,1) ~= "!" then
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
for _, source in pairs(claim.references) do
-- Please use sparingly - this is an *expensive call*.
if source.snaks[sourceproperty] then return true end
p.getValueFromID = function(frame)
local itemID = mw.text.trim(frame.args[1] or "")
local propertyID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity(itemID)
local claims
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
return getValue(entity, claims, propertyID, ", ")
else
return ""
end
end
return false
else
else
for _, source in pairs(claim.references) do
return input_parm
for key in pairs(source.snaks) do
end
if key ~= string.sub(sourceproperty,2) then return true end
end
local function getQualifier(frame, outputHook)
local propertyID = mw.text.trim(frame.args[1] or "")
local qualifierID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity()
if entity.claims[propertyID] ~= nil then
local out = {}
for k, v in pairs(entity.claims[propertyID]) do
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
if v2.snaktype == 'value' then
out[#out + 1] = outputHook(v2);
end
end
end
end
return table.concat(out, ", "), true
else
return "", false
end
end
return false
else
return input_parm, false
end
end
end
end
 
p.getQualifierValue = function(frame)
function atdate(claim, mydate)
local function outputValue(value)
local refdate, mydateyear
local qnumber = "Q" .. value.datavalue.value["numeric-id"]
if not mydate or mydate == "" then
if (mw.wikibase.getSitelink(qnumber)) then
refdate = os.date("!*t")
return "[[" .. mw.wikibase.getSitelink(qnumber) .. "]]"
else
if string.match(mydate, "^%d+$") then
refdate = { year = tonumber(mydate) }
mydateyear = tonumber(mydate)
else
else
refdate = datavalueTimeToDateObject({ time = mw.language.getContentLanguage():formatDate("+Y-m-d\\TH:i:s\\Z", mydate) })
return "[[:d:" .. qnumber .. "|" ..qnumber .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
mydateyear = 0
end
end
end
end
local refjd = julianDay(refdate)
return (getQualifier(frame, outputValue))
local exactdate = getQualifierSortValue(claim, propertyId["pointoftime"])
end
local mindate = getQualifierSortValue(claim, propertyId["starttime"])
 
local maxdate = getQualifierSortValue(claim, propertyId["endtime"])
-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
p.getRawValue = function(frame)
if exactdate then
local go, errorOrentity, claims, propertyID = parseInput(frame)
-- if there is an exact date in the qualifier, and the atdate parameter is on year precision, mindate is the beginning of the year and maxdate is 31st Dec of that particular year
if not go then
local refmaxjd
return errorOrentity
if mydateyear > 0 then
end
refmaxjd = julianDay({ year = tonumber(mydate), month=12, day=31 })
local entity = errorOrentity
else
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
refmaxjd = refjd
-- if number type: remove thousand separators, bounds and units
end
if isType(claims, "quantity") then
if exactdate < refjd or exactdate > refmaxjd then return false end
result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
else
result = mw.ustring.gsub(result, "(%d)±.*", "%1")
if mindate and mindate > refjd then return false end
if maxdate and maxdate < refjd then return false end
end
end
return result
end


return true -- success, the claim was valid at "mydate"
-- This is used to get the unit name for the numeric value returned by getRawValue
p.getUnits = function(frame)
local go, errorOrentity, claims, propertyID = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
if isType(claims, "quantity") then
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
end
return result
end
end


local function notdeprecated(claim)
-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
  return claim.rank ~= "deprecated"
p.getUnitID = function(frame)
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local result
if isType(claims, "quantity") then
-- get the url for the unit entry on Wikidata:
result = claims[1].mainsnak.datavalue.value.unit
-- and just reurn the last bit from "Q" to the end (which is the QID):
result = mw.ustring.sub(result, mw.ustring.find(result, "Q"), -1)
end
return result
end
end


--returns a table of claims excluding claims not passed the filters
p.getRawQualifierValue = function(frame)
function filterClaims(frame, claims)
local function outputHook(value)
local function filter(condition, filterfunction)
if value.datavalue.value["numeric-id"] then
if not frame.args[condition] then
return mw.wikibase.getLabel("Q" .. value.datavalue.value["numeric-id"])
return
else
return value.datavalue.value
end
end
local ret, gotData = getQualifier(frame, outputHook)
if gotData then
ret = string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
end
return ret
end
 
-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
-- Dates and times are stored in ISO 8601 format (sort of).
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
-- So I'll just supply "Z" in the call to formatDate below:
p.getDateValue = function(frame)
local date_format = mw.text.trim(frame.args[3] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[4] or i18n["datetime"]["default-addon"])
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local out = {}
for k, v in pairs(claims) do
if v.mainsnak.datavalue.type == 'time' then
local timestamp = v.mainsnak.datavalue.value.time
local dateprecision = v.mainsnak.datavalue.value.precision
-- A year can be stored like this: "+1872-00-00T00:00:00Z",
-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
-- and that's the last day of 1871, so the year is wrong.
-- So fix the month 0, day 0 timestamp to become 1 January instead:
timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
end
end
local newclaims = {}
end
for i, claim in pairs(claims) do
return table.concat(out, ", ")
if filterfunction(claim, frame.args[condition]) then
end
table.insert(newclaims, claim)
p.getQualifierDateValue = function(frame)
end
local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
local function outputHook(value)
local timestamp = value.datavalue.value.time
return parseDateValue(timestamp, date_format, date_addon)
end
return (getQualifier(frame, outputHook))
end
 
-- This is used to fetch all of the images with a particular property, e.g. image (P18), Gene Atlas Image (P692), etc.
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
p.getImages = function(frame)
local sep = mw.text.trim(frame.args[3] or " ")
local imgsize = mw.text.trim(frame.args[4] or "frameless")
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
if (claims[1] and claims[1].mainsnak.datatype == "commonsMedia") then
local out = {}
for k, v in pairs(claims) do
local filename = v.mainsnak.datavalue.value
out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
end
end
claims = newclaims
return table.concat(out, sep)
else
return ""
end
end
end


filter('hasqualifier', hasqualifier)
-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
filter('hassource', hassource)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
filter('atdate', atdate)
-- uses the newer mw.wikibase calls instead of directly using the snaks
if not frame.args.includedeprecated then
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
frame.args.notdeprecated = true
p.getTAValue = function(frame)
    filter('notdeprecated', notdeprecated)
local ent = mw.wikibase.getEntity()
    end
local props = ent:formatPropertyValues('P1323')
local out = {}
-- use additional unnamed parameters as qualifier conditions (in pairs)
local t = {}
for key in pairs(frame.args) do
for k, v in pairs(props) do
if type(key) == "number" and key > 2 and key % 2 == 1 then
if k == 'value' then
-- key = 3, 5, 7 and so on
t = mw.text.split( v, ", ")
local newclaims = {}
for k2, v2 in pairs(t) do
local values = frame.args[key]
out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
local negated = string.sub(values, 1, 1) == "!"
if negated then values = string.sub(values, 2) end
for i, claim in pairs(claims) do
local hasvalue = false
for val in mw.text.gsplit(values, ",") do
if qualifierhasvalue(claim, frame.args[key - 1], val) then
hasvalue = true
break
end
end
if hasvalue ~= negated then table.insert(newclaims, claim) end
end
end
claims = newclaims
end
end
end
end
local ret = table.concat(out, "<br> ")
return claims
if #ret == 0 then
ret = "Invalid TA"
end
return ret
end
end


local p = {}
--[[
This is used to return an image legend from Wikidata
image is property P18
image legend is property P2096


function p.isSubclass(frame)
Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
if not frame.args["parent"] then return "" end
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
If QID is omitted or blank, the current article is used (not an expensive call)
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447


local maxDepth
Ranks are: 'preferred' > 'normal'
maxDepth = tonumber(frame.args["maxDepth"]) or 5
This returns the label from the first image with 'preferred' rank
Or the label from the first image with 'normal' rank if preferred returns nothing
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
]]


local result
p.getImageLegend = function(frame)
if frame.args["id"] == frame.args["parent"] then  
-- look for named parameter id; if it's blank make it nil
result = true
local id = frame.args.id
else
if id and (#id == 0) then
result = isParent(frame.args["id"], frame.args["parent"], frame.args["exitItem"], maxDepth)
id = nil
end
 
-- look for named parameter lang
-- it should contain a two-character ISO-639 language code
-- if it's blank fetch the language of the local wiki
local lang = frame.args.lang
if (not lang) or (#lang < 2) then
lang = mw.language.getContentLanguage().code
end
end
 
-- mw.log(numberIsParentCalls) --uncomment to load number of isParent() calls into log
-- first unnamed parameter is the local parameter, if supplied
local input_parm = mw.text.trim(frame.args[1] or "")
if frame.args["returnInt"] then
if input_parm == "FETCH_WIKIDATA" then
if result == true then return 1 else return "" end
local ent = mw.wikibase.getEntity(id)
local imgs
if ent and ent.claims then
imgs = ent.claims.P18
end
local imglbl
if imgs then
-- look for an image with 'preferred' rank
for k1, v1 in pairs(imgs) do
if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
-- if we don't find one, look for an image with 'normal' rank
if (not imglbl) then
for k1, v1 in pairs(imgs) do
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
end
end
return imglbl
else
else
if result then return result else return false end
return input_parm
end
end
end
end


function p.descriptionIn(frame)
-- This is used to get the QIDs of all of the values of a property, as a comma separated list if multiple values exist
local langcode = frame.args[1]
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |FETCH_WIKIDATA}}
local id = frame.args[2]
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |<InputParameter> |qid=<QID>}}
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
 
local entity = mw.wikibase.getEntity(id)
p.getPropertyIDs = function(frame)
if entity and entity.descriptions then
local go, errorOrentity, propclaims = parseInput(frame)
local desc = entity.descriptions[langcode or wiki.langcode]
if not go then
if desc then return desc.value end
return errorOrentity
end
local entity = errorOrentity
-- if wiki-linked value collect the QID in a table
if (propclaims[1] and propclaims[1].mainsnak.snaktype == "value" and propclaims[1].mainsnak.datavalue.type == "wikibase-entityid") then
local out = {}
for k, v in pairs(propclaims) do
out[#out + 1] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
end
return table.concat(out, ", ")
else
else
return "";
-- not a wikibase-entityid, so return empty
return ""
end
end
end
end


function p.labelIn(frame)
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
local langcode = frame.args[1]
function p.pageId(frame)
local id = frame.args[2]
return mw.wikibase.getEntityIdForCurrentPage()
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
local entity = mw.wikibase.getEntity(id)
if entity and entity.labels then
local label = entity.labels[langcode or wiki.langcode]
if label then return label.value end
else
return "";
end
end
end


Zeile 674: Zeile 871:
local qualifierId = frame.args["qualifier"]
local qualifierId = frame.args["qualifier"]
local parameter = frame.args["parameter"]
local parameter = frame.args["parameter"]
local language = frame.args["language"]
local list = frame.args["list"]
local list = frame.args["list"]
local includeempty = frame.args["includeempty"]
local listMaxItems = tonumber(frame.args["listMaxItems"]) or 0
local references = frame.args["references"]
local references = frame.args["references"]
local sort = frame.args["sort"]
local sortEmptiesFirst = frame.args["sortEmptiesFirst"]
local sortInItem = frame.args["sortInItem"]
local inverse = frame.args["inverse"]
local showerrors = frame.args["showerrors"]
local showerrors = frame.args["showerrors"]
local default = frame.args["default"]
local default = frame.args["default"]
Zeile 688: Zeile 878:


-- get wikidata entity
-- get wikidata entity
if id then
if not mw.wikibase.isValidEntityId(id) then
if showerrors then
return printError("entity-not-valid")
else
local temp = mw.title.new(i18n["maintenance-pages"]["entity-not-valid"], "Modul").exists
return default
end
elseif not mw.wikibase.entityExists(id) then
if showerrors then
return printError("entity-not-found")
else
local temp = mw.title.new(i18n["maintenance-pages"]["entity-not-found"], "Modul").exists
return default
end
end
end
local entity = mw.wikibase.getEntity(id)
local entity = mw.wikibase.getEntity(id)
if not entity then
if not entity then
if showerrors then return printError("entity-not-found") else return default end
if showerrors then return printError("entity-not-found") else return default end
end
end
-- check if property exists
local realProp = mw.wikibase.resolvePropertyId(property)
if not realProp then
local temp = mw.title.new(i18n["maintenance-pages"]["property-not-existing"], "Modul").exists
end
-- fetch the first claim of satisfying the given property
-- fetch the first claim of satisfying the given property
local claims
local claims = findClaims(entity, property)
if entity.claims then claims = entity.claims[realProp] end
if not claims or not claims[1] then
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
if showerrors then return printError("property-not-found") else return default end
end
end
--filter claims
claims = filterClaims(frame, claims)
if not claims[1] then return default end


-- get initial sort indices
-- get initial sort indices
Zeile 733: Zeile 893:
sortindices[#sortindices + 1] = idx
sortindices[#sortindices + 1] = idx
end
end
 
-- sort by claim rank
local comparator
local comparator = function(a, b)
if sort then
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
comparator = function(a, b) --comparator function for sorting statements based on qualifier value
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
-- load qualifier values
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
local QualifierSortValueA = getQualifierSortValue(claims[a], sort)
return ranka < rankb
local QualifierSortValueB = getQualifierSortValue(claims[b], sort)
-- if either of the two statements does not have this qualifer:
---- if sortEmptiesFirst=true: sort it to the beginning
---- else: always sort it to the end
if not QualifierSortValueB then
if not QualifierSortValueA then
-- if neither of the two statements has this qualifier, arbitrarily but consistently return a < b
return a < b
elseif sortEmptiesFirst then
return false
else
return true
end
elseif not QualifierSortValueA then
if sortEmptiesFirst then return true else return false end
end
if type(QualifierSortValueA) ~= type(QualifierSortValueB) and not (tonumber(QualifierSortValueA) and tonumber(QualifierSortValueB)) then
if tonumber(QualifierSortValueA) then return true
elseif tonumber(QualifierSortValueB) then return false
elseif tostring(QualifierSortValueA) and tostring(QualifierSortValueB) then
if inverse then return tostring(QualifierSortValueA) > tostring(QualifierSortValueB) else return tostring(QualifierSortValueA) < tostring(QualifierSortValueB) end
else return false end -- different types, neither numbers nor strings, no chance to compare => random result to avoid script error
elseif tonumber(QualifierSortValueA) and tonumber(QualifierSortValueB) then
QualifierSortValueA = tonumber(QualifierSortValueA)
QualifierSortValueB = tonumber(QualifierSortValueB)
end
if inverse then
return QualifierSortValueA > QualifierSortValueB
else
return QualifierSortValueA < QualifierSortValueB
end
end
elseif sortInItem then
-- fill table sortkeys
local sortkeys = {}
local snakSingle
local sortkeyValueId
local claimContainingValue
for idx, claim in pairs(claims) do
snakSingle = getQualifierSnak(claim)
sortkeyValueId = "Q" .. getSnakValue(snakSingle, "numeric-id")
claimContainingValue = mw.wikibase.getEntity(sortkeyValueId).claims[mw.wikibase.resolvePropertyId(sortInItem)]
if claimContainingValue then
sortkeys[#sortkeys + 1] = getValueOfClaim(claimContainingValue[1])
else
sortkeys[#sortkeys + 1] = ""
end
end
comparator = function(a, b)
if inverse then
return sortkeys[a] > sortkeys [b]
else
return sortkeys[a] < sortkeys [b]
end
end
else
-- sort by claim rank
comparator = function(a, b)
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
return ranka < rankb
end
end
end
table.sort(sortindices, comparator)
table.sort(sortindices, comparator)
Zeile 810: Zeile 905:
local error
local error
if list then
if list then
list = string.gsub(list, "\\n", "\n") -- if a newline is provided (whose backslash will be escaped) unescape it
local value
local value
-- iterate over all elements and return their value (if existing)
-- iterate over all elements and return their value (if existing)
Zeile 816: Zeile 910:
for idx in pairs(claims) do
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
local claim = claims[sortindices[idx]]
value, error = getValueOfClaim(claim, qualifierId, parameter)
value, error = getValueOfClaim(claim, qualifierId, parameter)
if not value and value ~= 0 and showerrors then value = error end
if not value and showerrors then value = error end
if not value and value ~= 0 and includeempty then value = "" end
if value and references then value = value .. getReferences(frame, claim) end
if value and references then value = value .. getReferences(frame, claim) end
result[#result + 1] = value
result[#result + 1] = value
end
end
if listMaxItems and listMaxItems > 0 then
result = table.concat(result, list)
result = table.concat(result, list, 1, math.min(#result, listMaxItems))
else
result = table.concat(result, list)
end
else
else
-- return first element
-- return first element
local claim = claims[sortindices[1]]
local claim = claims[sortindices[1]]
if language == "Q" then
result, error = getValueOfClaim(claim, qualifierId, parameter)
result, error = "Q" .. getSnakValue(getQualifierSnak(claim), "numeric-id")
if result and references then result = result .. getReferences(frame, claim) end
elseif language and claim.mainsnak.datatype == "monolingualtext" then
-- iterate over claims to find adequate language
for idx, claim in pairs(claims) do
if claim.mainsnak.datavalue.value.language == language then
result, error = getValueOfClaim(claim, qualifierId, parameter)
break
end
end
else
result, error = getValueOfClaim(claim, qualifierId, parameter)
end
if references == "only" then
result = getReferences(frame, claim)
elseif result and references then  
result = result .. getReferences(frame, claim)  
end
end
end


Zeile 856: Zeile 928:
end
end


function p.getValue(frame)
-- look into entity object
local param = frame.args[2]
function p.ViewSomething(frame)
if param == "FETCH_WIKIDATA" or param == i18n["FETCH_WIKIDATA"] then return p.claim(frame) else return param end
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
end
local id = f.args.id
if id and (#id == 0) then
id = nil
end
local data = mw.wikibase.getEntity(id)
if not data then
return nil
end
 
local i = 1
while true do
local index = f.args[i]
if not index then
if type(data) == "table" then
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
else
return tostring(data)
end
end


function p.pageId(frame)
data = data[index] or data[tonumber(index)]
local id = frame.args[1]
if not data then
local entity = mw.wikibase.getEntity(id)
return
if not entity then return "" else return entity.id end
end
end


function p.labelOf(frame)
i = i + 1
local id = frame.args[1]
-- returns the label of the given entity/property id
-- if no id is given, the one from the entity associated with the calling Wikipedia article is used
if not id then
local entity = mw.wikibase.getEntity()
if not entity then return printError("entity-not-found") end
id = entity.id
end
end
return mw.wikibase.label(id)
end
end


function p.sitelinkOf(frame)
-- getting sitelink of a given wiki
local id = frame.args[1]
-- get sitelink of current item if qid not supplied
-- returns the Wikipedia article name of the given entity
function p.getSiteLink(frame)
-- if no id is given, the one from the entity associated with the calling Wikipedia article is used
local qid = frame.args.qid
if not id then
if qid == "" then qid = nil end
local entity = mw.wikibase.getEntity()
local f = mw.text.trim( frame.args[1] or "")
if not entity then return printError("entity-not-found") end
local entity = mw.wikibase.getEntity(qid)
id = entity.id
if not entity then
return
end
local link = entity:getSitelink( f )
if not link then
return
end
end
return mw.wikibase.sitelink(id)
return link
end
end


function p.badges(frame)
function p.Dump(frame)
local site = frame.args[1]
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
local id = frame.args[2]
local data = mw.wikibase.getEntity(f.args.id)
if not site then return printError("site-not-found") end
if not data then
local entity = mw.wikibase.getEntity(id)
return i18n.warnDump
if not entity then return printError("entity-not-found") end
local badges = entity.sitelinks[site].badges
if badges then
local result
for idx = 1, #badges do
if result then result = result .. "/" .. badges[idx] else result = badges[idx] end
end
return result
end
end
end
function p.sitelinkCount(frame)
local filter = "^.*" .. (frame.args[1] or "") .. "$"
local id = frame.args[2]


local entity = mw.wikibase.getEntity(id)
local i = 1
local count = 0
while true do
if entity and entity.sitelinks then
local index = f.args[i]
for project, _ in pairs(entity.sitelinks) do
if not index then
if string.find(project, filter) then count = count + 1 end
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
end
end
end
return count
end


-- call this in cases of script errors within a function instead of {{#invoke:Wikidata|<method>|...}} call {{#invoke:Wikidata|debug|<method>|...}}
data = data[index] or data[tonumber(index)]
function p.debug(frame)
if not data then
local func = frame.args[1]
return i18n.warnDump
if func then
-- create new parameter set, where the first parameter with the function name is removed
local newargs = {}
for key, val in pairs(frame.args) do
if type(key) == "number" then
if key > 1 then newargs[key - 1] = val end
else
newargs[key] = val
end
end
end
frame.args = newargs
local status, result = pcall(p[func], frame)
-- if status then return tostring(result) or "" else return '<span class="error">' .. result .. '</span>' end -- revert
if status then return result else return '<span class="error">' .. result .. '</span>' end
else
return printError("invalid-parameters")
end
end


function p.printEntity(frame)
i = i + 1
local id = frame.args[1]
local entity = mw.wikibase.getEntity(id)
if entity then return "<pre>" .. mw.text.jsonEncode(entity, mw.text.JSON_PRETTY) .. "</pre>" end
end
 
-- formfill Template:Coordinate (NS, EW, name from WikidataEntity) and expand it
-- füllt Vorlage:Coordinate (NS, EW, name mit Wikidata-Werten) + expandiert sie
--  1st frame.arg                            .. Q prefixed entity id (mandatory)
--  named frame.arg "type", "region", "text" .. see doc of 'Coordinate' template
function p.ffCoordinate(frame)
local f = frame
local id = f.args[1] or f.args.Q
local name = f.args.name or p.labelIn{ args = { nil, id, id = id }}
local coord = mw.text.split(p.claim{ args = { "P625", id, id = id }}, '/')
coord[1] = tonumber(coord[1])
coord[2] = tonumber(coord[2])
 
local t, r = f.args.type, f.args.region
if not t
then t = p.claim{ args = { "P31", id, id = id, language = "Q" }}
t = t and t:gsub("Q.*", {
Q8502  = "mountain",
Q54050 = "landmark"
})
if not t or t and t:find("Q", 1, true)
then t="" -- no default, let Coordinate warn about unset type= param
end
end
if not r
then r = p.claim{ args = { "P17", id, id = id, language = "Q" }}
r = r and p.claim{ args = { "P297", r, id = r }}
if not r
then r="" -- no default, let Coordinate warn about unset region= param
end
end
end
return ('<span data-sort-value="%010.6f"></span>'):format((f.args.sortkey
or "EW"):find("EW", 1, true) and coord[2]+360.0 or coord[1]+180.0
) .. f:expandTemplate{ title = 'Coordinate', args = {
NS = coord[1], EW = coord[2], type = t, region = r,
text = f.args.text or (f.args.maplink and "ICON0" or "/"),
name = name, simple = f.args.simple
}} .. (not f.args.maplink and "" or (" " ..
--f:callParserFunction{ name="#statements", args={ "P625", from = id } }
f:callParserFunction{ name="#tag:maplink", args={ "",
class = "no-icon", text = f.args.mlname and name,
zoom = 12, latitude = coord[1], longitude = coord[2]
}}
))
end
function p.ffCoordinateAndLatLonMaplink(frame)
frame.args.maplink = 1
--frame.args.mlname = nil
return p.ffCoordinate(frame)
end
end
function p.ffCoordinateAndMaplink(frame)
frame.args.maplink = 1
frame.args.mlname = 1
return p.ffCoordinate(frame)
end


return p
return p

Version vom 13. Januar 2023, 13:50 Uhr

Die Dokumentation für dieses Modul kann unter Modul:Wikidata/doc erstellt werden

-- vim: set noexpandtab ft=lua ts=4 sw=4:
require('Module:No globals')

local p = {}
local debug = false


------------------------------------------------------------------------------
-- module local variables and functions

local wiki =
{
	langcode = mw.language.getContentLanguage().code
}

-- internationalisation
local i18n =
{
	["errors"] =
	{
		["property-not-found"] = "Property not found.",
		["entity-not-found"] = "Wikidata entity not found.",
		["unknown-claim-type"] = "Unknown claim type.",
		["unknown-entity-type"] = "Unknown entity type.",
		["qualifier-not-found"] = "Qualifier not found.",
		["site-not-found"] = "Wikimedia project not found.",
		["unknown-datetime-format"] = "Unknown datetime format.",
		["local-article-not-found"] = "Article is not yet available in this wiki."
	},
	["datetime"] =
	{
		-- $1 is a placeholder for the actual number
		[0] = "$1 billion years",	-- precision: billion years
		[1] = "$100 million years",	-- precision: hundred million years
		[2] = "$10 million years",	-- precision: ten million years
		[3] = "$1 million years",	-- precision: million years
		[4] = "$100,000 years",		-- precision: hundred thousand years
		[5] = "$10,000 years",		-- precision: ten thousand years
		[6] = "$1 millennium",		-- precision: millennium
		[7] = "$1 century",			-- precision: century
		[8] = "$1s",				-- precision: decade
		-- the following use the format of #time parser function
		[9]  = "Y",					-- precision: year,
		[10] = "F Y",				-- precision: month
		[11] = "F j, Y",			-- precision: day
		[12] = "F j, Y ga",			-- precision: hour
		[13] = "F j, Y g:ia",		-- precision: minute
		[14] = "F j, Y g:i:sa",		-- precision: second
		["beforenow"] = "$1 BCE",	-- how to format negative numbers for precisions 0 to 5
		["afternow"] = "$1 CE",		-- how to format positive numbers for precisions 0 to 5
		["bc"] = '$1 "BCE"',		-- how print negative years
		["ad"] = "$1",				-- how print positive years
		-- the following are for function getDateValue() and getQualifierDateValue()
		["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
									-- #4 (getQualifierDateValue) argument
		["default-addon"] = "BC",	-- default value of the #4 (getDateValue) or
									-- #5 (getQualifierDateValue) argument
		["prefix-addon"] = false,	-- set to true for languages put "BC" in front of the
									-- datetime string; or the addon will be suffixed
		["addon-sep"] = " ",		-- separator between datetime string and addon (or inverse)
		["format"] =				-- options of the 3rd argument
		{
			["mdy"] = "F j, Y",
			["my"] = "F Y",
			["y"] = "Y",
			["dmy"] = "j F Y",
			["ymd"] = "Y-m-d",
			["ym"] = "Y-m"
		}
	},
	["monolingualtext"] = '<span lang="%language">%text</span>',
	["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
	["ordinal"] =
	{
		[1] = "st",
		[2] = "nd",
		[3] = "rd",
		["default"] = "th"
	}
}

if wiki.langcode ~= "en" then
	--require("Module:i18n").loadI18n("Module:Wikidata/i18n", i18n)
	-- got idea from [[:w:Module:Wd]]
	local module_title; if ... == nil then
		module_title = mw.getCurrentFrame():getTitle()
	else
		module_title = ...
	end
	require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
end

-- this function needs to be internationalised along with the above:
-- takes cardinal numer as a numeric and returns the ordinal as a string
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
local function makeOrdinal (cardinal)
	local ordsuffix = i18n.ordinal.default
	if cardinal % 10 == 1 then
		ordsuffix = i18n.ordinal[1]
	elseif cardinal % 10 == 2 then
		ordsuffix = i18n.ordinal[2]
	elseif cardinal % 10 == 3 then
		ordsuffix = i18n.ordinal[3]
	end
	-- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th'
	-- similarly for 12 and 13, etc.
	if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then
		ordsuffix = i18n.ordinal.default
	end
	return tostring(cardinal) .. ordsuffix
end

local function printError(code)
	return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
end
local function parseDateFormat(f, timestamp, addon, prefix_addon, addon_sep) 
	local year_suffix
	local tstr = ""
	local lang_obj = mw.language.new(wiki.langcode)
	local f_parts = mw.text.split(f, 'Y', true)
	for idx, f_part in pairs(f_parts) do
		year_suffix = ''
		if string.match(f_part, "x[mijkot]$") then
			-- for non-Gregorian year
			f_part = f_part .. 'Y'
		elseif idx < #f_parts then
			-- supress leading zeros in year
			year_suffix = lang_obj:formatDate('Y', timestamp)
			year_suffix = string.gsub(year_suffix, '^0+', '', 1)
		end
		tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
	end
	if addon ~= "" and prefix_addon then
		return addon .. addon_sep .. tstr
	elseif addon ~= "" then
		return tstr .. addon_sep .. addon
	else
		return tstr
	end
end
local function parseDateValue(timestamp, date_format, date_addon)
	local prefix_addon = i18n["datetime"]["prefix-addon"]
	local addon_sep = i18n["datetime"]["addon-sep"]
	local addon = ""

	-- check for negative date
	if string.sub(timestamp, 1, 1) == '-' then
		timestamp = '+' .. string.sub(timestamp, 2)
		addon = date_addon
	end
	local _date_format = i18n["datetime"]["format"][date_format]
	if _date_format ~= nil then
		return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
	else
		return printError("unknown-datetime-format")
	end
end

-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
-- with the millennium/century/decade handling of formatDate()
local function parseDateFull(timestamp, precision, date_format, date_addon)
	local prefix_addon = i18n["datetime"]["prefix-addon"]
	local addon_sep = i18n["datetime"]["addon-sep"]
	local addon = ""

	-- check for negative date
	if string.sub(timestamp, 1, 1) == '-' then
		timestamp = '+' .. string.sub(timestamp, 2)
		addon = date_addon
	end

	-- get the next four characters after the + (should be the year now in all cases)
	-- ok, so this is dirty, but let's get it working first
	local intyear = tonumber(string.sub(timestamp, 2, 5))
	if intyear == 0 and precision <= 9 then
		return ""
	end

	-- precision is 10000 years or more
	if precision <= 5 then
		local factor = 10 ^ ((5 - precision) + 4)
		local y2 = math.ceil(math.abs(intyear) / factor)
		local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
		if addon ~= "" then
			-- negative date
			relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
		else
			relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
		end
		return relative
	end

	-- precision is decades (8), centuries (7) and millennia (6)
	local era, card
	if precision == 6 then
		card = math.floor((intyear - 1) / 1000) + 1
		era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
	end
	if precision == 7 then
		card = math.floor((intyear - 1) / 100) + 1
		era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
	end
	if precision == 8 then
		era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
	end
	if era then
		if addon ~= "" then
			era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
		else
			era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
		end
		return era
	end

	local _date_format = i18n["datetime"]["format"][date_format]
	if _date_format ~= nil then
		-- check for precision is year and override supplied date_format
		if precision == 9 then
			_date_format = i18n["datetime"][9]
		end
		return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
	else
		return printError("unknown-datetime-format")
	end
end

-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- use these as the second parameter and this function instead of the built-in "pairs" function
-- to iterate over all qualifiers and snaks in the intended order.
local function orderedpairs(array, order)
	if not order then return pairs(array) end

	-- return iterator function
	local i = 0
	return function()
		i = i + 1
		if order[i] then
			return order[i], array[order[i]]
		end
	end
end

-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
local function normalizeDate(date)
	date = mw.text.trim(date, "+")
	-- extract year
	local yearstr = mw.ustring.match(date, "^\-?%d+")
	local year = tonumber(yearstr)
	-- remove leading zeros of year
	return year .. mw.ustring.sub(date, #yearstr + 1), year
end

local function formatDate(date, precision, timezone)
	precision = precision or 11
	local date, year = normalizeDate(date)
	if year == 0 and precision <= 9 then return "" end

	-- precision is 10000 years or more
	if precision <= 5 then
		local factor = 10 ^ ((5 - precision) + 4)
		local y2 = math.ceil(math.abs(year) / factor)
		local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
		if year < 0 then
			relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
		else
			relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
		end
		return relative
	end

	-- precision is decades, centuries and millennia
	local era
	if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
	if precision == 7 then era = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(year) - 1) / 100) + 1)) end
	if precision == 8 then era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(year) / 10) * 10)) end
	if era then
		if year < 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
		elseif year > 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era) end
		return era
	end

	-- precision is year
	if precision == 9 then
		return year
	end

	-- precision is less than years
	if precision > 9 then
		--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
		timezone = tonumber(timezone)
		if timezone and timezone ~= 0 then
			timezone = -timezone
			timezone = string.format("%.2d%.2d", timezone / 60, timezone % 60)
			if timezone[1] ~= '-' then timezone = "+" .. timezone end
			date = mw.text.trim(date, "Z") .. " " .. timezone
		end
		]]--

		local formatstr = i18n.datetime[precision]
		if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
		elseif year < 0 then
			-- Mediawiki formatDate doesn't support negative years
			date = mw.ustring.sub(date, 2)
			formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.bc, "$1", i18n.datetime[9]))
		elseif year > 0 and i18n.datetime.ad ~= "$1" then
			formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.ad, "$1", i18n.datetime[9]))
		end
		return mw.language.new(wiki.langcode):formatDate(formatstr, date)
	end
end

local function printDatavalueEntity(data, parameter)
	-- data fields: entity-type [string], numeric-id [int, Wikidata id]
	local id

	if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
	elseif data["entity-type"] == "property" then id = "P" .. data["numeric-id"]
	else return printError("unknown-entity-type")
	end

	if parameter then
		if parameter == "link" then
			local linkTarget = mw.wikibase.getSitelink(id)
			local linkName = mw.wikibase.getLabel(id)
			if linkTarget then
				-- if there is a local Wikipedia article link to it using the label or the article title
				return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
			else
				-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
				if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
			end
		else
			return data[parameter]
		end
	else
		return mw.wikibase.getLabel(id) or id
	end
end

local function printDatavalueTime(data, parameter)
	-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
	--   precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
	--   calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
	if parameter then
		if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
		elseif parameter == "time" then data.time = normalizeDate(data.time) end
		return data[parameter]
	else
		return formatDate(data.time, data.precision, data.timezone)
	end
end

local function printDatavalueMonolingualText(data, parameter)
	-- data fields: language [string], text [string]
	if parameter then
		return data[parameter]
	else
		local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
		return result
	end
end

local function findClaims(entity, property)
	if not property or not entity or not entity.claims then return end

	if mw.ustring.match(property, "^P%d+$") then
		-- if the property is given by an id (P..) access the claim list by this id
		return entity.claims[property]
	else
		property = mw.wikibase.resolvePropertyId(property)
		if not property then return end

		return entity.claims[property]
	end
end

local function getSnakValue(snak, parameter)
	if snak.snaktype == "value" then
		-- call the respective snak parser
		if snak.datavalue.type == "string" then return snak.datavalue.value
		elseif snak.datavalue.type == "globecoordinate" then return printDatavalueCoordinate(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "quantity" then return printDatavalueQuantity(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "time" then return printDatavalueTime(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "wikibase-entityid" then return printDatavalueEntity(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "monolingualtext" then return printDatavalueMonolingualText(snak.datavalue.value, parameter)
		end
	end
	return mw.wikibase.renderSnak(snak)
end

local function getQualifierSnak(claim, qualifierId)
	-- a "snak" is Wikidata terminology for a typed key/value pair
	-- a claim consists of a main snak holding the main information of this claim,
	-- as well as a list of attribute snaks and a list of references snaks
	if qualifierId then
		-- search the attribute snak with the given qualifier as key
		if claim.qualifiers then
			local qualifier = claim.qualifiers[qualifierId]
			if qualifier then return qualifier[1] end
		end
		return nil, printError("qualifier-not-found")
	else
		-- otherwise return the main snak
		return claim.mainsnak
	end
end

local function getValueOfClaim(claim, qualifierId, parameter)
	local error
	local snak
	snak, error = getQualifierSnak(claim, qualifierId)
	if snak then
		return getSnakValue(snak, parameter)
	else
		return nil, error
	end
end

local function getReferences(frame, claim)
	local result = ""
	-- traverse through all references
	for ref in pairs(claim.references or {}) do
		local refparts
		-- traverse through all parts of the current reference
		for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
			if refparts then refparts = refparts .. ", " else refparts = "" end
			-- output the label of the property of the reference part, e.g. "imported from" for P143
			refparts = refparts .. tostring(mw.wikibase.getLabel(snakkey)) .. ": "
			-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
			for snakidx = 1, #snakval do
				if snakidx > 1 then refparts = refparts .. ", " end
				refparts = refparts .. getSnakValue(snakval[snakidx])
			end
		end
		if refparts then result = result .. frame:extensionTag("ref", refparts) end
	end
	return result
end

local function parseInput(frame)
	local qid = frame.args.qid
	if qid and (#qid == 0) then qid = nil end
	local propertyID = mw.text.trim(frame.args[1] or "")
	local input_parm = mw.text.trim(frame.args[2] or "")
	if input_parm ~= "FETCH_WIKIDATA" then
		return false, input_parm, nil, nil
	end
	local entity = mw.wikibase.getEntity(qid)
	local claims
	if entity and entity.claims then
		claims = entity.claims[propertyID]
		if not claims then
			return false, "", nil, nil
		end
	else
		return false, "", nil, nil
	end
	return true, entity, claims, propertyID
end
local function isType(claims, type)
	return claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == type
end
local function getValue(entity, claims, propertyID, delim, labelHook) 
	if labelHook == nil then
		labelHook = function (qnumber)
			return nil;
		end
	end
	if isType(claims, "wikibase-entityid") then
		local out = {}
		for k, v in pairs(claims) do
			local qnumber = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
			local sitelink = mw.wikibase.getSitelink(qnumber)
			local label = labelHook(qnumber) or mw.wikibase.getLabel(qnumber) or qnumber
			if sitelink then
				out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
			else
				out[#out + 1] = "[[:d:" .. qnumber .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
			end
		end
		return table.concat(out, delim)
	else
		-- just return best values
		return entity:formatPropertyValues(propertyID).value
	end
end

------------------------------------------------------------------------------
-- module global functions

if debug then
	function p.inspectI18n(frame)
		local val = i18n
		for _, key in pairs(frame.args) do
			key = mw.text.trim(key)
			val = val[key]
		end
		return val
	end
end

function p.descriptionIn(frame)
	local langcode = frame.args[1]
	local id = frame.args[2]
	-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
	return mw.wikibase.getEntity(id):getDescription(langcode or wiki.langcode)
end

function p.labelIn(frame)
	local langcode = frame.args[1]
	local id = frame.args[2]
	-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
	return mw.wikibase.getEntity(id):getLabel(langcode or wiki.langcode)
end

-- This is used to get a value, or a comma separated list of them if multiple values exist
p.getValue = function(frame)
	local delimdefault = ", " -- **internationalise later**
	local delim = frame.args.delimiter or ""
	delim = string.gsub(delim, '"', '')
	if #delim == 0 then
		delim = delimdefault
	end
	local go, errorOrentity, claims, propertyID = parseInput(frame)
	if not go then
		return errorOrentity
	end
	return getValue(errorOrentity, claims, propertyID, delim)
end

-- Same as above, but uses the short name property for label if available.
p.getValueShortName = function(frame)
	local go, errorOrentity, claims, propertyID = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	-- if wiki-linked value output as link if possible
	local function labelHook (qnumber)
		local label
		local claimEntity = mw.wikibase.getEntity(qnumber)
		if claimEntity ~= nil then
			if claimEntity.claims.P1813 then
				for k2, v2 in pairs(claimEntity.claims.P1813) do
					if v2.mainsnak.datavalue.value.language == "en" then
						label = v2.mainsnak.datavalue.value.text
					end
				end
			end
		end
		if label == nil or label == "" then return nil end
		return label
	end
	return getValue(errorOrentity, claims, propertyID, ", ", labelHook);
end

-- This is used to get a value, or a comma separated list of them if multiple values exist
-- from an arbitrary entry by using its QID.
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
-- Please use sparingly - this is an *expensive call*.
p.getValueFromID = function(frame)
	local itemID = mw.text.trim(frame.args[1] or "")
	local propertyID = mw.text.trim(frame.args[2] or "")
	local input_parm = mw.text.trim(frame.args[3] or "")
	if input_parm == "FETCH_WIKIDATA" then
		local entity = mw.wikibase.getEntity(itemID)
		local claims
		if entity and entity.claims then
			claims = entity.claims[propertyID]
		end
		if claims then
			return getValue(entity, claims, propertyID, ", ")
		else
			return ""
		end
	else
		return input_parm
	end
end
local function getQualifier(frame, outputHook) 
	local propertyID = mw.text.trim(frame.args[1] or "")
	local qualifierID = mw.text.trim(frame.args[2] or "")
	local input_parm = mw.text.trim(frame.args[3] or "")
	if input_parm == "FETCH_WIKIDATA" then
		local entity = mw.wikibase.getEntity()
		if entity.claims[propertyID] ~= nil then
			local out = {}
			for k, v in pairs(entity.claims[propertyID]) do
				for k2, v2 in pairs(v.qualifiers[qualifierID]) do
					if v2.snaktype == 'value' then
						out[#out + 1] = outputHook(v2);
					end
				end
			end
			return table.concat(out, ", "), true
		else
			return "", false
		end
	else
		return input_parm, false
	end
end
p.getQualifierValue = function(frame)
	local function outputValue(value)
		local qnumber = "Q" .. value.datavalue.value["numeric-id"]
		if (mw.wikibase.getSitelink(qnumber)) then
			return "[[" .. mw.wikibase.getSitelink(qnumber) .. "]]"
		else
			return "[[:d:" .. qnumber .. "|" ..qnumber .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
		end
	end
	return (getQualifier(frame, outputValue))
end

-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
p.getRawValue = function(frame)
	local go, errorOrentity, claims, propertyID = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
	-- if number type: remove thousand separators, bounds and units
	if isType(claims, "quantity") then
		result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
		result = mw.ustring.gsub(result, "(%d)±.*", "%1")
	end
	return result
end

-- This is used to get the unit name for the numeric value returned by getRawValue
p.getUnits = function(frame)
	local go, errorOrentity, claims, propertyID = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
	if isType(claims, "quantity") then
		result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
	end
	return result
end

-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
p.getUnitID = function(frame)
	local go, errorOrentity, claims = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	local result
	if isType(claims, "quantity") then
		-- get the url for the unit entry on Wikidata:
		result = claims[1].mainsnak.datavalue.value.unit
		-- and just reurn the last bit from "Q" to the end (which is the QID):
		result = mw.ustring.sub(result, mw.ustring.find(result, "Q"), -1)
	end
	return result
end

p.getRawQualifierValue = function(frame)
	local function outputHook(value)
		if value.datavalue.value["numeric-id"] then
			return mw.wikibase.getLabel("Q" .. value.datavalue.value["numeric-id"])
		else
			return value.datavalue.value
		end
	end
	local ret, gotData = getQualifier(frame, outputHook)
	if gotData then
		ret = string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
	end
	return ret
end

-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
-- Dates and times are stored in ISO 8601 format (sort of).
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
-- So I'll just supply "Z" in the call to formatDate below:
p.getDateValue = function(frame)
	local date_format = mw.text.trim(frame.args[3] or i18n["datetime"]["default-format"])
	local date_addon = mw.text.trim(frame.args[4] or i18n["datetime"]["default-addon"])
	local go, errorOrentity, claims = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	local out = {}
	for k, v in pairs(claims) do
		if v.mainsnak.datavalue.type == 'time' then
			local timestamp = v.mainsnak.datavalue.value.time
			local dateprecision = v.mainsnak.datavalue.value.precision
			-- A year can be stored like this: "+1872-00-00T00:00:00Z",
			-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
			-- and that's the last day of 1871, so the year is wrong.
			-- So fix the month 0, day 0 timestamp to become 1 January instead:
			timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
			out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
		end
	end
	return table.concat(out, ", ")
end
p.getQualifierDateValue = function(frame)
	local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
	local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
	local function outputHook(value)
		local timestamp = value.datavalue.value.time
		return parseDateValue(timestamp, date_format, date_addon)
	end
	return (getQualifier(frame, outputHook))
end

-- This is used to fetch all of the images with a particular property, e.g. image (P18), Gene Atlas Image (P692), etc.
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
p.getImages = function(frame)
	local sep = mw.text.trim(frame.args[3] or " ")
	local imgsize = mw.text.trim(frame.args[4] or "frameless")
	local go, errorOrentity, claims = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	if (claims[1] and claims[1].mainsnak.datatype == "commonsMedia") then
		local out = {}
		for k, v in pairs(claims) do
			local filename = v.mainsnak.datavalue.value
			out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
		end
		return table.concat(out, sep)
	else
		return ""
	end
end

-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
-- uses the newer mw.wikibase calls instead of directly using the snaks
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
p.getTAValue = function(frame)
	local ent = mw.wikibase.getEntity()
	local props = ent:formatPropertyValues('P1323')
	local out = {}
	local t = {}
	for k, v in pairs(props) do
		if k == 'value' then
			t = mw.text.split( v, ", ")
			for k2, v2 in pairs(t) do
				out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
			end
		end
	end
	local ret = table.concat(out, "<br> ")
	if #ret == 0 then
		ret = "Invalid TA"
	end
	return ret
end

--[[
This is used to return an image legend from Wikidata
image is property P18
image legend is property P2096

Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
If QID is omitted or blank, the current article is used (not an expensive call)
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447

Ranks are: 'preferred' > 'normal'
This returns the label from the first image with 'preferred' rank
Or the label from the first image with 'normal' rank if preferred returns nothing
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
]]

p.getImageLegend = function(frame)
	-- look for named parameter id; if it's blank make it nil
	local id = frame.args.id
	if id and (#id == 0) then
		id = nil
	end

	-- look for named parameter lang
	-- it should contain a two-character ISO-639 language code
	-- if it's blank fetch the language of the local wiki
	local lang = frame.args.lang
	if (not lang) or (#lang < 2) then
		lang = mw.language.getContentLanguage().code
	end

	-- first unnamed parameter is the local parameter, if supplied
	local input_parm = mw.text.trim(frame.args[1] or "")
	if input_parm == "FETCH_WIKIDATA" then
		local ent = mw.wikibase.getEntity(id)
		local imgs
		if ent and ent.claims then
			imgs = ent.claims.P18
		end
		local imglbl
		if imgs then
			-- look for an image with 'preferred' rank
			for k1, v1 in pairs(imgs) do
				if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
					local imglbls = v1.qualifiers.P2096
					for k2, v2 in pairs(imglbls) do
						if v2.datavalue.value.language == lang then
							imglbl = v2.datavalue.value.text
							break
						end
					end
				end
			end
			-- if we don't find one, look for an image with 'normal' rank
			if (not imglbl) then
				for k1, v1 in pairs(imgs) do
					if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
						local imglbls = v1.qualifiers.P2096
						for k2, v2 in pairs(imglbls) do
							if v2.datavalue.value.language == lang then
								imglbl = v2.datavalue.value.text
								break
							end
						end
					end
				end
			end
		end
		return imglbl
	else
		return input_parm
	end
end

-- This is used to get the QIDs of all of the values of a property, as a comma separated list if multiple values exist
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |FETCH_WIKIDATA}}
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |<InputParameter> |qid=<QID>}}

p.getPropertyIDs = function(frame)
	local go, errorOrentity, propclaims = parseInput(frame)
	if not go then
		return errorOrentity
	end
	local entity = errorOrentity
	-- if wiki-linked value collect the QID in a table
	if (propclaims[1] and propclaims[1].mainsnak.snaktype == "value" and propclaims[1].mainsnak.datavalue.type == "wikibase-entityid") then
		local out = {}
		for k, v in pairs(propclaims) do
			out[#out + 1] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
		end
		return table.concat(out, ", ")
	else
		-- not a wikibase-entityid, so return empty
		return ""
	end
end

-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.pageId(frame)
	return mw.wikibase.getEntityIdForCurrentPage()
end

function p.claim(frame)
	local property = frame.args[1] or ""
	local id = frame.args["id"]
	local qualifierId = frame.args["qualifier"]
	local parameter = frame.args["parameter"]
	local list = frame.args["list"]
	local references = frame.args["references"]
	local showerrors = frame.args["showerrors"]
	local default = frame.args["default"]
	if default then showerrors = nil end

	-- get wikidata entity
	local entity = mw.wikibase.getEntity(id)
	if not entity then
		if showerrors then return printError("entity-not-found") else return default end
	end
	-- fetch the first claim of satisfying the given property
	local claims = findClaims(entity, property)
	if not claims or not claims[1] then
		if showerrors then return printError("property-not-found") else return default end
	end

	-- get initial sort indices
	local sortindices = {}
	for idx in pairs(claims) do
		sortindices[#sortindices + 1] = idx
	end
	-- sort by claim rank
	local comparator = function(a, b)
		local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
		local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
		local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
		return ranka < rankb
	end
	table.sort(sortindices, comparator)

	local result
	local error
	if list then
		local value
		-- iterate over all elements and return their value (if existing)
		result = {}
		for idx in pairs(claims) do
			local claim = claims[sortindices[idx]]
			value, error = getValueOfClaim(claim, qualifierId, parameter)
			if not value and showerrors then value = error end
			if value and references then value = value .. getReferences(frame, claim) end
			result[#result + 1] = value
		end
		result = table.concat(result, list)
	else
		-- return first element
		local claim = claims[sortindices[1]]
		result, error = getValueOfClaim(claim, qualifierId, parameter)
		if result and references then result = result .. getReferences(frame, claim) end
	end

	if result then return result else
		if showerrors then return error else return default end
	end
end

-- look into entity object
function p.ViewSomething(frame)
	local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
	local id = f.args.id
	if id and (#id == 0) then
		id = nil
	end
	local data = mw.wikibase.getEntity(id)
	if not data then
		return nil
	end

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			if type(data) == "table" then
				return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
			else
				return tostring(data)
			end
		end

		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end

		i = i + 1
	end
end

-- getting sitelink of a given wiki
-- get sitelink of current item if qid not supplied
function p.getSiteLink(frame)
	local qid = frame.args.qid
	if qid == "" then qid = nil end
	local f = mw.text.trim( frame.args[1] or "")
	local entity = mw.wikibase.getEntity(qid)
	if not entity then
		return
	end
	local link = entity:getSitelink( f )
	if not link then
		return
	end
	return link
end

function p.Dump(frame)
	local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
	local data = mw.wikibase.getEntity(f.args.id)
	if not data then
		return i18n.warnDump
	end

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
		end

		data = data[index] or data[tonumber(index)]
		if not data then
			return i18n.warnDump
		end

		i = i + 1
	end
end

return p