Mòdul:Wikidata: diferència entre les revisions

Contingut suprimit Contingut afegit
actualització, corr. títol i tractament dates
actualització, noves opcions, més seguretat, preparació per Wikidata Bridge
Línia 1:
-- version 2019111120200511 from master @cawiki
 
local p = {}
 
--------------------------------------------------------- Initialization of variables --------------------
 
-- internationalisation at [[Module:Wikidata/i18n]]
local i18n = { -- internationalisation at [[Module:Wikidata/i18n]]
local i18n = {
["errors"] = {
["property-not-found"] = "Property not found.",
["qualifier-not-found"] = "Qualifier not found.",
['not-from-content-page'] = "Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing."
},
["datetime"] =
["datetime"] = {
{
-- $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
[1] = "$100 million years", -- precision: hundred million years
Linha 27 ⟶ 31:
[10] = "F Y", -- precision: month
[11] = "F j, Y", -- precision: day
["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
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["years-old"] = {
 
["citesingular"] = { "", -- Citeyear webold, parametersas in {{PLURAL:$1|singular|plural}}
["urlplural"] = "url", -- years old
["paucal"] = "", -- for languages with 3 plural forms as in {{PLURAL:$1|singular|paucal|plural}}
["title"] = "title",
},
["website"] = "website",
["access-date"] = "access-date",
["cite"] = { -- cite parameters
["archive-url"] = "archive-url",
["archive-datetitle"] = "archive-datetitle",
["author"] = "author",
["publisherdate"] = "publisherdate",
["quotepages"] = "quotepages",
["language"] = "language",
-- cite web parameters
["date"] = "date",
["pagesurl"] = "pagesurl",
["website"] = "website",
}
["access-date"] = "access-date",
["archive-url"] = "archive-url",
["archive-date"] = "archive-date",
["publisher"] = "publisher",
["quote"] = "quote",
-- cite journal parameters
["work"] = "work",
["issue"] = "issue",
["issn"] = "issn",
["doi"] = "doi"
},
-- 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
}
 
local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
 
local required = ... -- variadic arguments from require function
----------------------------------------------------------------------------
-- module local functions
 
local wiki =
{
langcode = mw.language.getContentLanguage().code,
module_title = required or mw.getCurrentFrame():getTitle()
module_title = 'Module:Wikidata', -- title of this module for access to its /subpages, change if necessary
}
 
local untranslated -- used in infobox modules: nil or true
-- Credit to http://stackoverflow.com/a/1283608/2644759
local _ -- variable for unused returned values, avoiding globals
-- cc-by-sa 3.0
 
-- 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
Linha 79 ⟶ 96:
end
 
local function loadI18n(lang)
local exist, resi18n_title = pcall(require, wiki.module_title .. "/i18n")
if lang ~= wiki.langcode then i18n_title = "/i18n/" .. lang end
local exist, res = pcall(require, wiki.module_title .. i18n_title)
if exist and next(res) ~= nil then
tableMerge(i18n, res.i18n)
cases = res.cases
end
if lang ~= wiki.langcode and cases.location == nil then
end
cases.location = require(wiki.module_title .. '/i18n').cases.location
 
cases.locationcontext = require(wiki.module_title .. '/i18n').cases.locationcontext
loadI18n()
 
local function case(word, localcase, ...)
if word == nil or word == '' or cases[localcase] == nil then
return word
end
return cases[localcase](word, ...)
end
 
-- Table of language codes: requested or default and its fallbacks
local function findLang(langcode)
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode or '') == false then
local myframecframe = mw.getCurrentFrame()
local pframe = cframe:getParent()
langcode = myframe.args.lang
if langcode == nilpframe orand langcode == "" orpframe.args.lang
if mw.language.isKnownLanguageTag(langcode or '') == false then
if not mw.title.getCurrentTitle().isContentPage then
langcode = myframe:getParent().args.lang
langcode = cframe:preprocess('{{int:lang}}')
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
end
if not mw.title.getCurrentTitle().isContentPage then
if mw.language.isKnownLanguageTag(langcode or '') == false then
langcode = myframe:preprocess( '{{int:lang}}' )
langcode = wiki.langcode
end
if langcode == nil or langcode == "" or mw.language.isKnownLanguageTag(langcode) == false then
langcode = wiki.langcode
end
end
end
end
loadI18n(langcode)
local languages = mw.language.getFallbacksFor(langcode)
table.insert(languages, 1, langcode)
if langcode == wiki.langcode then
for _, l in ipairs(i18n.addfallback) do
table.insert(languages, l)
end
end
return languages
end
 
-- Argument is 'set' when it exists (not nil) or when it is not an empty string.
-- Helper function to obtain the default language code
local function p.langisSet(framevar)
return findLangnot (frame.args[1]var == nil or var == '')[1]
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
return label
end
 
-- get safely a serialized snak
local function getSnak(statement, snaks)
local ret = statement
for i, v in ipairs(snaks) do
if not ret then return end
ret = ret[v]
end
return ret
end
 
Linha 126 ⟶ 170:
local function getLabelByLangs(id, languages)
local label
local lang = languages[1]
for _, l in ipairs(languages) do
if lang == wiki.langcode then
if l == wiki.langcode then
-- using getLabelWithLang when possible instead of getLabelByLang
-- using getLabelWithLang when possible instead of getLabelByLang, do not solve redirects pending phab:T157868
label, lang = mw.wikibase.getLabelWithLang(id)
label, l = mw.wikibase.getLabelWithLang(id)
else
else
for _, l in ipairs(languages) do
label = mw.wikibase.getLabelByLang(id, l)
end
if label then
lang = l
break
if label then
break
end
end
end
Linha 145 ⟶ 189:
local function feminineGender(id)
local claims = mw.wikibase.getBestStatements(id or mw.wikibase.getEntityIdForCurrentPage(),'P21')
if getSnak(claims, {1, "mainsnak", "datavalue"}) == nil then -- no claim, novalue or somevalue
if #claims == 0 then
return false
elseif claims[1].mainsnak.datavalue == nil then -- novalue or somevalue
return false
else
Linha 168 ⟶ 210:
end
 
-- Add an icon for no label in requested language
-- Fetch unit symbol
local function unitSymboladdLabelIcon(idlabel_id, lang, uselang, icon)
local claimsret_lang, ret_icon = findClaims(id'', 'P5061')
if icon then
local langclaims = {}
if claimslang and lang ~= uselang then
ret_lang = " <sup>(" .. lang .. ")</sup>"
for _, snak in ipairs(claims) do
if snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value and
not langclaims[snak.mainsnak.datavalue.value.language] -- just the first one by language
then
langclaims[snak.mainsnak.datavalue.value.language] = snak.mainsnak.datavalue.value.text
end
end
if label_id and (lang == nil or lang ~= uselang) then
for _, l in ipairs(lang) do
ret_icon = " [[File:Noun Project label icon 1116097 cc mirror.svg|10px|baseline|"
if langclaims[l] then
.. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain()
return langclaims[l]
.. "|link=https://www.wikidata.org/wiki/Special:EntityPage/" .. label_id .. "?uselang=" .. uselang .. "]]"
end
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 langclaims["mul"]ret_lang --.. last tryret_icon
end
 
-- Add aan smallicon pencilfor asediting icona forstatement editwith onrequirements for Wikidata Bridge
local function addEditIcon(id, lang, uselang, iconparameters)
local ret = ''
if icon and lang ~= uselang then
if i18n.addpencil and parameters.editicon and parameters.id and parameters.property then
return " [[File:Arbcom ru editing.svg|12px|" .. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain() .. "|link=d:" .. id .. "]]"
ret = ' <span data-bridge-edit-flow="single-best-value">'
.. "[[File:Arbcom ru editing.svg|10px|baseline|"
.. 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
return ret
end
-- add edit icon to the last element of a table
local function addEditIconTable(thetable, parameters)
if #thetable == 0 or not i18n.addpencil then
return thetable
end
local last_element = thetable[#thetable]
local the_icon = addEditIcon(parameters)
-- 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
break
end
end
local last_tags = string.reverse(tags)
local offset = string.find(last_element, last_tags .. '$')
if offset then
thetable[#thetable] = string.sub(last_element, 1, offset - 1) .. the_icon .. last_tags
else
thetable[#thetable] = last_element .. the_icon
end
return ''thetable
end
 
-- Escape URL escapes to avoid Lua captures
local function urlEscapescaptureEscapes(text)
return mw.ustring.gsub(text, "(%%%d)", "%%%1")
end
 
-- expandTemplate or callParserFunction
local function expandBraces(text, formatting)
if text == nil or formatting == nil then return text end
Linha 232 ⟶ 305:
end
braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
braces_expanded = urlEscapescaptureEscapes(braces_expanded)
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
Linha 239 ⟶ 312:
end
 
local-- functionResolve resolveEntityId(id)Wikidata --redirects, pending phab:T157868
local function resolveEntityId(id)
if not id or not mw.wikibase.isValidEntityId(id) then return id end
-- if no label in local language nor its fallbacksEnglish, maybe it is a redirect
-- not using mw.title.new(id).isRedirect as it is expensive
-- currently getLabelByLang does not follows redirects
if mw.wikibase.getLabel(id) == nil then
if mw.wikibase.getLabelByLang(id, 'en') == nil then
local entity = mw.wikibase.getEntity(id) -- expensive function
if not entity then return nil end
Linha 252 ⟶ 327:
require(wiki.module_title .. '/debug').track('redirect/' .. id)
else
-- no redirect and no English label, fix it to avoid expensive functions
require(wiki.module_title .. '/debug').track('label')
require(wiki.module_title .. '/debug').track('label/' .. id)
Linha 261 ⟶ 336:
end
 
local 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)
if not property then return end
end
local claims = mw.wikibase.getAllStatements(entityId, property)
return #claims > 0 and claims or nil
end
 
-- format data type math
local function printDatatypeMath(data)
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
end
 
-- format data type musical-notation
local function printDatavalueString(data, parameters)
local function printDatatypeMusical(data, formatting)
if parameters.formatting == 'weblink' then
local attr = {}
return '[' .. data .. ' ' .. mw.text.split(data, '//' )[2] .. ']'
if formatting == 'sound' then
elseif mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
attr.sound = 1
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', data), parameters.formatting)
end
return mw.getCurrentFrame():extensionTag('score', data, attr)
end
 
-- format data type string
local function printDatatypeString(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(data, parameters.case, data, parameters.lang[1])
else
return data
end
return data
end
 
-- format data type url
local function printDatavalueUrl(data, parameters)
returnlocal printDatavalueString(urlEscapesfunction 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
return '[' .. data .. ' ' .. label .. ']'
end
return printDatatypeString(data, parameters)
end
 
-- format data type external-id
local function printDatatypeExternal(data, parameters)
if parameters.formatting == 'externalid' then
local p_stat = mw.wikibase.getBestStatements(parameters.property, 'P1630') -- formatter URL
local p_link_pattern = getSnak(p_stat, {1, "mainsnak", "datavalue", "value"})
if p_link_pattern then
local p_link = mw.ustring.gsub(p_link_pattern, '$1', {['$1'] = data})
return '[' .. p_link .. ' ' .. data .. ']'
end
end
return printDatatypeString(data, parameters)
end
 
-- format data type commonsMedia
local function printDatatypeMedia(data, parameters)
local icon
if not string.find((parameters.formatting or ''), '$1', 1, true) then
icon = "no-icon"
end
return printDatatypeString(data, parameters), icon
end
 
-- format data type globe-coordinate
local function printDatatypeCoordinate(data, formatting)
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
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 function printDatavalueCoordinate(data, parameter)
local latitude = roundPrecision(data.latitude, precision)
local globes = {['Q3134']='callisto',['Q596']='ceres',['Q15040']='dione',['Q2']='earth',['Q3303']='enceladus',
local longitude = roundPrecision(data.longitude, precision)
['Q3143']='europa',['Q17975']='phoebe',['Q3169']='ganymede',['Q3123']='io',['Q17958']='iapetus',
if formatting and string.find(formatting, '$lat', 1, true) and string.find(formatting, '$lon', 1, true) then
['Q308']='mercury',['Q15034']='mimas',['Q405']='moon',['Q15050']='rhea',['Q15047']='tethys',
local ret = mw.ustring.gsub(formatting, '$l[ao][tn]', {['$lat'] = latitude, ['$lon'] = longitude})
['Q111']='mars',['Q2565']='titan',['Q3359']='triton',['Q313']='venus',['Q3030']='vesta'}
if parameter and mw.ustring.find(parameter, '$lat', 1, true) and mw.ustringstring.find(parameterformatting, '$longlobe', 1, true) then
local ret = mw.ustring.gsub(mw.ustring.gsub(parameter, '$lat', data.latitude), '$lon', data.longitude)
if mw.ustring.find(parameter, '$globe', 1, true) then
local myglobe = 'earth'
if isSet(data.globe and 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, parameterformatting)
elseif parameterformatting == 'latitude' then
return data.latitude, "no-icon"
elseif parameterformatting == 'longitude' then
return data.longitude, "no-icon"
elseif parameterformatting == 'dimension' then
return data.dimension, "no-icon"
else --default formatting='globe'
if isSet(data.globe) == '' or data.globe == nilfalse 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
 
-- Local functions for data value quantity
local function unitSymbol(id, lang) -- get unit symbol or code
local unit_symbol = ''
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
unit_symbol = require(wiki.module_title .. "/Units").getUnit(0, '', id, true)
end
if unit_symbol == '' then
-- fetch it
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
return unit_symbol
end
 
local function getUnit(amount, id, parameters) -- get unit symbol or name
local suffix = ''
if parameters.formatting == "unitcode" then
-- get unit symbol
local unit_symbol = unitSymbol(id, parameters.lang)
if isSet(unit_symbol) then
suffix = unit_symbol
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
 
local function roundPrecision(in_num, out_num)
-- rounds out_num with defaultsignificant precisionfigures of in_num (default precision)
-- first, count digits after decimal mark, handling cases like '12.345e6'
local exponent, prec
Linha 339 ⟶ 531:
end
 
-- format data type quantity
local function printDatavalueQuantity(data, parameters)
local function printDatatypeQuantity(data, parameters)
local amount = data.amount
amount = mw.ustring.gsub(amount, "%+", "")
local sortkey = string.format("%09d", amount)
local suffix = ""
local conv_amount, conv_suffix
if string.sub(parameters.formatting or '', 1, 4) == "unit" or parameters.convert then
-- example "unit": "http://www.wikidata.org/entity/Q174728"
Linha 349 ⟶ 542:
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)
if parameters.convert and parameters.convert ~= unit_id then
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 = resolveEntityId(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'}
Linha 356 ⟶ 559:
['Q11597'] = {['Q25267'] = '$1-273.15', ['Q42289'] = '($1-273.15)*1.8000+32.00'}
}
if conv_temp[unit_id] and conv_temp[unit_id][parameters.convertconvert_to] then
local amount_f = mw.getCurrentFrame():callParserFunction('#expr', mw.ustring.gsub(conv_temp[unit_id][parameters.convertconvert_to], "$1", amount))
amountconv_amount = math.floor(tonumber(amount_f) + 0.5)
unit_id = parameters.convert
else
local conversions = mw.wikibase.getAllStatements(unit_id, 'P2442') -- conversion to standard unit
Linha 365 ⟶ 567:
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/" .. parameters.convertconvert_to then
amountconv_amount = roundPrecision(amount, amount * tonumber(conv.mainsnak.datavalue.value.amount))
unit_id = parameters.convert
break
end
Linha 373 ⟶ 574:
end
end
if conv_amount then
end
conv_suffix = getUnit(conv_amount, convert_to, parameters)
if parameters.formatting == "unitcode" then
-- get unit symbol
local unit_symbol = ''
if parameters.lang[1] == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
unit_symbol = require(wiki.module_title .. "/Units").getUnit(amount, '', unit_id, true, '')
end
if unit_symbol == '' then
unit_symbol = unitSymbol(unit_id, parameters.lang)
end
if unit_symbol then
suffix = " " .. unit_symbol
end
end
if suffix == '' then
-- get unit name
local unit_label, lang = getLabelByLangs(unit_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, unit_id, false, '')
else
suffix = " " .. (unit_label or unit_id) .. addEditIcon(unit_id, lang, parameters.lang[1], parameters.editicon)
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
end
amountlocal lang_obj = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
local sortkey = string.format("%019d", tonumber(amount) * 1000)
if parameters.case then
amount = case(parameters.case, amount, parameters.lang[1])
else
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
return amount .. suffix, sortkey
end
 
-- format data type time
local function printDatavalueTime(data, parameters)
local function printDatatypeTime(data, parameters)
-- Dates and times are stored in ISO 8601 format
local timestamp = data.time
local post_format
local calendar_add = ""
local precision = data.precision or 11
if string.sub(timestamp, 1, 1) == '-' then
Linha 412 ⟶ 614:
elseif string.sub(timestamp, 2, 3) == '00' then
post_format = i18n.datetime["ad"]
elseif precision > 8 then
else
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
Linha 423 ⟶ 625:
end
local function dformatTime(fform, tstamp)
local ts = t or timestamppattern
local form =if type(fform) == "function" and f(ts) or f -- function in i18n.datetime[precision]then
pattern = form(stamp)
if string.sub(ts, 1, 1) == '-' then ts = '+' .. string.sub(ts, 2) end -- formatDate() only supports years from 0
else
return mw.language.new(parameters.lang[1]):formatDate(form, ts)
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
Linha 437 ⟶ 653:
end
local precision = data.precision or 11
local intyear = tonumber(string.match(timestamp, "[+-](%d+)"))
local ret = ""
Linha 444 ⟶ 659:
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(intyear) / factor)
local relative = mw.ustring.gsubformatTime(i18n.datetime[precision], "$1", tostring(y2))
if post_format == i18n.datetime["bc"] then
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
Linha 454 ⟶ 669:
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) / 100010^(9 - precision)) + 1
ifret mw.ustring.find= formatTime(i18n.datetime[6precision], "$1"card) then
ret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(card))
else
ret = d(i18n.datetime[6], string.format("%04d", tostring(card)))
end
ret = postFormat(ret)
elseif precision == 7 then -- centuries
local card = math.floor((math.abs(intyear) - 1) / 100) + 1
if mw.ustring.find(i18n.datetime[7], "$1") then
ret = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(card))
else
ret = d(i18n.datetime[7], string.format("%04d", tostring(card)))
end
ret = postFormat(ret) .. calendar_add
elseif precision == 8 then -- decades
local card = math.floor(math.abs(intyear) / 10) * 10
ret = postFormat(mw.ustring.gsubformatTime(i18n.datetime[8], "$1", tostring(card))) .. calendar_add
ret = postFormat(ret)
elseif intyear > 9999 then -- not a valid timestamp
return
elseif precision == 9 or parameters.formatting == 'Y' then -- precision is year
ret = postFormat(tostringformatTime(i18n.datetime[9], intyear)) .. calendar_add
ret = postFormat(ret) .. calendar_add
elseif precision == 10 then -- month
timestampret = formatTime(i18n.datetime[10], timestamp .. " + 1 day") -- formatDate yyyy-mm-00 returns the previous month
ret = d(i18n.datetime[10])
ret = postFormat(ret) .. calendar_add
ret, _ = string.gsub(ret, "([ %[])0+", "%1") -- supress leading zeros in year, optionally linked
else -- precision 11, day
ret = dformatTime(parameters.formatting or i18n.datetime[11], timestamp)
ret = postFormat(ret) .. calendar_add
ret, _ = string.gsub(ret, "([ %[])0+", "%1")
end
return ret, timestamp
end
 
-- format data value wikibase-entityid: types wikibase-item, wikibase-property
local function printDatavalueEntity(data, parameters)
local function printDatatypeEntity(data, parameters)
local entityId = data['id']
local entity_pageentity_id = data['Special:EntityPage/id' .. entityId]
if parameters.formatting == 'raw' then
return entity_id, entity_id
if data['entity-type'] == 'item' then
entityId = resolveEntityId(entityId)
end
return entityId, entityId
end
local entity_page = 'Special:EntityPage/' .. entity_id
local label, lang = getLabelByLangs(entityId, parameters.lang)
local label, lang = getLabelByLangs(entity_id, parameters.lang)
local sitelink = mw.wikibase.getSitelink(entityId)
local sitelink = mw.wikibase.getSitelink(entity_id)
local parameter = parameters.formatting
local labelcase = label or sitelink
if parameters.case == 'gender' and parameters.gender == 'feminineform' then
labelcase = feminineForm(entityIdentity_id, lang) or labelcase
end
elseif parameters.case ~= 'gender' then
labelcase = case(labelcase, if parameters.case, lang,~= 'gender' entityId)then
labelcase = case(parameters.case, labelcase, lang, parameters.lang[1], entity_id, parameters.id)
end
local ret1, ret2
if parameter == 'label' then
ret1 = (labelcase or entityId)entity_id
ret2 = labelcase or entityIdentity_id
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'wikidatad:' .. entity_page)
ret2 = sitelink or entityIdentity_id
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
ret1 = mw.ustring.gsub(parameter, '$1', labelcase or entityIdentity_id)
ret1 = expandBraces(ret1, parameter)
ret2 = labelcase or entityIdentity_id
else
if parameter == "ucfirst" or parameter == "ucinternallink" then
if labelcase =and lang then
labelcase and= mw.language.new(lang):ucfirst(labelcase)
end
-- only first of a list, reset formatting for next ones
if parameter == "ucinterlanllink" then
Linha 535 ⟶ 740:
ret2 = labelcase
else
ret1 = '[[wikidatad:' .. entity_page .. '|' .. (labelcase or entityIdentity_id) .. ']]'
ret2 = labelcase or entityIdentity_id
end
end
return ret1 .. addEditIconaddLabelIcon(entity_pageentity_id, lang, parameters.lang[1], parameters.editicon), ret2
end
 
