Moodul:Wikidata: erinevus redaktsioonide vahel

Eemaldatud sisu Lisatud sisu
uus versioon saksa vikist
Intgr (arutelu | kaastöö)
Uuendatud ingliskeelsest Wikipediast: en:Module:Wikidata
1. rida:
-- vim: set noexpandtab ft=lua ts=4 sw=4:
-- allikas: https://de.wikipedia.org/w/index.php?title=Modul:Wikidata&oldid=151025002
require('Module:No globals')
-- 3.02.2016 seisuga
 
local p = {}
-- module local variables
local wikidebug = false
 
 
------------------------------------------------------------------------------
-- module local variables and functions
 
local wiki =
{
langcode = mw.language.getContentLanguage().code
9. rida ⟶ 15. rida:
 
-- internationalisation
local i18n =
{
["errors"] = {
{
["property-not-found"] = "Omadust ei leitud.",
["entityproperty-not-found"] = "WikidataProperty andmeüksustnot ei leitudfound.",
["unknownentity-claimnot-typefound"] = "UnknownWikidata entity claimnot typefound.",
["unknown-entityclaim-type"] = "Unknown entityclaim type.",
["qualifierunknown-notentity-foundtype"] = "QualifierUnknown notentity foundtype.",
["sitequalifier-not-found"] = "Wikimedia siteQualifier 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 mldbillion aastatyears", -- precision: billion years
[1] = "$100 mlnmillion aastatyears", -- precision: hundred million years
[2] = "$10 mlnmillion aastatyears", -- precision: ten million years
[3] = "$1 mlnmillion aastatyears", -- precision: million years
[4] = "$100.,000 aastatyears", -- precision: hundred thousand years
[5] = "$10.,000 aastatyears", -- precision: ten thousand years
[6] = "$1. aastatuhatmillennium", -- precision: milleniummillennium
[7] = "$1. sajandcentury", -- precision: century
[8] = "$1er1s", -- precision: decade
-- the following use the format of #time parser function
[9] = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[11] = "j. F j, Y", -- precision: day
[12] = 'j. "F Yj, Y ga"kell" G', -- precision: hour
[13] = "j. F j, Y Gg:iia", -- precision: minute
[14] = "j. F j, Y Gg:i:ssa", -- precision: second
["beforenow"] = "vor $1 BCE", -- how to format negative numbers for precisions 0 to 5
["afternow"] = "in $1 CE", -- how to format positive numbers for precisions 0 to 5
["bc"] = '$1 "eKr.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]]",
["FETCH_WIKIDATA"] = "ABFRAGE_WIKIDATA"
["ordinal"] =
{
[1] = "st",
[2] = "nd",
[3] = "rd",
["default"] = "th"
}
}
 
--require("Module:i18n").loadI18n("Module:Wikidata/i18n", i18n)
--important properties
-- got idea from [[:w:Module:Wd]]
local propertyId = {
local module_title; if ... == nil then
["starttime"] = "P580",
module_title = mw.getCurrentFrame():getTitle()
["endtime"] = "P582"
else
}
module_title = ...
end
require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
 
-- this function needs to be internationalised along with the above:
local formatchar = {
-- takes cardinal numer as a numeric and returns the ordinal as a string
[10] = {"n","m","M","F","xg"}, --precision: month
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
[11] = {"W","j","d","z","D","l","N","w"}, --precision: day
local function makeOrdinal (cardinal)
[12] = {"a","A","g","h","G","H"}, --precision: hour
local ordsuffix = i18n.ordinal.default
[13] = {"i"}, --precision: minute
if cardinal % 10 == 1 then
[14] = {"s","U"} --precision: second
ordsuffix = i18n.ordinal[1]
}
elseif cardinal % 10 == 2 then
 
ordsuffix = i18n.ordinal[2]
local p = { }
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
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local tstr = ""
-- use these as the second parameter and this function instead of the built-in "pairs" function
local lang_obj = mw.language.new(wiki.langcode)
-- to iterate over all qualifiers and snaks in the intended order.
local functionf_parts orderedpairs= mw.text.split(arrayf, 'Y', ordertrue)
iffor notidx, orderf_part then returnin pairs(arrayf_parts) enddo
year_suffix = ''
if string.match(f_part, "x[mijkot]$") then
-- return iterator function
-- for non-Gregorian year
local i = 0
f_part = f_part .. 'Y'
return function()
elseif idx < #f_parts then
i = i + 1
-- supress leading zeros in year
if order[i] then
year_suffix = lang_obj:formatDate('Y', timestamp)
return order[i], array[order[i]]
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
end
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
function p.descriptionIn(frame)
if string.sub(timestamp, 1, 1) == '-' then
local langcode = frame.args[1]
timestamp = '+' .. string.sub(timestamp, 2)
local id = frame.args[2]
addon = date_addon
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
end
local entity = mw.wikibase.getEntity(id)
local _date_format = i18n["datetime"]["format"][date_format]
if entity and entity.descriptions then
if _date_format ~= nil then
local desc = entity.descriptions[langcode or wiki.langcode]
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
if desc then return desc.value end
else
return printError("unknown-datetime-format")
end
end
 
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
function p.labelIn(frame)
-- with the millennium/century/decade handling of formatDate()
local langcode = frame.args[1]
local function parseDateFull(timestamp, precision, date_format, date_addon)
local id = frame.args[2]
local prefix_addon = i18n["datetime"]["prefix-addon"]
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
local entityaddon_sep = mw.wikibase.getEntity(id)i18n["datetime"]["addon-sep"]
local addon = ""
if entity and entity.labels then
 
local label = entity.labels[langcode or wiki.langcode]
-- check for negative date
if label then return label.value end
if string.sub(timestamp, 1, 1) == '-' then
timestamp = '+' .. string.sub(timestamp, 2)
addon = date_addon
end
end
 
-- get the next four characters after the + (should be the year now in all cases)
local function printDatavalueCoordinate(data, parameter)
-- ok, so this is dirty, but let's get it working first
-- data fields: latitude [double], longitude [double], altitude [double], precision [double], globe [wikidata URI, usually http://www.wikidata.org/entity/Q2 [earth]]
local intyear = tonumber(string.sub(timestamp, 2, 5))
if parameter then
if intyear == 0 and precision <= 9 then
if parameter == "globe" then data.globe = mw.ustring.match(data.globe, "Q%d+") end -- extract entity id from the globe URI
return data[parameter]""
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")
return data.latitude .. "/" .. data.longitude -- combine latitude and longitude, which can be decomposed using the #titleparts wiki function
end
end
 
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local function printDatavalueQuantity(data, parameter)
-- use these as the second parameter and this function instead of the built-in "pairs" function
-- data fields: amount [number], unit [string], upperBound [number], lowerBound [number]
-- to iterate over all qualifiers and snaks in the intended order.
if not parameter or parameter == "amount" then
local function orderedpairs(array, order)
return tonumber(data.amount)
if not order then return pairs(array) end
elseif parameter == "unit" then
 
return mw.ustring.match(data.unit, "Q%d+")
-- return iterator function
else
local i = 0
return data[parameter]
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, "+")
134. rida ⟶ 249. rida:
end
 
local function formatDate(date, precision, timezone)
-- 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
function formatDate(date, precision, timezone, formatstr)
precision = precision or 11
local date, year = normalizeDate(date)
date = string.gsub(date, "-00%f[%D]", "-01")
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)
150. rida ⟶ 263. rida:
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end
 
-- precision is decades, centuries and milleniamillennia
local era
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
164. rida ⟶ 277. rida:
return era
end
 
-- precision is years or lessyear
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)
176. rida ⟶ 294. rida:
end
]]--
 
