Modul:Wikidata: Perbedaan antara revisi

Konten dihapus Konten ditambahkan
pranala lokal dan pranala Wikidata (titik kecil)
Farras (bicara | kontrib)
k update
Baris 1:
-- vim: set noexpandtab ft=lua ts=4 sw=4:
-- version 20190319 from master @cawiki
require('Module:No globals')
 
local p = {}
local debug = false
 
 
-----------------------------------------------------------------------------
------------------------------------------------------------------------------
-- internationalisation at [[Module:Wikidata/i18n]]
-- module local i18nvariables =and {functions
 
["errors"] = {
local wiki =
{
langcode = mw.language.getContentLanguage().code
}
 
-- internationalisation
local i18n =
{
["errors"] =
{
["property-not-found"] = "Property not found.",
["entity-not-found"] = "Wikidata entity not found.",
Baris 14 ⟶ 26:
["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.",
['not-from-content-page'] = "Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing ."
},
["datetime"] =
Baris 24 ⟶ 35:
[2] = "$10 million years", -- precision: ten million years
[3] = "$1 million years", -- precision: million years
[4] = "$100000100,000 years", -- precision: hundred thousand years; thousand separators added afterwards
[5] = "$1000010,000 years", -- precision: ten thousand years; thousand separators added afterwards
[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
Baris 36 ⟶ 47:
[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()
["bc-addon"] = " BC", -- suffix for negative dates
["addefault-addonformat"] = "dmy" , -- suffixdefault value forof 1stthe century#3 AD(getDateValue) datesor
-- #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"] =
["cite"] = { -- Cite web parameters
{
["url"] = "url",
["title"1] = "titlest",
["website"2] = "websitend",
["access-date"3] = "access-daterd",
["archive-urldefault"] = "archive-urlth",
["archive-date"] = "archive-date",
["author"] = "author",
["publisher"] = "publisher",
["quote"] = "quote",
["language"] = "language",
["date"] = "date",
["pages"] = "pages"
}
}
 
if wiki.langcode ~= "en" then
local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
--require("Module:i18n").loadI18n("Module:Wikidata/i18n", i18n)
 
-- got idea from [[:w:Module:Wd]]
local wiki =
local module_title; if ... == nil then
{
module_title = mw.getCurrentFrame():getTitle()
langcode = mw.language.getContentLanguage().code,
else
module_title = "Module:Wikidata",
module_title = ...
module_planetsData = "Module:Mapa cos celeste/dades" -- data for astronomical objects, maps for non Earth globes
}
 
----------------------------------------------------------------------------
-- module local functions
 
-- Credit to http://stackoverflow.com/a/1283608/2644759
-- cc-by-sa 3.0
local function tableMerge(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
tableMerge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
return t1
end
 
-- this function needs to be internationalised along with the above:
local function loadI18n()
-- takes cardinal numer as a numeric and returns the ordinal as a string
local exist, res = pcall(require, wiki.module_title .. "/i18n")
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
if exist and next(res) ~= nil then
local function makeOrdinal (cardinal)
tableMerge(i18n, res.i18n)
local ordsuffix = i18n.ordinal.default
cases = res.cases
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)
loadI18n()
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
 
local function case(word, localcase, lang)
if word == nil or word == '' or cases[localcase] == nil then
return word
end
return cases[localcase](word, lang)
end
local function parseDateFormat(f, timestamp, addon, prefix_addon, addon_sep)
 
local year_suffix
local function findLang(langcode)
local tstr = ""
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
local myframelang_obj = mw.getCurrentFramelanguage.new(wiki.langcode)
local f_parts = mw.text.split(f, 'Y', true)
langcode = myframe.args.lang
for idx, f_part in pairs(f_parts) do
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
year_suffix = ''
langcode = myframe:getParent().args.lang
if string.match(f_part, "x[mijkot]$") then
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
-- for non-Gregorian year
if not mw.title.getCurrentTitle().isContentPage then
f_part = f_part .. 'Y'
langcode = myframe:preprocess( '{{int:lang}}' )
elseif idx < #f_parts then
end
-- supress leading zeros in year
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
year_suffix = lang_obj:formatDate('Y', timestamp)
langcode = wiki.langcode
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
local languages = mw.language.getFallbacksFor(langcode)
return addon .. addon_sep .. tstr
table.insert(languages, 1, langcode)
elseif addon ~= "" then
return languages
return tstr .. addon_sep .. addon
end
 
-- mw.wikibase.getLabelWithLang or getLabelByLang with a table of languages
local function getLabelByLangs(id, languages)
local label
local lang = languages[1]
if lang == wiki.langcode then
-- using getLabelWithLang when possible instead of getLabelByLang
label, lang = mw.wikibase.getLabelWithLang(id)
else
return tstr
for _, l in ipairs(languages) do
label = mw.wikibase.getLabelByLang(id, l)
lang = l
if label then
break
end
end
end
return label, lang
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
-- Is gender femenine? true or false
if string.sub(timestamp, 1, 1) == '-' then
local function feminineGender(id)
timestamp = '+' .. string.sub(timestamp, 2)
local claims = mw.wikibase.getBestStatements(id or mw.wikibase.getEntityIdForCurrentPage(),'P21')
addon = date_addon
if #claims == 0 then
end
return false
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")
local genderId = claims[1].mainsnak.datavalue.value.id
if genderId == "Q6581072" or genderId == "Q1052281" or genderId == "Q43445" then -- female, transgender female, female organism
return true
end
end
return false
end
 
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
-- Fetch female form of label
-- with the millennium/century/decade handling of formatDate()
local function feminineForm(id, lang)
local function parseDateFull(timestamp, precision, date_format, date_addon)
local feminine_claims = mw.wikibase.getBestStatements(id, 'P2521') -- female form of label
local prefix_addon = i18n["datetime"]["prefix-addon"]
for _, feminine_claim in ipairs(feminine_claims) do
local addon_sep = i18n["datetime"]["addon-sep"]
if feminine_claim.mainsnak.datavalue.value.language == lang then
local addon = ""
return feminine_claim.mainsnak.datavalue.value.text
 
end
-- check for negative date
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)
-- Fetch unit symbol
-- ok, so this is dirty, but let's get it working first
local function unitSymbol(id, lang)
local claimsintyear = findClaimstonumber(mwstring.wikibase.getEntitysub(id)timestamp, 'P5061'2, 5))
if intyear == 0 and precision <= 9 then
local langclaims = {}
return ""
if claims then
for _, snak in ipairs(claims) do
if snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value and
not langclaims[snak.mainsnak.datavalue.value.language] -- just the first one by language
then
langclaims[snak.mainsnak.datavalue.value.language] = snak.mainsnak.datavalue.value.text
end
end
for _, l in ipairs(lang) do
if langclaims[l] then
return langclaims[l]
end
end
end
return langclaims["mul"] -- last try
end
 
-- precision is 10000 years or more
-- Add a small pencil as icon for edit on Wikidata
if precision <= 5 then
local function addEditIcon(id, lang, uselang, icon)
local factor = 10 ^ ((5 - precision) + 4)
if icon and lang ~= uselang then
local y2 = math.ceil(math.abs(intyear) / factor)
return " [[File:Arbcom ru editing.svg|12px|" .. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain() .. "|link=d:" .. id .. "]]"
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
return ''
end
 
-- precision is decades (8), centuries (7) and millennia (6)
local function urlEscapes(text)
local era, card
-- escape URL escapes to avoid Lua captures
if precision == 6 then
return mw.ustring.gsub(text, "(%%%d)", "%%%1")
card = math.floor((intyear - 1) / 1000) + 1
end
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
 
local function expandBraces(text, formatting)
if text == nil or formatting == nil then return text end
-- only expand braces if provided in argument, not included in value as in Q1164668
if mw.ustring.find(formatting, '{{', 1, true) == nil then return text end
if type(text) ~= "string" then
text = tostring(text)
end
if precision == 7 then
card = math.floor((intyear - 1) / 100) + 1
for braces in mw.ustring.gmatch(text, "{{(.-)}}") do
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
local parts = mw.text.split(braces, "|")
end
local title_part = parts[1]
if precision == 8 then
local parameters = {}
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
for i = 2, #parts do
end
if mw.ustring.find(parts[i], "=") then
if era then
local subparts = mw.text.split(parts[i], "=")
if addon ~= "" then
parameters[subparts[1]] = subparts[2]
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
else
table.insert(parameters, parts[i])
end
end
local braces_expanded
if mw.ustring.find(title_part, ":")
and mw.text.split(title_part, ":")[1] ~= mw.site.namespaces[10].name -- not a prefix Template:
then
braces_expanded = mw.getCurrentFrame():callParserFunction{name=title_part, args=parameters}
else
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
braces_expanded = mw.getCurrentFrame():expandTemplate{title=title_part, args=parameters}
end
return era
braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
braces_expanded = urlEscapes(braces_expanded)
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
return text
end
 
local _date_format = i18n["datetime"]["format"][date_format]
local function printDatatypeMath(data)
if _date_format ~= nil then
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
-- check for precision is year and override supplied date_format
end
if precision == 9 then
 
_date_format = i18n["datetime"][9]
local function printDatavalueString(data, parameters)
end
if parameters.formatting == 'weblink' then
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
return '[' .. data .. ' ' .. mw.text.split(data, '//' )[2] .. ']'
elseif mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
--local escaped_data = mw.ustring.gsub(data, "%%", "%%%") -- escape % character, normally used in url, avoiding invalid capture in gsub
-- done in expandBraces
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', data), parameters.formatting)
elseif parameters.case then
return case(data, parameters.case, parameters.lang[1])
else
return printError("unknown-datetime-format")
return data
end
end
 
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local function printDatavalueUrl(data, parameters)
-- use these as the second parameter and this function instead of the built-in "pairs" function
-- escape URL escapes to avoid Lua captures
-- to iterate over all qualifiers and snaks in the intended order.
return printDatavalueString(urlEscapes(data), parameters)
local function orderedpairs(array, order)
end
if not order then return pairs(array) end
 
local function printDatavalueCoordinate(data, parameter)
-- return iterator function
if parameter == 'latitude' then
local i = 0
return data.latitude
return function()
elseif parameter == 'longitude' then
i = i + 1
return data.longitude
if order[i] then
elseif parameter == 'dimension' then
return data.dimensionorder[i], array[order[i]]
else --default formatting='globe'
if data.globe == '' or data.globe == nil or data.globe == 'http://www.wikidata.org/entity/Q2' then
return 'earth'
else
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
if pcall(require, wiki.module_planetsData) then
local globetable = mw.loadData(wiki.module_planetsData)
for _, globe in pairs(globetable.maps) do
if globe.wikidata == globenum then
return globe.coord_globe
end
end
end
return globenum
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 printDatavalueQuantity(data, parameters)
local function normalizeDate(date)
-- exemples: 277±1 Centímetre, 1,94 metre
date = mw.text.trim(date, "+")
local amount = data.amount
-- extract year
amount = mw.ustring.gsub(amount, "%+", "")
local sortkeyyearstr = stringmw.formatustring.match(date, "^\-?%09dd+", amount)
local year = tonumber(yearstr)
amount = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
-- remove leading zeros of year
-- This is used to get the unit name for a numeric value
return year .. mw.ustring.sub(date, #yearstr + 1), year
local suffix = ""
if parameters.formatting == "unit" or parameters.formatting == "unitcode" then
-- get the url for the unit entry on Wikidata:
local unitID = data.unit
-- and just return the last bit from "Q" to the end (which is the QID):
unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)
if mw.ustring.sub(unitID, 1, 1) == "Q" then
if parameters.formatting == "unitcode" then
local unit_symbol = ''
if parameters.lang[1] == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
unit_symbol = require(wiki.module_title .. "/Units").getUnit(amount, '', unitID, true, '')
end
if unit_symbol == '' then
unit_symbol = unitSymbol(unitID, parameters.lang)
if not unit_symbol then
local unit_label, lang = getLabelByLangs(unitID, parameters.lang)
unit_symbol = unit_label .. addEditIcon(unitID, lang, parameters.lang[1], parameters.editicon)
end
end
suffix = " " .. unit_symbol
else
local unit_label, lang = getLabelByLangs(unitID, parameters.lang)
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
suffix = " " .. require(wiki.module_title .. "/Units").getUnit(amount, unit_label, unitID, false, '')
else
suffix = " " .. (unit_label or unitID) .. addEditIcon(unitID, lang, parameters.lang[1], parameters.editicon)
end
end
end
end
return amount .. suffix, sortkey
end
 
local function printDatavalueTimeformatDate(datadate, parametersprecision, timezone)
precision = precision or 11
-- Dates and times are stored in ISO 8601 format
local timestampdate, year = data.timenormalizeDate(date)
if year == 0 and precision <= 9 then return "" end
local sortkey = timestamp
 
local addon = ""
local calendar_add = ""
-- check for negative date, ex. "-0027-01-16T00:00:00Z"
if string.sub(timestamp, 1, 1) == '-' then
timestamp = '+' .. string.sub(timestamp, 2)
addon = i18n.datetime["bc-addon"]
elseif string.sub(timestamp, 2, 3) == '00' then
addon = i18n.datetime["ad-addon"]
else
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
if (timestamp < "+1582-10-15T00:00:00Z" and calendar_model[calendar_id] == "gregorian")
or (timestamp > "+1582-10-04T00:00:00Z" and calendar_model[calendar_id] == "julian")
then
calendar_add = " <sup>(" .. mw.message.new('Wikibase-time-calendar-' .. calendar_model[calendar_id]):inLanguage(parameters.lang[1]):plain() .. ")</sup>"
end
end
local function d(f, t)
local ts = t or timestamp
local form = type(f) == "function" and f(ts) or f -- function in i18n.datetime[precision]
return mw.language.new(parameters.lang[1]):formatDate(form, ts) .. addon .. calendar_add
end
local precision = data.precision or 11
local intyear = tonumber(mw.ustring.match(timestamp, "^\+?%d+"))
local ret = ""
-- precision is 10000 years or more
if precision <= 5 then
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(intyearyear) / factor)
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if addonyear ==< i18n.datetime["bc-addon"]0 then
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
-- negative date
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
retrelative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
local ret_number = string.match(ret, "%d+")
end
if ret_number ~= nil then
 
ret = mw.ustring.gsub(ret, ret_number, mw.language.new(parameters.lang[1]):formatNum(tonumber(ret_number)))
-- 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
]]--
-- precision is millennia, centuries or decades
 
elseif precision == 6 then
local cardformatstr = mathi18n.floor((intyear - 1) / 1000) + 1datetime[precision]
if year == 0 then formatstr = mw.ustring.findgsub(formatstr, i18n.datetime[69], "$1") then
elseif year < 0 then
ret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(card)) .. addon .. calendar_add
-- Mediawiki formatDate doesn't support negative years
else
date = mw.ustring.sub(date, 2)
ret = d(i18n.datetime[6], string.format("%04d", tostring(card)))
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)
elseif precision == 7 then
local card = math.floor((math.abs(intyear) - 1) / 100) + 1
if mw.ustring.find(i18n.datetime[7], "$1") then
ret = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(card)) .. addon .. calendar_add
else
ret = d(i18n.datetime[7], string.format("%04d", tostring(card)))
end
elseif precision == 8 then
local card = math.floor(math.abs(intyear) / 10) * 10
ret = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(card)) .. addon .. calendar_add
-- precision is year
elseif parameters.formatting == 'Y' or precision == 9 then
ret = tostring(intyear) .. addon .. calendar_add
-- precision is month
elseif precision == 10 then
timestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous month
ret, _ = string.gsub(d(i18n.datetime[10]), " 0+", " ") -- supress leading zeros in year
elseif parameters.formatting then
ret, _ = string.gsub(d(parameters.formatting), "([ %[])0+", "%1") -- supress leading zeros in year optionally linked
else
ret, _ = string.gsub(d(i18n.datetime[11]), " 0+", " ")
end
return ret, sortkey
end
 