-- format data type monolingualtext
local function printDatavalueMonolingualText(data, parameters)
local function printDatatypeMonolingual(data, parameters)
-- data fields: language [string], text [string]
Linha 553 ⟶ 759:
local result = data["text"]
if data["language"] ~= wiki.langcode then
result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext,'<span lang="%%language$1">$2</span>', '$[12]', {["$1"]=data["language"]), ["%%text$2", ]=data["text"]})
end
if mw.ustring.find((parameters.formatting or ''), '$', 1, true) then
Linha 561 ⟶ 767:
end
return result
end
 
local function printError(key)
return '<span class="error">' .. i18n.errors[key] .. '</span>'
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
 
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)
if not property then return end
end
local claims = mw.wikibase.getAllStatements(entityId, property)
if #claims == 0 then
claims = nil
end
return claims
end
 
local function getSnakValue(snak, parameters)
if snak.snaktype == 'value' then
-- see Special:ListDatatypes
-- call the respective snak parser
if snak.datatype == 'math'"string" then
return printDatatypeString(snak.datavalue.value, parameters)
-- other data value string, tabular-data not implemented
elseif snak.datatype == "commonsMedia" then
return printDatatypeMedia(snak.datavalue.value, parameters)
elseif snak.datatype == "url" then
return printDatatypeUrl(snak.datavalue.value, parameters)
elseif snak.datatype == "external-id" then
return printDatatypeExternal(snak.datavalue.value, parameters)
elseif snak.datatype == 'math' then
return printDatatypeMath(snak.datavalue.value)
elseif snak.datatype == "url"'musical-notation' then
return printDatavalueUrlprintDatatypeMusical(snak.datavalue.value, parameters.formatting)
-- other data types
elseif snak.datavalue.type == "string" then
elseif snak.datatype == 'wikibase-item' or snak.datatype == 'wikibase-property' then
return printDatavalueString(snak.datavalue.value, parameters)
elseif return printDatatypeEntity(snak.datavalue.typevalue, == "globecoordinate" thenparameters)
elseif snak.datatype == 'monolingualtext' then
return printDatavalueCoordinate(snak.datavalue.value, parameters.formatting)
elseif return printDatatypeMonolingual(snak.datavalue.typevalue, == "quantity" thenparameters)
elseif snak.datatype == "globe-coordinate" then
return printDatavalueQuantity(snak.datavalue.value, parameters)
elseif return printDatatypeCoordinate(snak.datavalue.typevalue, == "time" thenparameters.formatting)
elseif snak.datatype == "quantity" then
return printDatavalueTime(snak.datavalue.value, parameters)
elseif return printDatatypeQuantity(snak.datavalue.typevalue, == 'wikibase-entityid' thenparameters)
elseif snak.datatype == "time" then
return printDatavalueEntity(snak.datavalue.value, parameters)
elseif return printDatatypeTime(snak.datavalue.typevalue, == 'monolingualtext' thenparameters)
return printDatavalueMonolingualText(snak.datavalue.value, parameters)
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
return mw.wikibase.renderSnak(snak)
end
 
