avtomatik tuzatish xatosi: enwiki versiyasi bilan almashtirilgani bekor qilindi
-- modules reading Wikidata degrade to nil instead of erroring. Auto-added on import.
-- modules reading Wikidata degrade to nil instead of erroring. Auto-added on import.
if not mw.wikibase then mw.wikibase = setmetatable({}, { __index = function() return function() return nil end end }) end
if not mw.wikibase then mw.wikibase = setmetatable({}, { __index = function() return function() return nil end end }) end
-- vim: set noexpandtab ft=lua ts=4 sw=4:
local i18n = {
require('strict')
    ["errors"] = {
        ["property-param-not-provided"] = "Xossa koʻrsatkichi berilmagan",
        ["entity-not-found"] = "Obyekt topilmadi.",
        ["unknown-claim-type"] = "Noma’lum da’vo turi.",
        ["unknown-snak-type"] = "Noma’lum snek turi.",
        ["unknown-datavalue-type"] = "Nomaʼlum maʼlumotlar qiymati turi.",
        ["unknown-entity-type"] = "Nomaʼlum obyekt turi.",
        ["unknown-property-module"] = "Siz ham property-moduleni, ham property-functionni oʻrnatishingiz kerak.",
        ["unknown-claim-module"] = "Siz ham claim-moduleni, ham claim-functionni oʻrnatishingiz kerak.",
        ["unknown-value-module"] = "Siz ham value-moduleni, ham value-functionni oʻrnatishingiz kerak.",
        ["property-module-not-found"] = "Xossalarni koʻrsatish uchun modul topilmadi",
        ["property-function-not-found"] = "Xossalarni koʻrsatish uchun funksiya topilmadi",
        ["claim-module-not-found"] = "Tasdiqni koʻrsatish uchun modul topilmadi.",
        ["claim-function-not-found"] = "Tasdiqni koʻrsatish uchun funksiya topilmadi.",
        ["value-module-not-found"] = "Qiymatni koʻrsatish uchun modul topilmadi.",
        ["value-function-not-found"] = "Qiymatni koʻrsatish uchun funksiya topilmadi."
    },
    ["somevalue"] = "''nomaʼlum''",
    ["novalue"] = "",
    ["approximate"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="около, приблизительно">прибл. </span>',
    ["presumably"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="предположительно">предп. </span>',
}


local p = {}
-- settings, may differ from project to project
local debug = false
local categoryLinksToEntitiesWithMissingLabel = '';
local categoryLocalValuePresent = '[[Turkum:ZiyoSfera:Vikimaʼlumotlarda qayta aniqlash maqolalari]]';
local outputReferences = true;


-- sources that shall be omitted if any preffered sources exists
local deprecatedSources = {
Q36578 = true, -- Gemeinsame Normdatei
Q63056 = true, -- Find a Grave
Q15222191 = true, -- BNF
};
local preferredSources = {
Q5375741  = true, -- Encyclopædia Britannica Online
Q17378135  = true, -- Great Soviet Encyclopedia (1969—1978)
};


------------------------------------------------------------------------------
-- module local variables and functions


local wiki =
local moduleSources = require('Module:Sources')
{
langcode = mw.language.getContentLanguage().code
}


-- internationalisation
local p = {}
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."
},
["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
-- the following are for function getDateValue() and getQualifierDateValue()
["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
-- #4 (getQualifierDateValue) argument
["default-addon"] = "BC", -- default value of the #4 (getDateValue) or
-- #5 (getQualifierDateValue) argument
["prefix-addon"] = false, -- set to true for languages put "BC" in front of the
-- datetime string; or the addon will be suffixed
["addon-sep"] = " ", -- separator between datetime string and addon (or inverse)
["format"] = -- options of the 3rd argument
{
["mdy"] = "F j, Y",
["my"] = "F Y",
["y"] = "Y",
["dmy"] = "j F Y",
["ymd"] = "Y-m-d",
["ym"] = "Y-m"
}
},
["monolingualtext"] = '<span lang="%language">%text</span>',
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
["ordinal"] =
{
[1] = "st",
[2] = "nd",
[3] = "rd",
["default"] = "th"
}
}


if wiki.langcode ~= "en" then
-- Wikibase mavjud bo‘lmagan vikilarda modul skript xatosi bermasligi uchun
--require("Module:i18n").loadI18n("Module:Wikidata/i18n", i18n)
-- barcha Wikibase chaqiruvlari xavfsiz yordamchi funksiyalar orqali bajariladi.
-- got idea from [[:w:Module:Wd]]
local function hasWikibase()
local module_title; if ... == nil then
return mw.wikibase ~= nil
module_title = mw.getCurrentFrame():getTitle()
else
module_title = ...
end
require('Module:i18n').loadI18n(module_title..'/i18n', i18n)
end
end


-- this function needs to be internationalised along with the above:
local function safeGetEntityObject( entityId )
-- takes cardinal numer as a numeric and returns the ordinal as a string
if not hasWikibase() then
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
return nil
local function makeOrdinal (cardinal)
local ordsuffix = i18n.ordinal.default
if cardinal % 10 == 1 then
ordsuffix = i18n.ordinal[1]
elseif cardinal % 10 == 2 then
ordsuffix = i18n.ordinal[2]
elseif cardinal % 10 == 3 then
ordsuffix = i18n.ordinal[3]
end
end
-- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th'
-- similarly for 12 and 13, etc.
if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then
ordsuffix = i18n.ordinal.default
end
return tostring(cardinal) .. ordsuffix
end


local function printError(code)
local getter = mw.wikibase.getEntityObject or mw.wikibase.getEntity
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
if type( getter ) ~= 'function' then
end
return nil
local function parseDateFormat(f, timestamp, addon, prefix_addon, addon_sep)
local year_suffix
local tstr = ""
local lang_obj = mw.language.new(wiki.langcode)
local f_parts = mw.text.split(f, 'Y', true)
for idx, f_part in pairs(f_parts) do
year_suffix = ''
if string.match(f_part, "x[mijkot]$") then
-- for non-Gregorian year
f_part = f_part .. 'Y'
elseif idx < #f_parts then
-- supress leading zeros in year
year_suffix = lang_obj:formatDate('Y', timestamp)
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
end
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
end
end
if addon ~= "" and prefix_addon then
return addon .. addon_sep .. tstr
elseif addon ~= "" then
return tstr .. addon_sep .. addon
else
return tstr
end
end
local function parseDateValue(timestamp, date_format, date_addon)
local prefix_addon = i18n["datetime"]["prefix-addon"]
local addon_sep = i18n["datetime"]["addon-sep"]
local addon = ""


-- check for negative date
local ok, entity
if string.sub(timestamp, 1, 1) == '-' then
if entityId and entityId ~= '' then
timestamp = '+' .. string.sub(timestamp, 2)
ok, entity = pcall( getter, entityId )
addon = date_addon
end
local _date_format = i18n["datetime"]["format"][date_format]
if _date_format ~= nil then
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
else
else
return printError("unknown-datetime-format")
ok, entity = pcall( getter )
end
end
end
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
-- with the millennium/century/decade handling of formatDate()
local function parseDateFull(timestamp, precision, date_format, date_addon)
local prefix_addon = i18n["datetime"]["prefix-addon"]
local addon_sep = i18n["datetime"]["addon-sep"]
local addon = ""


-- check for negative date
if ok then
if string.sub(timestamp, 1, 1) == '-' then
return entity
timestamp = '+' .. string.sub(timestamp, 2)
addon = date_addon
end
end


-- get the next four characters after the + (should be the year now in all cases)
return nil
-- ok, so this is dirty, but let's get it working first
end
local intyear = tonumber(string.sub(timestamp, 2, 5))
if intyear == 0 and precision <= 9 then
return ""
end


-- precision is 10000 years or more
local function safeWikibaseLabel( entityId )
if precision <= 5 then
if not hasWikibase() or type( mw.wikibase.label ) ~= 'function' then
local factor = 10 ^ ((5 - precision) + 4)
return nil
local y2 = math.ceil(math.abs(intyear) / factor)
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if addon ~= "" then
-- negative date
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end
end


-- precision is decades (8), centuries (7) and millennia (6)
local ok, label = pcall( mw.wikibase.label, entityId )
local era, card
if ok then
if precision == 6 then
return label
card = math.floor((intyear - 1) / 1000) + 1
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
end
if precision == 7 then
card = math.floor((intyear - 1) / 100) + 1
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
end
if precision == 8 then
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
end
if era then
if addon ~= "" then
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
else
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
end
return era
end
end


local _date_format = i18n["datetime"]["format"][date_format]
return nil
if _date_format ~= nil then
-- check for precision is year and override supplied date_format
if precision == 9 then
_date_format = i18n["datetime"][9]
end
return parseDateFormat(_date_format, timestamp, addon, prefix_addon, addon_sep)
else
return printError("unknown-datetime-format")
end
end
end


-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
local function safeWikibaseSitelink( entityId )
-- use these as the second parameter and this function instead of the built-in "pairs" function
if not hasWikibase() or type( mw.wikibase.sitelink ) ~= 'function' then
-- to iterate over all qualifiers and snaks in the intended order.
return nil
local function orderedpairs(array, order)
end
if not order then return pairs(array) end


-- return iterator function
local ok, sitelink = pcall( mw.wikibase.sitelink, entityId )
local i = 0
if ok then
return function()
return sitelink
i = i + 1
if order[i] then
return order[i], array[order[i]]
end
end
end
end


-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
return nil
local function normalizeDate(date)
date = mw.text.trim(date, "+")
-- extract year
local yearstr = mw.ustring.match(date, "^\-?%d+")
local year = tonumber(yearstr)
-- remove leading zeros of year
return year .. mw.ustring.sub(date, #yearstr + 1), year
end
end


local function formatDate(date, precision, timezone)
local function safePropertyParserFunction( frame, propertyId )
precision = precision or 11
if not frame or not propertyId or propertyId == '' then
local date, year = normalizeDate(date)
return ''
if year == 0 and precision <= 9 then return "" end
end


-- precision is 10000 years or more
local ok, value = pcall( function()
if precision <= 5 then
return frame:callParserFunction( '#property', propertyId )
local factor = 10 ^ ((5 - precision) + 4)
end )
local y2 = math.ceil(math.abs(year) / factor)
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
if year < 0 then
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
else
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
end
return relative
end


-- precision is decades, centuries and millennia
if ok and value then
local era
return value
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
if precision == 7 then era = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(year) - 1) / 100) + 1)) end
if precision == 8 then era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(year) / 10) * 10)) end
if era then
if year < 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
elseif year > 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era) end
return era
end
end