local function printDatavalueEntity(data, parametersparameter)
-- data fields: entity-type [string], numeric-id [int, Wikidata id]
local entityId = data['id']
local id
local entityIdPreffix = data['entity-type'] == 'property' and "Property:" .. entityId or entityId
 
if parameters.formatting == 'raw' then
if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
return entityId, entityId
elseif data["entity-type"] == "property" then id = "P" .. data["numeric-id"]
else return printError("unknown-entity-type")
end
 
local label, lang = getLabelByLangs(entityId, parameters.lang)
if parameter then
local sitelink = mw.wikibase.getSitelink(entityId)
local if parameter == "link" parameters.formattingthen
local labelcaselinkTarget = label or mw.wikibase.sitelink(id)
local linkName = mw.wikibase.label(id)
if parameters.gender == 'feminineform' and lang ~= nil then -- case gender and item is female
if linkTarget then
labelcase = feminineForm(entityId, lang) or labelcase
-- if there is a local Wikipedia article link to it using the label or the article title
end
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
if parameters.case then
labelcase = case(labelcase, parameters.case, lang)
end
local ret1, ret2
if parameter == 'label' then
ret1 = (labelcase or entityId)
ret2 = labelcase or entityId
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'wikidata:' .. entityIdPreffix)
ret2 = sitelink or entityId
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
ret1 = mw.ustring.gsub(parameter, '$1', labelcase or entityId)
ret1 = expandBraces(ret1, parameter)
ret2 = labelcase or entityId
else
if parameter == "ucfirst" or parameter == "ucinternallink" then
labelcase = labelcase and mw.language.new(lang):ucfirst(labelcase)
-- only first of a list, reset formatting for next ones
if parameter == "ucinterlanllink" then
parameters.formatting = 'internallink'
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
parameters.formatting = nil -- default format
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
end
end
if sitelink then
ret1 = '[[' .. sitelink .. '|' .. labelcase .. ']]'
ret2 = labelcase
elseif label and (parameter == 'internallink' or parameter == 'ucinternallink') then
ret1 = '[[' .. label .. '|' .. labelcase .. ']]'
ret2 = labelcase
else
return data[parameter]
ret1 = '[[wikidata:' .. entityIdPreffix .. '|' .. (labelcase or entityId) .. ']]'
ret2 = labelcase or entityId
end
else
return mw.wikibase.label(id) or id
end
return ret1 .. addEditIcon(entityIdPreffix, lang, parameters.lang[1], parameters.editicon), ret2
end
 