local function printError(key)
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
 
Linha 638 ⟶ 823:
-- iterate over monolingualtext qualifiers to get local language
for idx in pairs(qualifier) do
if getSnak(qualifier[idx]., {"datavalue.", "value", and qualifier[idx].datavalue.value."language"}) == parameters.lang[1] then
return qualifier[idx]
end
Linha 656 ⟶ 841:
end
 
local function getValueOfClaim(claim, qualifierId, parameters)
local snak, error = getQualifierSnak(claim, qualifierId, parameters)
local error
local snak
snak, error = getQualifierSnak(claim, qualifierId, parameters)
if not snak then
return nil, nil, error
elseif snak[1] then -- a multi qualifier
local result, sortkey = {}, {}
local sortkey = {}
for idx in pairs(snak) do
result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
Linha 693 ⟶ 875:
end
 
-- see d:Help:Sources
local function getReferences(claim)
local function getReferences(claim, lang)
local refaliases = {
local notproperref = {
citeWeb = "Q5637226",
["P143"] = true, -- imported from
author = "P50",
["P3452"] = true, -- inferred from
publisher = "P123",
["P887"] = true, -- based on heuristic
importedFrom = "P143",
["P4656"] = true -- Wikimedia import URL
statedIn = "P248",
pages = "P304",
publicationDate = "P577",
startTime = "P580",
endTime = "P582",
chapter = "P792",
retrieved = "P813",
referenceURL = "P854",
archiveURL = "P1065",
title = "P1476",
quote = "P1683",
shortName = "P1813",
language = "P2439",
archiveDate = "P2960"
}
local result = ""
Linha 719 ⟶ 888:
local refparts
local refs = {}
local validref = true
local ref_name
-- traverse through all parts of the current reference
for snakkey, snakval in pairs(claim.references[ref].snaks or {}) do
for partkey, _ in pairs(claim.references[ref].snaks[snakkey] or {}) do
if snakkey ~= refaliases.importedFrom then -- "imported from" is not a proper reference
if notproperref[snakkey] then -- not a proper reference
validref = false
break
end
end
if validref then
for snakidx = 1, #snakval do
if snakidx > 1 then refparts = refparts .. ", " end
refparts = refparts or '' .. getSnakValue(snakval[snakidx], {lang={wiki.langcode}lang})
end
refs[snakkey] = refparts
refparts = nil
if snakkey == "P248" then -- stated in
ref_name = snakval[1].datavalue.value.id
end
end
end
-- fill missing values with parent item
-- get title of general template for citing web references
if ref_name then
local template = mw.wikibase.getSitelink(refaliases.citeWeb) or ""
local function refParent(qid, pid, formatting)
template = mw.text.split(template, ":")[2] -- split off namespace from front
local snak = getSnak(mw.wikibase.getBestStatements(qid, pid), {1, "mainsnak"})
return snak and getSnakValue(snak, {formatting=formatting, lang=lang})
end
refs['P50'] = refs['P50'] or refParent(ref_name, 'P50', 'label') -- author
refs['P407'] = refs['P407'] or refParent(ref_name, 'P407', 'label') -- language of work
refs['P123'] = refs['P123'] or refParent(ref_name, 'P123', 'label') -- publisher
refs['P577'] = refs['P577'] or refParent(ref_name, 'P577') -- date
refs['P1433'] = refs['P1433'] or refParent(ref_name, 'P1433', 'label') -- published in
refs['P304'] = refs['P304'] or refParent(ref_name, 'P304') -- page(s)
refs['P433'] = refs['P433'] or refParent(ref_name, 'P433') -- issue
refs['P236'] = refs['P236'] or refParent(ref_name, 'P236') -- ISSN
refs['P356'] = refs['P356'] or refParent(ref_name, 'P356') -- DOI
end
-- (1)get if both "reference URL" and "title" areof present,local then use the general templatetemplates for citing web references
local template_web = mw.wikibase.getSitelink('Q5637226') or ""
if refs[refaliases.referenceURL] and (refs[refaliases.title] or refs[refaliases.statedIn]) and template then
template_web = mw.text.split(template_web, ":")[2] -- split off namespace from front
local citeParams = {}
local template_journal = mw.wikibase.getSitelink('Q5624899') or ""
citeParams[i18n['cite']['url']] = refs[refaliases.referenceURL]
template_journal = mw.text.split(template_journal, ":")[2]
citeParams[i18n['cite']['title']] = refs[refaliases.title] or refs[refaliases.statedIn]:match("^%[%[.-|(.-)%]%]")
citeParams[i18n['cite']['website']] = refs[refaliases.statedIn]
local citeParams[i18n['cite']['language']] = refs[refaliases.language]{}
if refs['P854'] and (refs['P1476'] or refs['P248']) and template_web then
citeParams[i18n['cite']['date']] = refs[refaliases.publicationDate]
-- if both "reference URL" and "title" (or "stated in") are present, then use cite web template
citeParams[i18n['cite']['access-date']] = refs[refaliases.retrieved]
citeParams[i18n['cite']['archive-url']] = refs[refaliases.archiveURL'P854']
if refs['P248'] and refs['P1476'] == nil then
citeParams[i18n['cite']['archive-date']] = refs[refaliases.archiveDate]
citeParams[i18n['cite']['publishertitle']] = refs[refaliases'P248']:match("^%[%[.publisher-|(.-)%]%]")
else
citeParams[i18n['cite']['quote']] = refs[refaliases.quote]
citeParams[i18n['cite']['pagestitle']] = refs[refaliases.pages'P1476']
citeParams[i18n['cite']['authorwebsite']] = refs[refaliases.author'P248']
end
refparts = mw.getCurrentFrame():expandTemplate{title=template, args=citeParams}
citeParams[i18n['cite']['author']] = refs['P50']
else
citeParams[i18n['cite']['language']] = refs['P407']
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_web, args=citeParams}
elseif refs['P1433'] and (refs['P1476'] or refs['P248']) and template_journal then
-- if both "published in" and "title" (or "stated in") are present, then use cite journal template
citeParams[i18n['cite']['work']] = refs['P1433']
citeParams[i18n['cite']['title']] = refs['P1476'] or refs['P248']
citeParams[i18n['cite']['author']] = refs['P50']
citeParams[i18n['cite']['date']] = refs['P577']
citeParams[i18n['cite']['issue']] = refs['P433']
citeParams[i18n['cite']['pages']] = refs['P304']
citeParams[i18n['cite']['language']] = refs['P407']
citeParams[i18n['cite']['issn']] = refs['P236']
citeParams[i18n['cite']['doi']] = refs['P356']
refparts = mw.getCurrentFrame():expandTemplate{title=template_journal, args=citeParams}
elseif validref then
-- raw ouput
forlocal k,snaksorder v in orderedpairs(refs or {},= claim.references[ref]["snaks-order"]) do
local function indexed(a)
if k and v then
for _, b in ipairs(snaksorder) do
if refparts then refparts = refparts .. ", " else refparts = "" end
if b == a then return true end
refparts = refparts .. tostring(mw.wikibase.getLabel(k)) .. ": "
end
refparts = refparts .. v
return false
end
for k, _ in pairs(refs or {}) do
if not indexed(k) then
table.insert(snaksorder, k)
end
end
local italics = "''"
for _, k in ipairs(snaksorder) do
if refs[k] then
refparts = refparts and refparts .. " " or ""
refparts = refparts .. mw.ustring.gsub(getLabelByLangs(k, lang), "^%l", mw.ustring.upper) .. ": "
refparts = refparts .. italics .. refs[k] .. italics .. "."
italics = ""
end
end
end
if refparts then result = result .. mw.getCurrentFrame():extensionTag("ref", refparts, {name=ref_name}) end
end
return result
end
 