if formatstr then
local formatstr = i18n.datetime[precision]
for i=(precision+1), 14 do
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], "")
elseif year < 0 then
196. rida ⟶ 305. rida:
end
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
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
221. rida ⟶ 311. rida:
-- 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
232. rida ⟶ 322. rida:
local linkName = mw.wikibase.label(id)
if linkTarget then
-- if there is a local Wikipedia article link to it using the label or the article title
local link = linkTarget
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
-- if there is a local Wikipedia article linking to it, use the label or the article title
if linkName and (linkName ~= linkTarget) then link = link .. "|" .. linkName end
return "[[" .. link .. "]]"
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
245. rida ⟶ 333. rida:
else
return mw.wikibase.label(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
258. rida ⟶ 359. rida:
end
 
local function getSnakValuefindClaims(snakentity, parameterproperty)
if not property or not entity or not entity.claims then return end
-- snaks have three types: "novalue" for null/nil, "somevalue" for not null/not nil, or "value" for actual data
 
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
273. rida ⟶ 387. rida:
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,
290. rida ⟶ 404. rida:
end
 
local function datavalueTimeToDateObjectgetValueOfClaim(dataclaim, 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 snak
352. rida ⟶ 415. rida:
end
 
local function getReferences(frame, claim)
local result = ""
-- traverse through all references
361. rida ⟶ 424. rida:
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.label(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
373. rida ⟶ 436. rida:
end
 
local function hasqualifierparseInput(claim, qualifierpropertyframe)
local negotiateqid = frame.args.qid
if string.sub(qualifierproperty,qid 1,and 1)(#qid == "!"0) then negotiate = true else negotiateqid = falsenil end
local propertyID = mw.text.trim(frame.args[1] or "")
if not claim.qualifiers and not negotiate then return false end
local input_parm = mw.text.trim(frame.args[2] or "")
if not claim.qualifiers and negotiate then return true end
if input_parm ~= "FETCH_WIKIDATA" then
if qualifierproperty == '' then return true end
return false, input_parm, nil, nil
if not negotiate and not claim.qualifiers[qualifierproperty] then return false end
end
if negotiate and claim.qualifiers[string.sub(qualifierproperty, 2)] then return false end
local entity = mw.wikibase.getEntityObject(qid)
return true
local claims
end
if entity and entity.claims then
 
claims = entity.claims[propertyID]
local function hassource(claim, sourceproperty)
if not claim.referencesclaims then return false end
return false, "", nil, nil
if sourceproperty == '' then return true end
if string.sub(sourceproperty,1,1) ~= "!" then
for _, source in pairs(claim.references) do
if source.snaks[sourceproperty] then return true end
end
return false
else
return false, "", nil, nil
for _, source in pairs(claim.references) do
end
for key in pairs(source.snaks) do
return true, entity, claims, propertyID
if key ~= string.sub(sourceproperty,2) then return true end
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.sitelink(qnumber)
local label = labelHook(qnumber) or mw.wikibase.label(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 falsetable.concat(out, delim)
else
-- just return best values
return entity:formatPropertyValues(propertyID).value
end
end
 
------------------------------------------------------------------------------
function atdate(claim, mydate)
-- module global functions
local refdate
 
if not mydate or mydate == "" then
if debug then
refdate = os.date("!*t")
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.getEntityObject(id).descriptions[langcode or wiki.langcode].value
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.getEntityObject(id).labels[langcode or wiki.langcode].value
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
if string.match(mydate, "^%d+$") then
end
refdate = { year = tonumber(mydate) }
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.getEntityObject()
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
refdate = datavalueTimeToDateObject({ time = mw.language.getContentLanguage():formatDate("+Y-m-d\\TH:i:s\\Z", mydate) })
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.sitelink(qnumber)) then
return "[[" .. mw.wikibase.sitelink(qnumber) .. "]]"
else
return "[[:d:" .. qnumber .. "|" ..qnumber .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return (getQualifier(frame, outputValue))
local refjd = julianDay(refdate)
local mindate = getQualifierSortValue(claim, propertyId["starttime"])
local maxdate = getQualifierSortValue(claim, propertyId["endtime"])
if mindate and mindate > refjd then return false end
if maxdate and maxdate < refjd then return false end
return true
end
 
-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
--returns a table of claims excluding claims not passed the filters
p.getRawValue = function(frame)
function filterClaims(frame, claims)
local go, errorOrentity, claims, propertyID = parseInput(frame)
local function filter(condition, filterfunction)
if not frame.args[condition]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.label("Q" .. value.datavalue.value["numeric-id"])
else
return value.datavalue.value
end
end
local newclaims = {}
local ret, gotData = getQualifier(frame, outputHook)
for i, claim in pairs(claims) do
if gotData then
if filterfunction(claim, frame.args[condition]) then
ret = string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
table.insert(newclaims, claim)
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.getEntityObject()
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
claims = newclaims
end
local ret = table.concat(out, "<br> ")
if #ret == 0 then
ret = "Invalid TA"
end
return ret
end
 
--[[
filter('hasqualifier', hasqualifier)
This is used to return an image legend from Wikidata
filter('hassource', hassource)
image is property P18
filter('atdate', atdate)
image legend is property P2096
 
Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
return claims
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.getEntityObject(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)
local entity = mw.wikibase.getEntityObject()
if not entity then return nil else return entity.id end
end
 
451. rida ⟶ 870. rida:
local qualifierId = frame.args["qualifier"]
local parameter = frame.args["parameter"]
local language = frame.args["language"]
local list = frame.args["list"]
local includeempty = frame.args["includeempty"]
local references = frame.args["references"]
local sort = frame.args["sort"]
local sortInItem = frame.args["sortInItem"]
local inverse = frame.args["inverse"]
local showerrors = frame.args["showerrors"]
local default = frame.args["default"]
463. rida ⟶ 877. rida:
 
-- get wikidata entity
local entity = mw.wikibase.getEntitygetEntityObject(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 entity.claims then claims = entity.claims[mw.wikibase.resolvePropertyId(property)] end
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
end
 
--filter claims
claims = filterClaims(frame, claims)
if not claims[1] then return default end
 
-- get initial sort indices
483. rida ⟶ 892. rida:
sortindices[#sortindices + 1] = idx
end
-- sort by claim rank
local comparator = function(a, b)
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
if sort then
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
-- sort by time qualifier
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
comparator = function(a, b)
return ranka < rankb
local timea = getQualifierSortValue(claims[a], sort) or ''
end
local timeb = getQualifierSortValue(claims[b], sort) or ''
if type(timea) ~= type(timeb) and not (tonumber(timea) and tonumber(timeb)) then
if tonumber(timea) then return true
elseif tonumber(timeb) then return false
elseif tostring(timea) and tostring(timeb) then
if inverse then return tostring(timea) > tostring(timeb) else return tostring(timea) < tostring(timeb) end
else return false end -- different types, neither numbers nor strings, no chance to compare => random result to avoid script error
elseif tonumber(timea) and tonumber(timeb) then
timea = tonumber(timea)
timeb = tonumber(timeb)
end
if inverse then
return timea > timeb
else
return timea < timeb
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
table.sort(sortindices, comparator)
 
543. rida ⟶ 904. rida:
local error
if list then
list = string.gsub(list, "\\n", "\n") -- if a newline is provided (whose backslash will be escaped) unescape it
local value
-- iterate over all elements and return their value (if existing)
549. rida ⟶ 909. rida:
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
value, error = getValueOfClaim(claim, qualifierId, parameter)
if not value and value ~= 0 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
result[#result + 1] = value
557. rida ⟶ 916. rida:
result = table.concat(result, list)
else
-- return first element
local claim = claims[sortindices[1]]
result, error = getValueOfClaim(claim, qualifierId, parameter)
if 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 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.getValue(frame)
function p.ViewSomething(frame)
local param = frame.args[2]
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
if param == "FETCH_WIKIDATA" or param == i18n["FETCH_WIKIDATA"] then return p.claim(frame) else return param end
local id = f.args.id
end
if id and (#id == 0) then
id = nil
end
local data = mw.wikibase.getEntityObject(id)
if not data then
return nil
end
 
local i = 1
function p.pageId(frame)
while true do
local id = frame.args[1]
local entityindex = mwf.wikibase.getEntity(id)args[i]
if not entityindex then return nil else return entity.id end
if type(data) == "table" then
end
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)]
function p.labelOf(frame)
if not data then
local id = frame.args[1]
return
-- returns the label of the given entity/property id
end
-- if no id is given, the one from the entity associated with the calling Wikipedia article is used
 
if not id then
i = i + 1
local entity = mw.wikibase.getEntity()
if not entity then return printError("entity-not-found") end
id = entity.id
end
return mw.wikibase.label(id)
end
 
-- getting sitelink of a given wiki
function p.sitelinkOf(frame)
-- get sitelink of current item if qid not supplied
local id = frame.args[1]
function p.getSiteLink(frame)
-- returns the Wikipedia article name of the given entity
local qid = frame.args.qid
-- if no id is given, the one from the entity associated with the calling Wikipedia article is used
if notqid id== "" then qid = nil end
local entityf = mw.wikibasetext.getEntitytrim( frame.args[1] or "")
local entity = mw.wikibase.getEntity(qid)
if not entity then return printError("entity-not-found") end
id if =not entity.id then
return
end
local link = entity:getSitelink( f )
if not link then
return
end
return mw.wikibase.sitelink(id)link
end
 
function p.badgesDump(frame)
local sitef = (frame.args[1] or frame.args.id) and frame or frame:getParent()
local iddata = framemw.wikibase.getEntityObject(f.args[2].id)
if not sitedata then return printError("site-not-found") end
return i18n.warnDump
local entity = mw.wikibase.getEntity(id)
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
 
local i = 1
function p.sitelinkCount(frame)
while true do
local filter = "^.*" .. (frame.args[1] or "") .. "$"
local idindex = framef.args[2i]
if not index then
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
local entity = mw.wikibase.getEntity(id)
local count = 0
if entity and entity.sitelinks then
for project, _ in pairs(entity.sitelinks) do
if string.find(project, filter) then count = count + 1 end
end
end
return count
end
 
data = data[index] or data[tonumber(index)]
-- call this in cases of script errors within a function instead of {{#invoke:Wikidata|<method>|...}} call {{#invoke:Wikidata|debug|<method>|...}}
if not data then
function p.debug(frame)
return i18n.warnDump
local func = frame.args[1]
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
 
frame.args = newargs
i = i + 1
local status, result = pcall(p[func], frame)
if status then return result else return '<span class="error">' .. result .. '</span>' end
else
return '<span class="error">invalid parameters</span>'
end
end
 
function p.printEntity(frame)
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