local function printDatavalueMonolingualTextprintDatavalueTime(data, parametersparameter)
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
-- data fields: language [string], text [string]
-- 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 parameters.list == "lang" and data["language"] ~= parameters.lang[1] then
if parameter then
return
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
elseif parameters.formatting == "language" or parameters.formatting == "text" then
elseif parameter == "time" then data.time = normalizeDate(data.time) end
return data[parameters.formatting]
return data[parameter]
else
return formatDate(data.time, data.precision, data.timezone)
end
local result = data["text"]
if data["language"] ~= wiki.langcode then
result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
end
if mw.ustring.find((parameters.formatting or ''), '$', 1, true) then
-- output format defined with $text, $language
result = mw.ustring.gsub(parameters.formatting, '$text', result)
result = mw.ustring.gsub(result, '$language', data["language"])
end
return result
end
 
local function printErrorprintDatavalueMonolingualText(keydata, parameter)
-- data fields: language [string], text [string]
return '<span class="error">' .. i18n.errors[key] .. '</span>'
if parameter then
end
return data[parameter]
 
else
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
-- use these as the second parameter and this function instead of the built-in "pairs" function
return result
-- 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
 
local function findClaims(entity, property)
if not property or not entity or not entity.claims then return end
 
if not mw.ustring.match(property, "^P%d+$") then
-- getif the property is given by an id for(P..) access the givenclaim labellist by this id
return entity.claims[property]
else
property = mw.wikibase.resolvePropertyId(property)
if not property then return end
 