-- Move to Module:Wikibase?
function p.getSiteLink(frame)
--require(wiki.module_title .. '/debug').track('getSiteLink')
local id = frame.args[1]
if id == nil or id == '' then
id = mw.wikibase.getEntityIdForCurrentPage()
if id == nil then
return
end
end
return mw.wikibase.getSitelink(id, frame.args[2])
end
 
Linha 784 ⟶ 1.001:
local list = {}
for i = 0, num_qual do
if isSet(args[type_list .. i] and args[type_list .. i] ~= '') then
listed = true
list[tostring(i)] = {}
localfor valuesv =in mwstring.text.splitgmatch(args[type_list .. i], "/",'Q%d+') true)do
for _, v in ipairs(values) do
list[tostring(i)][v] = true
list[tostring(i)][resolveEntityId(v)] = true
end
Linha 807 ⟶ 1.022:
end
 
local function p.claimgetEntityId(frame, unnamed)
local args = frame.args or frame
if mw.title.new(frame:getParent():getTitle()).isContentPage then
local pargs = frame.args and frame:getParent().args
if not mw.title.new(frame:getTitle()).isSubpage then
local id = args.item or args.from or (unnamed and mw.text.trim(args[1] or '') or nil)
-- invoked from a content page and not invoking a module subpage
if not isSet(id) and pargs then
return printError("not-from-content-page")
id = pargs.item or pargs.from or (unnamed and mw.text.trim(pargs[1] or '') or nil)
end
if isSet(id) then
if string.find(id, ":") then -- remove prefix as Property:Pid
id = mw.text.split(id, ":")[2]
end
else
id = mw.wikibase.getEntityIdForCurrentPage()
end
return id
return p._main(frame.args, frame:getParent().args)
end
 
