Модуль:Wikidata: различия между версиями

м
1 версия импортирована: Шаблоны:Для шаблонов
м (1 версия импортирована: Шаблоны Цвет Википедия)
м (1 версия импортирована: Шаблоны:Для шаблонов)
 
(не показано 7 промежуточных версий 2 участников)
Строка 1: Строка 1:
-- settings, may differ from project to project
---settings, may differ from project to project
local fileDefaultSize = '267x400px';
local fileDefaultSize = '267x400px'
local outputReferences = true;
local outputReferences = true
local writingSystemElementId = 'Q8209'
local langElementId = 'Q7737'


-- Ссылки на используемые модули, которые потребуются в 99% случаев загрузки страниц (чтобы иметь на виду при переименовании)
---Ссылки на используемые модули, которые потребуются в 99% случаев загрузки страниц (чтобы иметь на виду при переименовании)
local moduleSources = require( 'Module:Sources' )
local moduleSources = require( 'Module:Sources' )
local WDS = require( 'Module:WikidataSelectors' );
local WDS = require( 'Module:WikidataSelectors' )


-- Константы
---Константы
local contentLanguageCode = mw.getContentLanguage():getCode();
---@type string
 
local CONTENT_LANGUAGE_CODE = mw.language.getContentLanguage():getCode()
local p = {};
local config = nil;


local p = {}
local g_config, g_frame
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
formatStatementDefault, formatProperty, getSourcingCircumstances,
formatStatementDefault, getSourcingCircumstances, getPropertyParams
getPropertyDatatype, getPropertyParams, throwError, toBoolean;


---@param obj table
---@param target table
---@param skipEmpty boolean | nil
---@return table
local function copyTo( obj, target, skipEmpty )
local function copyTo( obj, target, skipEmpty )
for k, v in pairs( obj ) do
    for key, val in pairs( obj ) do
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
        if skipEmpty ~= true or ( val ~= nil and val ~= '' ) then
target[k] = v;
            target[ key ] = val
end
        end
end
    end
return target;
    return target
end
end


---@param prev number | nil
---@param next number | nil
---@return number | nil
local function min( prev, next )
local function min( prev, next )
if ( prev == nil ) then return next;
    if prev == nil or prev > next then
elseif ( prev > next ) then return next;
        return next
else return prev; end
    end
    return prev
end
end


---@param prev number | nil
---@param next number | nil
---@return number | nil
local function max( prev, next )
local function max( prev, next )
if ( prev == nil ) then return next;
    if prev == nil or prev < next then
elseif ( prev < next ) then return next;
        return next
else return prev; end
    end
    return prev
end
end


---@param section string
---@param code string
---@return any | nil
local function getConfig( section, code )
local function getConfig( section, code )
if config == nil then
    if g_config == nil then
config = require( 'Module:Wikidata/config' );
        g_config = require( 'Module:Wikidata/config' )
end;
    end
if not config then
    if not g_config then
config = {};
        g_config = {}
end
    end


if not section then
    if not section then
return config;
        return g_config
end
    end
if not code then
    if not code then
return config[ section ] or {};
        return g_config[ section ] or {}
end
    end


if not config[ section ] then
    if not g_config[ section ] then
return nil;
        return nil
end
    end
return config[ section ][ code ];
    return g_config[ section ][ code ]
end
end


local function getCategoryByCode( code, sortkey )
---@param code string
local value = getConfig( 'categories', code );
---@param sortKey string | nil
if not value or value == '' then
---@return string
return '';
local function getCategoryByCode( code, sortKey )
end
    local value = getConfig( 'categories', code )
    if not value or value == '' then
if sortkey ~= nil then
        return ''
return '[[Category:' .. value .. '|' .. sortkey .. ']]'; -- экранировать?
    end
else
 
return '[[Category:' .. value .. ']]';
    if sortKey ~= nil then
end
        return '[[Category:' .. value .. '|' .. sortKey .. ']]'; -- экранировать?
    else
        return '[[Category:' .. value .. ']]'
    end
end
end


local function splitISO8601(str)
---@param isoStr string | table
if 'table' == type(str) then
---@return table | nil
if str.args and str.args[1] then
local function splitISO8601( isoStr )
str = '' .. str.args[1]
    if 'table' == type( isoStr ) then
else
        if isoStr.args and isoStr.args[ 1 ] then
return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )
            isoStr = '' .. isoStr.args[ 1 ]
end
        else
end
            return 'unknown argument type: ' .. type( isoStr ) .. ': ' .. table.tostring( isoStr )
local Y, M, D = (function(str)
        end
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
    end
local Y, M, D = mw.ustring.match( str, pattern )
    local Y, M, D = ( function( str )
return tonumber(Y), tonumber(M), tonumber(D)
        local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
end) (str);
        local _Y, _M, _D = mw.ustring.match( str, pattern )
local h, m, s = (function(str)
        return tonumber( _Y ), tonumber( _M ), tonumber( _D )
local pattern = "T(%d+):(%d+):(%d+)%Z";
    end )( isoStr )
local H, M, S = mw.ustring.match( str, pattern);
    local h, m, s = ( function( str )
return tonumber(H), tonumber(M), tonumber(S);
        local pattern = "T(%d+):(%d+):(%d+)%Z"
end) (str);
        local _H, _M, _S = mw.ustring.match( str, pattern )
local oh,om = ( function(str)
        return tonumber( _H ), tonumber( _M ), tonumber( _S )
if str:sub(-1)=="Z" then return 0,0 end; -- ends with Z, Zulu time
    end )( isoStr )
-- matches ±hh:mm, ±hhmm or ±hh; else returns nils
    local oh, om = ( function( str )
local pattern = "([-+])(%d%d):?(%d?%d?)$";
        if str:sub(-1) == "Z" then -- ends with Z, Zulu time
local sign, oh, om = mw.ustring.match( str, pattern);
            return 0, 0
sign, oh, om = sign or "+", oh or "00", om or "00";
        end
return tonumber(sign .. oh), tonumber(sign .. om);
        -- matches ±hh:mm, ±hhmm or ±hh; else returns nils
end )(str)
        local pattern = "([-+])(%d%d):?(%d?%d?)$"
return {year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s};
        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 )( isoStr )
    return { year=Y, month=M, day=D, hour=( h + oh ), min=( m + om ), sec=s }
end
end


---@param time string
---@param precision number
---@return table | nil
local function parseTimeBoundaries( time, precision )
local function parseTimeBoundaries( time, precision )
local s = splitISO8601( time );
    local s = splitISO8601( time )
if (not s) then return nil; end
    if not s then
        return nil
    end


if ( precision >= 0 and precision <= 8 ) then
    if precision >= 0 and precision <= 8 then
local powers = { 1000000000 , 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 }
        local powers = { 1000000000 , 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 }
local power = powers[ precision + 1 ];
        local power = powers[ precision + 1 ]
local left = s.year - ( s.year % power );
        local left = s.year - ( s.year % power )
return { tonumber(os.time( {year=left, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
        return { tonumber( os.time( { year=left, month=1, day=1, hour=0, min=0, sec=0 } ) ) * 1000,
tonumber(os.time( {year=left + power - 1, month=12, day=31, hour=29, min=59, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=left + power - 1, month=12, day=31, hour=29, min=59, sec=58 } ) ) * 1000 + 1999 }
end
    end


if ( precision == 9 ) then
    if precision == 9 then
return { tonumber(os.time( {year=s.year, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
        return { tonumber( os.time( { year=s.year, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
tonumber(os.time( {year=s.year, month=12, day=31, hour=23, min=59, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=s.year, month=12, day=31, hour=23, min=59, sec=58} )) * 1000 + 1999 }
end
    end


if ( precision == 10 ) then
    if precision == 10 then
local lastDays = {31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        local lastDays = { 31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
local lastDay = lastDays[s.month];
        local lastDay = lastDays[ s.month ]
return { tonumber(os.time( {year=s.year, month=s.month, day=1, hour=0, min=0, sec=0} )) * 1000,
        return { tonumber( os.time( { year=s.year, month=s.month, day=1, hour=0, min=0, sec=0 } ) ) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=lastDay, hour=23, min=59, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=s.year, month=s.month, day=lastDay, hour=23, min=59, sec=58 } ) ) * 1000 + 1999 }
end
    end


if ( precision == 11 ) then
    if precision == 11 then
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=0, min=0, sec=0} )) * 1000,
        return { tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=0, min=0, sec=0 } ) ) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=23, min=59, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=23, min=59, sec=58 } ) ) * 1000 + 1999 }
end
    end


if ( precision == 12 ) then
    if precision == 12 then
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=0, sec=0} )) * 1000,
        return { tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=s.hour, min=0, sec=0 } ) ) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=59, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=s.hour, min=59, sec=58 } ) ) * 1000 + 1999 }
end
    end


if ( precision == 13 ) then
    if precision == 13 then
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} )) * 1000,
        return { tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0 } ) ) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=58} )) * 1000 + 1999 };
                tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=58 } ) ) * 1000 + 1999 }
end
    end


if ( precision == 14 ) then
    if precision == 14 then
local t = tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} ) );
        local t = tonumber( os.time( { year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0 } ) )
return { t * 1000, t * 1000 + 999 };
        return { t * 1000, t * 1000 + 999 }
end
    end


error('Unsupported precision: ' .. precision );
    error( 'Unsupported precision: ' .. precision )
end
end


--[[
---Функция для формирования категории на основе wikidata/config
Преобразует строку в булевое значение
---@param options table
---@param entityId string
---@return string
local function extractCategory( options, entityId )
    if not entityId or not options.category or options.nocat then
        return ''
    end
    if type( entityId ) ~= 'string' then
        entityId = entityId.id
    end
    local claims = WDS.load( entityId, options.category )
    if not claims then
        return ''
    end
 
    for _, claim in pairs( claims ) do
        if claim
                and claim.mainsnak
                and claim.mainsnak.datavalue
                and claim.mainsnak.datavalue.type == 'wikibase-entityid'
        then
            local catEntityId = claim.mainsnak.datavalue.value.id
            local wbStatus, catSiteLink = pcall( mw.wikibase.getSitelink, catEntityId )
 
            if wbStatus and catSiteLink then
                return '[[' .. catSiteLink .. ']]'
            end
        end
    end


Принимает: строковое значение (может отсутствовать)
    return ''
Возвращает: булевое значение true или false, если получается распознать значение, или defaultValue во всех остальных случаях
end
]]
 
---Преобразует строку в булевое значение
---@param valueToParse string
---@return boolean Преобразованное значение, если его удалось распознать, или defaultValue во всех остальных случаях
local function toBoolean( valueToParse, defaultValue )
local function toBoolean( valueToParse, defaultValue )
if ( valueToParse ~= nil ) then
    if valueToParse ~= nil then
if valueToParse == false or valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
        if valueToParse == false or valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
return false
            return false
end
        end
return true
        return true
end
    end
return defaultValue;
    return defaultValue
end
end


