Modulu:Wikidata: berrikuspenen arteko aldeak
Ezabatutako edukia Gehitutako edukia
formatting sound for musical-notation, access to all functions via require, fixes for raw novalue/somevalue |
No edit summary |
||
1. lerroa:
-- version
local p = {}
--
local i18n = { -- internationalisation at [[Module:Wikidata/i18n]]
["errors"] = {
["property-not-found"] = "Property not found.",
["qualifier-not-found"] = "Qualifier not found.",
},
["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
23 ⟶ 28 lerroa:
[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
},
["years-old"] = {
["singular"] = "", -- year old, as in {{PLURAL:$1|singular|plural}}
["plural"] = "", -- years old
["paucal"] = "", -- for languages with 3 plural forms as in {{PLURAL:$1|singular|paucal|plural}}
},
["cite"] = { -- Cite web parameters
47 ⟶ 52 lerroa:
["date"] = "date",
["pages"] = "pages"
},
-- local wiki settings
["addpencil"] = false, -- adds a pencil icon linked to Wikidata statement, planned to overwrite by Wikidata Bridge
["categorylabels"] = "", -- Category:Pages with Wikidata labels not translated (void for no local category)
["addfallback"] = {} -- additional fallback language codes
}
local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]
local required = ... -- variadic arguments from require function
local wiki =
{
langcode = mw.language.getContentLanguage().code,
module_title = required or mw.getCurrentFrame():getTitle()
}
local untranslated -- used in infobox modules: nil or true
-- 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
78 ⟶ 89 lerroa:
end
local function loadI18n(lang)
local
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
cases.location = require(wiki.module_title .. '/i18n').cases.location
cases.locationcontext = require(wiki.module_title .. '/i18n').cases.locationcontext
end
end
-- Table of language codes: requested or default and its fallbacks
local function findLang(langcode)
if mw.language.isKnownLanguageTag(langcode or '') == false then
115 ⟶ 118 lerroa:
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.
local function
return not (var == nil or var == '')
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
129 ⟶ 153 lerroa:
local function getLabelByLangs(id, languages)
local label
local lang
for _, l in ipairs(languages) do
if l == wiki.langcode then
label, l = mw.wikibase.getLabelWithLang(id)
else
label = mw.wikibase.getLabelByLang(id, l)
end
if label then
lang = l
break
end
end
148 ⟶ 172 lerroa:
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
return false
else
171 ⟶ 193 lerroa:
end
-- get safely a serialized snak
local function
local
for i, v in ipairs(snaks) do
ret = ret[v]
end
return ret
end
-- Add an icon for no label in requested language
local function addLabelIcon(label_id, lang, uselang, icon)
local ret_lang, ret_icon = '', ''
if icon then
if lang and lang ~= uselang then
ret_lang = " <sup>(" .. lang .. ")</sup>"
end
if label_id and (lang == nil or lang ~= uselang) then
ret_icon = " [[File:Noun Project label icon 1116097 cc mirror.svg|10px|baseline|"
.. mw.message.new('Translate-taction-translate'):inLanguage(uselang):plain()
.. "|link=https://www.wikidata.org/wiki/Special:EntityPage/" .. label_id .. "?uselang=" .. uselang .. "]]"
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
end
-- Add
local function addEditIcon(
local ret = ''
if i18n.addpencil and parameters.editicon and parameters.id and parameters.property then
ret = ' <span data-bridge-edit-flow="overwrite">'
.. "[[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
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
local function
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
235 ⟶ 298 lerroa:
end
braces = mw.ustring.gsub(braces, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characters
braces_expanded =
text = mw.ustring.gsub(text, "{{" .. braces .. "}}", braces_expanded)
end
242 ⟶ 305 lerroa:
end
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 fallbacks, maybe it is a redirect
264 ⟶ 328 lerroa:
end
-- format data type math
local function printDatatypeMath(data)
return mw.getCurrentFrame():callParserFunction('#tag:math', data)
end
-- format data type musical-notation
local function printDatatypeMusical(data, formatting)
local attr = {}
if formatting == 'sound' then
276 ⟶ 342 lerroa:
end
-- format data type string
local function printDatatypeString(data, parameters)
if mw.ustring.find((parameters.formatting or ''), '$1', 1, true) then -- formatting = a pattern
elseif parameters.case then
return case(parameters.case, data, parameters.lang[1])
end
return data
end
-- format data type url
local function printDatatypeUrl(data, parameters)
if parameters.formatting == 'weblink' then
local label_parts = mw.text.split(string.gsub(data, '/$', ''), '/')
local label = string.gsub(label_parts[3], '^www%.', '')
if #label_parts > 3 then
label = label .. '…'
end
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
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 latitude = roundPrecision(data.latitude, precision)
local longitude = roundPrecision(data.longitude, precision)
if formatting and string.find(formatting, '$lat', 1, true) and string.find(formatting, '$lon', 1, true) then
local ret = mw.ustring.gsub(formatting, '$l[ao][tn]', {['$lat'] = latitude, ['$lon'] = longitude})
if string.find(formatting, '$globe', 1, true) then
local myglobe = 'earth'
if isSet(data.globe) then
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
myglobe = globes
end
ret = mw.ustring.gsub(ret, '$globe', myglobe)
end
return expandBraces(ret,
elseif
return
elseif
return
elseif
return data.dimension, "no-icon"
else --default formatting='globe'
if isSet(data.globe) ==
return 'earth', "no-icon"
else
local globenum = mw.text.split(data.globe, 'entity/')[2]
return globes
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
-- first, count digits after decimal mark, handling cases like '12.345e6'
local exponent, prec
350 ⟶ 511 lerroa:
end
-- format data type quantity
local function printDatatypeQuantity(data, parameters)
local amount = data.amount
amount = mw.ustring.gsub(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"
360 ⟶ 522 lerroa:
unit_id = mw.ustring.sub(unit_id, mw.ustring.find(unit_id, "Q"), -1)
if string.sub(unit_id, 1, 1) == "Q" then
suffix = getUnit(amount, unit_id, parameters)
local convert_to
if parameters.convert == "default" or parameters.convert == "default2" then
local exist, units = pcall(require, wiki.module_title .. "/Units")
if exist and next(units.convert_default) ~= nil then
convert_to = units.convert_default[unit_id]
end
elseif string.sub(parameters.convert or '', 1, 1) == "Q" then
convert_to = parameters.convert
end
if convert_to and convert_to ~= unit_id then
-- convert units
local conv_temp = { -- formulae for temperatures ºC, ºF, ªK: [from] = {[to] = 'formula'}
367 ⟶ 539 lerroa:
['Q11597'] = {['Q25267'] = '$1-273.15', ['Q42289'] = '($1-273.15)*1.8000+32.00'}
}
if conv_temp[unit_id] and conv_temp[unit_id][
local amount_f = mw.getCurrentFrame():callParserFunction('#expr', mw.ustring.gsub(conv_temp[unit_id][
else
local conversions = mw.wikibase.getAllStatements(unit_id, 'P2442') -- conversion to standard unit
376 ⟶ 547 lerroa:
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/" ..
break
end
384 ⟶ 554 lerroa:
end
end
if conv_amount then
conv_suffix = getUnit(conv_amount, convert_to, parameters)
end
elseif parameters.convert == 'M' and tonumber(amount) > 10^8 then
conv_amount = math.floor(amount/10^6 + 0.5)
conv_suffix = ' M' .. string.sub(suffix, 2)
end
end
end
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 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
423 ⟶ 594 lerroa:
elseif string.sub(timestamp, 2, 3) == '00' then
post_format = i18n.datetime["ad"]
elseif precision > 8 then
-- calendar model
local calendar_model = {["Q12138"] = "gregorian", ["Q1985727"] = "gregorian", ["Q11184"] = "julian", ["Q1985786"] = "julian"}
434 ⟶ 605 lerroa:
end
local function
local
pattern = form(stamp)
else
pattern = form
end
stamp = tostring(stamp)
if mw.ustring.find(pattern, "$1") then
return mw.ustring.gsub(pattern, "$1", stamp)
elseif string.sub(stamp, 1, 1) == '-' then -- formatDate() only supports years from 0
stamp = '+' .. string.sub(stamp, 2)
elseif string.sub(stamp, 1, 1) ~= '+' then -- not a valid timestamp, it is a number
stamp = string.format("%04d", stamp)
end
local ret = mw.language.new(parameters.lang[1]):formatDate(pattern, stamp)
ret = string.gsub(ret, "^(%[?%[?)0+", "%1") -- supress leading zeros
ret = string.gsub(ret, "( %[?%[?)0+", "%1")
return ret
end
448 ⟶ 633 lerroa:
end
local intyear = tonumber(string.match(timestamp, "[+-](%d+)"))
local ret = ""
455 ⟶ 639 lerroa:
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(intyear) / factor)
local relative =
if post_format == i18n.datetime["bc"] then
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
465 ⟶ 649 lerroa:
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) /
ret = postFormat(ret)
elseif precision == 8 then -- decades
local card = math.floor(math.abs(intyear) / 10) * 10
ret =
ret = postFormat(ret)
elseif intyear > 9999 then -- not a valid timestamp
return
elseif precision == 9 or parameters.formatting == 'Y' then -- precision is year
ret =
ret = postFormat(ret) .. calendar_add
elseif precision == 10 then -- month
ret = postFormat(ret) .. calendar_add
else -- precision 11, day
ret =
ret = postFormat(ret) .. calendar_add
end
return ret, timestamp
end
-- format data type wikibase-item
local
if parameters.formatting == 'raw' then
if data['entity-type'] == 'item' then
end
return
end
local entity_page = 'Special:EntityPage/' .. entity_id
local label, lang = getLabelByLangs(entity_id, parameters.lang)
local sitelink = mw.wikibase.getSitelink(entity_id)
local parameter = parameters.formatting
local labelcase = label or sitelink
if
labelcase = feminineForm(
end
labelcase = case(parameters.case, labelcase, lang, parameters.lang[1], entity_id, parameters.id)
end
local ret1, ret2
if parameter == 'label' then
ret1 =
ret2 = labelcase or
elseif parameter == 'sitelink' then
ret1 = (sitelink or '
ret2 = sitelink or
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
ret1 = mw.ustring.gsub(parameter, '$1', labelcase or
ret1 = expandBraces(ret1, parameter)
ret2 = labelcase or
else
if parameter == "ucfirst" or parameter == "ucinternallink" then
548 ⟶ 723 lerroa:
ret2 = labelcase
else
ret1 = '[[
ret2 = labelcase or
end
end
return ret1 ..
end
-- format data type monolingualtext
local function printDatatypeMonolingual(data, parameters)
-- data fields: language [string], text [string]
566 ⟶ 742 lerroa:
local result = data["text"]
if data["language"] ~= wiki.langcode then
result = mw.ustring.gsub(
end
if mw.ustring.find((parameters.formatting or ''), '$', 1, true) then
574 ⟶ 750 lerroa:
end
return result
end
local function getSnakValue(snak, parameters)
if snak.snaktype == 'value' then
-- see Special:ListDatatypes
if snak.datatype == "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 == 'musical-notation' then
return printDatatypeMusical(snak.datavalue.value, parameters.formatting)
-- other data types
elseif snak.datatype == 'wikibase-item' then
return printDatatypeItem(snak.datavalue.value, parameters)
elseif snak.datatype == 'monolingualtext' then
return printDatatypeMonolingual(snak.datavalue.value, parameters)
elseif snak.datatype == "globe-coordinate" then
return printDatatypeCoordinate(snak.datavalue.value, parameters.formatting)
elseif snak.datatype == "quantity" then
return printDatatypeQuantity(snak.datavalue.value, parameters)
elseif snak.datatype == "time" then
return printDatatypeTime(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
609 ⟶ 823 lerroa:
end
return claims
end
655 ⟶ 837 lerroa:
-- iterate over monolingualtext qualifiers to get local language
for idx in pairs(qualifier) do
if getSnak(qualifier[idx]
return qualifier[idx]
end
674 ⟶ 856 lerroa:
function getValueOfClaim(claim, qualifierId, parameters)
local snak, error = getQualifierSnak(claim, qualifierId, parameters)
if not snak then
return nil, nil, error
elseif snak[1] then -- a multi qualifier
local result, sortkey = {}, {}
for idx in pairs(snak) do
result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
693 ⟶ 872 lerroa:
local function getValueOfParentClaim(claim, qualifierId, parameters)
local qids = mw.text.split(qualifierId, '/', true)
local
local parent_raw
if qids[1] == parameters.property then
else
end
if string.sub(
local parent_qids = mw.text.split(parent_raw, '/', true)
for idx, p_qid in ipairs(parent_qids) do
local parent_claims = mw.wikibase.getBestStatements(p_qid, qids[2])
if parent_claims[1] then
-- raw parent value needed for while/black lists, lang for avoiding an error on types other than entity
valueraw[idx], _, _ = getValueOfClaim(parent_claims[1], nil, {["formatting"]="raw", ["lang"]=parameters.lang})
end
end
end
return mw.text.listToText(value, parameters.qseparator, parameters.qconjunction), sortkey[1], valueraw[1]
end
local function getReferences(claim)
local
["P143"] = true, -- imported from
["P3452"] = true, -- inferred from
["P887"] = true, -- based on heuristic
["P4656"] = true -- Wikimedia import URL
}
local result = ""
736 ⟶ 905 lerroa:
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 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
745 ⟶ 922 lerroa:
refs[snakkey] = refparts
refparts = nil
if snakkey == "P248" then -- stated in
ref_name = snakval[1].datavalue.value.id
end
end
end
-- get title of general template for citing web references
local template = mw.wikibase.getSitelink(
template = mw.text.split(template, ":")[2] -- split off namespace from front
--
if refs[
local citeParams = {}
citeParams[i18n['cite']['url']] = refs[
citeParams[i18n['cite']['title']] = refs[
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
citeParams[i18n['cite']['
refparts = mw.getCurrentFrame():expandTemplate{title=template, args=citeParams}
else
-- raw ouput
local italics = "''"
for k, v in orderedpairs(refs or {}, claim.references[ref]["snaks-order"]) do
if k and v then
refparts = refparts ..
refparts = refparts .. italics .. v .. italics .. "."
italics = ""
end
end
end
if refparts then result = result .. mw.getCurrentFrame():extensionTag("ref", refparts, {name=ref_name}) end
end
return result
end
824 ⟶ 993 lerroa:
end
local function
local args = frame.args or frame
local pargs = frame.args and frame:getParent().args
local id = args.item or args.from or (unnamed and mw.text.trim(args[1] or '') or nil)
if not isSet(id) and pargs then
id = pargs.item or pargs.from or (unnamed and mw.text.trim(pargs[1] or '') or nil)
end
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
end
-- Main function claim ---------------------------------------------
-- on debug console use: =p.claim{item="Q...", property="P...", ...}
function p.claim(frame)
if not required and frame.args and isSet(frame:getParent().args.sandbox) then
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) then
return
else
return args.value
end
end
-- arguments
local
if id == nil then return end
local property = string.upper(args.property or "")
local qualifierId = {}
qualifierId[1] = isSet(args
local i = 2
while isSet(args["qualifier" .. i]) do
qualifierId[i] = string.upper(args["qualifier" .. i])
i = i + 1
end
local formatting = args
local convert = args
local case = args.case
local list = args
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)
local rowformat = args.rowformat
local references = args
local showerrors = args
local default = args
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
913 ⟶ 1.097 lerroa:
claims = findClaims(id, p)
if claims and claims[1] then
parameters.property = p
break
end
919 ⟶ 1.104 lerroa:
if showerrors then return printError("property-not-found") else return default end
end
-- set feminine case if gender is requested
928 ⟶ 1.110 lerroa:
if itemgender then
if string.match(itemgender, "^P%d+$") then
local
if snak_id then
idgender =
end
elseif string.match(itemgender, "^Q%d+$") then
967 ⟶ 1.149 lerroa:
table.sort(sortindices, comparator)
local result, result2
local error
if parameters.list or parameters.formatting == "table" then
1.086 ⟶ 1.268 lerroa:
value = nil
else
value = mw.ustring.gsub(rowformatting, "$0", value)
value = mw.ustring.gsub(value, "$R0", reference) -- add reference
for i, _ in ipairs(qualifierId) do
local valueq = valuerow["col" .. i]
1.095 ⟶ 1.277 lerroa:
-- 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
value = mw.ustring.gsub(value, "$" .. i .. "(%D)", valueq .. "%1")
end
1.105 ⟶ 1.288 lerroa:
value = expandBraces(value, rowformatting)
end
elseif value then
value = expandBraces(value, parameters.formatting)
value = value .. reference
end
if isSet(value) then
result[#result + 1] = value
if not parameters.list then
break
end
end
end
-- in a table, add edit icon on last element
if parameters.formatting == 'table' and parameters.editicon then
result = addEditIconTable(result, parameters)
end
result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
1.117 ⟶ 1.307 lerroa:
-- return first element
local claim = claims[sortindices[1]]
result,
if result and references then result = result .. getReferences(claim) end
end
if isSet(result) then
if i18n.addpencil and not (parameters.formatting == 'table' or (result2 and result2 == 'no-icon')) then
-- 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
1.150 ⟶ 1.346 lerroa:
end
--
local function uc_first(word)
1.171 ⟶ 1.354 lerroa:
local function getPropertyValue(id, property, parameter, langs, editicon, case)
local snaks = mw.wikibase.getBestStatements(id, property)
local mysnak = getSnak(snaks, {1, "mainsnak"})
if
return
end
local
local result = '-' -- default for 'no value'
if mysnak.datavalue then
result, _ = getSnakValue(mysnak, {formatting=parameter, lang=langs, editicon=editicon, case=case})
end
return
end
1.199 ⟶ 1.380 lerroa:
local function getParentObjects(id,
prop_format,
label_format,
languages,
propertySupString,
1.227 ⟶ 1.409 lerroa:
local label_self
_, label_self = getPropertyValue(id, propertyLabel,
local result = {}
1.236 ⟶ 1.418 lerroa:
local label, link
for _, propertySup in pairs(propertySups) do
_id, _link = getPropertyValue(id, propertySup,
if _id and _link then id = _id link = _link break end
end
1.249 ⟶ 1.431 lerroa:
end
_, label = getPropertyValue(id, propertyLabel,
if labelShow == nil or labelFilter[label] then
1.283 ⟶ 1.461 lerroa:
local function parentObjectsToString(result,
rowformat,
cascade,
sorting)
1.305 ⟶ 1.482 lerroa:
end
return
end
-- Returns pairs of instance label and property value fetching a recursive tree
function p.getParentValues(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()).getParentValues(frame)
end
local args = frame.args or frame -- via invoke or require
local
if id == nil then return end
local languages = findLang(args.lang)
local propertySup = args
local propertyLabel = args
local propertyLink = args
local
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
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
if isSet(args.uptolabelid) then
1.333 ⟶ 1.511 lerroa:
if isSet(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,"/")
1.340 ⟶ 1.521 lerroa:
local result = getParentObjects(id,
property_format,
label_format,
languages,
propertySup,
1.352 ⟶ 1.534 lerroa:
case,
include_self)
if #result == 0 then return end
local rowformat = args
local separator = args
local sorting = args
local cascade = (args.cascade == "true" or args.cascade == "yes")
rowformat,
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)
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
end
-- get id value of property/qualifier
local largs = mw.clone(args)
largs.list = "true"
largs.formatting = "raw"
largs.separator = "/·/"
largs.editicon = "false"
local items_list = p.claim(largs)
if not isSet(items_list) then return end
local items_table = mw.text.split(items_list, "/·/", true)
-- get internal link of property/qualifier
largs.formatting = "internallink"
local link_list = p.claim(largs)
local link_table = mw.text.split(link_list, "/·/", true)
-- get label of parent property
local parent_claim = getSnak(findClaims(items_table[1], args.parent), {1, "mainsnak", "datatype"})
if parent_claim == 'monolingualtext' then
largs.formatting = nil
largs.list = 'lang'
else
end
largs.property = args.parent
largs.qualifier = nil
for i, v in ipairs(items_table) do
local link_label = p.claim(
if isSet(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)
args.lang = findLang(args.lang)
return mw.text.listToText(link_table) .. addEditIcon(args)
end
-- Calculate number of years old ----------------------------
function p.yearsOld(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()).yearsOld(frame)
end
local args = frame.args or frame -- via invoke or require
local id =
local lang = mw.language.new('en')
local function getBestValue(id, prop)
local
return snak_value
end
1.479 ⟶ 1.673 lerroa:
local old_min = age(dates[1].max, dates[2].min)
local old_max = age(dates[1].min, dates[2].max)
local old, old_expr
if
old = "< 1"
old_max = 1 -- expression in singular
elseif old_min == old_max then
old = old_min
else
old = old_min .. "/" .. old_max
end
if args.formatting == 'unit' then
local langs = findLang(args.lang)
local yo, yo_sg, yo_pl, yo_pau
if langs[1] == wiki.langcode then
yo_sg = i18n["years-old"].singular
yo_pl = i18n["years-old"].plural
yo_pau = i18n["years-old"].paucal
end
if not isSet(yo_pl) then
yo_pl = getLabelByLangs('Q24564698', langs)
yo_sg = yo_pl
end
if not isSet(yo_pau) then
yo_pau = yo_pl
end
yo = mw.language.new(langs[1]):plural(old_max, {yo_sg, yo_pau, yo_pl})
if mw.ustring.find(yo, '$1', 1, true) then
old_expr = mw.ustring.gsub(yo, "$1", old)
else
old_expr = old .. ' ' .. yo
end
elseif args.formatting then
old_expr = expandBraces(mw.ustring.gsub(args.formatting, '$1', old), args.formatting)
else
old_expr = old
end
return
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 =
if
local editicon = not (args.editicon == "false" or args.editicon == "no") and mw.wikibase.isValidEntityId(id)
local
local label, lang
if args.label then
1.507 ⟶ 1.735 lerroa:
if label == nil then
if new_id then
label, lang = getLabelByLangs( if label then
if args.itemgender and feminineGender(args.itemgender) then
label = feminineForm(
end
label = mw.language.new(lang):ucfirst(mw.text.nowiki(label)) -- sanitize
end
label_icon = addLabelIcon(new_id or id, lang, languages[1], editicon)
end
end
end
1.522 ⟶ 1.752 lerroa:
if isSet(linked) and linked ~= "no" then
local article = mw.wikibase.getSitelink(id) or ("d:" .. id)
return "[[" .. article .. "|" .. (label or id) .. "]]" ..
else
return (label or id) ..
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
|