-- Main function claim ---------------------------------------------
-- Entry point from other modules or debugging, with a list of arguments.
-- Fromon otherdebug modulesconsole use: require("Module:Wikidata")=p._main(claim{item="Q...", property="P...", ...})
function p.claim(frame)
-- On debug console use: =p._main({item="Q...", lang="xx", property="P...", ...})
if not required and frame.args and isSet(frame:getParent().args.sandbox) then
function p._main(args, pargs)
return require(wiki.module_title .. "/" .. mw.message.new('Sandboxlink-subpage-name'):inLanguage(wiki.langcode):plain()).claim(frame)
end
local args = frame.args or frame -- via invoke or require
--If a value is already set, use it
if isSet(args.value) andthen
if args.value ~== 'NONE' then
return args.value
else
return args.value
end
end
-- arguments
local id = args.item or getEntityId(pargs and pargs.itemframe)
if id == nil orthen idreturn == "" thenend
local property = string.upper(args.property or "")
id = mw.wikibase.getEntityIdForCurrentPage()
end
local property = string.upper(args["property"] or "")
local qualifierId = {}
qualifierId[1] = isSet(args[".qualifier"]) and string.upper(args[".qualifier"]) or nil
local i = 2
while isSet(args["qualifier" .. i]) do
qualifierId[i] = string.upper(args["qualifier" .. i])
i = i + 1
end
local formatting = isSet(args[".formatting"];) ifand args.formatting == "" then formatting =or nil end
local convert = isSet(args[".convert"];) ifand args.convert == "" then convert =or nil end
if convert and string.sub(convert, 1, 1) ~= "Q" then convert = nil 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) orand 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
Linha 895 ⟶ 1.122:
-- fetch property
local claims = findClaims(id, property)
for p in string.gmatch(property, 'P%d+') do
claims = findClaims(id, p)
if claims and claims[1] then
parameters.property = p
break
end
end
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
end
-- find language and defaults
parameters.lang = findLang(args.lang)
-- set feminine case if gender is requested
local itemgender = args[".itemgender"]
local idgender
if itemgender then
if string.match(itemgender, "^P%d+$") then
local snaksnak_id = getSnak(mw.wikibase.getBestStatements(id, itemgender)[, {1], "mainsnak", "datavalue", "value", "id"})
if snak_id then
if snak and snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value then
idgender = snak.mainsnak.datavalue.value.idsnak_id
end
elseif string.match(itemgender, "^Q%d+$") then
Linha 947 ⟶ 1.178:
table.sort(sortindices, comparator)
local result, result2
local error
if parameters.list or parameters.formatting == "table" then
Linha 966 ⟶ 1.197:
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
Linha 1.027 ⟶ 1.258:
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
Linha 1.039 ⟶ 1.270:
end
if sorting_col then
local sorting_table = mw.text.split(sorting_col, '/%D+', true)
local comparator = function(a, b)
local valuea, valueb
Linha 1.059 ⟶ 1.290:
for idx in pairs(values) do
local valuerow = values[sortindices[idx]]
local reference = getReferences({["references"] = refs[sortindices[idx]]["col0"]}, parameters.lang)
 
