Lompat ke isi

Modul:Wikidata: Perbedaan antara revisi

Dari Wikipedia bahasa Indonesia, ensiklopedia bebas
Konten dihapus Konten ditambahkan
fix commons:OOUI icons; ganti dgn. rtl
k uji coba
Baris 1: Baris 1:
-- vim: set noexpandtab ft=lua ts=4 sw=4:
-- version 20200415 from master @cawiki
require('Module:No globals')


local p = {}
local p = {}
local debug = false


-- Initialization of variables --------------------


------------------------------------------------------------------------------
local i18n = { -- internationalisation at [[Module:Wikidata/i18n]]
-- module local variables and functions
["errors"] = {

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

-- internationalisation
local i18n =
{
["errors"] =
{
["property-not-found"] = "Property not found.",
["property-not-found"] = "Property not found.",
["entity-not-found"] = "Wikidata entity not found.",
["unknown-claim-type"] = "Unknown claim type.",
["unknown-entity-type"] = "Unknown entity type.",
["qualifier-not-found"] = "Qualifier not found.",
["qualifier-not-found"] = "Qualifier not found.",
["site-not-found"] = "Wikimedia project not found.",
["unknown-datetime-format"] = "Unknown datetime format.",
["local-article-not-found"] = "Article is not yet available in this wiki."
},
},
["datetime"] =
{
["datetime"] = {
-- $1 is a placeholder for the actual number
-- $1 is a placeholder for the actual number
["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 1st century AD dates
[0] = "$1 billion years", -- precision: billion years
[0] = "$1 billion years", -- precision: billion years
[1] = "$100 million years", -- precision: hundred million years
[1] = "$100 million years", -- precision: hundred million years
[2] = "$10 million years", -- precision: ten million years
[2] = "$10 million years", -- precision: ten million years
[3] = "$1 million years", -- precision: million years
[3] = "$1 million years", -- precision: million years
[4] = "$100000 years", -- precision: hundred thousand years; thousand separators added afterwards
[4] = "$100,000 years", -- precision: hundred thousand years
[5] = "$10000 years", -- precision: ten thousand years; thousand separators added afterwards
[5] = "$10,000 years", -- precision: ten thousand years
[6] = "$1 millennium", -- precision: millennium
[6] = "$1 millennium", -- precision: millennium
[7] = "$1 century", -- precision: century
[7] = "$1 century", -- precision: century
[8] = "$1s", -- precision: decade
[8] = "$1s", -- precision: decade
-- the following use the format of #time parser function
-- the following use the format of #time parser function
[9] = "Y", -- precision: year,
[9] = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[10] = "F Y", -- precision: month
[11] = "F j, Y", -- precision: day
[11] = "F j, Y", -- precision: day
[12] = "F j, Y ga", -- precision: hour
[13] = "F j, Y g:ia", -- precision: minute
[14] = "F j, Y g:i:sa", -- precision: second
["beforenow"] = "$1 BCE", -- how to format negative numbers for precisions 0 to 5
["afternow"] = "$1 CE", -- how to format positive numbers for precisions 0 to 5
["bc"] = '$1 "BCE"', -- how print negative years
["ad"] = "$1", -- how print positive years
-- the following are for function getDateValue() and getQualifierDateValue()
["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
-- #4 (getQualifierDateValue) argument
["default-addon"] = "BC", -- default value of the #4 (getDateValue) or
-- #5 (getQualifierDateValue) argument
["prefix-addon"] = false, -- set to true for languages put "BC" in front of the
-- datetime string; or the addon will be suffixed
["addon-sep"] = " ", -- separator between datetime string and addon (or inverse)
["format"] = -- options of the 3rd argument
{
["mdy"] = "F j, Y",
["my"] = "F Y",
["y"] = "Y",
["dmy"] = "j F Y",
["ymd"] = "Y-m-d",
["ym"] = "Y-m"
}
},
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
["years-old"] = {
["ordinal"] =
["singular"] = "", -- year old, as in {{PLURAL:$1|singular|plural}}
{
["plural"] = "", -- years old
[1] = "st",
["paucal"] = "", -- for languages with 3 plural forms as in {{PLURAL:$1|singular|paucal|plural}}
[2] = "nd",
},
[3] = "rd",
["default"] = "th"
["cite"] = { -- Cite web parameters
}
["url"] = "url",
["title"] = "title",
["website"] = "website",
["access-date"] = "access-date",
["archive-url"] = "archive-url",
["archive-date"]= "archive-date",
["author"] = "author",
["publisher"] = "publisher",
["quote"] = "quote",
["language"] = "language",
["date"] = "date",
["pages"] = "pages"
},
-- local wiki settings
["addpencil"] = false, -- adds a pencil icon linked to Wikidata statement, planned to overwrite by Wikidata Bridge
["categorylabels"] = "", -- Category:Pages with Wikidata labels not translated (void for no local category)
["addfallback"] = {} -- additional fallback language codes
}
}


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 required = ... -- variadic arguments from require function
local wiki =
local module_title; if ... == nil then
module_title = mw.getCurrentFrame():getTitle()
{
else
langcode = mw.language.getContentLanguage().code,
module_title = required or mw.getCurrentFrame():getTitle()
module_title = ...
}

p.Untranslated = false

-- 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
end
require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
return t1
end
end


-- this function needs to be internationalised along with the above:
local function loadI18n(lang)
-- takes cardinal numer as a numeric and returns the ordinal as a string
local i18n_title = "/i18n"
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
if lang ~= wiki.langcode then i18n_title = "/i18n/" .. lang end
local function makeOrdinal (cardinal)
local exist, res = pcall(require, wiki.module_title .. i18n_title)
local ordsuffix = i18n.ordinal.default
if exist and next(res) ~= nil then
if cardinal % 10 == 1 then
tableMerge(i18n, res.i18n)
cases = res.cases
ordsuffix = i18n.ordinal[1]
elseif cardinal % 10 == 2 then
ordsuffix = i18n.ordinal[2]
elseif cardinal % 10 == 3 then
ordsuffix = i18n.ordinal[3]
end
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
end


local function printError(code)
-- Table of language codes: requested or default and its fallbacks
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
local function findLang(langcode)
end
if mw.language.isKnownLanguageTag(langcode or '') == false then
local function parseDateFormat(f, timestamp, addon, prefix_addon, addon_sep)
local cframe = mw.getCurrentFrame()
local year_suffix
local pframe = cframe:getParent()
local tstr = ""
langcode = pframe and pframe.args.lang
if mw.language.isKnownLanguageTag(langcode or '') == false then
local lang_obj = mw.language.new(wiki.langcode)
local f_parts = mw.text.split(f, 'Y', true)
if not mw.title.getCurrentTitle().isContentPage then
for idx, f_part in pairs(f_parts) do
langcode = cframe:preprocess('{{int:lang}}')
year_suffix = ''
end
if string.match(f_part, "x[mijkot]$") then
if mw.language.isKnownLanguageTag(langcode or '') == false then
-- for non-Gregorian year
langcode = wiki.langcode
f_part = f_part .. 'Y'
end
elseif idx < #f_parts then
-- supress leading zeros in year
year_suffix = lang_obj:formatDate('Y', timestamp)
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
end
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
end
end
if addon ~= "" and prefix_addon then
return addon .. addon_sep .. tstr
loadI18n(langcode)
elseif addon ~= "" then
return tstr .. addon_sep .. addon
local languages = mw.language.getFallbacksFor(langcode)
else
table.insert(languages, 1, langcode)
return tstr
if langcode == wiki.langcode then
for _, l in ipairs(i18n.addfallback) do
table.insert(languages, l)
end
end
end
return languages
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
-- Argument is 'set' when it exists (not nil) or when it is not an empty string.
if string.sub(timestamp, 1, 1) == '-' then
local function isSet(var)
timestamp = '+' .. string.sub(timestamp, 2)
return not (var == nil or var == '')
addon = date_addon
end

-- Set local case to a label
local function case(localcase, label, ...)
if not isSet(label) then return label end
if localcase == "smallcaps" then
return '<span style="font-variant: small-caps;">' .. label .. '</span>'
elseif cases[localcase] then
return cases[localcase](label, ...)
end
end
local _date_format = i18n["datetime"]["format"][date_format]
if _date_format ~= nil then
return label
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
end

-- mw.wikibase.getLabelWithLang or getLabelByLang with a table of languages
local function getLabelByLangs(id, languages)
local label
local lang
for _, l in ipairs(languages) do
if l == wiki.langcode then
-- using getLabelWithLang when possible instead of getLabelByLang
label, l = mw.wikibase.getLabelWithLang(id)
else
label = mw.wikibase.getLabelByLang(id, l)
end
if label then
lang = l
break
end
end
return label, lang
end

-- Is gender femenine? true or false
local function feminineGender(id)
local claims = mw.wikibase.getBestStatements(id or mw.wikibase.getEntityIdForCurrentPage(),'P21')
if #claims == 0 then
return false
elseif claims[1].mainsnak.datavalue == nil then -- novalue or somevalue
return false
else
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
end
return false
end
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
end


-- get the next four characters after the + (should be the year now in all cases)
-- get safely a serialized snak
-- ok, so this is dirty, but let's get it working first
local function getSnak(statement, snaks)
local intyear = tonumber(string.sub(timestamp, 2, 5))
local ret = statement
if intyear == 0 and precision <= 9 then
for i, v in ipairs(snaks) do
if ret == nil then return end
return ""
ret = ret[v]
end
end
return ret
end


-- precision is 10000 years or more
-- Add an icon for no label in requested language
if precision <= 5 then
local function addLabelIcon(label_id, lang, uselang, icon)
local factor = 10 ^ ((5 - precision) + 4)
local ret_lang, ret_icon = '', ''
local y2 = math.ceil(math.abs(intyear) / factor)
if icon then
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if lang and lang ~= uselang then
if addon ~= "" then
ret_lang = " <sup>(" .. lang .. ")</sup>"
-- negative date
end
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
if label_id and (lang == nil or lang ~= uselang) then
else
ret_icon = " [[File:OOjs_UI_icon_tag-rtl-progressive.svg|frameless|text-top|10px|"
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
.. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain()
.. "|link=https://www.wikidata.org/wiki/Special:EntityPage/" .. label_id .. "?uselang=" .. uselang .. "]]"
p.Untranslated = true
end
if isSet(i18n.categorylabels) and lang ~= uselang and uselang == wiki.langcode then
ret_icon = ret_icon .. '[[' .. i18n.categorylabels .. (lang and ']]' or '/Q]]')
end
end
return relative
end
end
return ret_lang .. ret_icon
end


-- precision is decades (8), centuries (7) and millennia (6)
-- Add an icon for editing a statement with requirements for Wikidata Bridge
local era, card
local function addEditIcon(parameters)
if precision == 6 then
local ret = ''
card = math.floor((intyear - 1) / 1000) + 1
if i18n.addpencil and parameters.editicon and parameters.id and parameters.property then
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
ret = ' <span data-bridge-edit-flow="overwrite">'
.. "[[File:OOjs UI icon edit-ltr-progressive.svg|frameless|text-top|10px|"
.. mw.message.new('Editlink'):inLanguage(parameters.lang[1]):plain()
.. "|link=https://www.wikidata.org/wiki/" .. parameters.id .. "?uselang=" .. parameters.lang[1] .. "#" .. parameters.property .. "]]"
.. "</span>"
end
end
if precision == 7 then
return ret
card = math.floor((intyear - 1) / 100) + 1
end
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
-- add edit icon to the last element of a table
end
local function addEditIconTable(thetable, parameters)
if #thetable == 0 or not i18n.addpencil then
if precision == 8 then
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
return thetable
end
end
if era then
local last_element = thetable[#thetable]
if addon ~= "" then
local the_icon = addEditIcon(parameters)
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
-- add it before last html closing tags
local tags = ''
local rev_element = string.reverse(last_element)
for tag in string.gmatch(rev_element, '(>%l+/<)') do
if string.match(rev_element, '^' .. tags .. tag) then
tags = tags .. tag
else
else
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
break
end
end
return era
end
end

local last_tags = string.reverse(tags)
local _date_format = i18n["datetime"]["format"][date_format]
local offset = string.find(last_element, last_tags .. '$')
if offset then
if _date_format ~= nil then
-- check for precision is year and override supplied date_format
thetable[#thetable] = string.sub(last_element, 1, offset - 1) .. the_icon .. last_tags
if precision == 9 then
_date_format = i18n["datetime"][9]
end
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
else
else
return printError("unknown-datetime-format")
thetable[#thetable] = last_element .. the_icon
end
end
return thetable
end
end


-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- Escape Lua captures
-- use these as the second parameter and this function instead of the built-in "pairs" function
local function captureEscapes(text)
-- to iterate over all qualifiers and snaks in the intended order.
return mw.ustring.gsub(text, "(%%%d)", "%%%1")
local function orderedpairs(array, order)
end
if not order then return pairs(array) end


-- return iterator function
-- expandTemplate or callParserFunction
local i = 0
local function expandBraces(text, formatting)
return function()
if text == nil or formatting == nil then return text end
i = i + 1
-- only expand braces if provided in argument, not included in value as in Q1164668
if order[i] then
if mw.ustring.find(formatting, '{{', 1, true) == nil then return text end
return order[i], array[order[i]]
if type(text) ~= "string" then
text = tostring(text)
end
for braces in mw.ustring.gmatch(text, "{{(.-)}}") do
local parts = mw.text.split(braces, "|")
local title_part = parts[1]
local parameters = {}
for i = 2, #parts do
local subparts = mw.ustring.find(parts[i], "=")
if subparts then
parameters[mw.ustring.sub(parts[i], 1, subparts-1)] = mw.ustring.sub(parts[i], subparts+1, -1)
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
braces_expanded = mw.getCurrentFrame():expandTemplate{title=title_part, args=parameters}
end
end
braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
braces_expanded = captureEscapes(braces_expanded)
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
end
return text
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
-- Resolve Wikidata redirects, pending phab:T157868
local function resolveEntityId(id)
local function normalizeDate(date)
date = mw.text.trim(date, "+")
if not id or not mw.wikibase.isValidEntityId(id) then return id end
-- extract year
-- if no label in local language nor its fallbacks, maybe it is a redirect
local yearstr = mw.ustring.match(date, "^\-?%d+")
-- not using mw.title.new(id).isRedirect as it is expensive
local year = tonumber(yearstr)
if mw.wikibase.getLabel(id) == nil then
-- remove leading zeros of year
local entity = mw.wikibase.getEntity(id) -- expensive function
return year .. mw.ustring.sub(date, #yearstr + 1), year
if not entity then return nil end
if id ~= entity.id then
-- Qid redirected to be fixed
-- see [[Special:WhatLinksHere/Template:Track/wikidata/redirect]]
require(wiki.module_title .. '/debug').track('redirect')
require(wiki.module_title .. '/debug').track('redirect/' .. id)
else
-- no redirect and no label, fix it to avoid expensive functions
require(wiki.module_title .. '/debug').track('label')
require(wiki.module_title .. '/debug').track('label/' .. id)
end
return entity.id
end
return id
end
end


local function formatDate(date, precision, timezone)
-- format data type math
precision = precision or 11
local function printDatatypeMath(data)
local date, year = normalizeDate(date)
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
if year == 0 and precision <= 9 then return "" end
end


-- precision is 10000 years or more
-- format data type musical-notation
if precision <= 5 then
local function printDatatypeMusical(data, formatting)
local attr = {}
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(year) / factor)
if formatting == 'sound' then
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
attr.sound = 1
if year < 0 then
end
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
return mw.getCurrentFrame():extensionTag('score', data, attr)
else
end
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)

-- format data value string
local function printDatavalueString(data, parameters)
if mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', {['$1'] = data}), parameters.formatting)
elseif parameters.case then
return case(parameters.case, data, parameters.lang[1])
end
return data
end

-- format data type url
local function printDatatypeUrl(data, parameters)
if parameters.formatting == 'weblink' then
local label_parts = mw.text.split(string.gsub(data, '/$', ''), '/')
local label = string.gsub(label_parts[3], '^www%.', '')
if #label_parts > 3 then
label = label .. '…'
end
end
return '[' .. data .. ' ' .. label .. ']'
return relative
end
end
return printDatavalueString(data, parameters)
end


-- precision is decades, centuries and millennia
-- format data type commonsMedia
local era
local function printDatatypeMedia(data, parameters)
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
local icon
if precision == 7 then era = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(year) - 1) / 100) + 1)) end
if not string.find((parameters.formatting or ''), '$1', 1, true) then
if precision == 8 then era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(year) / 10) * 10)) end
icon = "no-icon"
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
end
return printDatavalueString(data, parameters), icon
end