-- precision is year
return ''
if precision == 9 then
end
return year
end


-- precision is less than years
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement, formatStatementDefault, formatProperty, getSourcingCircumstances, loadCacheSafe, throwError, toBoolean;
if precision > 9 then
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
timezone = tonumber(timezone)
if timezone and timezone ~= 0 then
timezone = -timezone
timezone = string.format("%.2d%.2d", timezone / 60, timezone % 60)
if timezone[1] ~= '-' then timezone = "+" .. timezone end
date = mw.text.trim(date, "Z") .. " " .. timezone
end
]]--


local formatstr = i18n.datetime[precision]
local function copyTo( obj, target )
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
for k, v in pairs( obj ) do
elseif year < 0 then
target[k] = v
-- Mediawiki formatDate doesn't support negative years
date = mw.ustring.sub(date, 2)
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.bc, "$1", i18n.datetime[9]))
elseif year > 0 and i18n.datetime.ad ~= "$1" then
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.ad, "$1", i18n.datetime[9]))
end
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
end
end
return target;
end
end


local function printDatavalueEntity(data, parameter)
local function loadCacheSafe( entityId )
-- data fields: entity-type [string], numeric-id [int, Wikidata id]
local status, result = pcall( function() return mw.loadData( 'Module:WikidataCache/' .. entityId ) end );
local id
if ( status == true ) then
 
return result;
if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
elseif data["entity-type"] == "property" then id = "P" .. data["numeric-id"]
else return printError("unknown-entity-type")
end
end
return nil;
end


if parameter then
local function parseISO8601(str)
if parameter == "link" then
if 'table' == type(str) then
local linkTarget = mw.wikibase.getSitelink(id)
if str.args and str.args[1] then
local linkName = mw.wikibase.getLabel(id)
str = '' .. str.args[1]
if linkTarget then
-- if there is a local Wikipedia article link to it using the label or the article title
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
else
-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
end
else
else
return data[parameter]
return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )
end
end
else
return mw.wikibase.getLabel(id) or id
end
end
local Y, M, D = (function(str)
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
local Y, M, D = mw.ustring.match( str, pattern )
return tonumber(Y), tonumber(M), tonumber(D)
end) (str);
local h, m, s = (function(str)
local pattern = "T(%d+):(%d+):(%d+)%Z";
local H, M, S = mw.ustring.match( str, pattern);
return tonumber(H), tonumber(M), tonumber(S);
end) (str);
local oh,om = ( function(str)
if str:sub(-1)=="Z" then return 0,0 end; -- ends with Z, Zulu time
-- matches ±hh:mm, ±hhmm or ±hh; else returns nils
local pattern = "([-+])(%d%d):?(%d?%d?)$";
local sign, oh, om = mw.ustring.match( str, pattern);
sign, oh, om = sign or "+", oh or "00", om or "00";
return tonumber(sign .. oh), tonumber(sign .. om);
end )(str)
return tonumber(os.time({year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s})) * 1000;
end
end


local function printDatavalueTime(data, parameter)
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
--  precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
--  calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
if parameter then
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
elseif parameter == "time" then data.time = normalizeDate(data.time) end
return data[parameter]
else
return formatDate(data.time, data.precision, data.timezone)
end
end


local function printDatavalueMonolingualText(data, parameter)
local function toBoolean( valueToParse, defaultValue )
-- data fields: language [string], text [string]
    if ( valueToParse ) then
if parameter then
        if valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
return data[parameter]
            return false
else
        end
local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
        return true
return result
    end
end
    return defaultValue;
end
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
local function getEntityFromId( id )
-- if the property is given by an id (P..) access the claim list by this id
    if id and id ~= '' then
return entity.claims[property]
    local cached = loadCacheSafe( id );
else
    if ( cached ) then
property = mw.wikibase.resolvePropertyId(property)
    return cached;
if not property then return end
    end
        return safeGetEntityObject( id )
    end


return entity.claims[property]
    local entity = safeGetEntityObject();
    if ( entity and entity.id ) then
    local cached = loadCacheSafe( entity.id );
    if ( cached ) then
    return cached;
    end
end
end
    return entity;
end
end


local function getSnakValue(snak, parameter)
 
if snak.snaktype == "value" then
local function throwError( key )
-- call the respective snak parser
    error( i18n.errors[key] );
if snak.datavalue.type == "string" then return snak.datavalue.value
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
end


local function getQualifierSnak(claim, qualifierId)
 
-- a "snak" is Wikidata terminology for a typed key/value pair
local function getEntityIdFromValue( value )
-- a claim consists of a main snak holding the main information of this claim,
    local prefix = ''
-- as well as a list of attribute snaks and a list of references snaks
    if value['entity-type'] == 'item' then
if qualifierId then
        prefix = 'Q'
-- search the attribute snak with the given qualifier as key
    elseif value['entity-type'] == 'property' then
if claim.qualifiers then
        prefix = 'P'
local qualifier = claim.qualifiers[qualifierId]
    else
if qualifier then return qualifier[1] end
        throwError( 'unknown-entity-type' )
end
    end
return nil, printError("qualifier-not-found")
    return prefix .. value['numeric-id']
else
-- otherwise return the main snak
return claim.mainsnak
end
end
end


local function getValueOfClaim(claim, qualifierId, parameter)
 
local error
local function getUserFunction( options, prefix, defaultFunction )
local snak
   
snak, error = getQualifierSnak(claim, qualifierId)
    if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then
if snak then
   
return getSnakValue(snak, parameter)
        if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then