value = valuerow["col0"]
if parameters.formatting == "table" then
Linha 1.066 ⟶ 1.297:
value = nil
else
valuelocal rowformatting = mw.ustring.gsub(rowformat .. "$", "$0", value) -- fake end character added for easy gsub
value = mw.ustring.gsub(rowformatting, "$0", value)
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
local rowformatting = rowformat .. "$"
for i, _ in ipairs(qualifierId) do
local valueq = valuerow["col" .. i]
Linha 1.075 ⟶ 1.306:
-- 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 urlEscapescaptureEscapes(valueq) or ''
value = mw.ustring.gsub(value, "$" .. i .. "(%D)", valueq .. "%1")
end
Linha 1.085 ⟶ 1.317:
value = expandBraces(value, rowformatting)
end
elseif value then
else
value = expandBraces(value, parameters.formatting)
value = value .. reference
end
if isSet(value) then
result[#result + 1] = value
result[#result + 1] = value
if not parameters.list then
if not parameters.list then
break
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
Linha 1.097 ⟶ 1.336:
-- 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, parameters.lang) end
end
if isSet(result) then return result else
if i18n.addpencil and not (parameters.formatting == 'table' or (result2 and result2 == 'no-icon')) then
if showerrors then return error else return default end
-- add edit icon, except table added previously and except explicit no-icon internal flag
result = result .. addEditIcon(parameters)
end
else
if showerrors then result = error else result = default end
end
return result, not required and '' or untranslated
end
 
Linha 1.130 ⟶ 1.375:
end
 
-- debuggingLocal functions, seefor modulegetParentValues ../debug.-----------------------
function p.ViewSomething(frame)
return require(wiki.module_title .. "/debug").ViewSomething(frame)
end
 
function p.Dump(frame)
return require(wiki.module_title .. "/debug").Dump(frame)
end
 
function p.getEntityFromTree(frame)
return require(wiki.module_title .. "/debug").getEntityFromTree(frame)
end
 
-- local functions for getParentValues
 
local function uc_first(word)
Linha 1.151 ⟶ 1.383:
local function getPropertyValue(id, property, parameter, langs, editicon, case)
local snaks = mw.wikibase.getBestStatements(id, property)
local mysnak = getSnak(snaks, {1, "mainsnak"})
if snaksmysnak and== snaks[1] and snaks[1].mainsnaknil then
mysnak = snaks[1].mainsnak
else
return
end
local entityIdentity_id
local result = '-' -- default for 'no value'
if mysnak.datavalue then
entityIdentity_id = "Q" .. tostring(mysnak.datavalue.value['numeric-id'])
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon, case=case})
end
return entityIdentity_id, result
end
 