-- Обрачивает отформатированное значение в инлайновый или блочный тег.
---Обрачивает отформатированное значение в инлайновый или блочный тег.
-- @param value String value
---@param value string value
-- @param attributes Table of attributes
---@param attributes table of attributes
-- @return string HTML tag with value
---@return string HTML tag with value
local function wrapValue( value, attributes )
local function wrapValue( value, attributes )
local tagName = 'span';
    local tagName = 'span'
local spacer = '';
    local spacer = ''
if (
    if string.match( value, '\n' )
string.match( value, '\n' )
            or string.match( value, '<t[dhr][ >]' )
or string.match( value, '<t[dhr][ >]' )
            or string.match( value, '<div[ >]' )
or string.match( value, '<div[ >]' )
            or string.find( value, 'UNIQ%-%-imagemap' )
or string.find( value, 'UNIQ%-%-imagemap' )
    then
) then
        tagName = 'div'
tagName = 'div';
        spacer = '\n'
spacer = '\n'
    end
end
    local attrString = ''
local attrString = ''
    for key, val in pairs( attributes or {} ) do
for key, value in pairs( attributes or {} ) do
        local _key = mw.text.trim( key )
local _key = mw.text.trim( key )
        local _value = mw.text.encode( mw.text.trim( val ) )
local _value = mw.text.encode( mw.text.trim( value ) )
        attrString = attrString .. _key .. '="' .. _value .. '" '
attrString = attrString .. _key .. '="' .. _value .. '" '
    end
end
    return '<' .. tagName .. ' ' .. attrString .. '>' .. spacer .. value .. '</' .. tagName .. '>'
return '<' .. tagName .. ' ' .. attrString .. '>' .. spacer .. value .. '</' .. tagName .. '>';
end
end


-- Wraps formatted snak value into HTML tag with attributes.
---Wraps formatted snak value into HTML tag with attributes.
-- @param value String value of snak
---@param value string value of snak
-- @param hash Snak hash
---@param hash string
-- @param attributes Table of extra attributes
---@param attributes table of extra attributes
-- @return string HTML tag with value
---@return string HTML tag with value
local function wrapSnak( value, hash, attributes )
local function wrapSnak( value, hash, attributes )
local newAttributes = mw.clone( attributes or {} )
    local newAttributes = mw.clone( attributes or {} )
newAttributes['class'] = ( newAttributes['class'] or '' ) .. ' wikidata-snak'
    newAttributes[ 'class' ] = ( newAttributes[ 'class' ] or '' ) .. ' wikidata-snak'
 
if hash then
    if hash then
newAttributes['data-wikidata-hash'] = hash
        newAttributes[ 'data-wikidata-hash'] = hash
else
    else
newAttributes['class'] = newAttributes['class'] .. ' wikidata-main-snak'
        newAttributes[ 'class' ] = newAttributes[ 'class' ] .. ' wikidata-main-snak'
end
    end


return wrapValue( value, newAttributes )
    return wrapValue( value, newAttributes )
end
end


-- Wraps formatted statement value into HTML tag with attributes.
---Wraps formatted statement value into HTML tag with attributes.
-- @param value String value of statement
---@param value string value of statement
-- @param propertyId String PID of property
---@param propertyId string PID of property
-- @param claimId String ID of claim or nil for local value
---@param claimId string ID of claim or nil for local value
-- @param attributes Table of extra attributes
---@param attributes table of extra attributes
-- @return string HTML tag with value
---@return string HTML tag with value
local function wrapStatement( value, propertyId, claimId, attributes )
local function wrapStatement( value, propertyId, claimId, attributes )
local newAttributes = mw.clone( attributes or {} )
    local newAttributes = mw.clone( attributes or {} )
newAttributes['class'] = newAttributes['class'] or ''
    newAttributes[ 'class' ] = newAttributes[ 'class' ] or ''
newAttributes['data-wikidata-property-id'] = string.upper( propertyId )
    newAttributes[ 'data-wikidata-property-id' ] = string.upper( propertyId )


if claimId then
    if claimId then
newAttributes['class'] = newAttributes['class'] .. ' wikidata-claim'
        newAttributes[ 'class' ] = newAttributes[ 'class' ] .. ' wikidata-claim'
newAttributes['data-wikidata-claim-id'] = claimId
        newAttributes[ 'data-wikidata-claim-id' ] = claimId
else
    else
newAttributes['class'] = newAttributes['class'] .. ' no-wikidata'
        newAttributes[ 'class' ] = newAttributes[ 'class' ] .. ' no-wikidata'
end
    end


return wrapValue( value, newAttributes )
    return wrapValue( value, newAttributes )
end
end


-- Wraps formatted qualifier's statement value into HTML tag with attributes.
---Wraps formatted qualifier's statement value into HTML tag with attributes.
-- @param value String value of qualifier's statement
---@param value string value of qualifier's statement
-- @param propertyId String PID of qualifier
---@param qualifierId string PID of qualifier
-- @param attributes Table of extra attributes
---@param attributes table of extra attributes
-- @return string HTML tag with value
---@return string HTML tag with value
local function wrapQualifier( value, qualifierId, attributes )
local function wrapQualifier( value, qualifierId, attributes )
local newAttributes = mw.clone( attributes or {} )
    local newAttributes = mw.clone( attributes or {} )
newAttributes['data-wikidata-qualifier-id'] = string.upper( qualifierId )
    newAttributes[ 'data-wikidata-qualifier-id' ] = string.upper( qualifierId )
return wrapValue( value, newAttributes )
    return wrapValue( value, newAttributes )
end
end


--[[
---Функция для получения сущности (еntity) для текущей страницы
Функция для получения сущности (еntity) для текущей страницы
---Подробнее о сущностях см. d:Wikidata:Glossary/ru
Подробнее о сущностях см. d:Wikidata:Glossary/ru
---@param id string Идентификатор (типа P18, Q42)
 
---@return table Таблица, элементы которой индексируются с нуля
Принимает: строковый индентификатор (типа P18, Q42)
Возвращает: объект таблицу, элементы которой индексируются с нуля
]]
local function getEntityFromId( id )
local function getEntityFromId( id )
local entity;
    local entity
local wbStatus;
    local wbStatus


if id then
    if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
        wbStatus, entity = pcall( mw.wikibase.getEntity, id )
else
    else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
        wbStatus, entity = pcall( mw.wikibase.getEntity )
end
    end


return entity;
    return entity
end
end


--[[
---Внутренняя функция для формирования сообщения об ошибке
Внутрення функция для формирования сообщения об ошибке
---@param key string Ключ элемента в таблице config.errors (например entity-not-found)
 
---@return void
Принимает: ключ элемента в таблице config.errors (например entity-not-found)
Возвращает: строку сообщения
]]
local function throwError( key )
local function throwError( key )
error( getConfig( 'errors', key ) );
    error( getConfig( 'errors', key ) )
end
end


--[[
---Функция для получения идентификатора сущностей
Функция для получения идентификатора сущностей
---@param value table
 
---@return string
Принимает: объект таблицу сущности
Возвращает: строковый индентификатор (типа P18, Q42)
]]
local function getEntityIdFromValue( value )
local function getEntityIdFromValue( value )
local prefix = ''
    local prefix = ''
if value['entity-type'] == 'item' then
    if value[ 'entity-type' ] == 'item' then
prefix = 'Q'
        prefix = 'Q'
elseif value['entity-type'] == 'property' then
    elseif value[ 'entity-type' ] == 'property' then
prefix = 'P'
        prefix = 'P'
else
    else
throwError( 'unknown-entity-type' )
        throwError( 'unknown-entity-type' )
end
    end
return prefix .. value['numeric-id']
    return prefix .. value[ 'numeric-id' ]
end
end


-- проверка на наличие специилизированной функции в опциях
---Проверка на наличие специализированной функции в опциях
---@param options table
---@param prefix string
---@return function
local function getUserFunction( options, prefix, defaultFunction )
local function getUserFunction( options, prefix, defaultFunction )
-- проверка на указание специализированных обработчиков в параметрах,
    -- проверка на указание специализированных обработчиков в параметрах,
-- переданных при вызове
    -- переданных при вызове
if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then
    if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then
-- проверка на пустые строки в параметрах или их отсутствие
        -- проверка на пустые строки в параметрах или их отсутствие
if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then
        if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then
throwError( 'unknown-' .. prefix .. '-module' );
            throwError( 'unknown-' .. prefix .. '-module' )
end
        end
-- динамическая загруза модуля с обработчиком указанным в параметре
        -- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require( 'Module:' .. options[ prefix .. '-module' ] );
        local formatter = require( 'Module:' .. options[ prefix .. '-module' ] )
if formatter == nil then
        if formatter == nil then
throwError( prefix .. '-module-not-found' )
            throwError( prefix .. '-module-not-found' )
end
        end
local fun = formatter[ options[ prefix .. '-function' ] ]
        local fun = formatter[ options[ prefix .. '-function' ] ]
if fun == nil then
        if fun == nil then
throwError( prefix .. '-function-not-found' )
            throwError( prefix .. '-function-not-found' )
end
        end
return fun;
        return fun
end
    end


return defaultFunction;
    return defaultFunction
end
end


-- Выбирает свойства по property id, дополнительно фильтруя их по рангу
---Выбирает свойства по property id, дополнительно фильтруя их по рангу
---@param context table
---@param options table
---@param propertySelector string
---@return table | nil
local function selectClaims( context, options, propertySelector )
local function selectClaims( context, options, propertySelector )
if ( not context ) then error( 'context not specified' ); end;
    if not context then error( 'context not specified' ); end