-- precision is year
-- format data value globecoordinate
if precision == 9 then
local function printDatavalueCoordinate(data, formatting)
return year
local function globes(globe_id)
local globes = {['Q3134']='callisto',['Q596']='ceres',['Q15040']='dione',['Q2']='earth',['Q3303']='enceladus',
['Q3143']='europa',['Q17975']='phoebe',['Q3169']='ganymede',['Q3123']='io',['Q17958']='iapetus',
['Q308']='mercury',['Q15034']='mimas',['Q405']='moon',['Q15050']='rhea',['Q15047']='tethys',
['Q111']='mars',['Q2565']='titan',['Q3359']='triton',['Q313']='venus',['Q3030']='vesta'}
return globes[globe_id]
end
end
local function roundPrecision(num, prec)
if prec == nil or prec <= 0 then return num end
local sig = 10^math.floor(math.log10(prec)+.5) -- significant figure from sexagesimal precision: 0.00123 -> 0.001
return math.floor(num / sig + 0.5) * sig
end
local precision = data.precision
local latitude = roundPrecision(data.latitude, precision)
local longitude = roundPrecision(data.longitude, precision)
if formatting and string.find(formatting, '$lat', 1, true) and string.find(formatting, '$lon', 1, true) then
local ret = mw.ustring.gsub(formatting, '$l[ao][tn]', {['$lat'] = latitude, ['$lon'] = longitude})
if string.find(formatting, '$globe', 1, true) then
local myglobe = 'earth'
if isSet(data.globe) then
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
myglobe = globes(globenum) or 'earth'
end
ret = mw.ustring.gsub(ret, '$globe', myglobe)
end
return expandBraces(ret, formatting)
elseif formatting == 'latitude' then
return latitude, "no-icon"
elseif formatting == 'longitude' then
return longitude, "no-icon"
elseif formatting == 'dimension' then
return data.dimension, "no-icon"
else --default formatting='globe'
if isSet(data.globe) == false or data.globe == 'http://www.wikidata.org/entity/Q2' then
return 'earth', "no-icon"
else
local globenum = mw.text.split(data.globe, 'entity/')[2]
return globes(globenum) or globenum, "no-icon"
end
end
end