local function contains(tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
 
local function getParentObjects(id,
prop_format,
formatting,
label_format,
languages,
propertySupString,
Linha 1.192 ⟶ 1.413:
include_self)
if (upto_linkId == nil) then upto_linkId = "" end
local upto_link_ids = {}
for q in mw.text.splitgsplit(upto_linkId, '[/^Q%sd]+') do
upto_link_ids[q] = true
local propertySups = mw.text.split(propertySupString, '[/%s]+')
end
local propertySups = mw.text.split(propertySupString, '[^P%d]')
local lastlabel = uc_first(upto or '')
local maxloop = tonumber(upto) or ((lastlabel .. upto_linkId) == '' 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
Linha 1.207 ⟶ 1.431:
local label_self
_, label_self = getPropertyValue(id, propertyLabel, "label"label_format, languages)
local result = {}
local label, link, linktext
for iter = 1, maxloop do
local link, label, linklinktext, _id, _link
for _, propertySup in pairs(propertySups) do
_id, _link = getPropertyValue(id, propertySup, formattingprop_format, languages, editicon, grammatical_case)
if _id and _link then id = _id; link = _link break end
end
Linha 1.229 ⟶ 1.451:
end
_, label = getPropertyValue(id, propertyLabel, "label"label_format, languages, false, "infoboxlabel")
if label then
label = case(label, "infoboxlabel", languages[1])
end
if labelShow == nil or labelFilter[label] then
Linha 1.243 ⟶ 1.461:
end
if not tonumber(upto) and label == lastlabel or upto_link_ids[id] then
break
end
if contains(upto_link_ids, id) then
break
end
Linha 1.263 ⟶ 1.477:
local function parentObjectsToString(result,
rowformat,
separator,
cascade,
sorting)
Linha 1.285 ⟶ 1.498:
end
return mw.text.listToText(ret, separator, separator)
end
 
-- Returns pairs of instance label and property value fetching a recursive tree
function p.getParentValues(frame)
localif 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()).getParentValues(frame)
local id = args.item or frame:getParent().args.item
if id == "" or id == nil then
id = mw.wikibase.getEntityIdForCurrentPage()
if id == nil then return end
end
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame)
if id == nil then return end
local languages = findLang(args.lang)
local propertySup = args[".property"]; if not isSet(propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entity
local propertyLabel = args[".label"]; if not isSet(propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instance
local propertyLink = args[".valuetext"]; if propertyLink == "" then propertyLink = nil end --internallink
local uptoproperty_format = args["upto"].formatting; if uptoproperty_format == "" then uptoproperty_format = nil end
local label_format = args.labelformat; if not isSet(label_format) then label_format = "label" end
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 and args.uptolabelid ~= "") then
upto, _ = mw.wikibase.getLabelgetLabelByLangs(args.uptolabelid, languages)
end
if isSet(args.showlabelid and args.showlabelid ~= "") then
local showLabelList = {}
for substring in mw.text.gsplit(args.showlabelid, '[/^Q%sd]+') do
table.insert(showLabelList, mw.wikibase.getLabel(getLabelByLangs(substring, languages)) )
end
if #showLabelList > 0 then
labelShow = table.concat(showLabelList,"/")
Linha 1.319 ⟶ 1.537:
local result = getParentObjects(id,
property_format,
args.formatting,
label_format,
languages,
propertySup,
Linha 1.327 ⟶ 1.546:
editicon,
upto,
args.uptovalueid or args.uptolinkid,
last_only,
case,
include_self)
if #result == 0 then return end
local rowformat = args[".rowformat"]; if not isSet(rowformat == nil or rowformat == "") then rowformat = "$0 = $1" end
local separator = args[".separator"]; if not isSet(separator == nil or separator == "") then separator = "<br />" end
local sorting = args[".sorting"]; if sorting == "" then sorting = nil end
local cascade = (args.cascade == "true" or args.cascade == "yes")
returnlocal ret = parentObjectsToString(result,
rowformat,
separator,
cascade,
sorting)
ret = addEditIconTable(ret, {property=propertySup, editicon=editicon, id=id, lang=languages})
return mw.text.listToText(ret, separator, separator)
end
 
-- Link with a parent label --------------------
function p.linkWithParentLabel(frame)
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()).linkWithParentLabel(frame)
end
local args = {}
if frame.args then
for k, v in pairs(frame.args) do -- metatable
args[k] = v
end
else
args = frame -- via require
end
if isSet(args.value) then
return args.value
-- get internal link of property/qualifier
args.list = "true"
args.formatting = "internallink"
args.separator = "/·/"
local pargs = frame:getParent().args
local link_list = p._main(args, pargs)
if link_list == nil or link_list == "" then
return
end
local link_table = mw.text.split(link_list, "/·/", true)
-- get id value of property/qualifier
local largs = mw.clone(args)
args.formatting = "raw"
largs.list = "true"
local items_list = p._main(args, pargs)
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"})
args.property = args.parent
if parent_claim == 'monolingualtext' then
args.qualifier = nil
largs.formatting = nil
local parent_claims = findClaims(items_table[1], args.parent)
largs.list = 'lang'
if parent_claims and parent_claims[1].mainsnak.datatype == 'monolingualtext' then
args.formatting = nil
args.list = 'lang'
else
argslargs.formatting = "label"
argslargs.list = "false"
end
largs.property = args.parent
largs.qualifier = nil
for i, v in ipairs(items_table) do
argslargs.item = v
local link_label, _ = p._mainclaim(args, pargslargs)
if isSet(link_label and link_label ~= '') then
link_table[i] = mw.ustring.gsub(link_table[i] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
end
end
args.editicon = not (args.editicon == "false" or args.editicon == "no")
args.id = getEntityId(frame)
return mw.text.listToText(link_table)
args.lang = findLang(args.lang)
end
return mw.text.listToText(link_table) .. addEditIcon(args)
 
function p.years_old(frame)
require(wiki.module_title .. '/debug').track('years_old')
return p.yearsOld(frame)
end
 
-- Calculate number of years old ----------------------------
function p.yearsOld(frame)
localif 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()).yearsOld(frame)
local id = args.item
if id == '' or id == nil then
id = mw.wikibase.getEntityIdForCurrentPage()
end
local args = frame.args or frame -- via invoke or require
local id = getEntityId(frame)
local lang = mw.language.new('en')
local function getBestValue(id, prop)
local snaksnak_value = getSnak(mw.wikibase.getBestStatements(id, prop)[, {1], "mainsnak", "datavalue", "value"})
return snak_value
if snak and snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value then
return snak.mainsnak.datavalue.value
end
end
Linha 1.462 ⟶ 1.689:
local old_min = age(dates[1].max, dates[2].min)
local old_max = age(dates[1].min, dates[2].max)
local old, old_expr
local old = old_min == old_max and old_min or old_min .. "/" .. old_max
if args.formattingold_min == 0 and old_max == 0 then
old = "< 1"
old = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
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 oldold_expr
end
 