if ( not options ) then error( 'options 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 options.entityId then error( 'options.entity is missing' ); end
if ( not propertySelector ) then error( 'propertySelector not specified' ); end;
    if not propertySelector then error( 'propertySelector not specified' ); end


result = WDS.filter( options.entity.claims, propertySelector );
    local result = WDS.load( options.entityId, propertySelector )


if ( not result or #result == 0 ) then
    if not result or #result == 0 then
return nil;
        return nil
end
    end


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


return result;
    return result
end
end


--[[
---Функция для получения значения свойства элемента в заданный момент времени.
Функция для получения значения свойства элемента в заданный момент времени.
---@param entityId string
---@param boundaries table Временные границы
---@param propertyIds table<string>
---@param selectors table<string>
---@return table Таблица соответствующих значений свойства
local function getPropertyInBoundaries( context, entityId, boundaries, propertyIds, selectors )
    if type( entityId ) ~= 'string' then error( 'type of entityId argument expected string, but was ' .. type(entityId)); end


Принимает: контекст, элемент, временные границы, таблица ID свойства
    local results = {}
Возвращает: таблицу соответствующих значений свойства
 
]]
    if not propertyIds or #propertyIds == 0 then
local function getPropertyInBoundaries( context, entityId, boundaries, propertyIds, selectors )
        return results
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
    end


local results = {};
    for i, propertyId in ipairs( propertyIds ) do
        local selector
        if selectors ~= nil then
            selector = selectors[ i ] or selectors[ propertyId ] or propertyId
        else
            selector = propertyId
        end


if not propertyIds or #propertyIds == 0 then
        local fakeAllClaims = {}
return results;
        fakeAllClaims[ propertyId ] = mw.wikibase.getAllStatements( entityId, propertyId )
end


for _, propertyId in ipairs( propertyIds ) do
        local filteredClaims = WDS.filter( fakeAllClaims, selector .. '[rank:preferred, rank:normal]' )
local selector = selectors[_];
        if filteredClaims then
local propertyClaims = mw.wikibase.getAllStatements( entityId, propertyId );
            for _, claim in pairs( filteredClaims ) do
local fakeAllClaims = {};
                if not boundaries then
fakeAllClaims[propertyId] = propertyClaims;
                    table.insert( results, claim.mainsnak )
                else
local filteredClaims = WDS.filter( fakeAllClaims, selector .. '[rank:preferred, rank:normal]' );
                    local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' )
if filteredClaims then
                    local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' )
for _, claim in pairs( filteredClaims ) do
if not boundaries then
table.insert( results, claim.mainsnak );
else
local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' );


if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
                    if ( startBoundaries == nil or startBoundaries[ 1 ] <= boundaries[ 1 ] ) and
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
                            ( endBoundaries == nil or endBoundaries[ 1 ] >= boundaries[ 2 ] )
table.insert( results, claim.mainsnak );
                    then
end
                        table.insert( results, claim.mainsnak )
end
                    end
end
                end
end
            end
        end


if #results > 0 then
        if #results > 0 then
break;
            break
end
        end
end
    end


return results;
    return results
end
end


--[[
---@param context table
TODO
---@param statement table
]]
---@param qualifierId string
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
---@return table | nil
-- only support exact date so far, but need improvment
function p.getTimeBoundariesFromQualifier( _, context, statement, qualifierId )
local left = nil;
    -- only support exact date so far, but need improvement
local right = nil;
    local left, right
if ( statement.qualifiers and statement.qualifiers[qualifierId] ) then
    if statement.qualifiers and statement.qualifiers[ qualifierId ] then
for _, qualifier in pairs( statement.qualifiers[qualifierId] ) do
        for _, qualifier in pairs( statement.qualifiers[ qualifierId ] ) do
local boundaries = context.parseTimeBoundariesFromSnak( qualifier );
            local boundaries = context.parseTimeBoundariesFromSnak( qualifier )
if ( not boundaries ) then return nil; end
            if not boundaries then
left = min( left, boundaries[1] );
                return nil
right = max( right, boundaries[2] );
            end
end
            left = min( left, boundaries[ 1 ] )
end
            right = max( right, boundaries[ 2 ] )
        end
    end


if ( not left or not right ) then
    if not left or not right then
return nil;
        return nil
end
    end


return { left, right };
    return { left, right }
end
end


--[[
---@param frame table
TODO
---@param context table
]]
---@param statement table
---@param qualifierIds table<string>
---@return table | nil
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
if not qualifierIds then
    if not qualifierIds then
qualifierIds = { 'P582', 'P580', 'P585' };
        qualifierIds = { 'P582', 'P580', 'P585' }
end
    end


for _, qualifierId in ipairs( qualifierIds ) do
    for _, qualifierId in pairs( qualifierIds ) do
local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId );
        local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
if result then
        if result then
return result;
            return result
end
        end
end
    end


return nil;
    return nil
end
end


local CONTENT_LANGUAGE_CODE = mw.language.getContentLanguage():getCode();
---@type table<string>
local getLabelWithLang_DEFAULT_PROPERTIES = { "P1813", "P1448", "P1705" };
local getLabelWithLang_DEFAULT_PROPERTIES = { 'P1813', 'P1448', 'P1705' }
 
---@type table<string>
local getLabelWithLang_DEFAULT_SELECTORS = {
local getLabelWithLang_DEFAULT_SELECTORS = {
'P1813[language:' .. CONTENT_LANGUAGE_CODE .. '][!P3831,P3831:Q105690470]',
    'P1813[language:' .. CONTENT_LANGUAGE_CODE .. '][!P282,P282:' .. writingSystemElementId .. '][!P3831,P3831:Q105690470]',
'P1448[language:' .. CONTENT_LANGUAGE_CODE .. '][!P3831,P3831:Q105690470]',
    'P1448[language:' .. CONTENT_LANGUAGE_CODE .. '][!P282,P282:' .. writingSystemElementId .. '][!P3831,P3831:Q105690470]',
'P1705[language:' .. CONTENT_LANGUAGE_CODE .. '][!P3831,P3831:Q105690470]'
    'P1705[language:' .. CONTENT_LANGUAGE_CODE .. '][!P282,P282:' .. writingSystemElementId .. '][!P3831,P3831:Q105690470]'
};
}


--[[
---Функция для получения метки элемента в заданный момент времени.
Функция для получения метки элемента в заданный момент времени.
---@param context table
---@param options table
---@param entityId string
---@param boundaries table
---@param propertyIds table
---@param selectors table<string>
---@return string, string Текстовая метка элемента, язык метки
local function getLabelWithLang( context, options, entityId, boundaries, propertyIds, selectors )
    if type( entityId ) ~= 'string' then error( 'type of entityId argument expected string, but was ' .. type( entityId ) ); end
    if not entityId then
        return nil
    end


Принимает: контекст, элемент, временные границы
    local langCode = CONTENT_LANGUAGE_CODE
Возвращает: текстовую метку элемента, язык метки
]]
local function getLabelWithLang( context, options, entityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
if not entityId then
return nil;
end


local langCode = CONTENT_LANGUAGE_CODE;
    -- name from label
    local label
    if options.text and options.text ~= '' then
        label = options.text
    else
        if not propertyIds then
            propertyIds = getLabelWithLang_DEFAULT_PROPERTIES
            selectors = getLabelWithLang_DEFAULT_SELECTORS
        end


-- name from label
        -- name from properties
local label = nil;
        local results = getPropertyInBoundaries( context, entityId, boundaries, propertyIds, selectors )
if ( options.text and options.text ~= '' ) then
label = options.text;
else
if not propertyIds then
propertyIds = getLabelWithLang_DEFAULT_PROPERTIES;
selectors = getLabelWithLang_DEFAULT_SELECTORS;
end


-- name from properties
        for _, result in pairs( results ) do
local results = getPropertyInBoundaries( context, entityId, boundaries, propertyIds, selectors );
            if result.datavalue and result.datavalue.value then
                if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
                    label = result.datavalue.value.text
                    langCode = result.datavalue.value.language
                    break
                elseif result.datavalue.type == 'string' then
                    label = result.datavalue.value
                    break
                end
            end
        end


for _, result in pairs( results ) do
        if not label then
if result.datavalue and result.datavalue.value then
            label, langCode = mw.wikibase.getLabelWithLang( entityId )
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
            if not langCode then
label = result.datavalue.value.text;
                return nil
langCode = result.datavalue.value.language;
            end
break;
        end
elseif result.datavalue.type == 'string' then
    end
label = result.datavalue.value;
break;
end
end
end
if (not label) then
label, langCode = mw.wikibase.getLabelWithLang( entityId );
if not langCode then
return nil;
end
end
end


return label, langCode;
    return label, langCode
end
end


---@param context table
---@param options table
---@return string
local function formatPropertyDefault( context, options )
local function formatPropertyDefault( context, options )
if ( not context ) then error( 'context not specified' ); end;
    if not context then error( 'context not specified' ); end
if ( not options ) then error( 'options not specified' ); end;
    if not options then error( 'options not specified' ); end
if ( not options.entity ) then error( 'options.entity missing' ); end;
    if not options.entityId then error( 'options.entityId missing' ); end


local claims;
    local claims
if options.property then -- TODO: Почему тут может не быть property?
    if options.property then -- TODO: Почему тут может не быть property?
if options.rank then -- передать настройки ранга из конфига
        if options.rank then -- передать настройки ранга из конфига
claims = context.selectClaims( options, options.property .. options.rank );
            claims = context.selectClaims( options, options.property .. options.rank )
else
        else
claims = context.selectClaims( options, options.property );
            claims = context.selectClaims( options, options.property )
end
        end
end
    end
if claims == nil then
    if claims == nil then
return '' --TODO error?
        return '' --TODO error?
end
    end


-- Обход всех заявлений утверждения и с накоплением оформленных предпочтительных
    -- Обход всех заявлений утверждения и с накоплением оформленных предпочтительных
-- заявлений в таблице
    -- заявлений в таблице
local formattedClaims = {}
    local formattedClaims = {}


for i, claim in ipairs(claims) do
    for _, claim in pairs( claims ) do
local formattedStatement = context.formatStatement( options, claim )
        local formattedStatement = context.formatStatement( options, claim )
-- здесь может вернуться либо оформленный текст заявления, либо строка ошибки, либо nil
        -- здесь может вернуться либо оформленный текст заявления, либо строка ошибки, либо nil
if ( formattedStatement and formattedStatement ~= '' ) then
        if formattedStatement and formattedStatement ~= '' then
formattedStatement = context.wrapStatement( formattedStatement, options.property, claim.id )
        if not options.plain then
table.insert( formattedClaims, formattedStatement )
            formattedStatement = context.wrapStatement( formattedStatement, options.property, claim.id )
end
            end
end
            table.insert( formattedClaims, formattedStatement )
        end
    end


-- создание текстовой строки со списком оформленых заявлений из таблицы
    -- создание текстовой строки со списком оформленых заявлений из таблицы
local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
    local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
if out ~= '' then
    if out ~= '' then
if options.before then
        if options.before then
out = options.before .. out
            out = options.before .. out
end
        end
if options.after then
        if options.after then
out = out .. options.after
            out = out .. options.after
end
        end
end
    end


return out
    return out
end
end


-- create context
---Create context
local function initContext( options )
---@param initOptions table
local context = {
---@return table | nil
entity = options.entity,
local function initContext( initOptions )
formatSnak = formatSnak,
    local context = {
formatPropertyDefault = formatPropertyDefault,
        entityId = initOptions.entityId,
formatStatementDefault = formatStatementDefault,
        entity = initOptions.entity,
wrapSnak = wrapSnak,
        extractCategory = extractCategory,
wrapStatement = wrapStatement,
        formatSnak = formatSnak,
wrapQualifier = wrapQualifier,
        formatPropertyDefault = formatPropertyDefault,
}
        formatStatementDefault = formatStatementDefault,
context.cloneOptions = function( options )
        getPropertyInBoundaries = getPropertyInBoundaries,
local entity = options.entity;
        getTimeBoundariesFromQualifier = p.getTimeBoundariesFromQualifier,
options.entity = nil;
        getTimeBoundariesFromQualifiers = p.getTimeBoundariesFromQualifiers,
        wrapSnak = wrapSnak,
        wrapStatement = wrapStatement,
        wrapQualifier = wrapQualifier,
    }
    context.cloneOptions = function( options )
        local entity = options.entity
        options.entity = nil


newOptions = mw.clone( options );
        local newOptions = mw.clone( options )
options.entity = entity;
        options.entity = entity
newOptions.entity = entity;
        newOptions.entity = entity
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
        newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()


return newOptions;
        return newOptions
end;
    end
context.formatProperty = function( options )
    context.formatProperty = function( options )
local func = getUserFunction( options, 'property', context.formatPropertyDefault );
        local func = getUserFunction( options, 'property', context.formatPropertyDefault )
return func( context, options )
        return func( context, options )
end;
    end
context.formatStatement = function( options, statement ) return formatStatement( context, options, statement ) 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.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end
context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;
    context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end


context.parseTimeFromSnak = function( snak )
    context.parseTimeFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) then
        if snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time then
return tonumber(os.time( splitISO8601( tostring( snak.datavalue.value.time ) ) ) ) * 1000;
            return tonumber( os.time( splitISO8601( tostring( snak.datavalue.value.time ) ) ) ) * 1000
end
        end
return nil;
        return nil
end
    end
context.parseTimeBoundariesFromSnak = function( snak )
    context.parseTimeBoundariesFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time and snak.datavalue.value.precision ) then
        if snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time and snak.datavalue.value.precision then
