Module:Wikidata/sandbox : Tameẓla gar ileqman

Contenu supprimé Contenu ajouté
Sami At Ferḥat (mmeslay | attekki)
Aucun résumé des modifications
Sami At Ferḥat (mmeslay | attekki)
Aucun résumé des modifications
Ajerriḍ 1:
-- version 2018102820191205 from master @cawiki
 
local p = {}
Ajerriḍ 8:
["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.",
['not-from-content-page'] = "Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing ."
},
["datetime"] =
Ligne 24 ⟶ 17 :
[2] = "$10 million years", -- precision: ten million years
[3] = "$1 million years", -- precision: million years
[4] = "$100,000100000 years", -- precision: hundred thousand years; thousand separators added afterwards
[5] = "$10,00010000 years", -- precision: ten thousand years; thousand separators added afterwards
[6] = "$1 millennium", -- precision: millennium
[7] = "$1 century", -- precision: century
[8] = "$1s", -- precision: decade
-- the following use the format of #time parser function
[9] = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[11] = "F j, Y", -- precision: day
[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 positive1st yearscentury AD dates
["bc-addon"] = " BC", -- suffix for negative dates
["ad-addon"] = "" -- suffix for 1st century AD dates
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["years-old"] = {
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
["singular"] = "", -- year old, or nominative singular, translate it at /i18n
["plural"] = "", -- years old, or genitive plural, translate it at /i18n
["paucal"] = "", -- genitive singular only used for Russian and other Slavic languages
},
["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 cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
 
----------------------------------------------------------------------------
-- module local functions
 
local wiki =
{
langcode = mw.language.getContentLanguage().code,
module_title = "'Module:Wikidata"', -- title of this module for access to its /subpages, change if necessary
}
 
----------------------------------------------------------------------------
-- module local functions
 
-- Credit to http://stackoverflow.com/a/1283608/2644759
Ligne 101 ⟶ 93 :
loadI18n()
 
-- Argument is 'set' when it exists (not nil) or when it is not an empty string.
local function case(word, localcase, lang)
local function isSet(var)
if word == nil or word == '' or cases[localcase] == nil then
return not (var == nil or var == '')
return word
end
 
local function case(localcase, label, ...)
if not isSet(label) or cases[localcase] == nil then
return label
end
return cases[localcase](wordlabel, lang...)
end
 
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
Ligne 128 ⟶ 123 :
table.insert(languages, 1, langcode)
return languages
end
 
-- Helper function to obtain the default language code
function p.lang(frame)
local lang = frame and frame.args[1] -- nil via require
return findLang(lang)[1]
end
 
Ligne 151 ⟶ 152 :
-- Is gender femenine? true or false
local function feminineGender(id)
local entityclaims = mw.wikibase.getEntitygetBestStatements(id or mw.wikibase.getEntityIdForCurrentPage(),'P21')
if #claims == 0 then
local genderClaims = entity.claims["P21"] -- sex or gender
return false
if genderClaims then
elseif claims[1].mainsnak.datavalue == nil then -- novalue or somevalue
local genderId = getValueOfClaim(genderClaims[1], nil, {["formatting"]="raw"})
return false
else
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
Ligne 164 ⟶ 168 :
-- Fetch female form of label
local function feminineForm(id, lang)
local feminine_claims = findClaims(mw.wikibase.getEntitygetBestStatements(id), 'P2521') -- female form of label
iffor _, feminine_claim in ipairs(feminine_claims) thendo
for _,if feminine_claim.mainsnak.datavalue.value.language in== ipairs(feminine_claims)lang dothen
return feminine_claim.mainsnak.datavalue.value.text
local feminine_value = getValueOfClaim(feminine_claim, nil, {["list"]="lang", ["lang"]={lang}})
if feminine_value then
return feminine_value
end
end
end
Ligne 177 ⟶ 178 :
-- Fetch unit symbol
local function unitSymbol(id, lang)
local claims = findClaims(mw.wikibase.getEntity(id), 'P5061')
local langclaims = {}
if claims then
Ligne 202 ⟶ 203 :
end
return ''
end
 
-- Escape URL escapes to avoid Lua captures
local function urlEscapes(text)
return mw.ustring.gsub(text, "(%%%d)", "%%%1")
end
 
Ligne 217 ⟶ 223 :
local parameters = {}
for i = 2, #parts do
iflocal subparts = mw.ustring.find(parts[i], "=") then
localif subparts = mw.text.split(parts[i], "=")then
parameters[subpartsmw.ustring.sub(parts[i], 1], subparts-1)] = subpartsmw.ustring.sub(parts[2i], subparts+1, -1)
else
table.insert(parameters, parts[i])
Ligne 234 ⟶ 240 :
end
braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
braces_expanded = mw.ustring.gsuburlEscapes(braces_expanded, "(%%[0-9])", "%%%1") -- no captures in replacement string, i.e. url %-coded
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
return text
end
 
local function resolveEntityId(id) -- pending phab:T157868
if not id or not mw.wikibase.isValidEntityId(id) then return id end
-- if no label in local language nor its fallbacks, maybe it is a redirect
-- not using mw.title.new(id).isRedirect as it is expensive
if mw.wikibase.getLabel(id) == nil then
local entity = mw.wikibase.getEntity(id) -- expensive function
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
 
local function printDatatypeMath(data)
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
end
 
local function printDatatypeMusical(data, formatting)
local attr = {}
if formatting == 'sound' then
attr.sound = 1
end
return mw.getCurrentFrame():extensionTag('score', data, attr)
end
 
local function printDatavalueString(data, parameters)
if parameters.formatting == 'weblink' then
return '[' .. data .. ' ' .. mw.text.split(data, '//' )[2] .. ']'
elseif 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)
local escaped_data = mw.ustring.gsub(data, "%%", "%%%") -- escape % character, normally used in url, avoiding invalid capture in gsub
return expandBraces(mw.ustring.gsub(parameters.formatting, '$1', escaped_data), parameters.formatting)
elseif parameters.case then
return case(data, parameters.case, data, parameters.lang[1])
else
return data
end
end
 