-- Gets a label in a given language (content language by default) or its fallbacks, optionnally linked.
function p.getLabel(frame)
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 = mw.text.trimgetEntityId(args[1]frame, or ""true)
if not id or id == ""nil then return end
local editicon = not (args.editicon == "false" or args.editicon == "no") and mw.wikibase.isValidEntityId(id)
local pencillabel_icon = ''
local label, lang
if args.label then
Linha 1.490 ⟶ 1.751:
if label == nil then
id = resolveEntityId(id)
label, lang = getLabelByLangs(id, languages)
if label then
Linha 1.498 ⟶ 1.758:
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
pencillabel_icon = addEditIconaddLabelIcon('Special:EntityPage/' .. id, lang, languages[1], editicon)
end
end
local linked = args.linked
if isSet(linked and linked ~= "") and linked ~= "no" then
local article = mw.wikibase.getSitelink(id) or ("d:" .. id)
return "[[" .. article .. "|" .. (label or id) .. "]]" .. pencillabel_icon, not required and '' or untranslated
else
return (label or id) .. pencillabel_icon, not required and '' or untranslated
end
end
 
-- Utilities -----------------------------
-- See also module ../debug.
 
-- Copied from Module:Wikibase
function p.getSiteLink(frame)
local id = getEntityId(frame, 1)
if id == nil then
return
end
return mw.wikibase.getSitelink(id, mw.text.trim(frame.args[2] or ''))
end
 
-- Helper function for the default language code used
function p.lang(frame)
local lang = frame and frame.args[1] -- nil via require
return findLang(lang)[1]
end
 
-- Number of statements
function p.numStatements(frame)
local id = getEntityId(frame)
if id == nil then
return 0
end
local args = frame.args
local prop = mw.text.trim(args[1])
local num = mw.wikibase.getBestStatements(id, prop)
return #num
end
 
-- Returns true if property datavalue is found excluding novalue/somevalue
function p.validProperty(frame)
local property = mw.text.trim(frame.args[1])
local item = getEntityId(frame)
if item == nil then return end
local prop_data = getSnak(mw.wikibase.getBestStatements(item, property), {1, "mainsnak", "datavalue"})
return prop_data and true or nil
end