return parseTimeBoundaries( snak.datavalue.value.time, snak.datavalue.value.precision );
            return parseTimeBoundaries( snak.datavalue.value.time, snak.datavalue.value.precision )
end
        end
return nil;
        return nil
end
    end
context.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end;
    context.getSourcingCircumstances = function( statement )
context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;
        return getSourcingCircumstances( statement )
    end
    context.selectClaims = function( options, propertyId )
        return selectClaims( context, options, propertyId )
    end


return context
    return context
end
end


--[[
---Функция для оформления утверждений (statement)
Функция для оформления утверждений (statement)
---Подробнее о утверждениях см. d:Wikidata:Glossary/ru
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
---@param options table
---@return string Formatted wikitext.
local function formatProperty( options )
    -- Получение сущности по идентификатору
    local entity = getEntityFromId( options.entityId )
    if not entity then
        return -- throwError( 'entity-not-found' )
    end
    -- проверка на присутсвие у сущности заявлений (claim)
    -- подробнее о заявлениях см. d:Викиданные:Глоссарий
    if not entity.claims then
        return '' --TODO error?
    end


Принимает: таблицу параметров
    -- improve options
Возвращает: строку оформленного текста, предназначенного для отображения в статье
    options.frame = g_frame
]]
    options.entity = entity
local function formatProperty( options )
    options.extends = function( self, newOptions )
-- Получение сущности по идентификатору
        return copyTo( newOptions, copyTo( self, {} ) )
local entity = getEntityFromId( options.entityId )
    end
if not entity then
return -- throwError( 'entity-not-found' )
end
-- проверка на присутсвие у сущности заявлений (claim)
-- подробнее о заявлениях см. d:Викиданные:Глоссарий
if (entity.claims == nil) then
return '' --TODO error?
end


-- improve options
    if options.i18n then
options.frame = g_frame;
        options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) )
options.entity = entity;
    else
options.extends = function( self, newOptions )
        options.i18n = getConfig( 'i18n' )
return copyTo( newOptions, copyTo( self, {} ) )
    end
end


if ( options.i18n ) then
    local context = initContext( options )
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
local context = initContext( options );


return context.formatProperty( options );
    return context.formatProperty( options )
end
end


--[[
---Функция для оформления одного утверждения (statement)
Функция для оформления одного утверждения (statement)
---@param context table
 
---@param options table
Принимает: объект-таблицу утверждение и таблицу параметров
---@param statement table
Возвращает: строку оформленного текста с заявлением (claim)
---@return string Formatted wikitext.
]]
function formatStatement( context, options, statement )
function formatStatement( context, options, statement )
if ( not statement ) then
    if not statement then
error( 'statement is not specified or nil' );
        error( 'statement is not specified or nil' )
end
    end
if not statement.type or statement.type ~= 'statement' then
    if not statement.type or statement.type ~= 'statement' then
throwError( 'unknown-claim-type' )
        throwError( 'unknown-claim-type' )
end
    end


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


---@param statement table
---@return table
function getSourcingCircumstances( statement )
function getSourcingCircumstances( statement )
if (not statement) then error('statement is not specified') end;
    if not statement then
        error( 'statement is not specified' )
    end


local circumstances = {};
    local circumstances = {}
if ( statement.qualifiers
    if statement.qualifiers and statement.qualifiers.P1480 then
and statement.qualifiers.P1480 ) then
        for _, qualifier in pairs( statement.qualifiers.P1480 ) do
for i, qualifier in pairs( statement.qualifiers.P1480 ) do
            if qualifier
if ( qualifier
                    and qualifier.datavalue
and qualifier.datavalue
                    and qualifier.datavalue.type == 'wikibase-entityid'
and qualifier.datavalue.type == 'wikibase-entityid'
                    and qualifier.datavalue.value
and qualifier.datavalue.value
                    and qualifier.datavalue.value[ 'entity-type'] == 'item'
and qualifier.datavalue.value['entity-type'] == 'item' ) then
            then
table.insert(circumstances, qualifier.datavalue.value.id)
                table.insert( circumstances, qualifier.datavalue.value.id )
end
            end
end
        end
end
    end
return circumstances;
    return circumstances
end
end


--[[
---Функция для оформления одного утверждения (statement)
Функция для оформления одного утверждения (statement)
---@param context table Context.
---@param options table Parameters.
---@param statement table
---@return string Formatted wikitext.
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 )
объект-функцию оформления внутренних структур утверждения (snak) и
объект-функцию оформления ссылки на источники (reference)
Возвращает: строку оформленного текста с заявлением (claim)
]]
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 );
    options.qualifiers = statement.qualifiers


options.qualifiers = statement.qualifiers;
    local result = context.formatSnak( options, statement.mainsnak, circumstances )


local result = context.formatSnak( options, statement.mainsnak, circumstances );
     if options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] then
        local qualifierConfig = getPropertyParams( options.qualifier, nil, {} )
     if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
        if options.i18n then
    qualConfig = getPropertyParams( options.qualifier, nil, {})
            qualifierConfig.i18n = options.i18n
    if options.i18n then qualConfig.i18n = options.i18n end
        end
    local qualifierValues = {};
        if qualifierConfig.datatype == 'time' then
for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
            qualifierConfig.nolinks = true
local snakValue = context.formatSnak( qualConfig, qualifierSnak );
        end
if snakValue and snakValue ~= '' then
        local qualifierValues = {}
table.insert( qualifierValues, snakValue );
        for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
end
            local snakValue = context.formatSnak( qualifierConfig, qualifierSnak )
end
            if snakValue and snakValue ~= '' then
if ( result and result ~= '' and #qualifierValues ) then
                table.insert( qualifierValues, snakValue )
if qualConfig.invisible then  
            end
        result = result .. table.concat( qualifierValues, ', ' );
        end
else
        if result and result ~= '' and #qualifierValues then
        result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
            if qualifierConfig.invisible then
        end
                result = result .. table.concat( qualifierValues, ', ' )
            else
                result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')'
            end
         end
         end
     end
     end


if ( result and result ~= '' and options.references ) then
    if result and result ~= '' and options.references then
result = result .. context.formatRefs( options, statement );
        result = result .. context.formatRefs( options, statement )
end
    end


return result;
    return result
end
end


--[[
---Функция для оформления части утверждения (snak)
Функция для оформления части утверждения (snak)
---Подробнее о snak см. d:Викиданные:Глоссарий
Подробнее о snak см. d:Викиданные:Глоссарий
---@param context table Context.
---@param options table Parameters.
---@param snak table
---@param circumstances table
---@return string Formatted wikitext.
function formatSnak( context, options, snak, circumstances )
    circumstances = circumstances or {}
    local result


Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций
    if snak.snaktype == 'somevalue' then
Возвращает: строку оформленного викитекста
        if options[ 'somevalue' ] and options[ 'somevalue' ] ~= '' then
]]
            result = options[ 'somevalue' ]
function formatSnak( context, options, snak, circumstances )
        else
circumstances = circumstances or {};
            result = options.i18n[ 'somevalue' ]
        end
    elseif snak.snaktype == 'novalue' then
        if options[ 'novalue' ] and options[ 'novalue' ] ~= '' then
            result = options[ 'novalue' ]
        else
            result = options.i18n[ 'novalue' ]
        end
    elseif snak.snaktype == 'value' then
        result = formatDatavalue( context, options, snak.datavalue, snak.datatype )
        for _, item in pairs( circumstances ) do
            if options.i18n[ item ] then
                result = options.i18n[ item ] .. result
            end
        end
    else
        throwError( 'unknown-snak-type' )
    end


if snak.snaktype == 'somevalue' then
    if not result or result == '' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
        return nil
result = options['somevalue'];
    end
else
   
result = options.i18n['somevalue'];
    if options.plain then
end
    return result
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
result = options['novalue'];
else
result = options.i18n['novalue'];
end
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
for _, item in pairs(circumstances) do
if options.i18n[item] then
result = options.i18n[item] .. result;
end
end
else
throwError( 'unknown-snak-type' );
end
if ( not result or result == '' ) then
return nil;
end
end


return context.wrapSnak( result, snak.hash )
    return context.wrapSnak( result, snak.hash )
end
end


--[[
---Функция для оформления объектов-значений с географическими координатами
Функция для оформления объектов-значений с географическими координатами
---@param value string Raw value.
---@param options table Parameters.
---@return string Formatted string.
local function formatGlobeCoordinate( value, options )
    -- проверка на требование в параметрах вызова на возврат сырого значения
    if options[ 'subvalue' ] == 'latitude' then -- широты
        return value[ 'latitude' ]
    elseif options[ 'subvalue' ] == 'longitude' then -- долготы
        return value[ 'longitude' ]
    elseif options[ 'nocoord' ] and options[ 'nocoord' ] ~= '' then
        -- если передан параметр nocoord, то не выводить координаты
        -- обычно это делается при использовании нескольких карточек на странице
        return ''
    else
        -- в противном случае формируются параметры для вызова шаблона {{coord}}
        -- нужно дописать в документации шаблона, что он отсюда вызывается, и что
        -- любое изменние его парамеров  должно быть согласовано с кодом тут
 
        local coordModule = require( 'Module:Coordinates' )
 
        local globe = options.globe or ''
        if globe == '' and value[ 'globe' ] then
            local globes = require( 'Module:Wikidata/Globes' )
            globe = globes[ value[ 'globe' ] ] or ''
        end
 
        local display = 'inline'
        if options.display and options.display ~= '' then
            display = options.display
        elseif ( options.property:upper() == 'P625' ) then
            display = 'title'
        end
 
        local format = options.format or ''
        if format == '' then
            format = 'dms'
            if value[ 'precision' ] then
                local precision = value[ 'precision' ] * 60
                if precision >= 60 then
                    format = 'd'
                elseif precision >= 1 then
                    format = 'dm'
                end
            end
        end
 
        g_frame.args = {
            tostring( value[ 'latitude' ] ),
            tostring( value[ 'longitude' ] ),
            globe = globe,
            type = options.type and options.type or '',
            scale = options.scale and options.scale or '',
            display = display,
            format = format,
        }


Принимает: объект-значение и таблицу параметров,
        return coordModule.coord(g_frame)
Возвращает: строку оформленного текста
    end
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
return value['latitude']
elseif options['subvalue'] == 'longitude' then -- долготы
return value['longitude']
elseif options['nocoord'] and options['nocoord'] ~= '' then
-- если передан параметр nocoord, то не выводить координаты
-- обычно это делается при использовании нескольких карточек на странице
return ''
else
-- в противном случае формируются параметры для вызова шаблона {{coord}}
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров  должно быть согласовано с кодом тут
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or ''
if globe == '' and value['globe'] then
globes = require( 'Module:Wikidata/Globes' )
globe = globes[value['globe']] or ''
end
local display = 'inline'
if options.display and options.display ~= '' then
display = options.display
elseif ( options.property:upper() == 'P625' ) then
display = 'title'
end
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display  }
return coord_mod.coord(g_frame)
end
end
end


--[[
---Функция для оформления объектов-значений с файлами с Викисклада
Функция для оформления объектов-значений с файлами с Викисклада
---@param value string Raw value.
---@param options table Parameters.
---@return string Formatted string.
local function formatCommonsMedia( value, options )
    local image = value


Принимает: объект-значение и таблицу параметров,
    local caption = ''
Возвращает: строку оформленного текста
    if options[ 'caption' ] and options[ 'caption' ] ~= '' then
]]
        caption = options[ 'caption' ]
local function formatCommonsMedia( value, options )
    end
local image = value;
    if caption ~= '' then
        caption = wrapQualifier( caption, 'P2096', { class = 'media-caption', style = 'display:block' } )
    end


local caption = '';
    if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
if options[ 'caption' ] and options[ 'caption' ] ~= '' then
        -- если в value не содержится викикод или imagemap, то викифицируем имя файла
caption = options[ 'caption' ];
        -- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[phab:T28213]]
end
        image = '[[File:' .. value .. '|frameless'
if caption ~= '' then
        if options[ 'border' ] and options[ 'border' ] ~= '' then
caption = wrapQualifier( caption, 'P2096', { class = 'media-caption', style = 'display:block' } );
            image = image .. '|border'
end
        end


if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
        local size = options[ 'size' ]
-- если в value не содержится викикод или imagemap, то викифицируем имя файла
        if size and size ~= '' then
-- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[PHAB:T28213]]
            -- TODO: check localized pixel names too