return entity.claims[property]
end
return entity.claims[property]
end
 
local function getSnakValue(snak, parametersparameter)
if snak.snaktype == '"value'" then
-- call the respective snak parser
if snak.datatypedatavalue.type == 'math'"string" then return snak.datavalue.value
elseif snak.datavalue.type == "globecoordinate" then return printDatatypeMathprintDatavalueCoordinate(snak.datavalue.value, parameter)
elseif snak.datatypedatavalue.type == "urlquantity" then return printDatavalueQuantity(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "time" then return printDatavalueUrlprintDatavalueTime(snak.datavalue.value, parametersparameter)
elseif snak.datavalue.type == "stringwikibase-entityid" then return printDatavalueEntity(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "monolingualtext" then return printDatavalueStringprintDatavalueMonolingualText(snak.datavalue.value, parametersparameter)
elseif snak.datavalue.type == "globecoordinate" then
return printDatavalueCoordinate(snak.datavalue.value, parameters.formatting)
elseif snak.datavalue.type == "quantity" then
return printDatavalueQuantity(snak.datavalue.value, parameters)
elseif snak.datavalue.type == "time" then
return printDatavalueTime(snak.datavalue.value, parameters)
elseif snak.datavalue.type == 'wikibase-entityid' then
return printDatavalueEntity(snak.datavalue.value, parameters)
elseif snak.datavalue.type == 'monolingualtext' then
return printDatavalueMonolingualText(snak.datavalue.value, parameters)
end
elseif snak.snaktype == 'novalue' then
return mw.message.new('Wikibase-snakview-snaktypeselector-novalue'):inLanguage(parameters.lang[1]):plain()
elseif snak.snaktype == 'somevalue' then
return mw.message.new('Wikibase-snakview-snaktypeselector-somevalue'):inLanguage(parameters.lang[1]):plain()
end
return mw.wikibase.renderSnak(snak)
end
 
local function getQualifierSnak(claim, qualifierId, parameters)
-- 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,
Baris 553 ⟶ 397:
if claim.qualifiers then
local qualifier = claim.qualifiers[qualifierId]
if qualifier then return qualifier[1] end
if qualifier[1].datatype == "monolingualtext" then
-- iterate over monolingualtext qualifiers to get local language
for idx in pairs(qualifier) do
if qualifier[idx].datavalue.value and qualifier[idx].datavalue.value.language == parameters.lang[1] then
return qualifier[idx]
end
end
elseif parameters.list then
return qualifier
else
return qualifier[1]
end
end
end
return nil, printError("qualifier-not-found")
Baris 575 ⟶ 406:
end
 
local function getValueOfClaim(claim, qualifierId, parametersparameter)
local error
local snak
snak, error = getQualifierSnak(claim, qualifierId, parameters)
if not snak then
return nilgetSnakValue(snak, nil, errorparameter)
else
elseif snak[1] then -- a multi qualifier
return nil, error
local result = {}
end
local sortkey = {}
end
for idx in pairs(snak) do
 
result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
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.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
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts .. getSnakValue(snakval[snakidx])
end
end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
return mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]
else -- a property or a qualifier
return getSnakValue(snak, parameters)
end
return result
end
 
local function getValueOfParentClaimparseInput(claim, qualifierId, parametersframe)
local qidsqid = mwframe.textargs.split(qualifierId, '/', true)qid
if qid and (#qid == 0) then qid = nil end
local valueraw, parent_claims, value, sortkey
local propertyID = mw.text.trim(frame.args[1] or "")
if qids[1] == parameters.property then
local input_parm = mw.text.trim(frame.args[2] or "")
valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=parameters.lang})
if input_parm ~= "FETCH_WIKIDATA" then
return false, input_parm, nil, nil
end
local entity = mw.wikibase.getEntityObject(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
valueraw, _, _ = getValueOfClaim(claim, qids[1], {["formatting"]="raw", ["lang"]=parameters.lang})
end
return true, entity, claims, propertyID
if string.sub(valueraw or '', 1, 1) == "Q" then -- protection for 'no value'
end
parent_claims = mw.wikibase.getBestStatements(valueraw, qids[2])
local function isType(claims, type)
if parent_claims[1] ~= nil then
return claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == type
value, sortkey, _ = getValueOfClaim(parent_claims[1], nil, parameters)
end
-- raw parent value needed fot while/black lists, lang for avoiding an error on types other than entity
local function getValue(entity, claims, propertyID, delim, labelHook)
valueraw, _, _ = getValueOfClaim(parent_claims[1], nil, {["formatting"]="raw", ["lang"]=parameters.lang})
if labelHook == nil then
labelHook = function (qnumber)
return nil;
end
end
if isType(claims, "wikibase-entityid") then
return value, sortkey, valueraw
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 table.concat(out, delim)
else
-- just return best values
return entity:formatPropertyValues(propertyID).value
end
end
 
------------------------------------------------------------------------------
local function getReferences(claim)
-- module global functions
local refaliases = {
 
citeWeb = "Q5637226",
if debug then
author = "P50",
function p.inspectI18n(frame)
publisher = "P123",
local val = i18n
importedFrom = "P143",
for _, key in pairs(frame.args) do
statedIn = "P248",
key = mw.text.trim(key)
pages = "P304",
val = val[key]
publicationDate = "P577",
end
startTime = "P580",
return val
endTime = "P582",
end
chapter = "P792",
end
retrieved = "P813",
 
referenceURL = "P854",
function p.descriptionIn(frame)
archiveURL = "P1065",
local langcode = frame.args[1]
title = "P1476",
local id = frame.args[2]
quote = "P1683",
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
shortName = "P1813",
return mw.wikibase.getEntityObject(id).descriptions[langcode or wiki.langcode].value
language = "P2439",
end
archiveDate = "P2960"
 
}
function p.labelIn(frame)
local result = ""
local langcode = frame.args[1]
-- traverse through all references
local id = frame.args[2]
for ref in pairs(claim.references or {}) do
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
local refparts
return mw.wikibase.getEntityObject(id).labels[langcode or wiki.langcode].value
local refs = {}
end
-- traverse through all parts of the current reference
 
for snakkey, snakval in pairs(claim.references[ref].snaks or {}) do
-- This is used to get a value, or a comma separated list of them if multiple values exist
if snakkey ~= refaliases.importedFrom then -- "imported from" is not a proper reference
p.getValue = function(frame)
for snakidx = 1, #snakval do
local delimdefault = ", " -- **internationalise later**
if snakidx > 1 then refparts = refparts .. ", " end
local delim = frame.args.delimiter or ""
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang={wiki.langcode}})
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
refs[snakkey] = refparts
refparts = nil
end
end
if label == nil or label == "" then return nil end
return label
-- get title of general template for citing web references
end
local template = mw.wikibase.getSitelink(refaliases.citeWeb) or ""
return getValue(errorOrentity, claims, propertyID, ", ", labelHook);
template = mw.text.split(template, ":")[2] -- split off namespace from front
end
 