local function printDatatypeUrl(data, parameters)
return printDatavalueString(urlEscapes(data), parameters)
end
 
local function printDatavalueCoordinate(data, parameter)
local globes = {['Q3134']='callisto',['Q596']='ceres',['Q15040']='dione',['Q2']='earth',['Q3303']='enceladus',
if parameter == 'latitude' then
['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'}
if parameter and mw.ustring.find(parameter, '$lat', 1, true) and mw.ustring.find(parameter, '$lon', 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) 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, parameter)
elseif parameter == 'latitude' then
return data.latitude
elseif parameter == 'longitude' then
Ligne 265 ⟶ 323 :
return 'earth'
else
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
return globes[globenum] or globenum
if pcall(require, "Module:Mapa cos celeste/dades") then
local globetable = mw.loadData('Module:Mapa cos celeste/dades')
for _, globe in pairs(globetable.maps) do
if globe.wikidata == globenum then
return globe.coord_globe
end
end
end
return globenum
end
end
end
 
local function roundPrecision(in_num, out_num)
-- rounds out_num with default precision of in_num
-- first, count digits after decimal mark, handling cases like '12.345e6'
local exponent, prec
local integer, dot, decimals, expstr = in_num:match('^(%d*)(%.?)(%d*)(.*)')
local e = expstr:sub(1, 1)
if e == 'e' or e == 'E' then
exponent = tonumber(expstr:sub(2))
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
 