image = '[[File:' .. value .. '|frameless';
            if not string.match( size, 'px$' ) then
if options[ 'border' ] and options[ 'border' ] ~= '' then
                size = size .. 'px'
image = image .. '|border';
            end
end
        else
            size = fileDefaultSize
        end
        image = image .. '|' .. size


local size = options[ 'size' ];
        if options[ 'alt' ] and options[ 'alt' ] ~= '' then
if size and size ~= '' then
            image = image .. '|alt=' .. options[ 'alt' ]
-- TODO: check localized pixel names too
        end
if not string.match( size, 'px$' ) then
size = size .. 'px'
end
else
size = fileDefaultSize;
end
image = image .. '|' .. size;


if options[ 'alt' ] and options[ 'alt' ] ~= '' then
        if caption ~= '' then
image = image .. '|alt=' .. options[ 'alt' ];
            image = image .. '|' .. caption
end
        end
        image = image .. ']]'
if caption ~= '' then
image = image .. '|' .. caption
end
image = image .. ']]';


if caption ~= '' then
        if caption ~= '' then
image = image .. '<br>' .. caption;
            image = image .. '<br>' .. caption
end
        end
else
    else
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
        image = image .. caption .. getCategoryByCode( 'media-contains-markup' )
end
    end


return image
    return image
end
end


--[[
---Function for render math formulas
Fonction for render math formulas
---@param value string Value.
 
---@param options table Parameters.
@param string Value.
---@return string Formatted string.
@param table Parameters.
@return string Formatted string.
]]
local function formatMath( value, options )
local function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
    return options.frame:extensionTag{ name = 'math', content = value }
end
end


--[[
---Функция для оформления внешних идентификаторов
Функция для оформления внешних идентификаторов
---@param value string
---@param options table
---@return string
local function formatExternalId( value, options )
    local formatter = options.formatter
    local propertyId = options.property:upper()


Принимает: объект-значение и таблицу параметров,
    if not formatter or formatter == '' then
Возвращает: строку оформленного текста
        local isGoodFormat = false
]]
 
local function formatExternalId( value, options )
        local wbStatus, formatRegexStatements = pcall( mw.wikibase.getBestStatements, propertyId, 'P1793' )
local formatter = options.formatter;
        if wbStatus and formatRegexStatements then
            for _, statement in pairs( formatRegexStatements ) do
                if statement.mainsnak.snaktype == 'value' then
                    local pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' )
                    pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' )
                    if ( string.find( pattern, '|' ) or string.find( pattern, '%)%?' )
                            or mw.ustring.match( value, '^' .. pattern .. '$' ) ~= nil ) then
                        isGoodFormat = true
                        break
                    end
                end
            end
        end


if not formatter or formatter == '' then
        if isGoodFormat then
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, options.property:upper() )
            local formatterStatements
if wbStatus == true and propertyEntity then
            wbStatus, formatterStatements = pcall( mw.wikibase.getBestStatements, propertyId, 'P1630' )
local isGoodFormat = false;
            if wbStatus and formatterStatements then
local statements = propertyEntity:getBestStatements( 'P1793' );
                for _, statement in pairs( formatterStatements ) do
for _, statement in pairs( statements ) do
                    if statement.mainsnak.snaktype == 'value' then
if statement.mainsnak.snaktype == 'value' then
                        formatter = statement.mainsnak.datavalue.value
local pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
                        break
pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' );
                    end
if ( string.find( pattern, '|' ) or string.find( pattern, '%)%?' )
                end
or mw.ustring.match( value, '^' .. pattern .. '$' ) ~= nil ) then
            end
isGoodFormat = true;
        end
break;
    end
end
end
end


if ( isGoodFormat == true ) then
    if formatter and formatter ~= '' then
statements = propertyEntity:getBestStatements( 'P1630' );
        local encodedValue = mw.ustring.gsub( value, '%%', '%%%%' ) -- ломается, если подставить внутрь другого mw.ustring.gsub
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
formatter = statement.mainsnak.datavalue.value;
break
end
end
end
end
end


if formatter and formatter ~= '' then
        local link = mw.ustring.gsub(
local encodedValue = mw.ustring.gsub( value, '%%', '%%%%' ) -- ломается, если подставить внутрь другого mw.ustring.gsub
                mw.ustring.gsub( formatter, '$1', encodedValue ), '.',
                { [ ' ' ] = '%20', [ '+' ] = '%2b', [ '[' ] = '%5B', [ ']' ] = '%5D' } )
local link = mw.ustring.gsub(  
mw.ustring.gsub( formatter, '$1', encodedValue ), '.',
{ [' '] = '%20', ['+'] = '%2b', ['['] = '%5B', [']'] = '%5D' } )


local title = options.title
        local title = options.title
if not title or title == '' then
        if not title or title == '' then
title = '$1'
            title = '$1'
end
        end
title = mw.ustring.gsub(  
        title = mw.ustring.gsub(
mw.ustring.gsub( title, '$1', encodedValue ), '.',  
                mw.ustring.gsub( title, '$1', encodedValue ), '.',
{ ['['] = '(', [']'] = ')' } )
                { [ '[' ] = '(', [ ']' ] = ')' } )


return '[' .. link .. ' ' .. title .. ']'
        return '[' .. link .. ' ' .. title .. ']'
end
    end


return value
    return value
end
end


--[[
---Функция для оформления числовых значений
Функция для оформления числовых значений
---@param value table Объект-значение
---@param options table Таблица параметров
---@return string Оформленный текст
local function formatQuantity( value, options )
    -- диапазон значений
    local amount = string.gsub( value.amount, '^%+', '' )
    local lang = mw.language.getContentLanguage()
    local langCode = lang:getCode()
 
    local function formatNum( number, sigfig )
        local multiplier = ''
 
        if options.countByThousands then
            local powers = options.i18n.thousandPowers
            local pos = 1
            while math.abs( number ) >= 1000 and pos < #powers do
                number = number / 1000
                pos = pos + 1
            end
            multiplier = powers[ pos ]
 
            if math.abs( number ) >= 100 then
                sigfig = sigfig or 0
            elseif math.abs( number ) >= 10 then
                sigfig = sigfig or 1
            else
                sigfig = sigfig or 2
            end
        else
            sigfig = sigfig or 12 -- округление до 12 знаков после запятой, на 13-м возникает ошибка в точности
        end


Принимает: объект-значение и таблицу параметров,
        local iMultiplier = 10^sigfig
Возвращает: строку оформленного текста
        number = math.floor( number * iMultiplier + 0.5 ) / iMultiplier
]]
        return string.gsub( lang:formatNum( number ), '^-', '−' ) .. multiplier
local function formatQuantity( value, options )
    end
-- диапазон значений
 
local amount = string.gsub( value['amount'], '^%+', '' );
    local out = formatNum( tonumber( amount ) )
local lang = mw.language.getContentLanguage();
    if value.upperBound then
local langCode = lang:getCode();
        local diff = tonumber( value.upperBound ) - tonumber( amount )
        if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
            -- Пробуем понять до какого знака округлять
            local integer, dot, decimals, _ = value.upperBound:match( '^+?-?(%d*)(%.?)(%d*)(.*)' )
            local precision
            if dot == '' then
                precision = -integer:match( '0*$' ):len()
            else
                precision = #decimals
            end
            local bound = formatNum( diff, precision )
            if string.match( bound, 'E%-(%d+)' ) then -- если в экспоненциальном формате
                local digits = tonumber( string.match( bound, 'E%-(%d+)' ) ) - 2
                bound = formatNum( diff * 10 ^ digits, precision )
                bound = string.sub( bound, 0, 2 ) .. string.rep( '0', digits ) .. string.sub( bound, -string.len( bound ) + 2 )
            end
            out = out .. ' ± ' .. bound
        end
    end
 
    if options.unit and options.unit ~= '' then
        if options.unit ~= '-' then
            out = out .. ' ' .. options.unit
        end
    elseif value.unit and string.match( value.unit, 'http://www.wikidata.org/entity/' ) then
        local unitEntityId = string.gsub( value.unit, 'http://www.wikidata.org/entity/', '' )
        if unitEntityId ~= 'undefined' then
            local wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId )
            if wbStatus == true and unitEntity then
                if unitEntity.claims.P2370 and
                        unitEntity.claims.P2370[ 1 ].mainsnak.snaktype == 'value' and
                        not value.upperBound and
                        options.siConversion == true
                then
                    local conversionToSiUnit = string.gsub( unitEntity.claims.P2370[ 1 ].mainsnak.datavalue.value.amount, '^%+', '' )
                    if math.floor( math.log10( conversionToSiUnit ) ) ~= math.log10( conversionToSiUnit ) then
                        -- Если не степени десятки (переводить сантиметры в метры не надо!)
                        local outValue = tonumber( amount ) * conversionToSiUnit