-- precision is less than years
-- Local functions for data value quantity
if precision > 9 then
local function unitSymbol(id, lang) -- get unit symbol or code
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
local unit_symbol = ''
timezone = tonumber(timezone)
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
if timezone and timezone ~= 0 then
unit_symbol = require(wiki.module_title .. "/Units").getUnit(0, '', id, true)
timezone = -timezone
end
timezone = string.format("%.2d%.2d", timezone / 60, timezone % 60)
if unit_symbol == '' then
if timezone[1] ~= '-' then timezone = "+" .. timezone end
-- fetch it
date = mw.text.trim(date, "Z") .. " " .. timezone
local claims = findClaims(id, 'P5061')
if claims then
local langclaims = {}
table.insert(lang, 'mul') -- multilingual as last try
for _, snak in ipairs(claims) do
local snak_language = getSnak(snak, {"mainsnak", "datavalue", "value", "language"})
if snak_language and not langclaims[snak_language] then -- just the first one by language
langclaims[snak_language] = snak.mainsnak.datavalue.value.text
end
end
for _, l in ipairs(lang) do
if langclaims[l] then
return langclaims[l]
end
end
end
end
]]--
end
return unit_symbol
end


local formatstr = i18n.datetime[precision]
local function getUnit(amount, id, parameters) -- get unit symbol or name
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
local suffix = ''
elseif year < 0 then
if parameters.formatting == "unitcode" then
-- Mediawiki formatDate doesn't support negative years
-- get unit symbol
date = mw.ustring.sub(date, 2)
local unit_symbol = unitSymbol(id, parameters.lang)
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.bc, "$1", i18n.datetime[9]))
if isSet(unit_symbol) then
elseif year > 0 and i18n.datetime.ad ~= "$1" then
suffix = unit_symbol
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.ad, "$1", i18n.datetime[9]))
end
end
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
end
end
if suffix == '' then -- formatting=unit, or formatting=unitcode not found
-- get unit name
local unit_label, lang = getLabelByLangs(id, parameters.lang)
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
suffix = require(wiki.module_title .. "/Units").getUnit(amount, unit_label, id, false)
else
suffix = (unit_label or id) .. addLabelIcon(id, lang, parameters.lang[1], parameters.editicon)
end
end
if suffix ~= '' then
suffix = ' ' .. suffix
end
return suffix
end
end


local function roundPrecision(in_num, out_num)
local function printDatavalueEntity(data, parameter)
-- data fields: entity-type [string], numeric-id [int, Wikidata id]
-- rounds out_num with significant figures of in_num (default precision)
local id
-- first, count digits after decimal mark, handling cases like '12.345e6'