-- (1) if both "reference URL" and "title" are present, then use the general template for citing web references
-- This is used to get a value, or a comma separated list of them if multiple values exist
if refs[refaliases.referenceURL] and (refs[refaliases.title] or refs[refaliases.statedIn]) and template then
-- from an arbitrary entry by using its QID.
local citeParams = {}
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
citeParams[i18n['cite']['url']] = refs[refaliases.referenceURL]
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
citeParams[i18n['cite']['title']] = refs[refaliases.title] or refs[refaliases.statedIn]:match("^%[%[.-|(.-)%]%]")
-- Please use sparingly - this is an *expensive call*.
citeParams[i18n['cite']['website']] = refs[refaliases.statedIn]
p.getValueFromID = function(frame)
citeParams[i18n['cite']['language']] = refs[refaliases.language]
local itemID = mw.text.trim(frame.args[1] or "")
citeParams[i18n['cite']['date']] = refs[refaliases.publicationDate]
local propertyID = mw.text.trim(frame.args[2] or "")
citeParams[i18n['cite']['access-date']] = refs[refaliases.retrieved]
local input_parm = mw.text.trim(frame.args[3] or "")
citeParams[i18n['cite']['archive-url']] = refs[refaliases.archiveURL]
if input_parm == "FETCH_WIKIDATA" then
citeParams[i18n['cite']['archive-date']] = refs[refaliases.archiveDate]
local entity = mw.wikibase.getEntity(itemID)
citeParams[i18n['cite']['publisher']] = refs[refaliases.publisher]
local claims
citeParams[i18n['cite']['quote']] = refs[refaliases.quote]
if entity and entity.claims then
citeParams[i18n['cite']['pages']] = refs[refaliases.pages]
claims = entity.claims[propertyID]
citeParams[i18n['cite']['author']] = refs[refaliases.author]
end
refparts = mw.getCurrentFrame():expandTemplate{title=template, args=citeParams}
if claims then
return getValue(entity, claims, propertyID, ", ")
else
--return raw ouput""
end
for k, v in orderedpairs(refs or {}, claim.references[ref]["snaks-order"]) do
else
if k and v then
return input_parm
if refparts then refparts = refparts .. ", " else refparts = "" end
end
refparts = refparts .. tostring(mw.wikibase.getLabel(k)) .. ": "
end
refparts = refparts .. v
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
end
else
if refparts then result = result .. mw.getCurrentFrame():extensionTag("ref", refparts) end
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))
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
 
-- ReturnThis theis siteused linkto (forget the currentunit site)name for athe numeric value givenreturned databy item.getRawValue
function p.getSiteLinkgetUnits = function(frame)
local go, errorOrentity, claims, propertyID = parseInput(frame)
if frame.args[1] == nil then
if not go then
entity = mw.wikibase.getEntity()
return errorOrentity
if not entity then
end
return nil
local entity = errorOrentity
end
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
id = entity.id
if isType(claims, "quantity") then
else
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
id = frame.args[1]
end
return result
return mw.wikibase.getSitelink(id)
end
 
-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
-- Set whitelist or blacklist values
p.getUnitID = function(frame)
local function setWhiteOrBlackList(type_list, num_qual, args)
local go, errorOrentity, claims = parseInput(frame)
local i = 0
if not go then
local listed = false
return errorOrentity
local list = {}
while i <= num_qual do
if args[type_list .. i] and args[type_list .. i] ~= '' then
listed = true
list[tostring(i)] = {}
local values = mw.text.split(args[type_list .. i], "/", true)
for _, v in ipairs(values) do
list[tostring(i)][v] = true
end
end
i = i + 1
end
local entity = errorOrentity
return list, listed
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)
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
local function p.pageIdoutputHook(framevalue)
if value.datavalue.value["numeric-id"] then
local entity = mw.wikibase.getEntityObject()
return mw.wikibase.label("Q" .. value.datavalue.value["numeric-id"])
if not entity then return nil else return entity.id end
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
function p.claim(frame)
-- Dates and times are stored in ISO 8601 format (sort of).
if mw.title.new(frame:getParent():getTitle()).isContentPage then
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
if not mw.title.new(frame:getTitle()).isSubpage then
-- So I'll just supply "Z" in the call to formatDate below:
-- invoked from a content page and not invoking a module subpage
p.getDateValue = function(frame)
return printError("not-from-content-page")
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 ptable._mainconcat(frame.argsout, frame:getParent().args", ")
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.
-- Entry point from other modules or debugging, with a list of arguments.
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
-- From other modules use: require("Module:Wikidata")._main({item="Q...", property="P...", ...})
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
-- On debug console use: =p._main({item="Q...", lang="xx", property="P...", ...})
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
function p._main(args, pargs)
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
--If a value is already set, use it
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
if args.value and args.value ~= '' then
p.getImages = function(frame)
return args.value
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
-- arguments
local out = {}
local id = args.item or (pargs and pargs.item)
for k, v in pairs(claims) do
if id == nil or id == "" then
local filename = v.mainsnak.datavalue.value
id = mw.wikibase.getEntityIdForCurrentPage()
out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
end
return table.concat(out, sep)
else
return ""
end
end
local languages = findLang(args.lang)
 
local itemgender = args["itemgender"]
-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
local idgender
-- 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
if itemgender then
-- uses the newer mw.wikibase calls instead of directly using the snaks
if string.match(itemgender, "^P%d+$") 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
local snak = mw.wikibase.getBestStatements(id, itemgender)[1]
p.getTAValue = function(frame)
if snak and snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value then
local ent = mw.wikibase.getEntityObject()
idgender = snak.mainsnak.datavalue.value.id
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
elseif string.match(itemgender, "^Q%d+$") then
idgender = itemgender
end
end
local propertyret = stringtable.upperconcat(args[out, "property"]<br> or "")
if #ret == 0 then
local qualifierId = {}
ret = "Invalid TA"
qualifierId[1] = args["qualifier"] and string.upper(args["qualifier"]) or nil
local i = 2
while args["qualifier" .. i] do
qualifierId[i] = string.upper(args["qualifier" .. i])
i = i + 1
end
return ret
local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
end
local case = args.case
 