local function formatNum( number, sigfig )
                        if outValue > 0 then
local multiplier = ''
                            -- Пробуем понять до какого знака округлять
                            local integer, dot, decimals, _ = amount:match( '^(%d*)(%.?)(%d*)(.*)' )
if options.countByThousands then
                            local precision
local powers = options.i18n['thousandPowers']
                            if dot == '' then
local pos = 1
                                precision = -integer:match( '0*$' ):len()
while math.abs(number) >= 1000 and pos < #powers do
                            else
number = number / 1000
                                precision = #decimals
pos = pos + 1
                            end
end
                            local adjust = math.log10( math.abs( conversionToSiUnit ) ) + math.log10( 2 )
multiplier = powers[pos]
                            local minPrecision = 1 - math.floor( math.log10( outValue ) + 2e-14 )
                            out = formatNum( outValue, math.max( math.floor( precision + adjust ), minPrecision ) )
if math.abs(number) >= 100 then
                        else
sigfig = sigfig or 0
                            out = formatNum( outValue, 0 )
elseif math.abs(number) >= 10 then
                        end
sigfig = sigfig or 1
                        unitEntityId = string.gsub( unitEntity.claims.P2370[ 1 ].mainsnak.datavalue.value.unit, 'http://www.wikidata.org/entity/', '' )
else
                        wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId )
sigfig = sigfig or 2
                    end
end
                end
else
sigfig = sigfig or 12 -- округление до 12 знаков после запятой, на 13-м возникает ошибка в точности
end
local mult = 10^sigfig;
number = math.floor( number * mult + 0.5 ) / mult;
return string.gsub( lang:formatNum( number ), '^-', '' ) .. multiplier;
end


local out = formatNum( tonumber( amount ) );
                local label = getLabelWithLang( context, options, unitEntity.id, nil, { "P5061", "P558", "P558" }, {
if value.upperBound then
                    'P5061[language:' .. langCode .. ']',
local diff = tonumber( value.upperBound ) - tonumber( amount )
                    'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
                    'P558[!P282][!P407]'
-- Пробуем понять до какого знака округлять
                } )
local integer, dot, decimals, expstr = value.upperBound:match( '^+?-?(%d*)(%.?)(%d*)(.*)' )
local prec
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
bound = formatNum( diff, prec )
if string.match( bound, 'E%-(%d+)' ) then -- если в экспоненциальном формате
digits = tonumber( string.match( bound, 'E%-(%d+)' ) ) - 2
bound = formatNum( diff * 10 ^ digits, prec )
bound = string.sub( bound, 0, 2 ) .. string.rep( '0', digits ) .. string.sub( bound, -string.len( bound ) + 2 )
end
out = out .. ' ± ' .. bound
end
end


if options.unit and options.unit ~= '' then
                out = out .. ' ' .. label
if options.unit ~= '-' then
            end
out = out .. ' ' .. options.unit
        end
end
    end
elseif value.unit and string.match( value.unit, 'http://www.wikidata.org/entity/' ) then
local unitEntityId = string.gsub( value.unit, 'http://www.wikidata.org/entity/', '' );
if unitEntityId ~= 'undefined' then
local wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
if wbStatus == true and unitEntity then
if unitEntity.claims.P2370 and
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
not value.upperBound and
options.siConversion == true
then
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
-- Если не степени десятки (переводить сантиметры в метры не надо!)
outValue = tonumber( amount ) * conversionToSIunit
if ( outValue > 0 ) then
-- Пробуем понять до какого знака округлять
local integer, dot, decimals, expstr = amount:match( '^(%d*)(%.?)(%d*)(.*)' )
local prec
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
local adjust = math.log10( math.abs( conversionToSIunit )) + math.log10( 2 )
local minprec = 1 - math.floor( math.log10( outValue ) + 2e-14 );
out = formatNum( outValue, math.max( math.floor( prec + adjust ), minprec ));
else
out = formatNum( outValue, 0 )
end
unitEntityId = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.unit, 'http://www.wikidata.org/entity/', '' );
wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
end
end
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
local label = getLabelWithLang( context, options, unitEntity.id, nil, { "P5061", "P558", "P558" }, {
'P5061[language:' .. langCode .. ']',
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
'P558[!P282][!P407]'
} );
out = out .. ' ' .. label;
end
end
end


return out;
    return out
end
end


-- Функция для оформления URL
---Функция для оформления URL
---@param context table
---@param options table
---@param value string
local function formatUrlValue( context, options, value )
local function formatUrlValue( context, options, value )
if not options.length or options.length == '' then
    if not options.length or options.length == '' then
options.length = 25
        options.length = 25
end
    end


local moduleUrl = require( 'Module:URL' )
    local moduleUrl = require( 'Module:URL' )
return moduleUrl.formatUrlSingle( context, options, value )
    return moduleUrl.formatUrlSingle( context, options, value )
end
end


local DATATYPE_CACHE = {}
local DATATYPE_CACHE = {}


--[[
---Get property datatype by ID.
Get property datatype by ID.
---@param propertyId string Property ID, e.g. 'P123'.
---@return string Property datatype, e.g. 'commonsMedia', 'time' or 'url'.
local function getPropertyDatatype( propertyId )
    if not propertyId or not string.match( propertyId, '^P%d+$' ) then
        return nil
    end
 
    local cached = DATATYPE_CACHE[ propertyId ]
    if cached ~= nil then
        return cached
    end


@param string Property ID, e.g. 'P123'.
    local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId )
@return string Property datatype, e.g. 'commonsMedia', 'time' or 'url'.
    if wbStatus ~= true or not propertyEntity then
]]
        return nil
local function getPropertyDatatype( propertyId )
    end
if not propertyId or not string.match( propertyId, '^P%d+$' ) then
    mw.log("Loaded datatype " .. propertyEntity.datatype .. " of " .. propertyId .. ' from wikidata, consider passing datatype argument to formatProperty call or to Wikidata/config' )
return nil;
 
end
    DATATYPE_CACHE[ propertyId ] = propertyEntity.datatype
    return propertyEntity.datatype
local cached = DATATYPE_CACHE[propertyId];
end
if (cached ~= nil) then return cached; end


local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
---@param datavalue table
if wbStatus ~= true or not propertyEntity then
---@return function
return nil;
local function getPlainValueFunction( datavalue, _ )
end
    if datavalue.type == 'wikibase-entityid' then
mw.log("Loaded datatype " .. propertyEntity.datatype .. " of " .. propertyId .. ' from wikidata, consider passing datatype argument to formatProperty call or to Wikidata/config' )
        return function( _, _, value )
            return getEntityIdFromValue( value )
        end
    elseif datavalue.type == 'string' then
        return function( _, _, value )
            return value
        end
    elseif datavalue.type == 'monolingualtext' then
        return function( _, _, value )
            return value.text
        end
    elseif datavalue.type == 'globecoordinate' then
        return function( _, _, value )
            return value.latitude .. ',' .. value.longitude
        end
    elseif datavalue.type == 'quantity' then
        return function( _, _, value )
            return value.amount
        end
    elseif datavalue.type == 'time' then
        return function( _, _, value )
            return value.time
        end
    end


DATATYPE_CACHE[propertyId] = propertyEntity.datatype;
    throwError( 'unknown-datavalue-type' )
return propertyEntity.datatype;
end
end


---@param datavalue table
---@param datatype string
---@return function
local function getDefaultValueFunction( datavalue, datatype )
local function getDefaultValueFunction( datavalue, datatype )
-- вызов обработчиков по умолчанию для известных типов значений
    -- вызов обработчиков по умолчанию для известных типов значений
if datavalue.type == 'wikibase-entityid' then
    if datavalue.type == 'wikibase-entityid' then
-- Entity ID
        -- Entity ID
return function( context, options, value ) return formatEntityId( context, options, getEntityIdFromValue( value ) ) end;
        return function( context, options, value )
elseif datavalue.type == 'string' then
            return formatEntityId( context, options, getEntityIdFromValue( value ) )
-- String
        end
if datatype and datatype == 'commonsMedia' then
    elseif datavalue.type == 'string' then
-- Media
        -- String
return function( context, options, value )
        if datatype and datatype == 'commonsMedia' then
return formatCommonsMedia( value, options )
            -- Media
end;
            return function( _, options, value )
elseif datatype and datatype == 'external-id' then
                return formatCommonsMedia( value, options )
-- External ID
            end
return function( context, options, value )
        elseif datatype and datatype == 'external-id' then
return formatExternalId( value, options )
            -- External ID
end
            return function( _, options, value )
elseif datatype and datatype == 'math' then
                return formatExternalId( value, options )
-- Math formula
            end
return function( context, options, value )
        elseif datatype and datatype == 'math' then
return formatMath( value, options )
            -- Math formula
end
            return function( _, options, value )
elseif datatype and datatype == 'url' then
                return formatMath( value, options )
-- URL
            end
return formatUrlValue
        elseif datatype and datatype == 'url' then
end
            -- URL
return function( context, options, value ) return value end;
            return formatUrlValue
elseif datavalue.type == 'monolingualtext' then
        end
-- моноязычный текст (строка с указанием языка)
        return function( _, _, value )
return function( context, options, value )
            return value
if ( options.monolingualLangTemplate == 'lang' ) then
        end
if ( value.language == contentLanguageCode ) then
    elseif datavalue.type == 'monolingualtext' then
return value.text;
        -- моноязычный текст (строка с указанием языка)
end
        return function( _, options, value )
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
            if options.monolingualLangTemplate == 'lang' then
elseif ( options.monolingualLangTemplate == 'ref' ) then
                if value.language == CONTENT_LANGUAGE_CODE then
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
                    return value.text
else
                end
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
                return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } }
end
            elseif options.monolingualLangTemplate == 'ref' then
end;
                return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language }
elseif datavalue.type == 'globecoordinate' then
            else
-- географические координаты
                return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>'
return function( context, options, value ) return formatGlobeCoordinate( value, options ) end;
            end
elseif datavalue.type == 'quantity' then
        end
return function( context, options, value ) return formatQuantity( value, options ) end;
    elseif datavalue.type == 'globecoordinate' then
elseif datavalue.type == 'time' then
        -- географические координаты
return function( context, options, value )
        return function( _, options, value )
local moduleDate = require( 'Module:Wikidata/date' )
            return formatGlobeCoordinate( value, options )
return moduleDate.formatDate( context, options, value );
        end
end;
    elseif datavalue.type == 'quantity' then
else
        return function( _, options, value )
-- во всех стальных случаях возвращаем ошибку
            return formatQuantity( value, options )