local exponent, prec
if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
local integer, dot, decimals, expstr = in_num:match('^(%d*)(%.?)(%d*)(.*)')
elseif data["entity-type"] == "property" then id = "P" .. data["numeric-id"]
local e = expstr:sub(1, 1)
else return printError("unknown-entity-type")
if e == 'e' or e == 'E' then
exponent = tonumber(expstr:sub(2))
end
end
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
if exponent then
-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
prec = prec - exponent
end
-- significant figures
local in_bracket = 10^-prec -- -1 -> 10, 5 -> 0.00001
local out_bracket = in_bracket * out_num / in_num
out_bracket = 10^math.floor(math.log10(out_bracket)+.5) -- 1230 -> 1000, 0.00123 -> 0.001
-- round it (credit to Luc Bloom from http://lua-users.org/wiki/SimpleRound)
return math.floor(out_num/out_bracket + (out_num >=0 and 1 or -1) * 0.5) * out_bracket
end


if parameter then
-- format data value quantity
if parameter == "link" then
local function printDatavalueQuantity(data, parameters)
local linkTarget = mw.wikibase.getSitelink(id)
local amount = data.amount
local linkName = mw.wikibase.getLabel(id)
amount = mw.ustring.gsub(amount, "%+", "")
if linkTarget then
local suffix = ""
-- if there is a local Wikipedia article link to it using the label or the article title
local conv_amount, conv_suffix
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
if string.sub(parameters.formatting or '', 1, 4) == "unit" or parameters.convert then
else
-- example "unit": "http://www.wikidata.org/entity/Q174728"
-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
local unit_id = data.unit
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
unit_id = mw.ustring.sub(unit_id, mw.ustring.find(unit_id, "Q"), -1)
if string.sub(unit_id, 1, 1) == "Q" then
suffix = getUnit(amount, unit_id, parameters)
local convert_to
if parameters.convert == "default" or parameters.convert == "default2" then
local exist, units = pcall(require, wiki.module_title .. "/Units")
if exist and next(units.convert_default) ~= nil then
convert_to = units.convert_default[unit_id]
end
elseif string.sub(parameters.convert or '', 1, 1) == "Q" then
convert_to = parameters.convert
end
if convert_to and convert_to ~= unit_id then
-- convert units
local conv_temp = { -- formulae for temperatures ºC, ºF, ªK: [from] = {[to] = 'formula'}
['Q25267'] = {['Q42289'] = '$1*1.8+32', ['Q11597'] = '$1+273.15'},
['Q42289'] = {['Q25267'] = '($1-32)/1.8', ['Q11597'] = '($1+459.67)*5/9'},
['Q11597'] = {['Q25267'] = '$1-273.15', ['Q42289'] = '($1-273.15)*1.8000+32.00'}
}
if conv_temp[unit_id] and conv_temp[unit_id][convert_to] then
local amount_f = mw.getCurrentFrame():callParserFunction('#expr', mw.ustring.gsub(conv_temp[unit_id][convert_to], "$1", amount))
conv_amount = math.floor(tonumber(amount_f) + 0.5)
else
local conversions = mw.wikibase.getAllStatements(unit_id, 'P2442') -- conversion to standard unit
table.insert(conversions, mw.wikibase.getBestStatements(unit_id, 'P2370')[1]) -- conversion to SI unit
for _, conv in ipairs(conversions) do
if conv.mainsnak.snaktype == 'value' then -- no somevalue nor novalue
if conv.mainsnak.datavalue.value.unit == "http://www.wikidata.org/entity/" .. convert_to then
conv_amount = roundPrecision(amount, amount * tonumber(conv.mainsnak.datavalue.value.amount))
break
end
end
end
end
if conv_amount then
conv_suffix = getUnit(conv_amount, convert_to, parameters)
end
elseif parameters.convert == 'M' and tonumber(amount) > 10^8 then
conv_amount = math.floor(amount/10^6 + 0.5)
conv_suffix = ' M' .. string.sub(suffix, 2)
end
end
else
return data[parameter]
end
end
end
local lang_obj = mw.language.new(parameters.lang[1])
local sortkey = string.format("%019d", tonumber(amount) * 1000)
if parameters.case then
amount = case(parameters.case, amount, parameters.lang[1])
else
else
return mw.wikibase.getLabel(id) or id
amount = lang_obj:formatNum(tonumber(amount))
end
if conv_amount then
local conv_sortkey = string.format("%019d", tonumber(conv_amount) * 1000)
conv_amount = lang_obj:formatNum(tonumber(conv_amount))
if parameters.convert == 'default2' then
return conv_amount .. conv_suffix .. ' (' .. amount .. suffix .. ')', conv_sortkey
else
return conv_amount .. conv_suffix, conv_sortkey
end
end
end
return amount .. suffix, sortkey
end
end


local function printDatavalueTime(data, parameter)
-- format data value time
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
local function printDatavalueTime(data, parameters)
-- 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
-- Dates and times are stored in ISO 8601 format
-- 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]
local timestamp = data.time
if parameter then
local post_format
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
local calendar_add = ""
elseif parameter == "time" then data.time = normalizeDate(data.time) end
local precision = data.precision or 11
return data[parameter]
if string.sub(timestamp, 1, 1) == '-' then
post_format = i18n.datetime["bc"]
elseif string.sub(timestamp, 2, 3) == '00' then
post_format = i18n.datetime["ad"]
elseif precision > 8 then
-- 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 formatTime(form, stamp)
local pattern
if type(form) == "function" then
pattern = form(stamp)
else
pattern = form
end
stamp = tostring(stamp)
if mw.ustring.find(pattern, "$1") then
return mw.ustring.gsub(pattern, "$1", stamp)
elseif string.sub(stamp, 1, 1) == '-' then -- formatDate() only supports years from 0
stamp = '+' .. string.sub(stamp, 2)
elseif string.sub(stamp, 1, 1) ~= '+' then -- not a valid timestamp, it is a number
stamp = string.format("%04d", stamp)
end
local ret = mw.language.new(parameters.lang[1]):formatDate(pattern, stamp)
ret = string.gsub(ret, "^(%[?%[?)0+", "%1") -- supress leading zeros
ret = string.gsub(ret, "( %[?%[?)0+", "%1")
return ret
end
local function postFormat(t)
if post_format and mw.ustring.find(post_format, "$1") then
return mw.ustring.gsub(post_format, "$1", t)
end
return t
end
local intyear = tonumber(string.match(timestamp, "[+-](%d+)"))
local ret = ""
if precision <= 5 then -- precision is 10000 years or more
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(intyear) / factor)
local relative = formatTime(i18n.datetime[precision], y2)
if post_format == i18n.datetime["bc"] then
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
ret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
local ret_number = string.match(ret, "%d+")
if ret_number ~= nil then
ret = mw.ustring.gsub(ret, ret_number, mw.language.new(parameters.lang[1]):formatNum(tonumber(ret_number)))
end
elseif precision == 6 or precision == 7 then -- millennia or centuries
local card = math.floor((intyear - 1) / 10^(9 - precision)) + 1
ret = formatTime(i18n.datetime[precision], card)
ret = postFormat(ret)
elseif precision == 8 then -- decades
local card = math.floor(math.abs(intyear) / 10) * 10
ret = formatTime(i18n.datetime[8], card)
ret = postFormat(ret)
elseif intyear > 9999 then -- not a valid timestamp
return
elseif precision == 9 or parameters.formatting == 'Y' then -- precision is year
ret = formatTime(i18n.datetime[9], intyear)
ret = postFormat(ret) .. calendar_add
elseif precision == 10 then -- month
ret = formatTime(i18n.datetime[10], timestamp .. " + 1 day") -- formatDate yyyy-mm-00 returns the previous month
ret = postFormat(ret) .. calendar_add
else -- precision 11, day
ret = formatTime(parameters.formatting or i18n.datetime[11], timestamp)
ret = postFormat(ret) .. calendar_add
end
return ret, timestamp
end

-- format data value entity
local function printDatavalueEntity(data, parameters)
local entity_id = data['id']
if parameters.formatting == 'raw' then
if data['entity-type'] == 'item' then
entity_id = resolveEntityId(entity_id)
end
return entity_id, entity_id
end
local entity_page = 'Special:EntityPage/' .. entity_id
local label, lang = getLabelByLangs(entity_id, parameters.lang)
local sitelink = mw.wikibase.getSitelink(entity_id)
local parameter = parameters.formatting
local labelcase = label or sitelink
if parameters.gender == 'feminineform' then
labelcase = feminineForm(entity_id, lang) or labelcase
end
if parameters.case ~= 'gender' then
labelcase = case(parameters.case, labelcase, lang, entity_id, parameters.id)
end
local ret1, ret2
if parameter == 'label' then
ret1 = labelcase or entity_id
ret2 = labelcase or entity_id
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'd:' .. entity_page)
ret2 = sitelink or entity_id
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
ret1 = mw.ustring.gsub(parameter, '$1', labelcase or entity_id)
ret1 = expandBraces(ret1, parameter)
ret2 = labelcase or entity_id
else
else
return formatDate(data.time, data.precision, data.timezone)
if parameter == "ucfirst" or parameter == "ucinternallink" then
if labelcase and lang then
labelcase = mw.language.new(lang):ucfirst(labelcase)
end
-- only first of a list, reset formatting for next ones
if parameter == "ucinterlanllink" then
parameters.formatting = 'internallink'
else
parameters.formatting = nil -- default format
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
ret1 = '[[d:' .. entity_page .. '|' .. (labelcase or entity_id) .. ']]'
ret2 = labelcase or entity_id
end
end
end
return ret1 .. addLabelIcon(entity_id, lang, parameters.lang[1], parameters.editicon), ret2
end
end