local list = args["list"] or true; if (list == "false" or list == "no") then list = false end
--[[
local sorting_col = args.tablesort
This is used to return an image legend from Wikidata
local sorting_up = (args.sorting or "") ~= "-1"
image is property P18
local separator = args.separator
image legend is property P2096
local conjunction = args.conjunction or args.separator
 
local rowformat = args.rowformat
Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
local references = args["references"]
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
local showerrors = args["showerrors"]
If QID is omitted or blank, the current article is used (not an expensive call)
local default = args["default"]
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
local editicon = not (args.editicon == "false" or args.editicon == "no")
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447
 
local parameters = {["property"] = property, ["formatting"] = parameter, ["list"] = list, ["case"] = case,
Ranks are: 'preferred' > 'normal'
["lang"] = languages, ["editicon"] = editicon,
This returns the label from the first image with 'preferred' rank
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
Or the label from the first image with 'normal' rank if preferred returns nothing
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
-- defaults for table
]]
local preformat, postformat = "", ""
 
local whitelisted, blacklisted = false, false
p.getImageLegend = function(frame)
local whitelist, blacklist = {}, {}
-- look for named parameter id; if it's blank make it nil
if parameters.formatting == "table" then
local id = frame.args.id
parameters.separator = parameters.separator or "<br />"
if id and (#id == 0) then
parameters.conjunction = parameters.conjunction or "<br />"
id = nil
parameters.qseparator = ", "
end
parameters.qconjunction = ", "
 
if not rowformat then
-- look for named parameter lang
rowformat = "$0 ($1"
-- it should contain a two-character ISO-639 language code
i = 2
-- if it's blank fetch the language of the local wiki
while qualifierId[i] do
local lang = frame.args.lang
rowformat = rowformat .. ", $" .. i
if (not lang) or (#lang < 2) then
i = i + 1
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
rowformat = rowformat .. ")"
elseif if mw.ustring.find(rowformat,not "^[*#]"imglbl) then
for k1, v1 in pairs(imgs) do
parameters.separator = "</li><li>"
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
parameters.conjunction = "</li><li>"
local imglbls = v1.qualifiers.P2096
if mw.ustring.match(rowformat, "^[*#]") == "*" then
for k2, v2 in pairs(imglbls) do
preformat = "<ul><li>"
if v2.datavalue.value.language == lang then
postformat = "</li></ul>"
imglbl = v2.datavalue.value.text
else
break
preformat = "<ol><li>"
end
postformat = "</li></ol>"
end
end
end
end
rowformat = mw.ustring.gsub(rowformat, "^[*#] ?", "")
end
return imglbl
else
-- set whitelist and blacklist values
return input_parm
whitelist, whitelisted = setWhiteOrBlackList("whitelist", #qualifierId, args)
blacklist, blacklisted = setWhiteOrBlackList("blacklist", #qualifierId, args)
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
 
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.getEntitygetEntityObject(id)
if not entity then
if showerrors then return printError("entity-not-found") else return default end
Baris 833 ⟶ 888:
if showerrors then return printError("property-not-found") else return default end
end
 
-- set feminine case if gender is requested
local genderCase
local genderRequested = false
if parameters.case == "gender" or idgender then
genderRequested = true
elseif parameters.formatting == "table" then
if args["case0"] and args["case0"] == "gender" then
genderRequested = true
else
for i, qual in ipairs(qualifierId) do
if args["case" .. i] and args["case" .. i] == "gender" then
genderRequested = true
break
end
end
end
end
if genderRequested then
if feminineGender(idgender or id) then
genderCase = "feminineform"
if parameters.case == "gender" or idgender then
parameters.gender = genderCase
end
end
end
-- get initial sort indices
local sortindices = {}
Baris 868 ⟶ 897:
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 parameters.list or parameters.formatting == "table" then
local value
-- convert LF to line feed, <br /> may not work on some cases
parameters.separator = parameters.separator == "LF" and "\010" or parameters.separator
parameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction
-- i18n separators
parameters.separator = parameters.separator or mw.message.new('Comma-separator'):inLanguage(parameters.lang[1]):plain()
parameters.conjunction = parameters.conjunction or (mw.message.new('And'):inLanguage(parameters.lang[1]):plain() .. mw.message.new('Word-separator'):inLanguage(parameters.lang[1]):plain())
-- iterate over all elements and return their value (if existing)
result = {}
local value, valueq
local sortkey, sortkeyq
local values = {}
local sortkeys = {}
local refs = {}
local firstrank = parameters.list == "firstrank" and claims[sortindices[1]].rank or ''
local rowlist = {} -- rows to list with whitelist or blacklist
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
value, error = getValueOfClaim(claim, qualifierId, parameter)
local reference={}
if not whitelisted then rowlist[idx] = true end
if firstrank ~= '' and firstrank ~= claim.rank then
break
end
if parameters.formatting == "table" then
local params = mw.clone(parameters)
params.formatting = args["colformat0"]; if params.formatting == "" then params.formatting = nil end
if args["case0"] then
if args["case0"] == "gender" then
params.gender = genderCase
else
params.case = args["case0"]
end
end
value, sortkey, error = getValueOfClaim(claim, nil, params)
if value then
values[#values + 1] = {}
sortkeys[#sortkeys + 1] = {}
refs[#refs + 1] = {}
if whitelist["0"] or blacklist["0"] then
local valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=params.lang})
if whitelist["0"] and whitelist["0"][valueraw or ""] then
rowlist[#values] = true
elseif blacklist["0"] and blacklist["0"][valueraw or ""] then
rowlist[#values] = false
end
end
for i, qual in ipairs(qualifierId) do
local j = tostring(i)
params.formatting = args["colformat" .. j]; if params.formatting == "" then params.formatting = nil end
params.case = parameters.case
params.gender = parameters.gender
if args["case" .. j] then
if args["case" .. j] == "gender" then
params.gender = genderCase
else
params.case = args["case" .. j]
end
end
local valueq, sortkeyq, valueraw
if qual == property then -- hack for getting the property with another formatting, i.e. colformat1=raw
valueq, sortkeyq, _ = getValueOfClaim(claim, nil, params)
else
for q in mw.text.gsplit(qual, '%s*OR%s*') do
if string.find(q, ".+/.+") then
valueq, sortkeyq, valueraw = getValueOfParentClaim(claim, q, params)
elseif string.find(q, "^/.+") then
local claim2 = findClaims(entity, string.sub(q, 2))
if claim2 then
valueq, sortkeyq, _ = getValueOfClaim(claim2[1], nil, params)
end
else
valueq, sortkeyq, _ = getValueOfClaim(claim, q, params)
end
if valueq then break end
end
end
values[#values]["col" .. j] = valueq
sortkeys[#sortkeys]["col" .. j] = sortkeyq or valueq
if whitelist[j] or blacklist[j] then
valueq = valueraw or getValueOfClaim(claim, qual, {["formatting"]="raw", ["lang"]=params.lang})
if whitelist[j] and whitelist[j][valueq or ""] then
rowlist[#values] = true
elseif blacklist[j] and blacklist[j][valueq or ""] then
rowlist[#values] = false
end
end
end
end
else
value, sortkey, error = getValueOfClaim(claim, qualifierId[1], parameters)
values[#values + 1] = {}
sortkeys[#sortkeys + 1] = {}
refs[#refs + 1] = {}
end
if not value and showerrors then value = error end
if value and references then value = value .. getReferences(frame, claim) end
if value then
if references and claim.references then reference=claim.references end
refs[#refs]["col0"] =reference
values[#values]["col0"] = value
sortkeys[#sortkeys]["col0"] = sortkey or value
end
end
-- sort and format results
sortindices = {}
for idx in pairs(values) do
sortindices[#sortindices + 1] = idx
end
if sorting_col then
local sorting_table = mw.text.split(sorting_col, '/', true)
local comparator = function(a, b)
local valuea, valueb
local i = 1
while valuea == valueb and i <= #sorting_table do
valuea = sortkeys[a]["col" .. sorting_table[i]] or ''
valueb = sortkeys[b]["col" .. sorting_table[i]] or ''
i = i + 1
end
if sorting_up then
return valueb > valuea
end
return valueb < valuea
end
table.sort(sortindices, comparator)
end
result = {}
for idx in pairs(values) do
local valuerow = values[sortindices[idx]]
local reference = getReferences({["references"] = refs[sortindices[idx]]["col0"]})
 
value = valuerow["col0"]
if parameters.formatting == "table" then
if not rowlist[sortindices[idx]] then
value = nil
else
value = mw.ustring.gsub(rowformat .. "$", "$0", value) -- fake end character added for easy gsub
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
local rowformatting = rowformat .. "$"
for i, _ in ipairs(qualifierId) do
local valueq = valuerow["col" .. i]
if args["rowsubformat" .. i] and valueq then
-- add fake end character $
-- gsub $i not followed by a number so $1 doesn't match $10, $11...
-- remove fake end character
valueq = mw.ustring.gsub(args["rowsubformat" .. i] .. "$", "$" .. i .. "(%D)", valueq .. "%1")
valueq = string.sub(valueq, 1, -2)
rowformatting = mw.ustring.gsub(rowformatting, "$" .. i .. "(%D)", args["rowsubformat" .. i] .. "%1")
end
valueq = valueq and urlEscapes(valueq) or ''
value = mw.ustring.gsub(value, "$" .. i .. "(%D)", valueq .. "%1")
end
value = string.sub(value, 1, -2) -- remove fake end character
value = expandBraces(value, rowformatting)
end
else
value = expandBraces(value, parameters.formatting)
end
result[#result + 1] = value
if not parameters.list then
break
end
end
result = table.concat(result, list)
result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
else
-- return first element
local claim = claims[sortindices[1]]
result, _, error = getValueOfClaim(claim, qualifierId[1], parametersparameter)
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
Baris 1.050 ⟶ 929:
end
 
-- look into entity object
-- 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
 
-- debugging functions, see module ../debug.
function p.ViewSomething(frame)
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
return require(wiki.module_title .. "/debug").ViewSomething(frame)
local id = f.args.id
end
if id and (#id == 0) then
 
id = nil
function p.Dump(frame)
return require(wiki.module_title .. "/debug").Dump(frame)
end
 
function p.getEntityFromTree(frame)
return require(wiki.module_title .. "/debug").getEntityFromTree(frame)
end
 
-- getParentValues: returns a property value with its instance label fetching a recursive tree
 
local function uc_first(word)
return mw.ustring.upper(mw.ustring.sub(word, 1, 1)) .. mw.ustring.sub(word, 2)
end
 
local function getPropertyValue(id, property, parameter, langs, editicon)
local snaks = mw.wikibase.getBestStatements(id, property)
local mysnak
if snaks and snaks[1] and snaks[1].mainsnak then
mysnak = snaks[1].mainsnak
else
return
end
local data = mw.wikibase.getEntityObject(id)
if not data then
local entityId
return nil
local result = '-' -- default for 'no value'
if mysnak.datavalue then
entityId = "Q" .. tostring(mysnak.datavalue.value['numeric-id'])
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon})
end
return entityId, result
end
 
local i = 1
function p.getParentValues(frame)
while true do
local args = frame.args
local idindex = args.item or frame:getParent()f.args.item[i]
if idnot == "" or id == nilindex then
if type(data) == "table" then
id = mw.wikibase.getEntityIdForCurrentPage()
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
if id == nil then return end
end
local languages = findLang(args.lang)
local propertySup = args["property"]; if (propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entity
local propertyLabel = args["label"]; if (propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instance
local propertyLink = args["valuetext"]; if propertyLink == "" then propertyLink = nil end --internallink
local upto = args["upto"]; if upto == "" then upto = nil end
local labelShow = args["labelshow"]; if labelShow == "" then labelShow = nil end
local rowformat = args["rowformat"]; if (rowformat == nil or rowformat == "") then rowformat = "$0 = $1" end
local separator = args["separator"]; if (separator == nil or separator == "") then separator = "<br />" end
local sorting = args["sorting"]; if sorting == "" then sorting = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local lastlabel = uc_first(upto or '')
local maxloop = tonumber(upto) or (lastlabel == '' and 10 or 50)
local labelFilter = {}
if labelShow then
for i, v in ipairs(mw.text.split(labelShow, "/")) do
labelFilter[uc_first(v)] = true
end
end
local result = {}
local label, link, linktext
for iter = 1, maxloop do
local label, link
id, link = getPropertyValue(id, propertySup, args.formatting, languages, editicon)
if id then
_, label = getPropertyValue(id, propertyLabel, "label", languages)
if label and link then
if propertyLink then
_, linktext = getPropertyValue(id, propertyLink, "label", languages)
if linktext then
link = mw.ustring.gsub(link, "%[%[(.*)%|(.+)%]%]", "[[%2|" .. linktext .. "]] [[%1|·]]")
end
end
label = case(label, "infoboxlabel", languages[1])
if labelShow == nil or labelFilter[label] then
result[#result + 1] = {label, link}
labelFilter[label] = nil -- only first label found
end
if label == lastlabel then
break
end
else
return tostring(data)
break
end
else
break
end
end
local ret = {}
local first = 1
local last = #result
local iter = 1
if sorting == "-1" then first = #result; last = 1; iter = -1 end
 
data = data[index] or data[tonumber(index)]
for i = first, last, iter do
if not data then
local rowtext = mw.ustring.gsub(rowformat, "$[01]", {["$0"] = result[i][1], ["$1"] = result[i][2]})
return
ret[#ret +1] = expandBraces(rowtext, rowformat)
end
 
i = i + 1
end
return mw.text.listToText(ret, separator, separator)
end
 
-- getting sitelink of a given wiki
function p.linkWithParentLabel(frame)
-- get sitelink of current item if qid not supplied
local args = {}
function p.getSiteLink(frame)
for k, v in pairs(frame.args) do -- metatable
local qid = frame.args.qid
args[k] = v
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
-- get internal link of property/qualifier
args.list = "true"
args.formatting = "internallink"
args.separator = "/·/"
local pargs = frame:getParent().args
local link_list = p._main(args, pargs)
if link_list == nil or link_list == "" then
return
end
return link
local link_table = mw.text.split(link_list, "/·/", true)
-- get id value of property/qualifier
args.formatting = "raw"
local items_list = p._main(args, pargs)
local items_table = mw.text.split(items_list, "/·/", true)
-- get label of parent property
args.property = args.parent
args.qualifier = nil
local parent_claims = findClaims(mw.wikibase.getEntity(items_table[1]), args.parent)
if parent_claims and parent_claims[1].mainsnak.datatype == 'monolingualtext' then
args.formatting = nil
args.list = 'lang'
else
args.formatting = "label"
args.list = "false"
end
for i, v in ipairs(items_table) do
args.item = v
local link_label = p._main(args, pargs)
if link_label and link_label ~= '' then
link_table[i] = mw.ustring.gsub(link_table[i] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
end
end
return mw.text.listToText(link_table)
end
 
function p.years_oldDump(frame)
local argsf = (frame.args[1] or frame.args.id) and frame or frame:getParent()
local iddata = mw.wikibase.getEntityObject(f.args.itemid)
if idnot == '' or id == nildata then
return i18n.warnDump
id = mw.wikibase.getEntityIdForCurrentPage()
end
 
local lang = mw.language.new('en')
local i = 1
while true do
local function getBestValue(id, prop)
local snakindex = mwf.wikibase.getBestStatements(id, prop)args[1i]
if not index then
if snak and snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value then
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
return snak.mainsnak.datavalue.value
end
 
end
data = data[index] or data[tonumber(index)]
if not data then
local birth = getBestValue(id, 'P569')
return i18n.warnDump
if type(birth) ~= 'table' or birth.time == nil or birth.precision == nil or birth.precision < 8 then
return
end
local death = getBestValue(id, 'P570')
if type(death) ~= 'table' or death.time == nil or death.precision == nil then
death = {['time'] = lang:formatDate('c'), ['precision'] = 11} -- current date
elseif death.precision < 8 then
return
end
local dates = {}
dates[1] = {['min'] = {}, ['max'] = {}, ['precision'] = birth.precision}
dates[1].min.year = tonumber(mw.ustring.match(birth.time, "^[+-]?%d+"))
dates[1].min.month = tonumber(mw.ustring.match(birth.time, "\-(%d%d)\-"))
dates[1].min.day = tonumber(mw.ustring.match(birth.time, "\-(%d%d)T"))
dates[1].max = mw.clone(dates[1].min)
dates[2] = {['min'] = {}, ['max'] = {}, ['precision'] = death.precision}
dates[2].min.year = tonumber(mw.ustring.match(death.time, "^[+-]?%d+"))
dates[2].min.month = tonumber(mw.ustring.match(death.time, "\-(%d%d)\-"))
dates[2].min.day = tonumber(mw.ustring.match(death.time, "\-(%d%d)T"))
dates[2].max = mw.clone(dates[2].min)
for i, d in ipairs(dates) do
if d.precision == 10 then -- month
d.min.day = 1
local timestamp = string.format("%04d", tostring(math.abs(d.max.year)))
.. string.format("%02d", tostring(d.max.month))
.. "01"
d.max.day = tonumber(lang:formatDate("j", timestamp .. " + 1 month - 1 day"))
elseif d.precision < 10 then -- year or decade
d.min.day = 1
d.min.month = 1
d.max.day = 31
d.max.month = 12
if d.precision == 8 then -- decade
d.max.year = d.max.year + 9
end
end
end
local function age(d1, d2)
local years = d2.year - d1.year
if d2.month < d1.month or (d2.month == d1.month and d2.day < d1.day) then
years = years - 1
end
if d2.year > 0 and d1.year < 0 then
years = years - 1 -- no year 0
end
return years
end
local old_min = age(dates[1].max, dates[2].min)
local old_max = age(dates[1].min, dates[2].max)
local old = old_min == old_max and old_min or old_min .. "/" .. old_max
if args.formatting then
old = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
end
return old
end
 
i = i + 1
-- Gets a label in a given language (content language by default) or its fallbacks, optionnally linked.
function p.getLabel(frame)
local args = frame.args or frame -- via invoke or require
local id = mw.text.trim(args[1] or "")
if id == "" then return end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local pencil = ''
local label, lang
if args.label then
label = args.label
else
local languages = findLang(args.lang)
if languages[1] == wiki.langcode then
-- exceptions or labels fixed
local exist, labels = pcall(require, wiki.module_title .. "/labels")
if exist and next(labels.infoboxLabelsFromId) ~= nil then
label = labels.infoboxLabelsFromId[id]
end
end
if label == nil then
label, lang = getLabelByLangs(id, languages)
if label then
if args.itemgender and feminineGender(args.itemgender) then
label = feminineForm(id, lang) or label
end
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
pencil = addEditIcon(id, lang, languages[1], editicon)
end
end
local linked = args.linked
if linked and linked ~= "" and linked ~= "no" then
local article = mw.wikibase.getSitelink(id) or ("d:" .. id)
return "[[" .. article .. "|" .. (label or id) .. "]]" .. pencil
else
return (label or id) .. pencil
end
end
 
-- Return default language used
function p.lang(frame)
return findLang(frame.args[1])[1]
end