Mòdul:Wikidata: diferència entre les revisions
Contingut suprimit Contingut afegit
conversió list "false" a false |
getQualifierSnak amb monolingualtext |
||
Línia 221: | Línia 221: | ||
end |
end |
||
local function getQualifierSnak(claim, qualifierId) |
local function getQualifierSnak(claim, qualifierId, parameter) |
||
-- a "snak" is Wikidata terminology for a typed key/value pair |
-- a "snak" is Wikidata terminology for a typed key/value pair |
||
-- a claim consists of a main snak holding the main information of this claim, |
-- a claim consists of a main snak holding the main information of this claim, |
||
Línia 229: | Línia 229: | ||
if claim.qualifiers then |
if claim.qualifiers then |
||
local qualifier = claim.qualifiers[qualifierId] |
local qualifier = claim.qualifiers[qualifierId] |
||
if qualifier then |
if qualifier then |
||
-- iterate over monolingualtext qualifiers, if local language is requested |
|||
if parameter and parameter == wiki.langcode then |
|||
for idx in pairs(qualifier) do |
|||
if qualifier[idx].datavalue.value.language == parameter then |
|||
return qualifier[idx] |
|||
end |
|||
end |
|||
end |
|||
return qualifier[1] |
|||
end |
|||
end |
end |
||
return nil, printError("qualifier-not-found") |
return nil, printError("qualifier-not-found") |
||
Línia 241: | Línia 251: | ||
local error |
local error |
||
local snak |
local snak |
||
snak, error = getQualifierSnak(claim, qualifierId) |
snak, error = getQualifierSnak(claim, qualifierId, parameter) |
||
if snak then |
if snak then |
||
return getSnakValue(snak, parameter) |
return getSnakValue(snak, parameter) |
Revisió del 18:53, 29 jul 2016
Documentació del mòdul [ mostra ] [ modifica el codi ] [ mostra l'historial ] [ refresca ]
A continuació es mostra la documentació transclosa de la subpàgina /ús. [salta a la caixa de codi]
Aquesta pàgina és una redirecció. Per les darreres versions d'aquest mòdul, a partir de 20200210, vegeu Module:Wikidades. |
(en) This is a redirect page. For newer versions of this module, from 20200210, see Module:Wikidades. |
local p = {}
-- module local variables
local wiki =
{
langcode = mw.language.getContentLanguage().code
}
local i18n = {
["errors"] = {
["property-not-found"] = "Propietat no trobada.",
["entity-not-found"] = "Entitat no trobada.",
["unknown-claim-type"] = "Tipus d'afirmació (claim) desconegut.",
["unknown-entity-type"] = "Tipus d'entitat desconegut.",
["qualifier-not-found"] = "Qualificador no trobat.",
["site-not-found"] = "Projecte Wikimedia no trobat.",
["unknown-datetime-format"] = "Format data/horari desconegut.",
["local-article-not-found"] = "L'article encara no està disponible en aquest wiki"
},
["datetime"] =
{
-- $1 is a placeholder for the actual number
[0] = "$1 mil milions d'anys", -- precision: billion years
[1] = "$100 milions d'anys", -- precision: hundred million years
[2] = "$10 milions d'anys", -- precision: ten million years
[3] = "$1 milions d'anys", -- precision: million years
[4] = "$100.000 anys", -- precision: hundred thousand years
[5] = "$10.000 anys", -- precision: ten thousand years
[6] = "mil·lenni $1", -- precision: millennium
[7] = "segle $1", -- precision: century
[8] = "dècada del $1", -- precision: decade
-- the following use the format of #time parser function
[9] = "Y", -- precision: year,
[10] = "F Y", -- precision: month
[11] = "j F Y", -- precision: day
[12] = "j F Y ga", -- precision: hour
[13] = "j F Y g:ia", -- precision: minute
[14] = "j F Y g:i:sa", -- precision: second
["beforenow"] = "fa $1", -- how to format negative numbers for precisions 0 to 5
["afternow"] = "d'aquí $1", -- how to format positive numbers for precisions 0 to 5
["bc"] = '$1 aC', -- how print negative years
["ad"] = "$1" -- how print positive years
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["warnDump"] = "[[Categoria:Funció Dump del mòdul Wikidata]]"
}
local function printDatavalueString(data, parameter)
if parameter == 'weblink' then
return '[' .. data .. ' ' .. mw.text.split(data, '//' )[2] .. ']'
elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
return mw.ustring.gsub(parameter, '$1', data) .. '' -- Hack to get only the first result of the function
else
return data
end
end
local function printDatavalueCoordinate(data, parameter)
local globetable = {Q2 = 'earth', Q111 = 'mars', Q405 = 'moon'}
if parameter == 'latitude' then
return data.latitude
elseif parameter == 'longitude' then
return data.longitude
elseif parameter == 'dimension' then
return data.dimension
else
if data.globe == '' or data.globe == nil then
return 'earth'
else
local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
if globetable[globenum] then
return globetable[globenum]
else
return globenum
end
end
end
end
local function printDatavalueQuantity(data, parameter)
-- exemples: 277±1 Centímetre, 1,94 metre
local amount = data.amount
amount = mw.ustring.gsub(amount, "%+", "")
local lang = mw.language.new(wiki.langcode)
amount = lang:formatNum(tonumber(amount))
return amount
end
local function printDatavalueTime(data, parameter)
-- Dates and times are stored in ISO 8601 format
-- check for negative date, ex. "-0027-01-16T00:00:00Z"
local suffix = ""
local timestamp = data.time
if string.sub(timestamp, 1, 1) == '-' then
timestamp = '+' .. string.sub(timestamp, 2)
suffix = " aC"
elseif string.sub(timestamp, 2, 3) == '00' then
suffix = " dC"
end
local function d(f)
return mw.language.new(wiki.langcode):formatDate(f, timestamp) .. suffix
end
local precision = data.precision or 11
local any = tonumber(mw.ustring.match(timestamp, "^\+?%d+"))
local ret = ""
-- precision is 10000 years or more
if precision <= 5 then
local factor = 10 ^ ((5 - precision) + 4)
local y2 = math.ceil(math.abs(any) / factor)
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if suffix == " aC" then
ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
ret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
-- precision is decades, centuries or millennia
elseif precision == 6 then
ret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(any) - 1) / 1000) + 1)) .. suffix
elseif precision == 7 then -- segles
ret = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(any) - 1) / 100) + 1)) .. suffix
elseif precision == 8 then
ret = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(any) / 10) * 10)) .. suffix
-- precision is year
elseif parameter == 'year' or precision == 9 then
ret = tostring(any) .. suffix
-- precision is month
elseif precision == 10 then
timestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous month
ret, _ = string.gsub(d("F Y"), " 0+", " ") -- supress leading zeros in year
elseif parameter then
ret, _ = string.gsub(d(parameter), " 0+", " ")
else
ret, _ = string.gsub(d("j F Y"), " 0+", " ")
end
return ret
end
local function printDatavalueEntity(data, parameter)
local entityId = "Q" .. tostring(data['numeric-id'])
local label = mw.wikibase.label(entityId)
local sitelink = mw.wikibase.sitelink(entityId)
if parameter == 'raw' then
return entityId
elseif parameter == 'label' then
return (label or entityId)
elseif parameter == 'sitelink' then
return (sitelink or 'wikidata:' .. entityId)
else
if sitelink then
if label then
return '[[' .. sitelink .. '|' .. label .. ']]'
else
return '[[' .. sitelink .. ']]'
end
elseif label and parameter == 'internallink' then
return '[[' .. label .. ']]'
else
return '[[wikidata:' .. entityId .. '|' .. (label or entityId) .. ']]'
end
end
end
local function printDatavalueMonolingualText(data, parameter)
-- data fields: language [string], text [string]
local result = nil
if parameter == "language" or parameter == "text" then
result = data[parameter]
elseif parameter then
if data["language"] == wiki.langcode then
if parameter then
result = printDatavalueString(data["text"], parameter)
else
result = data["text"]
end
end
else
result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
end
return result
end
local function printError(key)
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
local function findClaims(entity, property)
if not property or not entity or not entity.claims then return end
if mw.ustring.match(property, "^P%d+$") then
-- if the property is given by an id (P..) access the claim list by this id
return entity.claims[property]
else
-- otherwise, iterate over all properties, fetch their labels and compare this to the given property name
for k, v in pairs(entity.claims) do
if mw.wikibase.label(k) == property then return v end
end
return
end
end
local function getSnakValue(snak, parameter)
if snak.snaktype == 'value' then
-- call the respective snak parser
if snak.datavalue.type == "string" then
return printDatavalueString(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "globecoordinate" then
return printDatavalueCoordinate(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "quantity" then
return printDatavalueQuantity(snak.datavalue.value, parameter)
elseif snak.datavalue.type == "time" then
return printDatavalueTime(snak.datavalue.value, parameter)
elseif snak.datavalue.type == 'wikibase-entityid' then
return printDatavalueEntity(snak.datavalue.value, parameter)
elseif snak.datavalue.type == 'monolingualtext' then
return printDatavalueMonolingualText(snak.datavalue.value, parameter)
end
end
return mw.wikibase.renderSnak(snak)
end
local function getQualifierSnak(claim, qualifierId, parameter)
-- a "snak" is Wikidata terminology for a typed key/value pair
-- a claim consists of a main snak holding the main information of this claim,
-- as well as a list of attribute snaks and a list of references snaks
if qualifierId then
-- search the attribute snak with the given qualifier as key
if claim.qualifiers then
local qualifier = claim.qualifiers[qualifierId]
if qualifier then
-- iterate over monolingualtext qualifiers, if local language is requested
if parameter and parameter == wiki.langcode then
for idx in pairs(qualifier) do
if qualifier[idx].datavalue.value.language == parameter then
return qualifier[idx]
end
end
end
return qualifier[1]
end
end
return nil, printError("qualifier-not-found")
else
-- otherwise return the main snak
return claim.mainsnak
end
end
local function getValueOfClaim(claim, qualifierId, parameter)
local error
local snak
snak, error = getQualifierSnak(claim, qualifierId, parameter)
if snak then
return getSnakValue(snak, parameter)
else
return nil, error
end
end
-- Return the site link (for the current site) for a given data item.
function p.getSiteLink( frame )
if frame.args[1] == nil then
entity = mw.wikibase.getEntityObject()
if not entity then
return nil
end
id = entity.id
else
id = frame.args[1]
end
return mw.wikibase.sitelink( id )
end
function p.claim(frame)
local args = frame.args
--If a value is already set, use it
if args.value and args.value ~= '' then
return args.value
end
local property = args["property"] or ""
property = property:gsub("^p(%d)", "P%1")
local id = args["item"]; if id == "" then id = nil end
local qualifierId = args["qualifier"] or args["qualifierProperty"] -- compatibilitat de transició
if qualifierId then qualifierId = qualifierId:gsub("^p(%d)", "P%1") end
local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
if not parameter and args["rank"] == "ca" then parameter = "ca" end -- compatibilitat de transició
local list = args["list"] or true
if list == "false" then list = false end
if args["rank"] and args["rank"] ~= '' then list = false end -- compatibilitat de transició
local showerrors = args["showerrors"]
local default = args["default"]
if default then showerrors = nil end
-- get wikidata entity
local entity = mw.wikibase.getEntityObject(id)
if not entity then
if showerrors then return printError("entity-not-found") else return default end
end
-- fetch the first claim of satisfying the given property
local claims = findClaims(entity, property)
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
end
-- This is used to get the unit name for a numeric value
local suffix = ""
if parameter == "unit" then
local result = entity:formatPropertyValues(property, mw.wikibase.entity.claimRanks).value
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
suffix = " " .. mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
end
end
-- get initial sort indices
local sortindices = {}
for idx in pairs(claims) do
sortindices[#sortindices + 1] = idx
end
-- sort by claim rank
local comparator = function(a, b)
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
return ranka < rankb
end
table.sort(sortindices, comparator)
local result
local error
if list then
local value
-- iterate over all elements and return their value (if existing)
result = {}
for idx in pairs(claims) do
local claim = claims[sortindices[idx]]
value, error = getValueOfClaim(claim, qualifierId, parameter)
if not value and showerrors then value = error end
result[#result + 1] = value
end
result = mw.text.listToText(result, args.separator, args.conjunction)
else
-- return first element
local claim = claims[sortindices[1]]
result, error = getValueOfClaim(claim, qualifierId, parameter)
end
if result then return result .. suffix else
if showerrors then return error else return default end
end
end
-- Return the statements with a format
function p.formatStatements(frame)
return p.claim(frame) -- compatibilitat de transició
end
--Return the qualifiers with a format
function p.formatQualifiers(frame)
return p.claim(frame) -- compatibilitat de transició
end
-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
-- uses the newer mw.wikibase calls instead of directly using the snaks
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
p.getTAValue = function(frame)
local ent = mw.wikibase.getEntityObject()
local props = ent:formatPropertyValues('P1323')
local out = {}
local t = {}
for k, v in pairs(props) do
if k == 'value' then
t = mw.text.split( v, ", ")
for k2, v2 in pairs(t) do
out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
end
end
end
local ret = table.concat(out, "<br> ")
if #ret == 0 then
ret = "Invalid TA"
end
return ret
end
-- look into entity object
function p.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.getEntityObject(id)
if not data then
return nil
end
local i = 1
while true do
local index = f.args[i]
if not index then
if type(data) == "table" then
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
else
return tostring(data)
end
end
data = data[index] or data[tonumber(index)]
if not data then
return
end
i = i + 1
end
end
-- 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)
local data = mw.wikibase.getEntityObject()
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 "<pre>" .. mw.dumpObject(data) .. "</pre>" .. i18n.warnDump
end
data = data[index] or data[tonumber(index)]
if not data then
return i18n.warnDump
end
i = i + 1
end
end
-- Look into entity object
-- From pl:Module:Wikidane, function V, by User:Paweł Ziemian
function p.getEntityFromTree(frame)
local data = mw.wikibase.getEntityObject()
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
return p