local function printDatavalueMonolingualText(data, parameter)
-- format data value monolingualtext
local function printDatavalueMonolingualText(data, parameters)
-- data fields: language [string], text [string]
-- data fields: language [string], text [string]
if parameter then
return data[parameter]
if parameters.list == "lang" and data["language"] ~= parameters.lang[1] then
else
return
local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
elseif parameters.formatting == "language" or parameters.formatting == "text" then
return data[parameters.formatting]
return result
end
end
local result = data["text"]
if data["language"] ~= wiki.langcode then
result = mw.ustring.gsub('<span lang="$1">$2</span>', '$[12]', {["$1"]=data["language"], ["$2"]=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
end


local function printError(key)
local function findClaims(entity, property)
if not property or not entity or not entity.claims then return end
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end


if mw.ustring.match(property, "^P%d+$") then
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
-- if the property is given by an id (P..) access the claim list by this id
-- use these as the second parameter and this function instead of the built-in "pairs" function
return entity.claims[property]
-- to iterate over all qualifiers and snaks in the intended order.
else
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

function findClaims(entityId, property)
if not property or not entityId then return end
if not mw.ustring.match(property, "^P%d+$") then
-- get property id for the given label
property = mw.wikibase.resolvePropertyId(property)
property = mw.wikibase.resolvePropertyId(property)
if not property then return end
if not property then return end

return entity.claims[property]
end
end
local claims = mw.wikibase.getAllStatements(entityId, property)
if #claims == 0 then
claims = nil
end
return claims
end
end


local function getSnakValue(snak, parameters)
local function getSnakValue(snak, parameter)
if snak.snaktype == 'value' then
if snak.snaktype == "value" then
-- call the respective snak parser
-- call the respective snak parser
if snak.datatype == 'math' then
if snak.datavalue.type == "string" then return snak.datavalue.value
return printDatatypeMath(snak.datavalue.value)
elseif snak.datavalue.type == "globecoordinate" then return printDatavalueCoordinate(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "quantity" then return printDatavalueQuantity(snak.datavalue.value, parameter)
elseif snak.datatype == 'musical-notation' then
return printDatatypeMusical(snak.datavalue.value, parameters.formatting)
elseif snak.datavalue.type == "time" then return printDatavalueTime(snak.datavalue.value, parameter)
elseif snak.datatype == "url" then
elseif snak.datavalue.type == "wikibase-entityid" then return printDatavalueEntity(snak.datavalue.value, parameter)
return printDatatypeUrl(snak.datavalue.value, parameters)
elseif snak.datavalue.type == "monolingualtext" then return printDatavalueMonolingualText(snak.datavalue.value, parameter)
elseif snak.datatype == "commonsMedia" then
return printDatatypeMedia(snak.datavalue.value, parameters)
elseif snak.datavalue.type == "string" then
return printDatavalueString(snak.datavalue.value, parameters)
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
end
elseif snak.snaktype == 'novalue' then
if parameters.formatting == 'raw' then return end
return mw.message.new('Wikibase-snakview-snaktypeselector-novalue'):inLanguage(parameters.lang[1]):plain()
elseif snak.snaktype == 'somevalue' then
if parameters.formatting == 'raw' then return end
return mw.message.new('Wikibase-snakview-snaktypeselector-somevalue'):inLanguage(parameters.lang[1]):plain()
end
end
return mw.wikibase.renderSnak(snak)
return mw.wikibase.renderSnak(snak)
end
end


local function getQualifierSnak(claim, qualifierId, parameters)
local function getQualifierSnak(claim, qualifierId)
-- a "snak" is Wikidata terminology for a typed key/value pair
-- a "snak" is Wikidata terminology for a typed key/value pair
-- a claim consists of a main snak holding the main information of this claim,
-- a claim consists of a main snak holding the main information of this claim,
Baris 814: Baris 397:
if claim.qualifiers then
if claim.qualifiers then
local qualifier = claim.qualifiers[qualifierId]
local qualifier = claim.qualifiers[qualifierId]
if qualifier then
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 getSnak(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
end
return nil, printError("qualifier-not-found")
return nil, printError("qualifier-not-found")
Baris 836: Baris 406:
end
end


function getValueOfClaim(claim, qualifierId, parameters)
local function getValueOfClaim(claim, qualifierId, parameter)
local snak, error = getQualifierSnak(claim, qualifierId, parameters)
local error
local snak
snak, error = getQualifierSnak(claim, qualifierId)
if not snak then
if snak then
return nil, nil, error
return getSnakValue(snak, parameter)
elseif snak[1] then -- a multi qualifier
local result = {}
local sortkey = {}
for idx in pairs(snak) do
result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
end
return mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]
else -- a property or a qualifier
return getSnakValue(snak, parameters)
end
end

local function getValueOfParentClaim(claim, qualifierId, parameters)
local qids = mw.text.split(qualifierId, '/', true)
local valueraw, parent_claims, value, sortkey
if qids[1] == parameters.property then
valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=parameters.lang})
else
else
return nil, error
valueraw, _, _ = getValueOfClaim(claim, qids[1], {["formatting"]="raw", ["lang"]=parameters.lang})
end
if string.sub(valueraw or '', 1, 1) == "Q" then -- protection for 'no value'
parent_claims = mw.wikibase.getBestStatements(valueraw, qids[2])
if parent_claims[1] ~= nil then
value, sortkey, _ = getValueOfClaim(parent_claims[1], nil, parameters)
-- raw parent value needed for while/black lists, lang for avoiding an error on types other than entity
valueraw, _, _ = getValueOfClaim(parent_claims[1], nil, {["formatting"]="raw", ["lang"]=parameters.lang})
end
end
end
return value, sortkey, valueraw
end
end


local function getReferences(claim)
local function getReferences(frame, claim)
local notproperref = {
["P143"] = true, -- imported from
["P3452"] = true, -- inferred from
["P887"] = true, -- based on heuristic
["P4656"] = true -- Wikimedia import URL
}
local result = ""
local result = ""
-- traverse through all references
-- traverse through all references
for ref in pairs(claim.references or {}) do
for ref in pairs(claim.references or {}) do
local refparts
local refparts
local refs = {}
local validref = true
-- traverse through all parts of the current reference
-- traverse through all parts of the current reference
for snakkey, snakval in pairs(claim.references[ref].snaks or {}) do
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
if refparts then refparts = refparts .. ", " else refparts = "" end
for partkey, _ in pairs(claim.references[ref].snaks[snakkey] or {}) do
-- output the label of the property of the reference part, e.g. "imported from" for P143
if notproperref[snakkey] then -- not a proper reference
refparts = refparts .. tostring(mw.wikibase.getLabel(snakkey)) .. ": "
validref = false
-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
break
for snakidx = 1, #snakval do
end
if snakidx > 1 then refparts = refparts .. ", " end
end
refparts = refparts .. getSnakValue(snakval[snakidx])
if validref then
for snakidx = 1, #snakval do
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang={wiki.langcode}})
end
refs[snakkey] = refparts
refparts = nil
end
end
-- get title of general template for citing web references
local template = mw.wikibase.getSitelink('Q5637226') or ""
template = mw.text.split(template, ":")[2] -- split off namespace from front
-- if both "reference URL" and "title" (or "stated in") are present, then use local cite web template
if refs['P854'] and (refs['P1476'] or refs['P248']) and template then
local citeParams = {}
citeParams[i18n['cite']['url']] = refs['P854']
citeParams[i18n['cite']['title']] = refs['P1476'] or refs['P248']:match("^%[%[.-|(.-)%]%]")
citeParams[i18n['cite']['author']] = refs['P50']
citeParams[i18n['cite']['website']] = refs['P248']
citeParams[i18n['cite']['language']] = refs['P2439']
citeParams[i18n['cite']['publisher']] = refs['P123']
citeParams[i18n['cite']['date']] = refs['P577']
citeParams[i18n['cite']['pages']] = refs['P304']
citeParams[i18n['cite']['access-date']] = refs['P813']
citeParams[i18n['cite']['archive-url']] = refs['P1065']
citeParams[i18n['cite']['archive-date']] = refs['P2960']
citeParams[i18n['cite']['quote']] = refs['P1683']
refparts = mw.getCurrentFrame():expandTemplate{title=template, args=citeParams}
else
-- raw ouput
local italics = "''"
for k, v in orderedpairs(refs or {}, claim.references[ref]["snaks-order"]) do
if k and v then
refparts = refparts and refparts .. " " or ""
refparts = refparts .. mw.ustring.gsub(mw.wikibase.getLabel(k), "^%l", mw.ustring.upper) .. ": "
refparts = refparts .. italics .. v .. italics .. "."
italics = ""
end
end
end
end
end
if refparts then result = result .. mw.getCurrentFrame():extensionTag("ref", refparts) end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
end
end
return result
return result
end
end


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


------------------------------------------------------------------------------
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
-- module global functions
function p.pageId(frame)
local entity = mw.wikibase.getEntityObject()
if not entity then return nil else return entity.id end
end


if debug then
function p.claim(frame)
function p.inspectI18n(frame)
if mw.title.new(frame:getParent():getTitle()).isContentPage then
local val = i18n
if not mw.title.new(frame:getTitle()).isSubpage then
for _, key in pairs(frame.args) do
-- invoked from a content page and not invoking a module subpage
key = mw.text.trim(key)
return printError("not-from-content-page")
val = val[key]
end
end
return val
end
end
return p._main(frame.args, frame:getParent().args)
end
end


function p.descriptionIn(frame)
local function tableParameters(args, parameters, column)
local column_params = mw.clone(parameters)
local langcode = frame.args[1]
local id = frame.args[2]
column_params.formatting = args["colformat"..column]; if column_params.formatting == "" then column_params.formatting = nil end
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
column_params.convert = args["convert" .. column]
return mw.wikibase.getEntity(id):getDescription(langcode or wiki.langcode)
if args["case" .. column] then
end
column_params.case = args["case" .. column]

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

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