local function printDatavalueQuantity(data, parameters)
-- exemples: 277±1 Centímetre, 1,94 metre
local amount = data.amount
amount = mw.ustring.gsub(amount, "%+", "")
local sortkey = string.format("%09d", amount)
amount = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
-- This is used to get the unit name for a numeric value
local suffix = ""
if string.sub(parameters.formatting or '', 1, 4) == "unit" or parameters.formatting == "unitcode"convert then
-- example "unit": "http://www.wikidata.org/entity/Q174728"
-- get the url for the unit entry on Wikidata:
local unitIDunit_id = data.unit
unit_id = mw.ustring.sub(unit_id, mw.ustring.find(unit_id, "Q"), -1)
-- and just return the last bit from "Q" to the end (which is the QID):
unitIDif = mw.ustringstring.sub(unitIDunit_id, mw.ustring.find(unitID1, 1) == "Q"), -1)then
if mwparameters.ustring.sub(unitID,convert 1,and 1)parameters.convert =~= "Q"unit_id then
-- convert units
local unit_label, lang = getLabelByLangs(unitID, parameters.lang)
local conv_temp = { -- formulae for temperatures ºC, ºF, ªK: [from] = {[to] = 'formula'}
local unit_symbol
['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][parameters.convert] then
local amount_f = mw.getCurrentFrame():callParserFunction('#expr', mw.ustring.gsub(conv_temp[unit_id][parameters.convert], "$1", amount))
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
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/" .. parameters.convert then
amount = roundPrecision(amount, amount * tonumber(conv.mainsnak.datavalue.value.amount))
unit_id = parameters.convert
break
end
end
end
end
end
if parameters.formatting == "unitcode" then
-- get unit symbol
unit_symbol = unitSymbol(unitID, parameters.lang)
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
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
-- get unit name
suffix = " " .. require(wiki.module_title .. "/Units").getUnit(amount, unit_label, unitID, parameters.formatting == "unitcode", unit_symbol)
local unit_label, lang = getLabelByLangs(unit_id, parameters.lang)
elseif parameters.formatting == "unitcode" and unit_symbol then
if lang == wiki.langcode and pcall(require, wiki.module_title .. "/Units") then
suffix = " " .. unit_symbol
suffix = " " .. require(wiki.module_title .. "/Units").getUnit(amount, unit_label, unit_id, false, '')
else
else
suffix = " " .. (unit_label or unitID) .. addEditIcon(unitID, lang, parameters.lang[1], parameters.editicon)
suffix = " " .. (unit_label or unit_id) .. addEditIcon(unit_id, lang, parameters.lang[1], parameters.editicon)
end
end
end
end
amount = mw.language.new(parameters.lang[1]):formatNum(tonumber(amount))
return amount .. suffix, sortkey
end
Ligne 313 ⟶ 421 :
-- Dates and times are stored in ISO 8601 format
local timestamp = data.time
local sortkey = timestamppost_format
local addon = ""
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
local calendar_add = ""
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
-- check for negative date, ex. "-0027-01-16T00:00:00Z"
if string.sub(timestamp, 1, 1) == '-' then
post_format = i18n.datetime["bc"]
timestamp = '+' .. string.sub(timestamp, 2)
addon = i18n.datetime["bc-addon"]
elseif string.sub(timestamp, 2, 3) == '00' then
addonpost_format = i18n.datetime["ad-addon"]
else
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
local calendar_id = mw.text.split(data.calendarmodel, 'entity/')[2]
if (timestamp < "+1582-10-15T00:00:00Z" and calendar_model[calendar_id] == "gregorian")
or (timestamp > "+1582-10-04T00:00:00Z" and calendar_model[calendar_id] == "julian")
then
calendar_add = " <sup>(" .. mw.message.new('Wikibase-time-calendar-' .. calendar_model[calendar_id]):inLanguage(parameters.lang[1]):plain() .. ")</sup>"
end
end
local function d(f, t)
local ts = t or timestamp
local form = type(f) == "function" and f(ts) or f -- function in i18n.datetime[precision]
if string.sub(ts, 1, 1) == '-' then ts = '+' .. string.sub(ts, 2) end -- formatDate() only supports years from 0
return mw.language.new(parameters.lang[1]):formatDate(form, ts) .. addon .. calendar_add
return mw.language.new(parameters.lang[1]):formatDate(form, ts)
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 precision = data.precision or 11
local intyear = tonumber(mw.ustringstring.match(timestamp, "^\[+?-](%d+)"))
local ret = ""
if precision <= 5 then -- 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 addonpost_format == i18n.datetime["bc-addon"] then
-- negative date
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+")
-- precision is millennia, centuries or decades
elseif if precisionret_number =~= 6nil then
ret = mw.ustring.gsub(ret, ret_number, mw.language.new(parameters.lang[1]):formatNum(tonumber(ret_number)))
end
elseif precision == 6 then -- millennia
local card = math.floor((intyear - 1) / 1000) + 1
if mw.ustring.find(i18n.datetime[6], "$1") then
ret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(card)) .. addon .. calendar_add
else
ret = d(i18n.datetime[6], string.format("%04d", tostring(card)))
end
ret = postFormat(ret)
elseif precision == 7 then
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)) .. addon .. calendar_add
else
ret = d(i18n.datetime[7], string.format("%04d", tostring(card)))
end
ret = postFormat(ret) .. calendar_add
elseif precision == 8 then
elseif precision == 8 then -- decades
local card = math.floor(math.abs(intyear) / 10) * 10
ret = postFormat(mw.ustring.gsub(i18n.datetime[8], "$1", tostring(card)) .. addon) .. calendar_add
elseif precision == 9 or parameters.formatting == 'Y' then -- precision is year
ret = postFormat(tostring(intyear)) .. calendar_add
elseif parameters.formatting == 'Y' or precision == 9 then
elseif precision == 10 then -- month
ret = tostring(intyear) .. addon .. calendar_add
-- precision is month
elseif precision == 10 then
timestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous month
ret, _ = string.gsub(d(i18n.datetime[10]), " 0+", " ") -- supress leading zeros in year
ret = postFormat(ret) .. calendar_add
elseif parameters.formatting then
ret, _ = string.gsub(d(parameters.formatting)ret, "([ %[])0+", "%1") -- supress leading zeros in year, optionally linked
else -- precision 11, day
else
ret, _ = string.gsub(d(parameters.formatting or i18n.datetime[11]), " 0+", " ")
ret = postFormat(ret) .. calendar_add
ret, _ = string.gsub(ret, "([ %[])0+", "%1")
end
return ret, sortkeytimestamp
end
 