else
            throwError( 'unknown-' .. prefix .. '-module' );
return nil, error
        end
end
       
        local formatter = require ('Module:' .. options[ prefix .. '-module' ]);
        if formatter == nil then
            throwError( prefix .. '-module-not-found' )
        end
        local fun = formatter[ options[ prefix .. '-function' ] ]
        if fun == nil then
            throwError( prefix .. '-function-not-found' )
        end
        return fun;
    end
 
  return defaultFunction;
end
end


local function getReferences(frame, claim)
 
local result = ""
local function selectClaims( context, options, propertySelector )
-- traverse through all references
if ( not context ) then error( 'context not specified'); end;
for ref in pairs(claim.references or {}) do
if ( not options ) then error( 'options not specified'); end;
local refparts
if ( not options.entity ) then error( 'options.entity is missing'); end;
-- traverse through all parts of the current reference
if ( not propertySelector ) then error( 'propertySelector not specified'); end;
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
 
if refparts then refparts = refparts .. ", " else refparts = "" end
local WDS = require('Module:WikidataSelectors')
-- output the label of the property of the reference part, e.g. "imported from" for P143
result = WDS.filter(options.entity.claims, propertySelector)
refparts = refparts .. tostring(mw.wikibase.getLabel(snakkey)) .. ": "
 