throwError( 'unknown-datavalue-type' )
        end
end
    elseif datavalue.type == 'time' then
        return function( context, options, value )
            local moduleDate = require( 'Module:Wikidata/date' )
            return moduleDate.formatDate( context, options, value )
        end
    end
 
    -- во всех стальных случаях возвращаем ошибку
    throwError( 'unknown-datavalue-type' )
end
end


--[[
---Функция для оформления значений (value)
Функция для оформления значений (value)
---Подробнее о значениях  см. d:Wikidata:Glossary/ru
Подробнее о значениях  см. d:Wikidata:Glossary/ru
---@param context table
 
---@param options table
Принимает: объект-значение и таблицу параметров,
---@param datavalue table
Возвращает: строку оформленного текста
---@param datatype string
]]
---@return string Оформленный текст
function formatDatavalue( context, options, datavalue, datatype )
function formatDatavalue( context, options, datavalue, datatype )
if ( not context ) then error( 'context not specified' ); end;
    if not context then error( 'context not specified' ); end
if ( not options ) then error( 'options not specified' ); end;
    if not options then error( 'options not specified' ); end
if ( not datavalue ) then error( 'datavalue not specified' ); end;
    if not datavalue then error( 'datavalue not specified' ); end
if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;
    if not datavalue.value then error( 'datavalue.value is missing' ); end


-- проверка на указание специализированных обработчиков в параметрах,
    -- проверка на указание специализированных обработчиков в параметрах,
-- переданных при вызове
    -- переданных при вызове
context.formatValueDefault = getDefaultValueFunction( datavalue, datatype );
    if options.plain then
local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
        context.formatValueDefault = getPlainValueFunction( datavalue, datatype )
return functionToCall( context, options, datavalue.value );
    else
        context.formatValueDefault = getDefaultValueFunction( datavalue, datatype )
    end
    local functionToCall = getUserFunction( options, 'value', context.formatValueDefault )
    return functionToCall( context, options, datavalue.value )
end
end


local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000}
 
--[[
Функция для оформления идентификатора сущности


Принимает: строку индентификатора (типа Q42) и таблицу параметров,
---Функция для оформления идентификатора сущности
Возвращает: строку оформленного текста
---@param context table
]]
---@param options table
---@param entityId string
---@return string Оформленный текст
function formatEntityId( context, options, entityId )
function formatEntityId( context, options, entityId )
-- получение локализованного названия
    -- получение локализованного названия
local boundaries = nil
    local boundaries
if options.qualifiers then
    if options.qualifiers then
boundaries = p.getTimeBoundariesFromQualifiers( frame, context, { qualifiers = options.qualifiers } )
        boundaries = p.getTimeBoundariesFromQualifiers( context.frame, context, { qualifiers = options.qualifiers } )
end
    end
if not boundaries then
    if not boundaries then
boundaries = DEFAULT_BOUNDARIES;
        boundaries = DEFAULT_BOUNDARIES
end
    end
local label, labelLanguageCode = getLabelWithLang( context, options, entityId, boundaries )
    local label, labelLanguageCode = getLabelWithLang( context, options, entityId, boundaries )


-- определение соответствующей показываемому элементу категории
    -- определение соответствующей показываемому элементу категории
local category = p.extractCategory( context, options, { id = entityId } )
    local category = context.extractCategory( options, { id = entityId } )


-- получение ссылки по идентификатору
    -- получение ссылки по идентификатору
local link = mw.wikibase.sitelink( entityId )
    local link = mw.wikibase.sitelink( entityId )
if link then
    if link then
-- ссылка на категорию, а не добавление страницы в неё
        -- ссылка на категорию, а не добавление страницы в неё
if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
        if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
link = ':' .. link
            link = ':' .. link
end
        end
if label and not options.rawArticle then
        if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
            if labelLanguageCode ~= CONTENT_LANGUAGE_CODE then
if ( contentLanguageCode ~= labelLanguageCode ) then
                label = '<span lang="' .. label .. '">' .. label .. '</span>'
return a .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
            end
else
            local a = '[[' .. link .. '|' .. label .. ']]'
return a .. category;
            if CONTENT_LANGUAGE_CODE ~= labelLanguageCode and 'mul' ~= labelLanguageCode then
end
                a = a .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' )
else
            end
return '[[' .. link .. ']]' .. category;
            return a .. category
end
        else
end
            return '[[' .. link .. ']]' .. category
        end
    end


if label then  -- TODO: возможно, лучше просто mw.wikibase.label(entityId)
    if label then  -- TODO: возможно, лучше просто mw.wikibase.getLabel(entityId)
-- красная ссылка
        -- красная ссылка
-- TODO: разобраться, почему не всегда есть options.frame
        -- TODO: разобраться, почему не всегда есть options.frame
local title = mw.title.new( label );
        local title = mw.title.new( label )
if title and not title.exists and options.frame then
        if title and not title.exists and options.frame then
local moduleRedLink = require( 'Module:Wikidata/redLink' )
            local moduleRedLink = require( 'Module:Wikidata/redLink' )
local rawLabel = mw.wikibase.label(entityId) or label -- без |text= и boundaries; or label - костыль
            local rawLabel = mw.wikibase.getLabel(entityId) or label -- без |text= и boundaries; or label - костыль
local redLink = moduleRedLink.formatRedLinkWithInfobox(rawLabel, label, entityId)
            local redLink = moduleRedLink.formatRedLinkWithInfobox(rawLabel, label, entityId)
return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category
            if CONTENT_LANGUAGE_CODE ~= labelLanguageCode and 'mul' ~= labelLanguageCode then
end
                redLink = '<span lang="' .. labelLanguageCode .. '">' .. redLink .. '</span>' ..
                        getCategoryByCode( 'links-to-entities-with-missing-local-language-label' )
            end
            return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category
        end


-- TODO: перенести до проверки на существование статьи
        -- TODO: перенести до проверки на существование статьи
local sup = '';
        local sup = ''
if ( not options.format or options.format ~= 'text' )
        if ( not options.format or options.format ~= 'text' )
and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: переписать на format=text
                and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: переписать на format=text
then
        then
sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d&#x5d;]</sup>'
            sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. CONTENT_LANGUAGE_CODE .. ' [d&#x5d;]</sup>'
end
        end


-- одноимённая статья уже существует - выводится текст и ссылка на ВД
        -- одноимённая статья уже существует - выводится текст и ссылка на ВД
return '<span class="iw" data-title="' .. label .. '">' .. label
        return '<span class="iw" data-title="' .. label .. '">' .. label
.. sup
                .. sup
.. '</span>' .. category
                .. '</span>' .. category
end
    end
-- сообщение об отсутвии локализованного названия
    -- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
    -- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' ) .. category;
    return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' ) .. category
end
end


--[[
---Функция для оформления утверждений (statement)
Функция для формирования категории на основе wikidata/config
---Подробнее о утверждениях см. d:Wikidata:Glossary/ru
]]
---@deprecated Use p.formatProperty() instead
function p.extractCategory( context, options, value )
---@param frame table
if ( not options.category or options.nocat ) then
---@return string Строка оформленного текста, предназначенная для отображения в статье
return '';
end
local propertyId = string.gsub( options.category, '([^Pp0-9].*)$', '');
local wbStatus, claims = pcall( mw.wikibase.getAllStatements, value.id, propertyId );
if ( wbStatus ~= true or not claims ) then return ''; end
allClaims = {}
allClaims[ propertyId ] = claims
claims = WDS.filter( allClaims, options.category )
if not claims then return ''; end
for _, claim in pairs( claims ) do
if ( claim
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'wikibase-entityid' ) then
local catEntityId = claim.mainsnak.datavalue.value.id;
local wbStatus, catSiteLink = pcall( mw.wikibase.getSitelink, catEntityId );
 
if ( wbStatus == true and catSiteLink ) then
return '[[' .. catSiteLink .. ']]';
end
end
end
 
return '';
end
--[[
Функция для оформления утверждений (statement)
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
 
Принимает: таблицу параметров
Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
-- устаревшее имя, не использовать
function p.formatStatements( frame )
function p.formatStatements( frame )
return p.formatProperty( frame );
    return p.formatProperty( frame )
end
end


--[[
---Получение параметров, которые обычно используются для вывода свойства.
Получение параметров, которые обычно используются для вывода свойства.
---@param propertyId string
]]
---@param datatype string
---@param params table
function getPropertyParams( propertyId, datatype, params )
function getPropertyParams( propertyId, datatype, params )
local config = getConfig();
    local config = getConfig()


-- Различные уровни настройки параметров, по убыванию приоритета
    -- Различные уровни настройки параметров, по убыванию приоритета
local propertyParams = {};
    local propertyParams = {}


-- 1. Параметры, указанные явно при вызове
    -- 1. Параметры, указанные явно при вызове
if params then
    if params then
for key, value in pairs( params ) do
        for key, value in pairs( params ) do
if value ~= '' then
            if value ~= '' then
propertyParams[ key ] = value;
                propertyParams[ key ] = value
end
            end
end
        end
    end
   
    if toBoolean( propertyParams.plain, false ) then
    propertyParams.separator = propertyParams.separator or ', '
propertyParams.conjunction = propertyParams.conjunction or ', '
else
    -- 2. Настройки конкретного параметра
    if config.properties and config.properties[ propertyId ] then
        for key, value in pairs( config.properties[ propertyId ] ) do
            if propertyParams[ key ] == nil then
                propertyParams[ key ] = value
            end
        end
    end
    -- 3. Указанный пресет настроек
    if propertyParams.preset and config.presets and
            config.presets[ propertyParams.preset ]
    then
        for key, value in pairs( config.presets[ propertyParams.preset ] ) do
            if propertyParams[ key ] == nil then
                propertyParams[ key ] = value
            end
        end
    end
    datatype = datatype or params.datatype or propertyParams.datatype or getPropertyDatatype( propertyId )
    if propertyParams.datatype == nil then
        propertyParams.datatype = datatype
    end
    -- 4. Настройки для типа данных
    if datatype and config.datatypes and config.datatypes[ datatype ] then
        for key, value in pairs( config.datatypes[ datatype ] ) do
            if propertyParams[ key ] == nil then
                propertyParams[ key ] = value
            end
        end
    end
    -- 5. Общие настройки для всех свойств
    if config.global then
        for key, value in pairs( config.global ) do
            if propertyParams[ key ] == nil then
                propertyParams[ key ] = value
            end
        end
    end
end
end


-- 2. Настройки конкретного параметра
    return propertyParams
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
for key, value in pairs( config[ 'properties' ][ propertyId ] ) do
if propertyParams[ key ] == nil then
propertyParams[ key ] = value;
end
end
end
 
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
config[ 'presets' ][ propertyParams[ 'preset' ] ]
then
for key, value in pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ] ) do
if propertyParams[ key ] == nil then
propertyParams[ key ] = value;
end
end
end
 
local datatype = datatype or params.datatype or propertyParams.datatype or getPropertyDatatype( propertyId );
if propertyParams.datatype == nil then
propertyParams.datatype = datatype;
end
 