local function printDatavalueEntity(data, parameters)
local entityId = data['id']
local entityIdPreffixentity_page = data['entity-typeSpecial:EntityPage/'] == 'property' and "Property:" .. entityId or entityId
if parameters.formatting == 'raw' then
if data['entity-type'] == 'item' then
entityId = resolveEntityId(entityId)
end
return entityId, entityId
end
Ligne 396 ⟶ 517 :
local parameter = parameters.formatting
local labelcase = label or sitelink
if parameters.gender == 'feminineform' and lang ~= nil then -- case gender and item is female
labelcase = feminineForm(entityId, lang) or labelcase
end
if parameters.case ~= 'gender' then
labelcase = case(labelcase, parameters.case, labelcase, lang, entityId, parameters.id)
end
local ret1, ret2
Ligne 407 ⟶ 528 :
ret2 = labelcase or entityId
elseif parameter == 'sitelink' then
ret1 = (sitelink or 'wikidata:' .. entityIdPreffixentity_page)
ret2 = sitelink or entityId
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
Ligne 415 ⟶ 536 :
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
Ligne 431 ⟶ 554 :
ret2 = labelcase
else
ret1 = '[[wikidata:' .. entityIdPreffixentity_page .. '|' .. (labelcase or entityId) .. ']]'
ret2 = labelcase or entityId
end
end
return ret1 .. addEditIcon(entityIdPreffixentity_page, lang, parameters.lang[1], parameters.editicon), ret2
end
 
Ligne 457 ⟶ 580 :
end
return result
end
 
local function printDatatypeMath(data)
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
end
 
local function printError(key)
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
 
Ligne 483 ⟶ 602 :
end
 
function findClaims(entityentityId, property)
if not property or not entity or not entity.claimsentityId then return end
if not mw.ustring.match(property, "^P%d+$") then
Ligne 491 ⟶ 610 :
if not property then return end
end
local claims = mw.wikibase.getAllStatements(entityId, property)
returnif entity.#claims[property] == 0 then
claims = nil
end
return claims
end
 
Ligne 500 ⟶ 622 :
if snak.datatype == 'math' then
return printDatatypeMath(snak.datavalue.value)
elseif snak.datatype == 'musical-notation' then
return printDatatypeMusical(snak.datavalue.value, parameters.formatting)
elseif snak.datatype == "url" then
return printDatatypeUrl(snak.datavalue.value, parameters)
elseif snak.datavalue.type == "string" then
return printDatavalueString(snak.datavalue.value, parameters)
Ligne 514 ⟶ 640 :
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
Ligne 567 ⟶ 695 :
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
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
return value, sortkey, valueraw
end
 
