Aitapihikewin:Wikidata

La documentation pour ce module peut être créée à Aitapihikewin:Wikidata/doc

-- version 20170727local p = {}local wiki = {langcode = mw.language.getContentLanguage().code}------------------------------------------------------------------------------- internationalisation at [[Module:Wikidata/i18n]]local i18n = {["errors"] = {["property-not-found"] = "Property not found.",["entity-not-found"] = "Wikidata entity not found.",["unknown-claim-type"] = "Unknown claim type.",["unknown-entity-type"] = "Unknown entity type.",["qualifier-not-found"] = "Qualifier not found.",["site-not-found"] = "Wikimedia project not found.",["unknown-datetime-format"] = "Unknown datetime format.",["local-article-not-found"] = "Article is not yet available in this wiki.",['not-from-content-page'] = "Do not invoke from content page. Use a template or use a module subpage like /sandbox for testing ."},["datetime"] ={-- $1 is a placeholder for the actual number[0] = "$1 billion years",-- precision: billion years[1] = "$100 million years",-- precision: hundred million years[2] = "$10 million years",-- precision: ten million years[3] = "$1 million years",-- precision: million years[4] = "$100,000 years",-- precision: hundred thousand years[5] = "$10,000 years",-- precision: ten thousand years[6] = "$1 millennium",-- precision: millennium[7] = "$1 century",-- precision: century[8] = "$1s",-- precision: decade-- the following use the format of #time parser function[9]  = "Y",-- precision: year, [10] = "F Y",-- precision: month[11] = "F j, Y",-- precision: day[12] = "F j, Y ga",-- precision: hour[13] = "F j, Y g:ia",-- precision: minute[14] = "F j, Y g:i:sa",-- precision: second["beforenow"] = "$1 BCE",-- how to format negative numbers for precisions 0 to 5["afternow"] = "$1 CE",-- how to format positive numbers for precisions 0 to 5["bc"] = '$1 "BCE"',-- how print negative years["ad"] = "$1",-- how print positive years["bc-addon"] = " BC",-- suffix for negative dates["ad-addon"] = ""-- suffix for 1st century AD dates},["monolingualtext"] = '<span lang="%language">%text</span>',["warnDump"] = "[[Categoria:Funció Dump del mòdul Wikidata]]"}local cases = {} -- functions for local grammatical cases defined at [[Module:Wikidata/i18n]]------------------------------------------------------------------------------ module local functions-- Credit to http://stackoverflow.com/a/1283608/2644759-- cc-by-sa 3.0local function tableMerge(t1, t2)for k,v in pairs(t2) doif type(v) == "table" thenif type(t1[k] or false) == "table" thentableMerge(t1[k] or {}, t2[k] or {})elset1[k] = vendelset1[k] = vendendreturn t1endlocal function loadI18n()local exist, res = pcall(require, "Module:Wikidata/i18n")if exist and next(res) ~= nil thentableMerge(i18n, res.i18n)cases = res.casesendendloadI18n()local function case(word, localcase)if word == nil or word == '' or cases[localcase] == nil thenreturn wordendreturn cases[localcase](word)endlocal function expandBraces(text)if text == nil then return text endif type(text) ~= "string" thentext = tostring(text)endfor braces in mw.ustring.gmatch(text, "{{(.-)}}") dolocal parts = mw.text.split(braces, "|")local title = parts[1]local parameters = {}for i = 2, #parts doif mw.ustring.find(parts[i], "=") thenlocal subparts = mw.text.split(parts[i], "=")parameters[subparts[1]] = subparts[2]elsetable.insert(parameters, parts[i])endendlocal braces_expandedif mw.ustring.find(title, ":") thenbraces_expanded = mw.getCurrentFrame():callParserFunction{name=title, args=parameters}elsebraces_expanded = mw.getCurrentFrame():expandTemplate{title=title, args=parameters}endtitle = mw.ustring.gsub(title, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") -- escape magic characterstext = mw.ustring.gsub(text, "{{" .. title .. ".-}}", braces_expanded)endreturn textendlocal 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 patternreturn expandBraces(mw.ustring.gsub(parameter, '$1', data))elsereturn dataendendlocal function printDatavalueCoordinate(data, parameter)if parameter == 'latitude' thenreturn data.latitudeelseif parameter == 'longitude' thenreturn data.longitudeelseif parameter == 'dimension' thenreturn data.dimensionelse --default formatting='globe'if data.globe == '' or data.globe == nil or data.globe == 'http://www.wikidata.org/entity/Q2' thenreturn 'earth'elselocal globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2local globetable = mw.loadData('Module:Mapa cos celeste/dades')for _, globe in pairs(globetable.maps) doif globe.wikidata == globenum thenreturn globe.coord_globeendendreturn globenumendendendlocal function printDatavalueQuantity(data, parameter)-- exemples: 277±1 Centímetre, 1,94 metrelocal amount = data.amountamount = mw.ustring.gsub(amount, "%+", "")local sortkey = string.format("%09d", amount)local lang = mw.language.new(wiki.langcode)amount = lang:formatNum(tonumber(amount))-- This is used to get the unit name for a numeric valuelocal suffix = ""if parameter == "unit" or parameter == "unitcode" then-- get the url for the unit entry on Wikidata:local unitID = data.unit-- and just return the last bit from "Q" to the end (which is the QID):unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)if mw.ustring.sub(unitID, 1, 1) == "Q" thenlocal unit_label = mw.wikibase.label(unitID)suffix = " " .. require("Module:Wikidata/Units").getUnit(amount, unit_label, unitID, parameter == "unitcode")endendreturn amount .. suffix, sortkeyendlocal function printDatavalueTime(data, parameter)-- Dates and times are stored in ISO 8601 formatlocal timestamp = data.timelocal sortkey = timestamplocal addon = ""-- check for negative date, ex. "-0027-01-16T00:00:00Z"if string.sub(timestamp, 1, 1) == '-' thentimestamp = '+' .. string.sub(timestamp, 2)addon = i18n.datetime["bc-addon"]elseif string.sub(timestamp, 2, 3) == '00' thenaddon = i18n.datetime["ad-addon"]endlocal function d(f, t)return mw.language.new(wiki.langcode):formatDate(f, t or timestamp) .. addonendlocal precision = data.precision or 11local intyear = tonumber(mw.ustring.match(timestamp, "^\+?%d+"))local ret = ""-- precision is 10000 years or moreif precision <= 5 thenlocal factor = 10 ^ ((5 - precision) + 4)local y2 = math.ceil(math.abs(intyear) / factor)local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))if addon == i18n.datetime["bc-addon"] then-- negative dateret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)elseret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)end-- precision is millennia, centuries or decadeselseif precision == 6 thenlocal card = math.floor((intyear - 1) / 1000) + 1if mw.ustring.find(i18n.datetime[6], "$1") thenret = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(card)) .. addonelseret = d(i18n.datetime[6], string.format("%04d", tostring(card)))endelseif precision == 7 thenlocal card = math.floor((math.abs(intyear) - 1) / 100) + 1if mw.ustring.find(i18n.datetime[7], "$1") thenret = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(card)) .. addonelseret = d(i18n.datetime[7], string.format("%04d", tostring(card)))endelseif precision == 8 thenlocal card = math.floor(math.abs(intyear) / 10) * 10ret = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(card)) .. addon-- precision is yearelseif parameter == 'Y' or precision == 9 thenret = tostring(intyear) .. addon-- precision is monthelseif precision == 10 thentimestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous monthret, _ = string.gsub(d(i18n.datetime[10]), " 0+", " ") -- supress leading zeros in yearelseif parameter thenret, _ = string.gsub(d(parameter), "([ %[])0+", "%1") -- supress leading zeros in year optionally linkedelseret, _ = string.gsub(d(i18n.datetime[11]), " 0+", " ")endreturn ret, sortkeyendlocal function printDatavalueEntity(data, parameters)local entityId = "Q" .. tostring(data['numeric-id'])local label = mw.wikibase.label(entityId)local sitelink = mw.wikibase.sitelink(entityId)local parameter = parameters.formattinglocal labelcase = label or sitelinkif parameters.case thenlabelcase = case(labelcase, parameters.case)endif parameter == 'raw' then return entityId, entityIdelseif parameter == 'label' thenreturn (labelcase or entityId), (labelcase or entityId)elseif parameter == 'sitelink' thenreturn (sitelink or 'wikidata:' .. entityId), (sitelink or entityId)elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a patternlocal ret = mw.ustring.gsub(parameter, '$1', labelcase or entityId)ret = expandBraces(ret)return ret, labelcase or entityIdelseif sitelink thenreturn '[[' .. sitelink .. '|' .. labelcase .. ']]', labelcaseelseif label and parameter == 'internallink' thenreturn '[[' .. label .. '|' .. labelcase .. ']]', labelcaseelsereturn '[[wikidata:' .. entityId .. '|' .. (labelcase or entityId) .. ']]', labelcase or entityIdendendendlocal function printDatavalueMonolingualText(data, parameter)-- data fields: language [string], text [string]local result = nilif parameter == "language" or parameter == "text" thenresult = data[parameter]elseif parameter thenif data["language"] == wiki.langcode thenresult = data["text"]endelseresult = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])endreturn resultendlocal function printDatatypeMath(data)return mw.getCurrentFrame():callParserFunction('#tag:math', data)endlocal function printError(key)    return '<span class="error">' .. i18n.errors[key] .. '</span>'endlocal function findClaims(entity, property)if not property or not entity or not entity.claims then return endif mw.ustring.match(property, "^P%d+$") then-- if the property is given by an id (P..) access the claim list by this idreturn entity.claims[property]elseproperty = mw.wikibase.resolvePropertyId(property)if not property then return endreturn entity.claims[property]endendlocal function getSnakValue(snak, parameters)local parameter = parameters.formattingif snak.snaktype == 'value' then-- call the respective snak parserif snak.datatype == 'math' thenreturn printDatatypeMath(snak.datavalue.value)elseif snak.datavalue.type == "string" thenreturn printDatavalueString(snak.datavalue.value, parameter)elseif snak.datavalue.type == "globecoordinate" thenreturn printDatavalueCoordinate(snak.datavalue.value, parameter)elseif snak.datavalue.type == "quantity" thenreturn printDatavalueQuantity(snak.datavalue.value, parameter)elseif snak.datavalue.type == "time" thenreturn printDatavalueTime(snak.datavalue.value, parameter)elseif snak.datavalue.type == 'wikibase-entityid' thenreturn printDatavalueEntity(snak.datavalue.value, parameters)elseif snak.datavalue.type == 'monolingualtext' thenreturn printDatavalueMonolingualText(snak.datavalue.value, parameter)endendreturn mw.wikibase.renderSnak(snak)endlocal function getQualifierSnak(claim, qualifierId, parameters)-- 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 snaksif qualifierId then-- search the attribute snak with the given qualifier as keyif claim.qualifiers thenlocal qualifier = claim.qualifiers[qualifierId]if qualifier then-- iterate over monolingualtext qualifiers to get local languagefor idx in pairs(qualifier) doif qualifier[idx].datavalue and qualifier[idx].datavalue.value and qualifier[idx].datavalue.value.language thenif qualifier[idx].datavalue.value.language == wiki.langcode thenreturn qualifier[idx]endendendif parameters.list thenreturn qualifierelsereturn qualifier[1]endendendreturn nil, printError("qualifier-not-found")else-- otherwise return the main snakreturn claim.mainsnakendendlocal function getValueOfClaim(claim, qualifierId, parameters)local errorlocal snaksnak, error = getQualifierSnak(claim, qualifierId, parameters)if not snak thenreturn nil, nil, errorelseif snak[1] then -- a multi qualifierlocal result = {}local sortkey = {}for idx in pairs(snak) doresult[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)endreturn mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]else -- a property or a qualifierreturn getSnakValue(snak, parameters)endend-- 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-- On debug console use: =p._debug({item="Q...", property="P...", ...})function p._debug(args)return p._main(args)endfunction p.claim(frame)if mw.title.new(frame:getParent():getTitle()).isContentPage and not mw.title.new(frame:getTitle()).isSubpage then-- invoked from a content page and not invoking a module subpagereturn printError("not-from-content-page")endreturn p._main(frame.args)endfunction p._main(args)--If a value is already set, use itif args.value and args.value ~= '' thenreturn args.valueend-- argumentslocal property = args["property"] or ""local id = args["item"]; if id == "" then id = nil endlocal idgender = args["itemgender"]if idgender and not string.match(idgender, "^Q%d+$") then -- id malformed, maybe "unknown value"idgender = nilendlocal qualifierId = {}qualifierId[1] = args["qualifier"]for i = 2, 9 doqualifierId[i] = args["qualifier" .. i]endlocal parameter = args["formatting"] or ''; if parameter == "" then parameter = nil endlocal case = args.caselocal list = args["list"] or true; if list == "false" then list = false endlocal sorting_col = args.tablesortlocal sorting_up = (args.sorting or "") ~= "-1"local separator = args.separatorlocal conjunction = args.conjunction or args.separatorlocal rowformat = args.rowformatlocal showerrors = args["showerrors"]local default = args["default"]property = property:gsub("^p(%d)", "P%1")if qualifierId[1] then qualifierId[1] = qualifierId[1]:gsub("^p(%d)", "P%1") endlocal parameters = {["formatting"] = parameter, ["list"] = list, ["case"] = case,["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}local preformat = ""local postformat = ""if parameters.formatting == "table" thenparameters.separator = parameters.separator or "<br />"parameters.conjunction = parameters.conjunction or "<br />"parameters.qseparator = ", "parameters.qconjunction = ", "if not rowformat thenrowformat = "$0 ($1"for i = 2, 9 doif qualifierId[i] thenrowformat = rowformat .. ", $" .. iendendrowformat = rowformat .. ")"elseif mw.ustring.find(rowformat, "^[*#]") thenparameters.separator = "</li><li>"parameters.conjunction = "</li><li>"if mw.ustring.match(rowformat, "^[*#]") == "*" thenpreformat = "<ul><li>"postformat = "</li></ul>"elsepreformat = "<ol><li>"postformat = "</li></ol>"endrowformat = mw.ustring.gsub(rowformat, "^[*#] ?", "")endendif default then showerrors = nil end-- get wikidata entitylocal entity = mw.wikibase.getEntityObject(id)if not entity thenif showerrors then return printError("entity-not-found") else return default endend-- fetch the first claim of satisfying the given propertylocal claims = findClaims(entity, property)if not claims or not claims[1] thenif showerrors then return printError("property-not-found") else return default endend-- find feminine case if gender is requestedlocal genderCaseif parameters.case == "gender" or idgender or parameters.formatting == "table" thenlocal genderEntity = idgender and mw.wikibase.getEntityObject(idgender) or entitylocal genderClaims = genderEntity.claims["P21"]if genderClaims thenlocal genderId = getValueOfClaim(genderClaims[1], nil, {["formatting"]="raw"})if genderId == "Q6581072" or genderId == "Q1052281" or genderId == "Q43445" then -- female, transgender female, female organismgenderCase = (parameters.case == "infoboxlabel") and "labelfeminine" or "feminine"if parameters.case == "gender" or idgender thenparameters.case = genderCaseendendendend-- get initial sort indiceslocal sortindices = {}for idx in pairs(claims) dosortindices[#sortindices + 1] = idxend-- sort by claim ranklocal 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 < rankbendtable.sort(sortindices, comparator)local resultlocal errorif parameters.list or parameters.formatting == "table" then-- convert LF to line feed, <br /> may not work on some casesparameters.separator = parameters.separator == "LF" and "\010" or parameters.separatorparameters.conjunction = parameters.conjunction == "LF" and "\010" or parameters.conjunction-- iterate over all elements and return their value (if existing)local value, valueqlocal sortkey, sortkeyqlocal values = {}local sortkeys = {}local firstrank = parameters.list == "firstrank" and claims[sortindices[1]].rank or ''for idx in pairs(claims) dolocal claim = claims[sortindices[idx]]if firstrank ~= '' and firstrank ~= claim.rank thenbreakendvalues[#values + 1] = {}sortkeys[#sortkeys + 1] = {}if parameters.formatting == "table" thenlocal params = mw.clone(parameters)params.formatting = args["colformat0"]if args["case0"] thenparams.case = args["case0"] == "gender" and genderCase or args["case0"]endvalue, sortkey, error =  getValueOfClaim(claim, nil, params)for i, qual in ipairs(qualifierId) doparams.formatting = args["colformat" .. i]if args["case" .. i] thenparams.case = args["case" .. i] == "gender" and genderCase or args["case" .. i]elseparams.case = parameters.caseendvalueq, sortkeyq, _ =  getValueOfClaim(claim, qual, params)values[#values]["col" .. i] = valueqsortkeys[#sortkeys]["col" .. i] = sortkeyq or valueqendelsevalue, sortkey, error =  getValueOfClaim(claim, qualifierId[1], parameters)endif not value and showerrors then value = error endvalues[#values]["col0"] = valuesortkeys[#sortkeys]["col0"] = sortkey or valueend-- sort and format resultssortindices = {}for idx in pairs(values) dosortindices[#sortindices + 1] = idxendif sorting_col thenlocal comparator = function(a, b)local valuea = sortkeys[a]["col" .. sorting_col] or ''local valueb = sortkeys[b]["col" .. sorting_col] or ''if sorting_up thenreturn valuea < valuebendreturn valuea > valuebendtable.sort(sortindices, comparator)endresult = {}for idx in pairs(values) dolocal valuerow = values[sortindices[idx]]value = valuerow["col0"]if parameters.formatting == "table" thenvalue = mw.ustring.gsub(rowformat, "$0", value)for i, _ in ipairs(qualifierId) dovalueq = valuerow["col" .. i]if args["rowsubformat" .. i] and valueq thenvalueq = mw.ustring.gsub(args["rowsubformat" .. i], "$" .. i, valueq)endvalue = mw.ustring.gsub(value, "$" .. i, valueq or '')endendvalue = expandBraces(value)result[#result + 1] = valueendresult = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformatelse-- return first elementlocal claim = claims[sortindices[1]]result, _, error = getValueOfClaim(claim, qualifierId[1], parameters)endif result then return result elseif showerrors then return error else return default endendend-- 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 stringp.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 retend-- look into entity objectfunction p.ViewSomething(frame)local f = (frame.args[1] or frame.args.item) and frame or frame:getParent()local id = f.args.itemif id and (#id == 0) thenid = nilendlocal data = mw.wikibase.getEntityObject(id)if not data thenreturn nilendlocal i = 1while true dolocal index = f.args[i]if not index thenif type(data) == "table" thenreturn frame:extensionTag('syntaxhighlight', mw.text.jsonEncode(data, mw.text.JSON_PRETTY), {lang = 'json'})elsereturn tostring(data)endenddata = data[index] or data[tonumber(index)]if not data thenreturnendi = i + 1endend-- 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 thenreturn i18n.warnDumpendlocal f = frame.args[1] and frame or frame:getParent()local i = 1while true dolocal index = f.args[i]if not index thenreturn frame:extensionTag('syntaxhighlight', mw.dumpObject(data), {lang = 'json'}) .. i18n.warnDumpenddata = data[index] or data[tonumber(index)]if not data thenreturn i18n.warnDumpendi = i + 1endend-- Look into entity object-- From pl:Module:Wikidane, function V, by User:Paweł Ziemianfunction p.getEntityFromTree(frame)local data = mw.wikibase.getEntityObject()if not data thenreturn nilendlocal f = frame.args[1] and frame or frame:getParent()local i = 1while true dolocal index = f.args[i]if not index thenreturn tostring(data)enddata = data[index] or data[tonumber(index)]if not data thenreturnendi = i + 1endend-- getParentValues: returns a property value with its instance label fetching a recursive treelocal function uc_first(word)return mw.ustring.upper(mw.ustring.sub(word, 1, 1)) .. mw.ustring.sub(word, 2)endlocal function getPropertyValue(id, property, parameter)local entity = mw.wikibase.getEntityObject(id)if not (entity and entity.claims) then return endlocal claims = entity.claims[property]if not claims then return end-- get initial sort indiceslocal sortindices = {}for idx in pairs(claims) dosortindices[#sortindices + 1] = idxend-- sort by claim ranklocal 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 < rankbendtable.sort(sortindices, comparator)local snak = claims[sortindices[1]].mainsnaklocal entityIdlocal result = '-' -- default for 'no value'if snak.datavalue thenentityId = "Q" .. tostring(snak.datavalue.value['numeric-id'])result, _ = getSnakValue(snak, {formatting=parameter})endreturn entityId, resultendfunction p.getParentValues(frame)local args = frame.argslocal id = args["item"]; if id == "" then id = nil endlocal propertySup = args["property"]; if (propertySup == nil or propertySup == "") then propertySup = "P131" end --administrative entitylocal propertyLabel = args["label"]; if (propertyLabel == nil or propertyLabel == "") then propertyLabel = "P31" end --instancelocal propertyLink = args["valuetext"]; if propertyLink == "" then propertyLink = nil end --internallinklocal upto = args["upto"]; if upto == "" then upto = nil endlocal labelShow = args["labelshow"]; if labelShow == "" then labelShow = nil endlocal rowformat = args["rowformat"]; if (rowformat == nil or rowformat == "") then rowformat = "$0 = $1" endlocal separator = args["separator"]; if (separator == nil or separator == "") then separator = "<br />" endlocal sorting = args["sorting"]; if sorting == "" then sorting = nil endlocal lastlabel = uc_first(upto or '')local maxloop = tonumber(upto) or (lastlabel == '' and 10 or 50)local labelFilter = {}if labelShow thenfor i, v in ipairs(mw.text.split(labelShow, "/")) dolabelFilter[uc_first(v)] = trueendendlocal result = {}local label, link, linktextfor iter = 1, maxloop dolocal label, linkid, link = getPropertyValue(id, propertySup, "internallink")if id then_, label = getPropertyValue(id, propertyLabel, "label")if label and link thenif propertyLink then_, linktext = getPropertyValue(id, propertyLink, "label")if linktext thenlink = mw.ustring.gsub(link, "%[%[(.*)%|.+%]%]", "[[%1|" .. linktext .. "]]")endendlabel = case(label, "infoboxlabel")if labelShow == nil or labelFilter[label] thenresult[#result + 1] = {label, link}endif label == lastlabel thenbreakendelsebreakendelsebreakendendlocal ret = {}local first = 1local last = #resultlocal iter = 1if sorting == "-1" then first = #result; last = 1; iter = -1 endfor i = first, last, iter dolocal rowtext = mw.ustring.gsub(rowformat, "$[01]", {["$0"] = result[i][1], ["$1"] = result[i][2]})ret[#ret +1] = expandBraces(rowtext)endreturn mw.text.listToText(ret, separator, separator)endfunction p.linkWithParentLabel(frame)local args = {}for k, v in pairs(frame.args) do -- metatableargs[k] = vendargs.list = "false"args.formatting = "internallink"local link = p._main(args) -- get internal link of property/qualifierargs.formatting = "raw"args.item = p._main(args) -- get item of property/qualifierargs.property = args.parentargs.qualifier = nilargs.formatting = "label"local link_label = p._main(args) -- get label of parent propertyif link_label thenlink = mw.ustring.gsub(link or '', "%[%[(.*)%|.+%]%]", "[[%1|" .. link_label .. "]]")endreturn linkendfunction p.years_old(frame)local args = frame.argslocal id = args.item; if id == '' then id = nil endlocal lang = mw.language.new('en')local function fetchsnak(id, snak)local ret = mw.wikibase.getEntityObject(id)for i, v in ipairs(snak) doif ret == nil then break endret = ret[v]endreturn retendlocal birth = fetchsnak(id, {'claims', 'P569', 1, 'mainsnak', 'datavalue', 'value'})if type(birth) ~= 'table' or birth.time == nil or birth.precision == nil or birth.precision < 8 thenreturnendlocal death = fetchsnak(id, {'claims', 'P570', 1, 'mainsnak', 'datavalue', 'value'})if type(death) ~= 'table' or death.time == nil or death.precision == nil thendeath = {['time'] = lang:formatDate('c'), ['precision'] = 11} -- current dateelseif death.precision < 8 thenreturnendlocal dates = {}dates[1] = {['min'] = {}, ['max'] = {}, ['precision'] = birth.precision}dates[1].min.year = tonumber(mw.ustring.match(birth.time, "^[+-]?%d+"))dates[1].min.month = tonumber(mw.ustring.match(birth.time, "\-(%d%d)\-"))dates[1].min.day = tonumber(mw.ustring.match(birth.time, "\-(%d%d)T"))dates[1].max = mw.clone(dates[1].min)dates[2] = {['min'] = {}, ['max'] = {}, ['precision'] = death.precision}dates[2].min.year = tonumber(mw.ustring.match(death.time, "^[+-]?%d+"))dates[2].min.month = tonumber(mw.ustring.match(death.time, "\-(%d%d)\-"))dates[2].min.day = tonumber(mw.ustring.match(death.time, "\-(%d%d)T"))dates[2].max = mw.clone(dates[2].min)for i, d in ipairs(dates) doif d.precision == 10 then -- monthd.min.day = 1local timestamp = string.format("%04d", tostring(math.abs(d.max.year))).. string.format("%02d", tostring(d.max.month)).. "01"d.max.day = tonumber(lang:formatDate("j", timestamp .. " + 1 month - 1 day"))elseif d.precision < 10 then -- year or decaded.min.day = 1d.min.month = 1d.max.day = 31d.max.month = 12if d.precision == 8 then -- decaded.max.year = d.max.year + 9endendendlocal function age(d1, d2)local years = d2.year - d1.yearif d2.month < d1.month or (d2.month == d1.month and d2.day < d1.day) thenyears = years - 1endif d2.year > 0 and d1.year < 0 thenyears = years - 1 -- no year 0endreturn yearsendlocal old_min = age(dates[1].max, dates[2].min)local old_max = age(dates[1].min, dates[2].max)local old = old_min == old_max and old_min or old_min .. "/" .. old_maxif args.formatting thenold = mw.ustring.gsub(args.formatting, '$1', old)endreturn oldendreturn p
🔥 Top keywords: OtitikowinApokwaratcicWikipetcia:Kaskina mamo awikKotakahi:Modifications récentesKotakahi:Mes discussionsKitci mokoman askiWikipetciaWikipetcia:WaskapiwinNatisinahikaniwoc:Bilgine-sor-.jpgManitobaOsapwakanKotakahi:RechercheMicta sipiKe ici aimihitonaniwok MediaWiki:Common.cssKanataKisisike tcipakwan askikwIckwatemWitcihici:Créer un articleRikwatoJemmy Echaquan-DubéJoyce EchaquanTipinKa wasikototc pisimwNikickatatowipitcikanaAsatiWikipetcia:Ke nanakatisitcAtikamekw pisimwMitcimKapeciwinPekopiwanPisimwSylvan LakePakekanJapanOtcakamoOspitonAtikamekw arimwewinAitapihikewin:YesnoPiciwKakone pisimwNatisinahikaniwoc:Bilgine-sor.jpgIndaKa notcitatc:KwamikagamiOrilliaJean-Pierre MoarOntarioKe ici aimihitonaniwok notcita iriniw:WasikonSuzanne Pineshish OttawaWapikon pisimwInnusWikipetcia:Chasse photographiqueFinlandeCarmen DubéTipapitcikesinihikan:M/DocumentationTakapikenikanicicWapitowapinanOmikwKaawtosiskak SakihikanKitotakanatikwRichmond HillKitci icihowinWamin ka kinkomakisitcTurkiaOmemewAsati otcepikasoRocky Mountain HouseTipahikinatikwTipapitcikesinihikan:DelinkAlbany RIAskiOtatakon pisimwVerdunWackeciwOnimiskiw ickoteLanaudierePimerikockwatcicTipanictawin:Miro tipatcimowictewAkokatcicOtonWapowanArthur QuoquochiKarkonacicAitapihikewin:StringMasinahikanKinokepitcikanMaskinoceCiwominanCoweminakModèle:Géolocalisation/DocumentationTcimanMediaWiki:Common.cssMediaWiki:Common.jsOtehimin pisimwNikikw PisimwWaskarentamakanMasinactetcitcikanOcakiSipiOtitikowin/Tipatcimoctakewina