-- Same as above, but uses the short name property for label if available.
local function getEntityId(frame, unnamed)
p.getValueShortName = function(frame)
local args = frame.args or frame
local go, errorOrentity, claims, propertyID = parseInput(frame)
local pargs = frame.args and frame:getParent().args
if not go then
local id = args.item or args.from or (unnamed and mw.text.trim(args[1] or '') or nil)
return errorOrentity
if not isSet(id) and pargs then
id = pargs.item or pargs.from or (unnamed and mw.text.trim(pargs[1] or '') or nil)
end
end
local entity = errorOrentity
if isSet(id) then
-- if wiki-linked value output as link if possible
if string.find(id, ":") then -- remove prefix as Property:Pid
local function labelHook (qnumber)
id = mw.text.split(id, ":")[2]
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
end
if label == nil or label == "" then return nil end
else
return label
id = mw.wikibase.getEntityIdForCurrentPage()
end
end
return getValue(errorOrentity, claims, propertyID, ", ", labelHook);
return id
end
end


-- This is used to get a value, or a comma separated list of them if multiple values exist
-- Main function claim ---------------------------------------------
-- from an arbitrary entry by using its QID.
-- on debug console use: =p.claim{item="Q...", property="P...", ...}
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
function p.claim(frame)
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
p.Untranslated = false
-- Please use sparingly - this is an *expensive call*.
if not required and frame.args and isSet(frame:getParent().args.sandbox) then
p.getValueFromID = function(frame)
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).claim(frame)
local itemID = mw.text.trim(frame.args[1] or "")
end
local args = frame.args or frame -- via invoke or require
local propertyID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
--If a value is already set, use it
if isSet(args.value) then
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity(itemID)
if args.value == 'NONE' then
local claims
return
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
return getValue(entity, claims, propertyID, ", ")
else
else
return args.value
return ""
end
end
else
return input_parm
end
end
end
local function getQualifier(frame, outputHook)
-- arguments
local id = getEntityId(frame)
local propertyID = mw.text.trim(frame.args[1] or "")
local qualifierID = mw.text.trim(frame.args[2] or "")
if id == nil then return end
local property = string.upper(args.property or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local qualifierId = {}
local entity = mw.wikibase.getEntity()
qualifierId[1] = isSet(args.qualifier) and string.upper(args.qualifier) or nil
if entity.claims[propertyID] ~= nil then
local i = 2
local out = {}
while isSet(args["qualifier" .. i]) do
for k, v in pairs(entity.claims[propertyID]) do
qualifierId[i] = string.upper(args["qualifier" .. i])
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
i = i + 1
if v2.snaktype == 'value' then
end
out[#out + 1] = outputHook(v2);
local formatting = args.formatting; if formatting == "" then formatting = nil end
end
local convert = args.convert; if convert == "" then convert = 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
local sorting_up = (args.sorting or "") ~= "-1"
local separator = isSet(args.separator) and args.separator
local conjunction = isSet(args.conjunction) and args.conjunction or separator
local rowformat = args.rowformat
local references = args.references
local showerrors = args.showerrors
local default = args.default
if default then showerrors = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no" or formatting == "raw")
local parameters = {["id"] = id, ["property"] = property, ["formatting"] = formatting, ["convert"] = convert,
["list"] = list, ["case"] = case, ["editicon"] = editicon,
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
parameters.lang = findLang(args.lang)
-- defaults for table
local preformat, postformat = "", ""
local whitelisted, blacklisted = false, false
local whitelist, blacklist = {}, {}
if parameters.formatting == "table" then
parameters.separator = parameters.separator or "<br />"
parameters.conjunction = parameters.conjunction or "<br />"
parameters.qseparator = ", "
parameters.qconjunction = ", "
if not rowformat then
rowformat = "$0 ($1"
i = 2
while qualifierId[i] do
rowformat = rowformat .. ", $" .. i
i = i + 1
end
end
return table.concat(out, ", "), true
rowformat = rowformat .. ")"
else
elseif mw.ustring.find(rowformat, "^[*#]") then
return "", false
parameters.separator = "</li><li>"
parameters.conjunction = "</li><li>"
if mw.ustring.match(rowformat, "^[*#]") == "*" then
preformat = "<ul><li>"
postformat = "</li></ul>"
else
preformat = "<ol><li>"
postformat = "</li></ol>"
end
rowformat = mw.ustring.gsub(rowformat, "^[*#] ?", "")
end
end
else
return input_parm, false
-- set whitelist and blacklist values
whitelist, whitelisted = setWhiteOrBlackList("whitelist", #qualifierId, args)
blacklist, blacklisted = setWhiteOrBlackList("blacklist", #qualifierId, args)
end
end
end
p.getQualifierValue = function(frame)
-- fetch property
local claims
local function outputValue(value)
local qnumber = "Q" .. value.datavalue.value["numeric-id"]
for p in string.gmatch(property, 'P%d+') do
if (mw.wikibase.getSitelink(qnumber)) then
claims = findClaims(id, p)
return "[[" .. mw.wikibase.getSitelink(qnumber) .. "]]"
if claims and claims[1] then
else
parameters.property = p
return "[[:d:" .. qnumber .. "|" ..qnumber .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
break
end
end
end
end
return (getQualifier(frame, outputValue))
if not claims or not claims[1] then
end
if showerrors then return printError("property-not-found") else return default 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
end
local entity = errorOrentity
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
-- set feminine case if gender is requested
-- if number type: remove thousand separators, bounds and units
local itemgender = args["itemgender"]
if isType(claims, "quantity") then
local idgender
result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
if itemgender then
result = mw.ustring.gsub(result, "(%d)±.*", "%1")
if string.match(itemgender, "^P%d+$") then
local snak_id = getSnak(mw.wikibase.getBestStatements(id, itemgender), {1, "mainsnak", "datavalue", "value", "id"})
if snak_id then
idgender = snak_id
end
elseif string.match(itemgender, "^Q%d+$") then
idgender = itemgender
end
end
end
return result
local gender_requested = false
end
if parameters.case == "gender" or idgender then

gender_requested = true
-- This is used to get the unit name for the numeric value returned by getRawValue
elseif parameters.formatting == "table" then
p.getUnits = function(frame)
for i=0, #qualifierId do
local go, errorOrentity, claims, propertyID = parseInput(frame)
if args["case" .. i] and args["case" .. i] == "gender" then
if not go then
gender_requested = true
return errorOrentity
break
end
end
end
end
local entity = errorOrentity
if gender_requested then
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
if feminineGender(idgender or id) then
if isType(claims, "quantity") then
parameters.gender = "feminineform"
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
end
return result
end

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

p.getRawQualifierValue = function(frame)
local function outputHook(value)
if value.datavalue.value["numeric-id"] then
return mw.wikibase.getLabel("Q" .. value.datavalue.value["numeric-id"])
else
return value.datavalue.value
end
end
end
end
local ret, gotData = getQualifier(frame, outputHook)
if gotData then
-- get initial sort indices
ret = string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
local sortindices = {}
for idx in pairs(claims) do
sortindices[#sortindices + 1] = idx
end
end
return ret
-- sort by claim rank
end
local comparator = function(a, b)

local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
-- Dates and times are stored in ISO 8601 format (sort of).
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
return ranka < rankb
-- 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
end
local entity = errorOrentity
table.sort(sortindices, comparator)
local out = {}
for k, v in pairs(claims) do
local result, result2
if v.mainsnak.datavalue.type == 'time' then
local error
local timestamp = v.mainsnak.datavalue.value.time
if parameters.list or parameters.formatting == "table" then
local dateprecision = v.mainsnak.datavalue.value.precision
-- convert LF to line feed, <br /> may not work on some cases
-- A year can be stored like this: "+1872-00-00T00:00:00Z",
parameters.separator = parameters.separator == "LF" and "\010" or parameters.separator
-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
parameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction
-- and that's the last day of 1871, so the year is wrong.
-- i18n separators
-- So fix the month 0, day 0 timestamp to become 1 January instead:
parameters.separator = parameters.separator or mw.message.new('Comma-separator'):inLanguage(parameters.lang[1]):plain()
timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
parameters.conjunction = parameters.conjunction or (mw.message.new('And'):inLanguage(parameters.lang[1]):plain() .. mw.message.new('Word-separator'):inLanguage(parameters.lang[1]):plain())
out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
-- iterate over all elements and return their value (if existing)
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]]
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 = tableParameters(args, parameters, "0")
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 = tableParameters(args, parameters, j)
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(id, 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 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
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
local rowformatting = rowformat .. "$" -- fake end character added for easy gsub
value = mw.ustring.gsub(rowformatting, "$0", value)
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
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 = captureEscapes(valueq)
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 captureEscapes(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
elseif value then
value = expandBraces(value, parameters.formatting)
value = value .. reference
end
if isSet(value) then
result[#result + 1] = value
if not parameters.list then
break
end
end
end
-- in a table, add edit icon on last element
if parameters.formatting == 'table' and parameters.editicon then
result = addEditIconTable(result, parameters)
end
result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
else
-- return first element
local claim = claims[sortindices[1]]
result, result2, error = getValueOfClaim(claim, qualifierId[1], parameters)
if result and references then result = result .. getReferences(claim) end
end
end
return table.concat(out, ", ")
end
if isSet(result) then
p.getQualifierDateValue = function(frame)
-- add edit icon
local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
if parameters.formatting == 'table' then
local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
return result -- added previously on last element
local function outputHook(value)
elseif result2 and result2 == 'no-icon' then
local timestamp = value.datavalue.value.time
return result
return parseDateValue(timestamp, date_format, date_addon)
elseif i18n.addpencil then
end
return result .. addEditIcon(parameters)
return (getQualifier(frame, outputHook))
else
end
return result

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


--[[
-- Local functions for getParentValues -----------------------
This is used to return an image legend from Wikidata
image is property P18
image legend is property P2096


Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
local function uc_first(word)
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
return mw.ustring.upper(mw.ustring.sub(word, 1, 1)) .. mw.ustring.sub(word, 2)
If QID is omitted or blank, the current article is used (not an expensive call)
end
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'
local function getPropertyValue(id, property, parameter, langs, editicon, case)
This returns the label from the first image with 'preferred' rank
local snaks = mw.wikibase.getBestStatements(id, property)
Or the label from the first image with 'normal' rank if preferred returns nothing
local mysnak
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
if snaks and snaks[1] and snaks[1].mainsnak then
]]
mysnak = snaks[1].mainsnak

else
p.getImageLegend = function(frame)
return
-- 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
end
local entity_id
local result = '-' -- default for 'no value'
if mysnak.datavalue then
entity_id = "Q" .. tostring(mysnak.datavalue.value['numeric-id'])
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon, case=case})
end
return entity_id, result
end


-- look for named parameter lang
local function contains(tab, val)
-- it should contain a two-character ISO-639 language code
for index, value in ipairs(tab) do
-- if it's blank fetch the language of the local wiki
if value == val then
local lang = frame.args.lang
return true
if (not lang) or (#lang < 2) then
end
lang = mw.language.getContentLanguage().code
end
end
return false
end


-- first unnamed parameter is the local parameter, if supplied
local function getParentObjects(id,
local input_parm = mw.text.trim(frame.args[1] or "")
formatting,
if input_parm == "FETCH_WIKIDATA" then
languages,
local ent = mw.wikibase.getEntity(id)
propertySupString,
local imgs
propertyLabel,
if ent and ent.claims then
propertyLink,
imgs = ent.claims.P18
labelShow,
editicon,
upto,
upto_linkId,
last_only,
grammatical_case,
include_self)
if (upto_linkId == nil) then upto_linkId = "" end
local upto_link_ids = mw.text.split(upto_linkId, '[/%s]+')
local propertySups = mw.text.split(propertySupString, '[/%s]+')
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 imglbl
end
if imgs then
-- look for an image with 'preferred' rank
local label_self
for k1, v1 in pairs(imgs) do
_, label_self = getPropertyValue(id, propertyLabel, "label", languages)
if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
local result = {}
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
local label, link, linktext
imglbl = v2.datavalue.value.text
break
for iter = 1, maxloop do
end
local label, link
end
for _, propertySup in pairs(propertySups) do
end
_id, _link = getPropertyValue(id, propertySup, formatting, languages, editicon, grammatical_case)
if _id and _link then id = _id link = _link break end
end
if not id or not link then break end
if propertyLink then
_, linktext = getPropertyValue(id, propertyLink, "label", languages)
if linktext then
link = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")
end
end
-- if we don't find one, look for an image with 'normal' rank
end
if (not imglbl) then
for k1, v1 in pairs(imgs) do
_, label = getPropertyValue(id, propertyLabel, "label", languages, editicon, "infoboxlabel")
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
if labelShow == nil or labelFilter[label] then
for k2, v2 in pairs(imglbls) do
result[#result + 1] = {label, link}
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
if label then
break
labelFilter[label] = nil -- only first label found
end
end
end
end
end
end
end
end
return imglbl
else
if not tonumber(upto) and label == lastlabel then
return input_parm
break
end
if contains(upto_link_ids, id) then
break
end
end
if last_only then
result = {result[#result]}
end
end
if include_self then table.insert(result, 1, {label_self, mw.title.getCurrentTitle().text}) end
return result
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
local function parentObjectsToString(result,
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |FETCH_WIKIDATA}}
rowformat,
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |<InputParameter> |qid=<QID>}}
cascade,

sorting)
p.getPropertyIDs = function(frame)
local go, errorOrentity, propclaims = parseInput(frame)
local ret = {}
if not go then
local first = 1
return errorOrentity
local last = #result
local iter = 1
if sorting == "-1" then first = #result; last = 1; iter = -1 end
for i = first, last, iter do
local rowtext = mw.ustring.gsub(rowformat, "$[01]", {["$0"] = result[i][1], ["$1"] = result[i][2]})
ret[#ret +1] = expandBraces(rowtext, rowformat)
end
end
local entity = errorOrentity
-- if wiki-linked value collect the QID in a table
if cascade then
if (propclaims[1] and propclaims[1].mainsnak.snaktype == "value" and propclaims[1].mainsnak.datavalue.type == "wikibase-entityid") then
local prefix = ""
for i = 1, #ret do
local out = {}
for k, v in pairs(propclaims) do
ret[i] = prefix .. "• " .. ret[i]
out[#out + 1] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
prefix = prefix .. "&nbsp;"
end
end
return table.concat(out, ", ")
else
-- not a wikibase-entityid, so return empty
return ""
end
end
return ret
end
end


-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
-- Returns pairs of instance label and property value fetching a recursive tree
function p.getParentValues(frame)
function p.pageId(frame)
return mw.wikibase.getEntityIdForCurrentPage()
if not required and frame.args and frame:getParent().args.sandbox then
end
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).getParentValues(frame)

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

-- get wikidata entity
local entity = mw.wikibase.getEntity(id)
if not entity then
if showerrors then return printError("entity-not-found") else return default end
end
end
-- fetch the first claim of satisfying the given property
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame)
local claims = findClaims(entity, property)
if id == nil then return end
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
local languages = findLang(args.lang)
local propertySup = args.property; if not isSet(propertySup) then propertySup = "P131" end --administrative entity
local propertyLabel = args.label; if not isSet(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 last_only = (args.last_only == "true" or args.last_only == "yes")
local labelShow = args.labelshow; if labelShow == "" then labelShow = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local include_self = (args.include_self == "true" or args.include_self == "yes")
local case = args.case; if case == "" then case = nil end
if isSet(args.uptolabelid) then
upto = mw.wikibase.getLabel(args.uptolabelid)
end
end

-- get initial sort indices
if isSet(args.showlabelid) then
local showLabelList = {}
local sortindices = {}
for substring in mw.text.gsplit(args.showlabelid, '[/%s]+') do
for idx in pairs(claims) do
sortindices[#sortindices + 1] = idx
table.insert(showLabelList, mw.wikibase.getLabel(substring))
end
if #showLabelList > 0 then
labelShow = table.concat(showLabelList,"/")
end
end
end
-- sort by claim rank
local result = getParentObjects(id,
local comparator = function(a, b)
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
args.formatting,
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
languages,
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
propertySup,
return ranka < rankb
propertyLabel,
end
propertyLink,
table.sort(sortindices, comparator)
labelShow,
editicon,
upto,
args.uptolinkid,
last_only,
case,
include_self)
if #result == 0 then return end
local rowformat = args.rowformat; if not isSet(rowformat) then rowformat = "$0 = $1" end
local separator = args.separator; if not isSet(separator) then separator = "<br />" end
local sorting = args.sorting; if sorting == "" then sorting = nil end
local cascade = (args.cascade == "true" or args.cascade == "yes")
local ret = parentObjectsToString(result,
rowformat,
cascade,
sorting)
ret = addEditIconTable(ret, {property=propertySup, editicon=editicon, id=id, lang=languages})
return mw.text.listToText(ret, separator, separator)
end


local result
-- Link with a parent label --------------------
local error
function p.linkWithParentLabel(frame)
if list then
if not required and frame.args and frame:getParent().args.sandbox then
local value
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).linkWithParentLabel(frame)
-- iterate over all elements and return their value (if existing)
end
local args = {}
result = {}
for idx in pairs(claims) do
if frame.args then
local claim = claims[sortindices[idx]]
for k, v in pairs(frame.args) do -- metatable
value, error = getValueOfClaim(claim, qualifierId, parameter)
args[k] = v
if not value and showerrors then value = error end
if value and references then value = value .. getReferences(frame, claim) end
result[#result + 1] = value
end
end
result = table.concat(result, list)
else
else
-- return first element
args = frame -- via require
local claim = claims[sortindices[1]]
result, error = getValueOfClaim(claim, qualifierId, parameter)
if result and references then result = result .. getReferences(frame, claim) end
end
end

if isSet(args.value) then
return args.value
if result then return result else
if showerrors then return error else return default end
end
-- get id value of property/qualifier
local largs = mw.clone(args)
largs.list = "true"
largs.formatting = "raw"
largs.separator = "/·/"
largs.editicon = "false"
local items_list = p.claim(largs)
if not isSet(items_list) then return end
local items_table = mw.text.split(items_list, "/·/", true)
-- get internal link of property/qualifier
largs.formatting = "internallink"
local link_list = p.claim(largs)
local link_table = mw.text.split(link_list, "/·/", true)
-- get label of parent property
local parent_claim = getSnak(findClaims(items_table[1], args.parent), {1, "mainsnak", "datatype"})
if parent_claim == 'monolingualtext' then
largs.formatting = nil
largs.list = 'lang'
else
largs.formatting = "label"
largs.list = "false"
end
largs.property = args.parent
largs.qualifier = nil
for i, v in ipairs(items_table) do
largs.item = v
local link_label = p.claim(largs)
if isSet(link_label) then
link_table[i] = mw.ustring.gsub(link_table[i] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
end
end
end
args.editicon = not (args.editicon == "false" or args.editicon == "no")
args.id = getEntityId(frame)
args.lang = findLang(args.lang)
return mw.text.listToText(link_table) .. addEditIcon(args)
end
end


-- look into entity object
-- Calculate number of years old ----------------------------
function p.yearsOld(frame)
function p.ViewSomething(frame)
if not required and frame.args and frame:getParent().args.sandbox then
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
local id = f.args.id
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).yearsOld(frame)
if id and (#id == 0) then
id = nil
end
end
local data = mw.wikibase.getEntity(id)
local args = frame.args or frame -- via invoke or require
if not data then
local id = getEntityId(frame)
return nil
local lang = mw.language.new('en')
local function getBestValue(id, prop)
local snak_value = getSnak(mw.wikibase.getBestStatements(id, prop), {1, "mainsnak", "datavalue", "value"})
return snak_value
end
end

local birth = getBestValue(id, 'P569')
local i = 1
while true do
if type(birth) ~= 'table' or birth.time == nil or birth.precision == nil or birth.precision < 8 then
local index = f.args[i]
return
if not index then
end
if type(data) == "table" then
local death = getBestValue(id, 'P570')
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
if type(death) ~= 'table' or death.time == nil or death.precision == nil then
else
death = {['time'] = lang:formatDate('c'), ['precision'] = 11} -- current date
return tostring(data)
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
end

end
data = data[index] or data[tonumber(index)]
if not data then
local function age(d1, d2)
return
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
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_expr
if old_min == 0 and old_max == 0 then
old = "< 1"
old_max = 1 -- expression in singular
elseif old_min == old_max then
old = old_min
else
old = old_min .. "/" .. old_max
end
if args.formatting == 'unit' then
local langs = findLang(args.lang)
local yo, yo_sg, yo_pl, yo_pau
if langs[1] == wiki.langcode then
yo_sg = i18n["years-old"].singular
yo_pl = i18n["years-old"].plural
yo_pau = i18n["years-old"].paucal
end
if not isSet(yo_pl) then
yo_pl = getLabelByLangs('Q24564698', langs)
yo_sg = yo_pl
end
if not isSet(yo_pau) then
yo_pau = yo_pl
end
yo = mw.language.new(langs[1]):plural(old_max, {yo_sg, yo_pau, yo_pl})
if mw.ustring.find(yo, '$1', 1, true) then
old_expr = mw.ustring.gsub(yo, "$1", old)
else
old_expr = old .. '&nbsp;' .. yo
end
elseif args.formatting then
old_expr = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
else
old_expr = old
end
return old_expr
end


i = i + 1
-- Gets a label in a given language (content language by default) or its fallbacks, optionnally linked.
function p.getLabel(frame)
p.Untranslated = false
if not required and frame.args and frame:getParent().args.sandbox then
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).getLabel(frame)
end
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame, true)
if id == nil then return end
local editicon = not (args.editicon == "false" or args.editicon == "no") and mw.wikibase.isValidEntityId(id)
local label_icon = ''
local label, lang
if args.label then
label = args.label
else
local languages = findLang(args.lang)
-- exceptions or labels fixed
local exist, labels = pcall(require, wiki.module_title .. "/labels" .. (languages[1] == wiki.langcode and '' or '/' .. languages[1]))
if exist and next(labels.infoboxLabelsFromId) ~= nil then
label = labels.infoboxLabelsFromId[id]
end
if label == nil then
local new_id = resolveEntityId(id)
if new_id then
label, lang = getLabelByLangs(new_id, languages)
if label then
if args.itemgender and feminineGender(args.itemgender) then
label = feminineForm(new_id, lang) or label
end
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
label_icon = addLabelIcon(new_id or id, lang, languages[1], editicon)
end
end
end
local linked = args.linked
if isSet(linked) and linked ~= "no" then
local article = mw.wikibase.getSitelink(id) or ("d:" .. id)
return "[[" .. article .. "|" .. (label or id) .. "]]" .. label_icon
else
return (label or id) .. label_icon
end
end
end
end


-- getting sitelink of a given wiki
-- Utilities -----------------------------
-- get sitelink of current item if qid not supplied
-- See also module ../debug.

-- Copied from Module:Wikibase
function p.getSiteLink(frame)
function p.getSiteLink(frame)
local id = getEntityId(frame, 1)
local qid = frame.args.qid
if id == nil then
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
return
end
end
local link = entity:getSitelink( f )
return mw.wikibase.getSitelink(id, mw.text.trim(frame.args[2] or ''))
if not link then
return
end
return link
end
end


function p.Dump(frame)
-- Helper function for the default language code used
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
function p.lang(frame)
local lang = frame and frame.args[1] -- nil via require
local data = mw.wikibase.getEntity(f.args.id)
if not data then
return findLang(lang)[1]
return i18n.warnDump
end
end


local i = 1
-- Number of statements
while true do
function p.numStatements(frame)
local id = getEntityId(frame)
local index = f.args[i]
if id == nil then
if not index then
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
return 0
end
end
local args = frame.args
local prop = mw.text.trim(args[1])
local num = mw.wikibase.getBestStatements(id, prop)
return #num
end


data = data[index] or data[tonumber(index)]
-- Returns true if property datavalue is found excluding novalue/somevalue
if not data then
function p.validProperty(frame)
return i18n.warnDump
local property = mw.text.trim(frame.args[1])
end
local item = getEntityId(frame)

if item == nil then return end
i = i + 1
local properties = mw.wikibase.getBestStatements(item, property)
end
if #properties == 0 then return end
return properties[1].mainsnak.datavalue and true or nil
end
end



Revisi per 30 Juni 2020 11.16

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

local p = {}
local debug = false


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return entity.claims[property]
	end
end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		i = i + 1
	end
end

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

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

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

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

		i = i + 1
	end
end

return p