-- 4. Настройки для типа данных
if datatype and config[ 'datatypes' ] and config[ 'datatypes' ][ datatype ] then
for key, value in pairs( config[ 'datatypes' ][ datatype ] ) do
if propertyParams[ key ] == nil then
propertyParams[ key ] = value;
end
end
end
 
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
for key, value in pairs( config[ 'global' ] ) do
if propertyParams[ key ] == nil then
propertyParams[ key ] = value;
end
end
end
 
return propertyParams;
end
end


---Функция для оформления утверждений (statement)
---Подробнее о утверждениях см. d:Wikidata:Glossary/ru
---@param frame table
---@return string Строка оформленного текста, предназначенная для отображения в статье
function p.formatProperty( frame )
function p.formatProperty( frame )
local args = frame.args
    local args = copyTo( frame.args, {} )


-- проверка на отсутствие обязательного параметра property
    -- проверка на отсутствие обязательного параметра property
if not args.property then
    if not args.property then
throwError( 'property-param-not-provided' )
        throwError( 'property-param-not-provided' )
end
    end
local override;
    local override
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '([^Pp0-9].*)$', function(w)  
    local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '([^Pp0-9].*)$', function(w)
if string.sub( w, 1, 1 ) == '~' then override = w; end
        if string.sub( w, 1, 1 ) == '~' then
return '';
            override = w
end ) )  
        end
args = getPropertyParams( propertyId, nil, args );
        return ''
if (override) then  
    end ) )
args[override:match('[,~]([^=]*)=')] = override:match('=(.*)')
 
args['property'] = propertyId
    if override then
end
        args[ override:match( '[,~]([^=]*)=' ) ] = override:match( '=(.*)' )
        args.property = propertyId
    end


local datatype = args.datatype;
    -- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
    local 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
        else
            args.entityId = mw.wikibase.getEntityIdForCurrentPage()
        end
        p_frame = p_frame:getParent()
    end


-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
    args = getPropertyParams( propertyId, nil, args )
p_frame = frame
    local datatype = args.datatype
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


args.plain = toBoolean( args.plain, false );
    -- перевод итоговых значений флагов в true/false и добавление значений
args.nocat = toBoolean( args.nocat, false );
    -- по умолчанию только в том случае, если они нигде не были указаны ранее
args.references = toBoolean( args.references, true );
    args.plain = toBoolean( args.plain, false )
    args.nocat = not args.plain and toBoolean( args.nocat, false )
    args.references = not args.plain and toBoolean( args.references, true )


-- если значение передано в параметрах вызова то выводим только его
    -- если значение передано в параметрах вызова то выводим только его
if args.value and args.value ~= '' then
    if args.value and args.value ~= '' then
-- специальное значение для скрытия Викиданных
        -- специальное значение для скрытия Викиданных
if args.value == '-' then
        if args.value == '-' then
return ''
            return ''
end
        end
local value = args.value
        local value = args.value


-- опция, запрещающая оформление значения, поэтому никак не трогаем
        -- опция, запрещающая оформление значения, поэтому никак не трогаем
if args.plain then
        if args.plain then
return value
            return value
end
        end


local context = initContext( args );
        local context = initContext( args )
-- обработчики по типу значения
        -- обработчики по типу значения
local wrapperExtraArgs = {}
        local wrapperExtraArgs = {}
if args['value-module'] and args['value-function'] and not string.find( value, '[%[%]%{%}]' ) then
        if args[ 'value-module' ] and args[ 'value-function' ] and not string.find( value, '[%[%]%{%}]' ) then
local func = getUserFunction( args, 'value' );
            local func = getUserFunction( args, 'value' )
value = func( context, args, value );
            value = func( context, args, value )
elseif datatype == 'commonsMedia' then
        elseif datatype == 'commonsMedia' then
value = formatCommonsMedia( value, args );
            value = formatCommonsMedia( value, args )
elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then
        elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then
wrapperExtraArgs['data-wikidata-external-id'] = value;
            wrapperExtraArgs[ 'data-wikidata-external-id' ] = mw.text.killMarkers( value )
value = formatExternalId( value, args );
            value = formatExternalId( value, args )
--elseif datatype == 'math' then
            --elseif datatype == 'math' then
-- args.frame = frame -- костыль: в formatMath нужно frame:extensionTag
            -- args.frame = frame -- костыль: в formatMath нужно frame:extensionTag
-- value = formatMath( value, args );
            -- value = formatMath( value, args )
elseif datatype == 'url' then
        elseif datatype == 'url' then
value = formatUrlValue( context, args, value );
            value = formatUrlValue( context, args, value )
end
        end


-- оборачиваем в тег для JS-функций
        -- оборачиваем в тег для JS-функций
if string.match( propertyId, '^P%d+$' ) then
        if string.match( propertyId, '^P%d+$' ) then
value = mw.text.trim( value )
            value = mw.text.trim( value )


-- временная штрафная категория для исправления табличных вставок
            -- временная штрафная категория для исправления табличных вставок
local allowTables = getPropertyParams(propertyId, nil, {})['allowTables']
            local allowTables = getPropertyParams( propertyId, nil, {} ).allowTables
if ( not allowTables
            if not allowTables
and string.match( value, '<t[dhr][ >]' )
                    and string.match( value, '<t[dhr][ >]' )
-- and not string.match( value, '<table[ >]' )
            -- and not string.match( value, '<table[ >]' )
-- and not string.match( value, '^%{%|' )
            -- and not string.match( value, '^%{%|' )
) then
            then
value = value .. getCategoryByCode( 'value-contains-table', propertyId )
                value = value .. getCategoryByCode( 'value-contains-table', propertyId )
else
            else
value = wrapStatement( value, propertyId, nil, wrapperExtraArgs );
                value = wrapStatement( value, propertyId, nil, wrapperExtraArgs )
end
            end
end
        end


return value
        return value
end
    end


if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
    -- ability to disable loading Wikidata
local callArgs = { propertyId };
    if args.entityId == '-' then
if args.entityId then
        return ''
callArgs.from = args.entityId;
    end
end
return frame:callParserFunction( '#property', callArgs );
end


g_frame = frame
    g_frame = frame
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
    -- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
return formatProperty( args )
    return formatProperty( args )
end
end


--[[
---Функция проверки на присутствие источника в списке нерекомендованных.
Функция проверки на присутствие источника в списке нерекомендованных.
---@param snaks table
 
---@return boolean
Принимает: таблицу snak'ов
local function isReferenceDeprecated( snaks )
Возвращает: true/false
    if not snaks then
]]
        return false
function isReferenceDeprecated( snaks )
    end
if not snaks then
    if snaks.P248
return false
            and snaks.P248[ 1 ]
end
            and snaks.P248[ 1 ].datavalue
if snaks.P248
            and snaks.P248[ 1 ].datavalue.value.id
and snaks.P248[1]
    then
and snaks.P248[1].datavalue
        local entityId = snaks.P248[ 1 ].datavalue.value.id
and snaks.P248[1].datavalue.value.id
        if getConfig( 'deprecatedSources', entityId ) then
then
            return true
local entityId = snaks.P248[1].datavalue.value.id
        end
if getConfig( 'deprecatedSources', entityId ) then
    elseif snaks.P1433
return true
            and snaks.P1433[ 1 ]
end
            and snaks.P1433[ 1 ].datavalue
elseif snaks.P1433
            and snaks.P1433[ 1 ].datavalue.value.id
and snaks.P1433[1]
    then
and snaks.P1433[1].datavalue
        local entityId = snaks.P1433[ 1 ].datavalue.value.id
and snaks.P1433[1].datavalue.value.id
        if getConfig( 'deprecatedSources', entityId ) then
then
            return true
local entityId = snaks.P1433[1].datavalue.value.id
        end
if getConfig( 'deprecatedSources', entityId ) then
    end
return true
    return false
end
end
return false
end
end


--[[
---Функция оформления ссылок на источники (reference)
Функция оформления ссылок на источники (reference)
---Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru
Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru
---
 
---Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
---Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
---@param context table
 
---@param options table
Принимает: объект-таблицу утверждение
---@param statement table
Возвращает: строку оформленных ссылок для отображения в статье
---@return string Оформленные примечания для отображения в статье
]]
function formatRefs( context, options, statement )
function formatRefs( context, options, statement )
if ( not context ) then error( 'context not specified' ); end;
    if not context then error( 'context not specified' ); end
if ( not options ) then error( 'options not specified' ); end;
    if not options then error( 'options not specified' ); end
if ( not options.entity ) then error( 'options.entity missing' ); end;
    if not options.entityId then error( 'options.entityId missing' ); end
if ( not statement ) then error( 'statement not specified' ); end;
    if not statement then error( 'statement not specified' ); end


if ( not outputReferences ) then
    if not outputReferences then
return '';
        return ''
end
    end


local references = {};
    ---@type string[]
if ( statement.references ) then
    local references = {}
    if statement.references then
        local hasNotDeprecated = false
        local displayCount = 0
        for _, reference in pairs( statement.references ) do
            if not isReferenceDeprecated( reference.snaks ) then
                hasNotDeprecated = true
            end
        end


local allReferences = statement.references;
        for _, reference in pairs( statement.references ) do
local hasNotDeprecated = false;
            local display = true
local displayCount = 0;
            if hasNotDeprecated then
for _, reference in pairs( statement.references ) do
                if isReferenceDeprecated( reference.snaks ) then
local entityId = nil;
                    display = false
if not isReferenceDeprecated( reference.snaks ) then
                end
hasNotDeprecated = true;
            end
end
            if displayCount >= 2 then
end
                if options.entityId and options.property then
 
                    local propertyId = mw.ustring.match( options.property, '^[Pp][0-9]+' )  -- TODO: обрабатывать не тут, а раньше
for _, reference in pairs( statement.references ) do
                    local moreReferences = '<sup>[[d:' .. options.entityId .. '#' .. string.upper( propertyId ) .. '|[…]]]</sup>'
local display = true;
                    table.insert( references, moreReferences )
if ( hasNotDeprecated ) then
                end
if isReferenceDeprecated( reference.snaks ) then
                break
display = false;
            end
end
            if display == true then
end
                ---@type string
if ( displayCount > 2 ) then
                local refText = moduleSources.renderReference( g_frame, options.entityId, reference )
if ( options.entity and options.property ) then
                if refText and refText ~= '' then
local propertyID = mw.ustring.match( options.property, '^[Pp][0-9]+' )  -- TODO: обрабатывать не тут, а раньше
                    table.insert( references, refText )
local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( propertyID ) .. '|[…]]]</sup>';
                    displayCount = displayCount + 1
table.insert( references, moreReferences );
                end
end
            end
break;
        end
end
    end
if ( display == true ) then
    return table.concat( references )
local refText = moduleSources.renderReference( g_frame, options.entity, reference );
if ( refText ~= '' ) then
table.insert( references, refText );
displayCount = displayCount + 1;
end
end
end
end
return table.concat( references );
end
end


return p
return p