-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
    if ( not result or #result == 0 ) then
for snakidx = 1, #snakval do
    return nil;
if snakidx > 1 then refparts = refparts .. ", " end
    end
refparts = refparts .. getSnakValue(snakval[snakidx])
   
end
    if options.limit and options.limit ~= '' and options.limit ~= '-'  then
local limit = tonumber( options.limit, 10 );
while #result > limit do
table.remove( result );
end
end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
end
end
return result
 
    return result;
end
end


local function parseInput(frame)
 
local qid = frame.args.qid
local function formatProperty( options )
if qid and (#qid == 0) then qid = nil end
    -- Получение сущности по идентификатору
local propertyID = mw.text.trim(frame.args[1] or "")
    local entity = getEntityFromId( options.entityId )
local input_parm = mw.text.trim(frame.args[2] or "")
    if not entity then
if input_parm ~= "FETCH_WIKIDATA" then
        return -- throwError( 'entity-not-found' )
return false, input_parm, nil, nil
    end
-- проверка на присутсвие у сущности заявлений (claim)
-- подробнее о заявлениях см. d:Викиданные:Глоссарий
    if (entity.claims == nil) then
        return '' --TODO error?
    end
 
-- improve options
options.frame = g_frame;
options.entity = entity;
options.extends = function( self, newOptions )
return copyTo( newOptions, copyTo( self, {} ) )
end
end
local entity = mw.wikibase.getEntity(qid)
 
local claims
if ( options.i18n ) then
if entity and entity.claims then
options.i18n = copyTo( options.i18n, copyTo( i18n, {} ) );
claims = entity.claims[propertyID]
if not claims then
return false, "", nil, nil
end
else
else
return false, "", nil, nil
options.i18n = i18n;
end
end
return true, entity, claims, propertyID
 
end
-- create context
local function isType(claims, type)
local context = { formatSnak = formatSnak, formatPropertyDefault = formatPropertyDefault, formatStatementDefault = formatStatementDefault }
return claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == type
context.formatProperty = function( options )
end
local func = getUserFunction( options, 'property', context.formatPropertyDefault );
local function getValue(entity, claims, propertyID, delim, labelHook)  
return func( context, options )
if labelHook == nil then
end;
labelHook = function (qnumber)
context.formatStatement = function( options, statement ) return formatStatement( context, options, statement ) end;
context.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end;
context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;
context.parseTimeFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) then
local timeISO6801 = tostring( snak.datavalue.value.time )
return parseISO8601( timeISO6801 );
end
return nil;
return nil;
end
end
end
context.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end;
if isType(claims, "wikibase-entityid") then
context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;
local out = {}
 
for k, v in pairs(claims) do
return context.formatProperty( options );
local qnumber = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
local sitelink = mw.wikibase.getSitelink(qnumber)
local label = labelHook(qnumber) or mw.wikibase.getLabel(qnumber) or qnumber
if sitelink then
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
else
out[#out + 1] = "[[:d:" .. qnumber .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return table.concat(out, delim)
else
-- just return best values
return entity:formatPropertyValues(propertyID).value
end
end
end


------------------------------------------------------------------------------
function formatPropertyDefault( context, options )
-- module global functions
if ( not context ) then error( 'context not specified' ); end;
if ( not options ) then error( 'options not specified' ); end;
if ( not options.entity ) then error( 'options.entity missing' ); end;


if debug then
    local claims = context.selectClaims( options, options.property );
function p.inspectI18n(frame)
    if (claims == nil) then
local val = i18n
        return '' --TODO error?
for _, key in pairs(frame.args) do
    end
key = mw.text.trim(key)
 
val = val[key]
 
end
    local formattedClaims = {}
return val
 
end
    for i, claim in ipairs(claims) do
end
        local formattedStatement = context.formatStatement( options, claim )
       
        if (formattedStatement) then
            formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
            table.insert( formattedClaims, formattedStatement )
        end
    end


function p.descriptionIn(frame)
local langcode = frame.args[1]
    return mw.text.listToText( formattedClaims, options.separator, options.conjunction )
local id = frame.args[2]
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
return mw.wikibase.getEntity(id):getDescription(langcode or wiki.langcode)
end
end


function p.labelIn(frame)
local langcode = frame.args[1]
local id = frame.args[2]
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
return mw.wikibase.getEntity(id):getLabel(langcode or wiki.langcode)
end


-- This is used to get a value, or a comma separated list of them if multiple values exist
function formatStatement( context, options, statement )
p.getValue = function(frame)
if ( not statement ) then
local delimdefault = ", " -- **internationalise later**
error( 'statement is not specified or nil' );
local delim = frame.args.delimiter or ""
delim = string.gsub(delim, '"', '')
if #delim == 0 then
delim = delimdefault
end
end
local go, errorOrentity, claims, propertyID = parseInput(frame)
    if not statement.type or statement.type ~= 'statement' then
if not go then
        throwError( 'unknown-claim-type' )
return errorOrentity
    end
end
 
return getValue(errorOrentity, claims, propertyID, delim)
    local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault );
    return functionToCall( context, options, statement );
end
end


-- Same as above, but uses the short name property for label if available.
function getSourcingCircumstances( statement )
p.getValueShortName = function(frame)
if (not statement) then error('statement is not specified') end;
local go, errorOrentity, claims, propertyID = parseInput(frame)
 
if not go then
local circumstances = {};
return errorOrentity
if ( statement.qualifiers
end
and statement.qualifiers.P1480 ) then
local entity = errorOrentity
for i, qualifier in pairs( statement.qualifiers.P1480 ) do
-- if wiki-linked value output as link if possible
if ( qualifier
local function labelHook (qnumber)
and qualifier.datavalue
local label
and qualifier.datavalue.type == 'wikibase-entityid'
local claimEntity = mw.wikibase.getEntity(qnumber)
and qualifier.datavalue.value
if claimEntity ~= nil then
and qualifier.datavalue.value["entity-type"] == 'item' ) then
if claimEntity.claims.P1813 then
local circumstance = 'Q' .. qualifier.datavalue.value["numeric-id"];
for k2, v2 in pairs(claimEntity.claims.P1813) do
if ( 'Q18086598' == circumstance ) then
if v2.mainsnak.datavalue.value.language == "en" then
circumstances.approximate = true;
label = v2.mainsnak.datavalue.value.text
end
end
end
end
if ( 'Q18122778' == circumstance ) then
end
circumstances.presumably = true;
if label == nil or label == "" then return nil end
return label
end
return getValue(errorOrentity, claims, propertyID, ", ", labelHook);
end
 
-- This is used to get a value, or a comma separated list of them if multiple values exist
-- from an arbitrary entry by using its QID.
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
-- Please use sparingly - this is an *expensive call*.
p.getValueFromID = function(frame)
local itemID = mw.text.trim(frame.args[1] or "")
local propertyID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity(itemID)
local claims
if entity and entity.claims then
claims = entity.claims[propertyID]
end
if claims then
return getValue(entity, claims, propertyID, ", ")
else
return ""
end
else
return input_parm
end
end
local function getQualifier(frame, outputHook)
local propertyID = mw.text.trim(frame.args[1] or "")
local qualifierID = mw.text.trim(frame.args[2] or "")
local input_parm = mw.text.trim(frame.args[3] or "")
if input_parm == "FETCH_WIKIDATA" then
local entity = mw.wikibase.getEntity()
if entity.claims[propertyID] ~= nil then
local out = {}
for k, v in pairs(entity.claims[propertyID]) do
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
if v2.snaktype == 'value' then
out[#out + 1] = outputHook(v2);
end
end
end
end
end
return table.concat(out, ", "), true
else
return "", false
end
end
else
return input_parm, false
end
end
end
return circumstances;
p.getQualifierValue = function(frame)
local function outputValue(value)
local qnumber = "Q" .. value.datavalue.value["numeric-id"]
if (mw.wikibase.getSitelink(qnumber)) then
return "[[" .. mw.wikibase.getSitelink(qnumber) .. "]]"
else
return "[[:d:" .. qnumber .. "|" ..qnumber .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
end
end
return (getQualifier(frame, outputValue))
end
end


-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
p.getRawValue = function(frame)
local go, errorOrentity, claims, propertyID = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
-- if number type: remove thousand separators, bounds and units
if isType(claims, "quantity") then
result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
result = mw.ustring.gsub(result, "(%d)±.*", "%1")
end
return result
end


-- This is used to get the unit name for the numeric value returned by getRawValue
function formatStatementDefault( context, options, statement )
p.getUnits = function(frame)
if (not context) then error('context is not specified') end;
local go, errorOrentity, claims, propertyID = parseInput(frame)
if (not options) then error('options is not specified') end;
if not go then
if (not statement) then error('statement is not specified') end;
return errorOrentity
end
local entity = errorOrentity
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
if isType(claims, "quantity") then
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
end
return result
end


-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
local circumstances = context.getSourcingCircumstances( statement );
p.getUnitID = function(frame)
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local result
if isType(claims, "quantity") then
-- get the url for the unit entry on Wikidata:
result = claims[1].mainsnak.datavalue.value.unit
-- and just reurn the last bit from "Q" to the end (which is the QID):
result = mw.ustring.sub(result, mw.ustring.find(result, "Q"), -1)
end
return result
end


p.getRawQualifierValue = function(frame)
if ( options.references ) then
local function outputHook(value)
    return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
if value.datavalue.value["numeric-id"] then
    else
return mw.wikibase.getLabel("Q" .. value.datavalue.value["numeric-id"])
    return context.formatSnak( options, statement.mainsnak, circumstances );
else
    end
return value.datavalue.value
end
end
local ret, gotData = getQualifier(frame, outputHook)
if gotData then
ret = string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
end
return ret
end
end


-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
-- Dates and times are stored in ISO 8601 format (sort of).
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
-- So I'll just supply "Z" in the call to formatDate below:
p.getDateValue = function(frame)
local date_format = mw.text.trim(frame.args[3] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[4] or i18n["datetime"]["default-addon"])
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
local out = {}
for k, v in pairs(claims) do
if v.mainsnak.datavalue.type == 'time' then
local timestamp = v.mainsnak.datavalue.value.time
local dateprecision = v.mainsnak.datavalue.value.precision
-- A year can be stored like this: "+1872-00-00T00:00:00Z",
-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
-- and that's the last day of 1871, so the year is wrong.
-- So fix the month 0, day 0 timestamp to become 1 January instead:
timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
end
end
return table.concat(out, ", ")
end
p.getQualifierDateValue = function(frame)
local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
local function outputHook(value)
local timestamp = value.datavalue.value.time
return parseDateValue(timestamp, date_format, date_addon)
end
return (getQualifier(frame, outputHook))
end


-- This is used to fetch all of the images with a particular property, e.g. image (P18), Gene Atlas Image (P692), etc.
function formatSnak( context, options, snak, circumstances )
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
circumstances = circumstances or {};
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
local hash = '';
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
local mainSnakClass = '';
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
if ( snak.hash ) then
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
hash = ' data-wikidata-hash="' .. snak.hash .. '"';
p.getImages = function(frame)
local sep = mw.text.trim(frame.args[3] or " ")
local imgsize = mw.text.trim(frame.args[4] or "frameless")
local go, errorOrentity, claims = parseInput(frame)
if not go then
return errorOrentity
end
local entity = errorOrentity
if (claims[1] and claims[1].mainsnak.datatype == "commonsMedia") then
local out = {}
for k, v in pairs(claims) do
local filename = v.mainsnak.datavalue.value
out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
end
return table.concat(out, sep)
else
else
return ""
mainSnakClass = ' wikidata-main-snak';
end
end
end


-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
-- which are then linked to https://ifaa.unifr.ch/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
local after = '</span>'
-- 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
    if snak.snaktype == 'somevalue' then
p.getTAValue = function(frame)
        return before .. options.i18n['somevalue'] .. after;
local ent = mw.wikibase.getEntity()
    elseif snak.snaktype == 'novalue' then
local props = ent:formatPropertyValues('P1323')
        return before .. options.i18n['novalue'] .. after;
local out = {}
    elseif snak.snaktype == 'value' then
local t = {}
if ( circumstances.presumably ) then
for k, v in pairs(props) do
before = before .. options.i18n.presumably;
if k == 'value' then
end
t = mw.text.split( v, ", ")
if ( circumstances.approximate ) then
for k2, v2 in pairs(t) do
before = before .. options.i18n.approximate;
out[#out + 1] = "[https://ifaa.unifr.ch/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> ")
        return before .. formatDatavalue( context, options, snak.datavalue ) .. after;
if #ret == 0 then
    else
ret = "Invalid TA"
        throwError( 'unknown-snak-type' );
end
    end
return ret
end
end


--[[
This is used to return an image legend from Wikidata
image is property P18
image legend is property P2096


Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
function formatGlobeCoordinate( value, options )
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
-- проверка на требование в параметрах вызова на возврат сырого значения
If QID is omitted or blank, the current article is used (not an expensive call)
    if options['subvalue'] == 'latitude' then -- широты
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
        return value['latitude']
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447
    elseif options['subvalue'] == 'longitude' then -- долготы
        return value['longitude']
    else
    -- в противном случае формируются параметры для вызова шаблона {{coord}}
    -- нужно дописать в документации шаблона, что он отсюда вызывается, и что
    -- любое изменние его парамеров  должно быть согласовано с кодом тут
        local eps = 0.0000001 -- < 1/360000
        local globe = '' -- TODO
        local lat = {}
        lat['abs'] = math.abs(value['latitude'])
        lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
        lat['d'] = math.floor(lat['abs'] + eps)
        lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
        lat['s'] = math.max(0, ((lat['abs'] - lat['d']) * 60 - lat['m']) * 60)
        local lon = {}
        lon['abs'] = math.abs(value['longitude'])
        lon['ew'] = value['longitude'] >= 0 and 'E' or 'W'
        lon['d'] = math.floor(lon['abs'] + eps)
        lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
        lon['s'] = math.max(0, ((lon['abs'] - lon['d']) * 60 - lon['m']) * 60)
        local coord = '{{coord'
        if (value['precision'] == nil) or (value['precision'] < 1/60) then -- по умолчанию с точностью до секунды
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['s'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['s'] .. '|' .. lon['ew']
        elseif value['precision'] < 1 then
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['ew']
        else
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['ew']
        end
        coord = coord .. '|globe:' .. globe
        if options['display'] then
            coord = coord .. '|display=' .. options.display
        else
            coord = coord .. '|display=title'
        end
        coord = coord .. '}}'


Ranks are: 'preferred' > 'normal'
        return g_frame:preprocess(coord)
This returns the label from the first image with 'preferred' rank
    end
Or the label from the first image with 'normal' rank if preferred returns nothing
end
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
]]


p.getImageLegend = function(frame)
local function getDefaultValueFunction( datavalue )
-- look for named parameter id; if it's blank make it nil
   
local id = frame.args.id
    if datavalue.type == 'wikibase-entityid' then
if id and (#id == 0) then
   
id = nil
        return function( context, options, value ) return formatEntityId( getEntityIdFromValue( value ), options ) end;
end
    elseif datavalue.type == 'string' then
   
        return function( context, options, value ) return value end;
    elseif datavalue.type == 'monolingualtext' then
   
        return function( context, options, value )
        if ( options.monolingualLangTemplate == 'lang' ) then
        return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
        elseif ( options.monolingualLangTemplate == 'ref' ) then
        return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
        else
        return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
        end
        end;
    elseif datavalue.type == 'globecoordinate' then
    -- geografik koordinatalar
        return function( context, options, value ) return formatGlobeCoordinate( value, options )  end;
    elseif datavalue.type == 'quantity' then
        return function( context, options, value )
        local amount = string.gsub(value['amount'], '^%+', '')
        local lang = mw.language.new( 'ru' )
        return lang:formatNum( tonumber( amount ) )
        end;
    elseif datavalue.type == 'time' then
        return function( context, options, value )
local moduleDate = require('Module:Wikidata/date')
    return moduleDate.formatDate( context, options, value );
        end;
    else
   
        throwError( 'unknown-datavalue-type' )
    end
end


-- look for named parameter lang
-- it should contain a two-character ISO-639 language code
function formatDatavalue( context, options, datavalue )
-- if it's blank fetch the language of the local wiki
if ( not context ) then error( 'context not specified' ); end;
local lang = frame.args.lang
if ( not options ) then error( 'options not specified' ); end;
if (not lang) or (#lang < 2) then
if ( not datavalue ) then error( 'datavalue not specified' ); end;
lang = mw.language.getContentLanguage().code
if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;
end


-- first unnamed parameter is the local parameter, if supplied
   
local input_parm = mw.text.trim(frame.args[1] or "")
    context.formatValueDefault = getDefaultValueFunction( datavalue );
if input_parm == "FETCH_WIKIDATA" then
    local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
local ent = mw.wikibase.getEntity(id)
    return functionToCall( context, options, datavalue.value );
local imgs
if ent and ent.claims then
imgs = ent.claims.P18
end
local imglbl
if imgs then
-- look for an image with 'preferred' rank
for k1, v1 in pairs(imgs) do
if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
-- if we don't find one, look for an image with 'normal' rank
if (not imglbl) then
for k1, v1 in pairs(imgs) do
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
local imglbls = v1.qualifiers.P2096
for k2, v2 in pairs(imglbls) do
if v2.datavalue.value.language == lang then
imglbl = v2.datavalue.value.text
break
end
end
end
end
end
end
return imglbl
else
return input_parm
end
end
end


-- This is used to get the QIDs of all of the values of a property, as a comma separated list if multiple values exist
--  
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |FETCH_WIKIDATA}}
local simpleReplaces = {
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |<InputParameter> |qid=<QID>}}
Q30 = '[[AQSh]]',
Q148 = '[[Xitoy Xalq Respublikasi|Xitoy]]',
Q183 = '[[Germaniya]]',
Q258 = '[[JAR]]',
Q423 = '[[Koreya Xalq Demokratik Respublikasi|KXDR]]',
Q2184 = '[[Rossiya Sovet Federativ Sotsialistik Respublikasi|Rossiya SFSR]]',
Q2895 = '[[Belorussiya Sovet Sotsialistik Respublikasi|Belorus SSR]]',
Q15180 = '[[Sovet Sotsialistik Respublikalari Ittifoqi|SSSR]]',
Q16957 = '[[Germaniya Demokratik Respublikasi|GDR]]',
Q130229 = '[[Gruziya Sovet Sotsialistik Respublikasi|Gruziya SSR]]',
Q130280 = '[[Estoniya Sovet Sotsialistik Respublikasi|Estoniya SSR]]',
Q131337 = '[[Ozarbayjon Sovet Sotsialistik Respublikasi|Ozarbayjon SSR]]',
Q132856 = '[[Armaniston Sovet Sotsialistik Respublikasi|Armaniston SSR]]',
Q133356 = '[[Ukraina Sovet Sotsialistik Respublikasi|Ukraina SSR]]',
Q168811 = '[[Qozogʻiston Sovet Sotsialistik Respublikasi|Qozogʻiston SSR]]',
Q170895 = '[[Moldova Sovet Sotsialistik Respublikasi|Moldova SSR]]',
Q173761 = '[[Litva Sovet Sotsialistik Respublikasi|Litva SSR]]',
Q192180 = '[[Latviya Sovet Sotsialistik Respublikasi|Latviya SSR]]',
Q199707 = '[[Turkmaniston Sovet Sotsialistik Respublikasi|Turkmaniston SSR]]',
Q199711 = '[[Tojikiston Sovet Sotsialistik Respublikasi|Tojikiston SSR]]',
Q484578 = '[[Oʻzbekiston Sovet Sotsialistik Respublikasi|Oʻzbekiston SSR]]',
}


p.getPropertyIDs = function(frame)
 
local go, errorOrentity, propclaims = parseInput(frame)
function formatEntityId( entityId, options )
if not go then
-- получение локализованного названия
return errorOrentity
    local label = nil;
end
    if ( options.text and options.text ~= '' ) then
local entity = errorOrentity
        label = options.text
-- if wiki-linked value collect the QID in a table
    else
if (propclaims[1] and propclaims[1].mainsnak.snaktype == "value" and propclaims[1].mainsnak.datavalue.type == "wikibase-entityid") then
    if ( simpleReplaces[entityId] ) then
local out = {}
return simpleReplaces[entityId];
for k, v in pairs(propclaims) do
out[#out + 1] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
end
end
return table.concat(out, ", ")
label = safeWikibaseLabel( entityId );
else
    end
-- not a wikibase-entityid, so return empty
 
return ""
-- получение ссылки по идентификатору
end
    local link = safeWikibaseSitelink( entityId )
end
    if link then
        if label then
            return '[[' .. link .. '|' .. label .. ']]'
        else
            return '[[' .. link .. ']]'
        end
    end


-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
    if label then
function p.pageId(frame)
        return label
return mw.wikibase.getEntityIdForCurrentPage()
    end
    -- сообщение об отсутвии локализованного названия
    -- not good, but better than nothing
    return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;
end
end


function p.claim(frame)
--[[  
local property = frame.args[1] or ""
  Функция для оформления утверждений (statement)
local id = frame.args["id"]
  Подробнее о утверждениях см. d:Wikidata:Glossary/ru
local qualifierId = frame.args["qualifier"]
local parameter = frame.args["parameter"]
local list = frame.args["list"]
local references = frame.args["references"]
local showerrors = frame.args["showerrors"]
local default = frame.args["default"]
if default then showerrors = nil end


-- get wikidata entity
  Принимает: таблицу параметров
local entity = mw.wikibase.getEntity(id)
  Возвращает: строку оформленного текста, предназначенного для отображения в статье
if not entity then
]]
if showerrors then return printError("entity-not-found") else return default end
-- устаревшее имя, не использовать
end
function p.formatStatements( frame )
-- fetch the first claim of satisfying the given property
return p.formatProperty( frame );
local claims = findClaims(entity, property)
end
if not claims or not claims[1] then
if showerrors then return printError("property-not-found") else return default end
end


-- get initial sort indices
function p.formatProperty( frame )
local sortindices = {}
    local args = frame.args
for idx in pairs(claims) do
    local plain = toBoolean( frame.args.plain, false );
sortindices[#sortindices + 1] = idx
    frame.args.nocat = toBoolean( frame.args.nocat, false );
end
    frame.args.references = toBoolean( frame.args.references, true );
-- 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 not frame.args.property then
if list then
        throwError( 'property-param-not-provided' )
local value
    end
-- iterate over all elements and return their value (if existing)
   
result = {}
   
for idx in pairs(claims) do
p_frame = frame
local claim = claims[sortindices[idx]]
while p_frame do
value, error = getValueOfClaim(claim, qualifierId, parameter)
if p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
if not value and showerrors then value = error end
copyTo( p_frame.args, args, true );
if value and references then value = value .. getReferences(frame, claim) end
end
result[#result + 1] = value
if p_frame.args and p_frame.args.from and p_frame.args.from ~= '' then
args.entityId = p_frame.args.from;
end
end
result = table.concat(result, list)
p_frame = p_frame:getParent();
else
-- return first element
local claim = claims[sortindices[1]]
result, error = getValueOfClaim(claim, qualifierId, parameter)
if result and references then result = result .. getReferences(frame, claim) end
end
end


if result then return result else
    local propertyValue = safePropertyParserFunction( frame, frame.args.property )
if showerrors then return error else return default end
 
end
    if frame.args.value and frame.args.value ~= '' then
end
        if plain or frame.args.nocat or propertyValue == '' then
                return frame.args.value
        else
                return args.value .. categoryLocalValuePresent;
        end
    end


-- look into entity object
    if ( plain ) then
function p.ViewSomething(frame)
    return propertyValue;
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
    end
local id = f.args.id
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
g_frame = frame
while true do
local index = f.args[i]
    return formatProperty( frame.args )
if not index then
end
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
function formatRefs( context, options, statement )
end
if ( not context ) then error( 'context not specified' ); end;
end
if ( not options ) then error( 'options not specified' ); end;
if ( not options.entity ) then error( 'options.entity missing' ); end;
if ( not statement ) then error( 'statement not specified' ); end;


-- getting sitelink of a given wiki
if ( not outputReferences ) then
-- get sitelink of current item if qid not supplied
return '';
function p.getSiteLink(frame)
local qid = frame.args.qid
if qid == "" then qid = nil end
local f = mw.text.trim( frame.args[1] or "")
local entity = mw.wikibase.getEntity(qid)
if not entity then
return
end
end
local link = entity:getSitelink( f )
if not link then
return
end
return link
end


function p.Dump(frame)
local result = '';
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
if ( statement.references ) then
local data = mw.wikibase.getEntity(f.args.id)
if not data then
return i18n.warnDump
end


local i = 1
local allReferences = statement.references;
while true do
local hasPreferred = false;
local index = f.args[i]
for _, reference in pairs( statement.references ) do
if not index then
if ( reference.snaks
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
if ( preferredSources[entityId] ) then
hasPreferred = true;
end
end
end
end


data = data[index] or data[tonumber(index)]
for _, reference in pairs( statement.references ) do
if not data then
local display = true;
return i18n.warnDump
if ( hasPreferred ) then
if ( reference.snaks
and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
if ( deprecatedSources[entityId] ) then
display = false;
end
end
end
if ( display ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
end
end
end
i = i + 1
end
end
return result
end
end


return p
return p

$2, $3 dagi (joriy) koʻrinishi

-- [zs-wikibase-guard] Ziyosfera has no Wikibase client; stub mw.wikibase so
-- modules reading Wikidata degrade to nil instead of erroring. Auto-added on import.
if not mw.wikibase then mw.wikibase = setmetatable({}, { __index = function() return function() return nil end end }) end
local i18n = {
    ["errors"] = {
        ["property-param-not-provided"] = "Xossa koʻrsatkichi berilmagan",
        ["entity-not-found"] = "Obyekt topilmadi.",
        ["unknown-claim-type"] = "Noma’lum da’vo turi.",
        ["unknown-snak-type"] = "Noma’lum snek turi.",
        ["unknown-datavalue-type"] = "Nomaʼlum maʼlumotlar qiymati turi.",
        ["unknown-entity-type"] = "Nomaʼlum obyekt turi.",
        ["unknown-property-module"] = "Siz ham property-moduleni, ham property-functionni oʻrnatishingiz kerak.",
        ["unknown-claim-module"] = "Siz ham claim-moduleni, ham claim-functionni oʻrnatishingiz kerak.",
        ["unknown-value-module"] = "Siz ham value-moduleni, ham value-functionni oʻrnatishingiz kerak.",
        ["property-module-not-found"] = "Xossalarni koʻrsatish uchun modul topilmadi",
        ["property-function-not-found"] = "Xossalarni koʻrsatish uchun funksiya topilmadi",
        ["claim-module-not-found"] = "Tasdiqni koʻrsatish uchun modul topilmadi.",
        ["claim-function-not-found"] = "Tasdiqni koʻrsatish uchun funksiya topilmadi.",
        ["value-module-not-found"] = "Qiymatni koʻrsatish uchun modul topilmadi.",
        ["value-function-not-found"] = "Qiymatni koʻrsatish uchun funksiya topilmadi."
    },
    ["somevalue"] = "''nomaʼlum''",
    ["novalue"] = "",
    ["approximate"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="около, приблизительно">прибл. </span>',
    ["presumably"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="предположительно">предп. </span>',
}

-- settings, may differ from project to project
local categoryLinksToEntitiesWithMissingLabel = '';
local categoryLocalValuePresent = '[[Turkum:ZiyoSfera:Vikimaʼlumotlarda qayta aniqlash maqolalari]]';
local outputReferences = true;

-- sources that shall be omitted if any preffered sources exists
local deprecatedSources = {
	Q36578 = true, -- Gemeinsame Normdatei
	Q63056 = true, -- Find a Grave
	Q15222191 = true, -- BNF
};
local preferredSources = {
	Q5375741  = true, -- Encyclopædia Britannica Online
	Q17378135  = true, -- Great Soviet Encyclopedia (1969—1978)
};


local moduleSources = require('Module:Sources')

local p = {}

-- Wikibase mavjud bo‘lmagan vikilarda modul skript xatosi bermasligi uchun
-- barcha Wikibase chaqiruvlari xavfsiz yordamchi funksiyalar orqali bajariladi.
local function hasWikibase()
	return mw.wikibase ~= nil
end

local function safeGetEntityObject( entityId )
	if not hasWikibase() then
		return nil
	end

	local getter = mw.wikibase.getEntityObject or mw.wikibase.getEntity
	if type( getter ) ~= 'function' then
		return nil
	end

	local ok, entity
	if entityId and entityId ~= '' then
		ok, entity = pcall( getter, entityId )
	else
		ok, entity = pcall( getter )
	end

	if ok then
		return entity
	end

	return nil
end

local function safeWikibaseLabel( entityId )
	if not hasWikibase() or type( mw.wikibase.label ) ~= 'function' then
		return nil
	end

	local ok, label = pcall( mw.wikibase.label, entityId )
	if ok then
		return label
	end

	return nil
end

local function safeWikibaseSitelink( entityId )
	if not hasWikibase() or type( mw.wikibase.sitelink ) ~= 'function' then
		return nil
	end

	local ok, sitelink = pcall( mw.wikibase.sitelink, entityId )
	if ok then
		return sitelink
	end

	return nil
end

local function safePropertyParserFunction( frame, propertyId )
	if not frame or not propertyId or propertyId == '' then
		return ''
	end

	local ok, value = pcall( function()
		return frame:callParserFunction( '#property', propertyId )
	end )

	if ok and value then
		return value
	end

	return ''
end

local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement, formatStatementDefault, formatProperty, getSourcingCircumstances, loadCacheSafe, throwError, toBoolean;

local function copyTo( obj, target )
	for k, v in pairs( obj ) do
		target[k] = v
	end
	return target;
end

local function loadCacheSafe( entityId )
	local status, result = pcall( function() return mw.loadData( 'Module:WikidataCache/' .. entityId ) end );
	if ( status == true ) then
		return result;
	end
	return nil;
end

local function parseISO8601(str)
	if 'table' == type(str) then
		if str.args and str.args[1] then
			str = '' .. str.args[1]
		else
			return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )
		end
	end
	local Y, M, D = (function(str) 
		local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
		local Y, M, D = mw.ustring.match( str, pattern )
		return tonumber(Y), tonumber(M), tonumber(D)
	end) (str);
	local h, m, s = (function(str) 
		local pattern = "T(%d+):(%d+):(%d+)%Z";
		local H, M, S = mw.ustring.match( str, pattern);
		return tonumber(H), tonumber(M), tonumber(S);
	end) (str);
	local oh,om = ( function(str)
		if str:sub(-1)=="Z" then return 0,0 end; -- ends with Z, Zulu time
		-- matches ±hh:mm, ±hhmm or ±hh; else returns nils
		local pattern = "([-+])(%d%d):?(%d?%d?)$";
		local sign, oh, om = mw.ustring.match( str, pattern);
		sign, oh, om = sign or "+", oh or "00", om or "00";
		return tonumber(sign .. oh), tonumber(sign .. om);
	end )(str)
	return tonumber(os.time({year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s})) * 1000;
end


local function toBoolean( valueToParse, defaultValue )
    if ( valueToParse ) then
        if valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
            return false
        end
        return true
    end
    return defaultValue;
end


local function getEntityFromId( id )
    if id and id ~= '' then
    	local cached = loadCacheSafe( id );
    	if ( cached ) then
    		return cached;
    	end
        return safeGetEntityObject( id )
    end

    local entity = safeGetEntityObject();
    if ( entity and entity.id ) then
    	local cached = loadCacheSafe( entity.id );
    	if ( cached ) then
    		return cached;
    	end
	end
    return entity;
end


local function throwError( key )
    error( i18n.errors[key] );
end


local function getEntityIdFromValue( value )
    local prefix = ''
    if value['entity-type'] == 'item' then
        prefix = 'Q'
    elseif value['entity-type'] == 'property' then
        prefix = 'P'
    else
        throwError( 'unknown-entity-type' )
    end
    return prefix .. value['numeric-id']
end


local function getUserFunction( options, prefix, defaultFunction )
    
    if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then
    	
        if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then
            throwError( 'unknown-' .. prefix .. '-module' );
        end
        
        local formatter = require ('Module:' .. options[ prefix .. '-module' ]);
        if formatter == nil then
            throwError( prefix .. '-module-not-found' )
        end
        local fun = formatter[ options[ prefix .. '-function' ] ]
        if fun == nil then
            throwError( prefix .. '-function-not-found' )
        end
        return fun;
    end

   	return defaultFunction;
end


local function selectClaims( context, options, propertySelector )
	if ( not context ) then error( 'context not specified'); end;
	if ( not options ) then error( 'options not specified'); end;
	if ( not options.entity ) then error( 'options.entity is missing'); end;
	if ( not propertySelector ) then error( 'propertySelector not specified'); end;

	local WDS = require('Module:WikidataSelectors')
	result = WDS.filter(options.entity.claims, propertySelector)

    if ( not result or #result == 0 ) then
    	return nil;
    end
    
    if options.limit and options.limit ~= '' and options.limit ~= '-'  then
		local limit = tonumber( options.limit, 10 );
		while #result > limit do
			table.remove( result );
		end
	end

    return result;
end


local function formatProperty( options )
    -- Получение сущности по идентификатору
    local entity = getEntityFromId( options.entityId )
    if not entity then
        return -- throwError( 'entity-not-found' )
    end
	-- проверка на присутсвие у сущности заявлений (claim)
	-- подробнее о заявлениях см. d:Викиданные:Глоссарий
    if (entity.claims == nil) then
        return '' --TODO error?
    end

	-- improve options
	options.frame = g_frame;
	options.entity = entity;
	options.extends = function( self, newOptions )
		return copyTo( newOptions, copyTo( self, {} ) )
	end

	if ( options.i18n ) then
		options.i18n = copyTo( options.i18n, copyTo( i18n, {} ) );
	else
		options.i18n = i18n;
	end

	-- create context
	local context = { formatSnak = formatSnak, formatPropertyDefault = formatPropertyDefault, formatStatementDefault = formatStatementDefault }
	context.formatProperty = function( options ) 
		local func = getUserFunction( options, 'property', context.formatPropertyDefault );
		return func( context, options )
	end;
	context.formatStatement = function( options, statement ) return formatStatement( context, options, statement ) end;
	context.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end;
	context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;
	
	context.parseTimeFromSnak = function( snak )
			if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) then
				local timeISO6801 = tostring( snak.datavalue.value.time )
				return parseISO8601( timeISO6801 );
			end
			return nil;
		end
	context.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end;
	context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;

	return context.formatProperty( options );
end

function formatPropertyDefault( context, options )
	if ( not context ) then error( 'context not specified' ); end;
	if ( not options ) then error( 'options not specified' ); end;
	if ( not options.entity ) then error( 'options.entity missing' ); end;

    local claims = context.selectClaims( options, options.property );
    if (claims == nil) then
        return '' --TODO error?
    end

  
    local formattedClaims = {}

    for i, claim in ipairs(claims) do
        local formattedStatement = context.formatStatement( options, claim )
        
        if (formattedStatement) then
            formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
            table.insert( formattedClaims, formattedStatement )
        end
    end

	
    return mw.text.listToText( formattedClaims, options.separator, options.conjunction )
end


function formatStatement( context, options, statement )
	if ( not statement ) then
		error( 'statement is not specified or nil' );
	end
    if not statement.type or statement.type ~= 'statement' then
        throwError( 'unknown-claim-type' )
    end

    local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault );
    return functionToCall( context, options, statement );
end

function getSourcingCircumstances( statement )
	if (not statement) then error('statement is not specified') end;

	local circumstances = {};
	if ( statement.qualifiers
			and statement.qualifiers.P1480 ) then
		for i, qualifier in pairs( statement.qualifiers.P1480 ) do
			if ( qualifier
					and qualifier.datavalue
					and qualifier.datavalue.type == 'wikibase-entityid'
					and qualifier.datavalue.value
					and qualifier.datavalue.value["entity-type"] == 'item' ) then
				local circumstance = 'Q' .. qualifier.datavalue.value["numeric-id"];
				if ( 'Q18086598' == circumstance ) then
					circumstances.approximate = true;
				end
				if ( 'Q18122778' == circumstance ) then
					circumstances.presumably = true;
				end
			end
		end
	end
	return circumstances;
end


function formatStatementDefault( context, options, statement )
	if (not context) then error('context is not specified') end;
	if (not options) then error('options is not specified') end;
	if (not statement) then error('statement is not specified') end;

	local circumstances = context.getSourcingCircumstances( statement );

	if ( options.references ) then
    	return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
    else
    	return context.formatSnak( options, statement.mainsnak, circumstances );
    end
end


function formatSnak( context, options, snak, circumstances )
	circumstances = circumstances or {};
	local hash = '';
	local mainSnakClass = '';
	if ( snak.hash ) then
		hash = ' data-wikidata-hash="' .. snak.hash .. '"';
	else
		mainSnakClass = ' wikidata-main-snak';
	end

	local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
	local after = '</span>'

    if snak.snaktype == 'somevalue' then
        return before .. options.i18n['somevalue'] .. after;
    elseif snak.snaktype == 'novalue' then
        return before .. options.i18n['novalue'] .. after;
    elseif snak.snaktype == 'value' then
		if ( circumstances.presumably ) then
			before = before .. options.i18n.presumably;
		end
		if ( circumstances.approximate ) then
			before = before .. options.i18n.approximate;
		end

        return before .. formatDatavalue( context, options, snak.datavalue ) .. after;
    else
        throwError( 'unknown-snak-type' );
    end
end


function formatGlobeCoordinate( value, options )
	-- проверка на требование в параметрах вызова на возврат сырого значения 
    if options['subvalue'] == 'latitude' then -- широты
        return value['latitude']
    elseif options['subvalue'] == 'longitude' then -- долготы
        return value['longitude']
    else
    	-- в противном случае формируются параметры для вызова шаблона {{coord}}
    	-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
    	-- любое изменние его парамеров  должно быть согласовано с кодом тут
        local eps = 0.0000001 -- < 1/360000
        local globe = '' -- TODO
        local lat = {}
        lat['abs'] = math.abs(value['latitude'])
        lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
        lat['d'] = math.floor(lat['abs'] + eps)
        lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
        lat['s'] = math.max(0, ((lat['abs'] - lat['d']) * 60 - lat['m']) * 60)
        local lon = {}
        lon['abs'] = math.abs(value['longitude'])
        lon['ew'] = value['longitude'] >= 0 and 'E' or 'W'
        lon['d'] = math.floor(lon['abs'] + eps)
        lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
        lon['s'] = math.max(0, ((lon['abs'] - lon['d']) * 60 - lon['m']) * 60)
        local coord = '{{coord'
        if (value['precision'] == nil) or (value['precision'] < 1/60) then -- по умолчанию с точностью до секунды
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['s'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['s'] .. '|' .. lon['ew']
        elseif value['precision'] < 1 then
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['ew']
        else
            coord = coord .. '|' .. lat['d'] .. '|' .. lat['ns']
            coord = coord .. '|' .. lon['d'] .. '|' .. lon['ew']
        end
        coord = coord .. '|globe:' .. globe
        if options['display'] then
            coord = coord .. '|display=' .. options.display
        else
            coord = coord .. '|display=title'
        end
        coord = coord .. '}}'

        return g_frame:preprocess(coord)
    end
end

local function getDefaultValueFunction( datavalue )
    
    if datavalue.type == 'wikibase-entityid' then
    	
        return function( context, options, value ) return formatEntityId( getEntityIdFromValue( value ), options ) end;
    elseif datavalue.type == 'string' then
    	
        return function( context, options, value ) return value end;
    elseif datavalue.type == 'monolingualtext' then
    	
        return function( context, options, value )
        	if ( options.monolingualLangTemplate == 'lang' ) then
	        	return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
        	elseif ( options.monolingualLangTemplate == 'ref' ) then
	        	return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
        	else
	        	return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
        	end
        end;
    elseif datavalue.type == 'globecoordinate' then
    	-- geografik koordinatalar
        return function( context, options, value ) return formatGlobeCoordinate( value, options )  end;
    elseif datavalue.type == 'quantity' then
        return function( context, options, value )
 
	        local amount = string.gsub(value['amount'], '^%+', '')
	        local lang = mw.language.new( 'ru' )
	        return lang:formatNum( tonumber( amount ) )
        end;
    elseif datavalue.type == 'time' then
        return function( context, options, value )
			local moduleDate = require('Module:Wikidata/date')
	    	return moduleDate.formatDate( context, options, value );
        end;
    else
    	 
        throwError( 'unknown-datavalue-type' )
    end
end

 
function formatDatavalue( context, options, datavalue )
	if ( not context ) then error( 'context not specified' ); end;
	if ( not options ) then error( 'options not specified' ); end;
	if ( not datavalue ) then error( 'datavalue not specified' ); end;
	if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;

    
    context.formatValueDefault = getDefaultValueFunction( datavalue );
    local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
    return functionToCall( context, options, datavalue.value );
end

-- 
local simpleReplaces = {
	Q30 = '[[AQSh]]',
	Q148 = '[[Xitoy Xalq Respublikasi|Xitoy]]',
	Q183 = '[[Germaniya]]',
	Q258 = '[[JAR]]',
	Q423 = '[[Koreya Xalq Demokratik Respublikasi|KXDR]]',
	Q2184 = '[[Rossiya Sovet Federativ Sotsialistik Respublikasi|Rossiya SFSR]]',
	Q2895 = '[[Belorussiya Sovet Sotsialistik Respublikasi|Belorus SSR]]',
	Q15180 = '[[Sovet Sotsialistik Respublikalari Ittifoqi|SSSR]]',
	Q16957 = '[[Germaniya Demokratik Respublikasi|GDR]]',
	Q130229 = '[[Gruziya Sovet Sotsialistik Respublikasi|Gruziya SSR]]',
	Q130280 = '[[Estoniya Sovet Sotsialistik Respublikasi|Estoniya SSR]]',
	Q131337 = '[[Ozarbayjon Sovet Sotsialistik Respublikasi|Ozarbayjon SSR]]',
	Q132856 = '[[Armaniston Sovet Sotsialistik Respublikasi|Armaniston SSR]]',
	Q133356 = '[[Ukraina Sovet Sotsialistik Respublikasi|Ukraina SSR]]',
	Q168811 = '[[Qozogʻiston Sovet Sotsialistik Respublikasi|Qozogʻiston SSR]]',
	Q170895 = '[[Moldova Sovet Sotsialistik Respublikasi|Moldova SSR]]',
	Q173761 = '[[Litva Sovet Sotsialistik Respublikasi|Litva SSR]]',
	Q192180 = '[[Latviya Sovet Sotsialistik Respublikasi|Latviya SSR]]',
	Q199707 = '[[Turkmaniston Sovet Sotsialistik Respublikasi|Turkmaniston SSR]]',
	Q199711 = '[[Tojikiston Sovet Sotsialistik Respublikasi|Tojikiston SSR]]',
	Q484578 = '[[Oʻzbekiston Sovet Sotsialistik Respublikasi|Oʻzbekiston SSR]]',
}


function formatEntityId( entityId, options )
	-- получение локализованного названия 
    local label = nil;
    if ( options.text and options.text ~= '' ) then
        label = options.text
    else
    	if ( simpleReplaces[entityId] ) then
			return simpleReplaces[entityId];
		end
		label = safeWikibaseLabel( entityId );
    end

	-- получение ссылки по идентификатору
    local link = safeWikibaseSitelink( entityId )
    if link then
        if label then
            return '[[' .. link .. '|' .. label .. ']]'
        else
            return '[[' .. link .. ']]'
        end
    end

    if label then
        return label
    end
    -- сообщение об отсутвии локализованного названия
    -- not good, but better than nothing
    return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;
end

--[[ 
  Функция для оформления утверждений (statement)
  Подробнее о утверждениях см. d:Wikidata:Glossary/ru

  Принимает: таблицу параметров
  Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
-- устаревшее имя, не использовать
function p.formatStatements( frame )
	return p.formatProperty( frame );
end

function p.formatProperty( frame )
    local args = frame.args
    local plain = toBoolean( frame.args.plain, false );
    frame.args.nocat = toBoolean( frame.args.nocat, false );
    frame.args.references = toBoolean( frame.args.references, true );

   
    if not frame.args.property then
        throwError( 'property-param-not-provided' )
    end
    
    
	p_frame = frame
	while p_frame do
		if p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
			copyTo( p_frame.args, args, true );
		end
		if p_frame.args and p_frame.args.from and p_frame.args.from ~= '' then
			args.entityId = p_frame.args.from;
		end
		p_frame = p_frame:getParent();
	end

    local propertyValue = safePropertyParserFunction( frame, frame.args.property )

    if frame.args.value and frame.args.value ~= '' then
        if plain or frame.args.nocat or propertyValue == '' then
                return frame.args.value
        else
                return args.value .. categoryLocalValuePresent;
        end
    end

    if ( plain ) then
    	return propertyValue;
    end

	g_frame = frame
	
    return formatProperty( frame.args )
end


function formatRefs( context, options, statement )
	if ( not context ) then error( 'context not specified' ); end;
	if ( not options ) then error( 'options not specified' ); end;
	if ( not options.entity ) then error( 'options.entity missing' ); end;
	if ( not statement ) then error( 'statement not specified' ); end;

	if ( not outputReferences ) then
		return '';
	end

	local result = '';
	if ( statement.references ) then

		local allReferences = statement.references;
		local hasPreferred = false;
		for _, reference in pairs( statement.references ) do
			if ( reference.snaks
					and reference.snaks.P248
					and reference.snaks.P248[1]
					and reference.snaks.P248[1].datavalue
					and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
				local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
				if ( preferredSources[entityId] ) then
					hasPreferred = true;
				end
			end
		end

		for _, reference in pairs( statement.references ) do
			local display = true;
			if ( hasPreferred ) then
				if ( reference.snaks
						and reference.snaks.P248
						and reference.snaks.P248[1]
						and reference.snaks.P248[1].datavalue
						and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
					local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
					if ( deprecatedSources[entityId] ) then
						display = false;
					end
				end
			end
			if ( display ) then
				result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
			end
		end
	end
	return result
end

return p