local function getReferences(claim)
local refaliases = {
citeWeb = "Q5637226",
author = "P50",
publisher = "P123",
importedFrom = "P143",
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 = ""
Ligne 600 ⟶ 747 :
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
Ligne 609 ⟶ 756 :
-- get title of general template for citing web references
local template = mw.wikibase.getSitelink(refaliases.citeWeb) or ""
template = mw.text.split(template, ":")[2] -- split off namespace from front
-- (1) if both "reference URL" and "title" are present, then use the general template for citing web references
Ligne 681 ⟶ 828 :
if property_id ~= nil then
local claims = findClaims(entityid, property_id)
if not claims or not claims[1] then
return nil
Ligne 712 ⟶ 859 :
-- Return the site link (for the current site) for a given data item.
function p.getSiteLink(frame)
local id if= frame.args[1] == nil then
if not isSet(id) then
entity = mw.wikibase.getEntity()
id = mw.wikibase.getEntityIdForCurrentPage()
if not entity then
if id == nil then
return nil
return
end
end
id = entity.id
end
else
return mw.wikibase.getSitelink(id =, frame.args[12])
end
return mw.wikibase.getSitelink(id)
end
 
-- Set whitelist or blacklist values
local function setWhiteOrBlackList(type_list, num_qual, args)
local i = 0
local listed = false
local list = {}
whilefor i <= 0, num_qual do
if isSet(args[type_list .. i] and args[type_list .. i] ~= '') then
listed = true
list[tostring(i)] = {}
Ligne 736 ⟶ 880 :
for _, v in ipairs(values) do
list[tostring(i)][v] = true
list[tostring(i)][resolveEntityId(v)] = true
end
end
i = i + 1
end
return list, listed
end
 
local function tableParameters(args, parameters, column)
function p.claim(frame)
local column_params = mw.clone(parameters)
if mw.title.new(frame:getParent():getTitle()).isContentPage then
column_params.formatting = args["colformat"..column]; if column_params.formatting == "" then column_params.formatting = nil end
if not mw.title.new(frame:getTitle()).isSubpage then
column_params.convert = args["convert" .. column]
-- invoked from a content page and not invoking a module subpage
if args["case" .. column] then
return printError("not-from-content-page")
column_params.case = args["case" .. column]
end
end
return column_params
return p._main(frame.args, frame:getParent().args)
end
 
-- on debug console use: =p.claim{item="Q...", property="P...", ...}
-- Entry point from other modules or debugging, with a list of arguments.
function p.claim(frame)
-- From other modules use: require("Module:Wikidata")._main({item="Q...", property="P...", ...})
local args = frame.args or frame -- via invoke or require
-- On debug console use: =p._main({item="Q...", lang="xx", property="P...", ...})
function p._main(args, pargs)
--If a value is already set, use it
if isSet(args.value and args.value ~= '') then
return args.value
end
-- arguments
local pargs = frame.args and frame:getParent().args
local id = args.item or (pargs and pargs.item); if id == "" then id = nil end
local languagesid = findLang(args.langitem or (pargs and pargs.item)
if not isSet(id) then
local idgender = args["itemgender"]
id = mw.wikibase.getEntityIdForCurrentPage()
if idgender and not string.match(idgender, "^Q%d+$") then -- id malformed, maybe "unknown value"
idgenderif id == nil then return end
end
local property = string.upper(args["property"] or "")
Ligne 777 ⟶ 920 :
i = i + 1
end
local parameterformatting = args["formatting"] or ''; if parameterformatting == "" then parameterformatting = nil end
local convert = args["convert"]; if convert == "" then convert = 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_col_alt = args.tablesortalt or ''
local sorting_up = (args.sorting or "") ~= "-1"
local separator = args.separator
Ligne 789 ⟶ 933 :
local showerrors = args["showerrors"]
local default = args["default"]
if default then showerrors = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local parameters = {["formattingid"] = parameterid, ["listproperty"] = listproperty, ["caseformatting"] = case, ["lang"] = languagesformatting, ["editiconconvert"] = editiconconvert,
["list"] = list, ["case"] = case, ["editicon"] = editicon,
["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
Ligne 828 ⟶ 974 :
blacklist, blacklisted = setWhiteOrBlackList("blacklist", #qualifierId, args)
end
if default then showerrors = nil end
-- fetch property
-- get wikidata entity
local claims
local entity = mw.wikibase.getEntity(id)
for p in string.gmatch(property, 'P%d+') do
if not entity then
claims = findClaims(id, p)
if showerrors then return printError("entity-not-found") else return default end
if claims and claims[1] then
break
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
-- find language and defaults
parameters.lang = findLang(args.lang)
-- set feminine case if gender is requested
local itemgender = args["itemgender"]
local genderCase
local idgender
if parameters.case == "gender" or idgender or parameters.formatting == "table" then
if itemgender then
if feminineGender(idgender or id) then
if string.match(itemgender, "^P%d+$") then
genderCase = "feminineform"
local snak = mw.wikibase.getBestStatements(id, itemgender)[1]
if parameters.case == "gender" or idgender then
if snak and snak.mainsnak and snak.mainsnak.datavalue and snak.mainsnak.datavalue.value then
parameters.gender = genderCase
idgender = snak.mainsnak.datavalue.value.id
end
elseif string.match(itemgender, "^Q%d+$") then
idgender = itemgender
end
end
local gender_requested = false
if parameters.case == "gender" or idgender then
gender_requested = true
elseif parameters.formatting == "table" then
for i=0, #qualifierId do
if args["case" .. i] and args["case" .. i] == "gender" then
gender_requested = true
break
end
end
end
if gender_requested then
if feminineGender(idgender or id) then
parameters.gender = "feminineform"
end
end
Ligne 860 ⟶ 1 028 :
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
Ligne 880 ⟶ 1 048 :
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[sortindices[idx]] = true end
if not whitelisted then rowlist[idx] = true end
if firstrank ~= '' and firstrank ~= claim.rank then
break
end
if parameters.formatting == "table" then
local params = mw.clonetableParameters(args, parameters, "0")
value, sortkey, error = getValueOfClaim(claim, nil, params)
params.formatting = args["colformat0"]; if params.formatting == "" then params.formatting = nil end
if args["case0"] then
params.gender = args["case0"] == "gender" and genderCase
end
value, sortkey, error = getValueOfClaim(claim, nil, params)
if value then
values[#values + 1] = {}
sortkeys[#sortkeys + 1] = {}
refs[#refs + 1] = {}
if whitelist["0"] or blacklist["0"] then
local valueraw, _, _ = getValueOfClaim(claim, nil, {["formatting"]="raw", ["lang"]=params.lang})
if whitelist["0"] and whitelist["0"][valueraw or ""] then
rowlist[#values] = true
Ligne 908 ⟶ 1 075 :
for i, qual in ipairs(qualifierId) do
local j = tostring(i)
params = tableParameters(args, parameters, j)
params.formatting = args["colformat" .. j]; if params.formatting == "" then params.formatting = nil end
iflocal args["case"valueq, ..sortkeyq, j] thenvalueraw
if qual == property then -- hack for getting the property with another formatting, i.e. colformat1=raw
params.gender = args["case" .. j] == "gender" and genderCase
valueq, sortkeyq, _ = getValueOfClaim(claim, nil, params)
else
for q in mw.text.gsplit(qual, '%s*OR%s*') do
params.case = parameters.case
if string.find(q, ".+/.+") then
params.gender = parameters.gender
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
if qual == property then qual = nil end -- hack for getting the property with another formatting, i.e. colformat1=raw
local valueq, sortkeyq, _ = getValueOfClaim(claim, qual, params)
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
Ligne 930 ⟶ 1 107 :
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 valuereference = value .. getReferences(claim).references end
refs[#refs]["col0"] = reference
values[#values]["col0"] = value
sortkeys[#sortkeys]["col0"] = sortkey or value
Ligne 947 ⟶ 1 126 :
end
if sorting_col then
local sorting_table = mw.text.split(sorting_col, '/', true)
local comparator = function(a, b)
local valuea, valueb
local valuea = sortkeys[a]["col" .. sorting_col] or sortkeys[a]["col" .. sorting_col_alt] or ''
local i = 1
local valueb = sortkeys[b]["col" .. sorting_col] or sortkeys[b]["col" .. sorting_col_alt] or ''
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 valueavalueb <> valuebvaluea
end
return valueavalueb >< valuebvaluea
end
table.sort(sortindices, comparator)
Ligne 960 ⟶ 1 146 :
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
Ligne 966 ⟶ 1 154 :
else
value = mw.ustring.gsub(rowformat .. "$", "$0", value) -- fake end character added for easy gsub
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
local rowformatting = rowformat .. "$"
for i, _ in ipairs(qualifierId) do
local valueq = valuerow["col" .. i]
Ligne 974 ⟶ 1 164 :
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
valuevalueq = mw.ustring.gsub(value,valueq "$"and .. i .. "urlEscapes(%Dvalueq)", (valueq or '') .. "%1")
value = mw.ustring.gsub(value, "$" .. i .. "(%D)", valueq .. "%1")
end
value = string.sub(value, 1, -2) -- remove fake end character
value = expandBraces(value, rowformatrowformatting)
end
elseif value then
else
value = expandBraces(value, parameters.formatting)
value = value .. reference
end
result[#result + 1] = value
Ligne 1 011 ⟶ 1 204 :
end
-- fetch the first claim of satisfying the given property
local claims = findClaims(entityid, property)
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
Ligne 1 024 ⟶ 1 217 :
-- 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
end
local ret = table.concat(out, "<br> ")
if #ret == 0 then
ret = "Invalid TA"
end
return ret
end
 
 
function p.processMarkup(frame)
Ligne 1 049 ⟶ 1 241 :
end
 
-- debugging functions, see module ../debug.
-- look into entity object
function p.ViewSomething(frame)
return require(wiki.module_title .. "/debug").ViewSomething(frame)
local f = (frame.args[1] or frame.args.item) and frame or frame:getParent()
local id = f.args.item
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 frame:extensionTag('syntaxhighlight', mw.text.jsonEncode(data, mw.text.JSON_PRETTY), {lang = 'json'})
else
return tostring(data)
end
end
data = data[index] or data[tonumber(index)]
if not data then
return
end
i = i + 1
end
end
 
-- Dump data tree structure
-- From pl:Module:Wikidane, by User:Paweł Ziemian
-- Funció pensada com a eina d'ajuda en previsualització.
function p.Dump(frame)
return require(wiki.module_title .. "/debug").Dump(frame)
local data = mw.wikibase.getEntity()
if not data then
return i18n.warnDump
end
local f = frame.args[1] and frame or frame:getParent()
 
local i = 1
while true do
local index = f.args[i]
if not index then
return frame:extensionTag('syntaxhighlight', mw.dumpObject(data), {lang = 'json'}) .. i18n.warnDump
end
data = data[index] or data[tonumber(index)]
if not data then
return i18n.warnDump
end
i = i + 1
end
end
 
-- Look into entity object
-- From pl:Module:Wikidane, function V, by User:Paweł Ziemian
function p.getEntityFromTree(frame)
return require(wiki.module_title .. "/debug").getEntityFromTree(frame)
local data = mw.wikibase.getEntity()
if not data then
return nil
end
local f = frame.args[1] and frame or frame:getParent()
local i = 1
while true do
local index = f.args[i]
if not index then
return tostring(data)
end
data = data[index] or data[tonumber(index)]
if not data then
return
end
i = i + 1
end
end
 
-- local functions for getParentValues
-- getParentValues: returns a property value with its instance label fetching a recursive tree
 
local function uc_first(word)
Ligne 1 153 ⟶ 1 273 :
if mysnak.datavalue then
entityId = "Q" .. tostring(mysnak.datavalue.value['numeric-id'])
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon, case = case})
end
Ligne 1 159 ⟶ 1 279 :
end
 
local function reversecontains(arrtab, val)
for index, value in ipairs(tab) do
local i, j = 1, #arr
if value == val then
 
return true
while i < j do
end
arr[i], arr[j] = arr[j], arr[i]
 
i = i + 1
j = j - 1
end
end
return false
 
local function contains (tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
 
return false
end
 
Ligne 1 192 ⟶ 1 301 :
last_only,
grammatical_case,
sorting,
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 '')
Ligne 1 219 ⟶ 1 327 :
local label, link
for _, propertySup in pairs(propertySups) do
_id, _link = getPropertyValue(id, propertySup, formatting, languages, editicon, grammatical_case)
if _id and _link then id = _id link = _link break end
end
Ligne 1 235 ⟶ 1 343 :
if label then
label = case(label, "infoboxlabel", label, languages[1])
end
Ligne 1 242 ⟶ 1 350 :
if label then
labelFilter[label] = nil -- only first label found
end
end
Ligne 1 249 ⟶ 1 357 :
break
end
if contains(upto_link_ids, id) then
break
Ligne 1 255 ⟶ 1 363 :
end
if last_only then
local last result = {result[#result]}
end
result = { }
result[#result + 1] = last
end
if include_self then table.insert(result, 1, {label_self, mw.title.getCurrentTitle().text}) end
 
return sorting == "-1" and reverse(result) or result
end
 
Ligne 1 269 ⟶ 1 375 :
rowformat,
separator,
cascade),
sorting)
local ret = {}
Ligne 1 275 ⟶ 1 382 :
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]})
Ligne 1 282 ⟶ 1 389 :
if cascade then
local prefix = ""
for i = 1, #ret do
ret[i] = prefix .. "• " .. ret[i]
prefix = prefix .. "&nbsp;"
end
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)
local args = frame.args or frame -- via invoke or require
local idpargs = argsframe.itemargs orand frame:getParent().args.item
iflocal id == ""args.item or id ==(pargs niland thenpargs.item)
if not isSet(id) then
id = mw.wikibase.getEntityIdForCurrentPage()
if id == nil then return end
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 upto = args["upto"]; if upto == "" then upto = nil end
Ligne 1 306 ⟶ 1 416 :
local labelShow = args["labelshow"]; if labelShow == "" then labelShow = nil end
local editicon = not (args.editicon == "false" or args.editicon == "no")
local sorting = args["sorting"]; if sorting == "" then sorting = nil end
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.getLabel(args.uptolabelid)
end
if isSet(args.showlabelid and args.showlabelid ~= "") then
local showLabelList = {} for substring in mw.text.gsplit(args.showlabelid, '[/%s]+') do table.insert(showLabelList, mw.wikibase.getLabel(substring)) end
if #showLabelList > 0 then
labelShow = table.concat(showLabelList,"/")
Ligne 1 322 ⟶ 1 431 :
local result = getParentObjects(id,
args.formatting,
languages,
propertySup,
propertyLabel,
propertyLink,
labelShow,
editicon,
upto,
args.uptolinkid,
last_only,
case,
include_self)
sorting,
include_self)
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")
 
return parentObjectsToString(result,
rowformat,
separator,
cascade),
sorting)
end
 
 
function p.linkWithParentLabel(frame)
Ligne 1 357 ⟶ 1 466 :
args.formatting = "internallink"
args.separator = "/·/"
local pargslink_list = frame:getParent()p.claim(args)
if not isSet(link_list) then
local link_list = p._main(args, pargs)
if link_list == nil or link_list == "" then
return
end
Ligne 1 366 ⟶ 1 474 :
-- get id value of property/qualifier
args.formatting = "raw"
local items_list = p._mainclaim(args, pargs)
local items_table = mw.text.split(items_list, "/·/", true)
Ligne 1 372 ⟶ 1 480 :
args.property = args.parent
args.qualifier = nil
local parent_claims = findClaims(mw.wikibase.getEntity(items_table[1]), args.parent)
if parent_claims and parent_claims[1].mainsnak.datatype == 'monolingualtext' then
args.formatting = nil
Ligne 1 382 ⟶ 1 490 :
for i, v in ipairs(items_table) do
args.item = v
local link_label = p._mainclaim(args, pargs)
if isSet(link_label and link_label ~= '') then
link_table[i] = mw.ustring.gsub(link_table[i] or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")
end
Ligne 1 391 ⟶ 1 499 :
end
 
function p.years_oldyearsOld(frame)
local args = frame.args or frame -- via invoke or require
local id = args.item
if id == '' ornot isSet(id == nil) then
id = mw.wikibase.getEntityIdForCurrentPage()
end
Ligne 1 460 ⟶ 1 568 :
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
 
Ligne 1 472 ⟶ 1 611 :
local args = frame.args or frame -- via invoke or require
local id = mw.text.trim(args[1] or "")
if not isSet(id == "") then return end
local editicon = not (args.editicon == "false" or args.editicon == "no")
Ligne 1 481 ⟶ 1 620 :
else
local languages = findLang(args.lang)
-- exceptions or labels fixed
if languages[1] == wiki.langcode then
local exist, labels = pcall(require, wiki.module_title .. "/labels" .. (languages[1] == wiki.langcode and '' or '/' .. languages[1]))
-- exceptions or labels fixed
if exist and next(labels.infoboxLabelsFromId) ~= nil then
local exist, labels = pcall(require, wiki.module_title .. "/labels")
iflabel exist= and next(labels.infoboxLabelsFromId) ~= nil then[id]
label = labels.infoboxLabelsFromId[id]
end
end
if label == nil then
id = resolveEntityId(id)
label, lang = getLabelByLangs(id, languages)
if label then
Ligne 1 497 ⟶ 1 635 :
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
pencil = addEditIcon('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) .. "]]" .. pencil