«Մոդուլ:Wikidata» խմբագրումներու միջեւ տարբերութիւն

Content deleted Content added
No edit summary
No edit summary
 
Տող 1.
local i18n = {
["errors"] = {
["property-param-not-provided"] = "Не дан параметр свойства",
["entity-not-found"] = "Сущность не найдена.",
["unknown-claim-type"] = "Неизвестный тип заявления.",
["unknown-snak-type"] = "Неизвестный тип снэка.",
["unknown-datavalue-type"] = "Неизвестный тип значения данных.",
["unknown-entity-type"] = "Неизвестный тип сущности.",
["unknown-property-module"] = "Вы должны установить и property-module, и property-function.",
["unknown-claim-module"] = "Вы должны установить и claim-module, и claim-function.",
["unknown-value-module"] = "Вы должны установить и value-module, и value-function.",
["property-module-not-found"] = "Модуль для отображения свойства не найден",
["property-function-not-found"] = "Функция для отображения свойства не найдена",
["claim-module-not-found"] = "Модуль для отображения утверждения не найден.",
["claim-function-not-found"] = "Функция для отображения утверждения не найдена.",
["value-module-not-found"] = "Модуль для отображения значения не найден.",
["value-function-not-found"] = "Функция для отображения значения не найдена."
},
["somevalue"] = "''անյայտ''",
["novalue"] = "''չկայ''",
["circa"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="մօտաւորապէս">մոտ. </span>',
["presumably"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="ենթադրաբար">ենթադր. </span>',
}
 
-- settings, may differ from project to project
local categoryLinksToEntitiesWithMissingLabel = '[[Ստորոգութիւն:Ուիքիփետիա:Ուիքիտուեալներու արեւմտահայերէն չթարգմանուած տարրեր պարունակող յօդուածներ]]';
local categoryLocalValuePresent = '[[Ստորոգութիւն:Ուիքիփետիա:Ուիքիտուեալներու արժէքներու վերաձեւակերպմամբ յօդուածներ]]';
local fileDefaultSize = '267x400px';
local outputReferences = true;
Տող 33 ⟶ 7՝
Q36578 = true, -- Gemeinsame Normdatei
Q63056 = true, -- Find a Grave
Q1798125 = true, -- LIBRIS
Q15222191 = true, -- BNF
Q15241312 = true, -- Freebase
};
Q29861311 = true, -- SNAC
local preferredSources = {
Q5375741 Q86999151 = true, -- Encyclopædia Britannica OnlineWeChangEd
Q523660 = true, -- International Music Score Library Project by https://ru.wikipedia.org/?diff=107090748
Q17378135 = true, -- Great Soviet Encyclopedia (1969—1978)
};
 
Տող 47 ⟶ 22՝
local contentLanguageCode = mw.getContentLanguage():getCode();
 
local p = {};
local config = nil;
 
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
Տող 53 ⟶ 29՝
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
 
local function copyTo( obj, target, skipEmpty )
for k, v in pairs( obj ) do
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
target[k] = v
target[k] = v;
end
end
return target;
Տող 70 ⟶ 48՝
elseif ( prev < next ) then return next;
else return prev; end
end
 
local function getConfig( section, code )
if config == nil then
config = require( 'Module:Wikidata/config' );
end;
if not config then
config = {};
end
 
if not section then
return config;
end
if not code then
return config[ section ] or {};
end
 
if not config[ section ] then
return nil;
end
return config[ section ][ code ];
end
 
local function getCategoryByCode( code )
local value = getConfig( 'categories', code );
if not value or value == '' then
return '';
end
return '[[Category:' .. value .. ']]';
end
 
Տող 80 ⟶ 87՝
end
end
local Y, M, D = (function(str)
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
local Y, M, D = mw.ustring.match( str, pattern )
return tonumber(Y), tonumber(M), tonumber(D)
end) (str);
local h, m, s = (function(str)
local pattern = "T(%d+):(%d+):(%d+)%Z";
local H, M, S = mw.ustring.match( str, pattern);
Տող 132 ⟶ 139՝
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,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=59, sec=58} )) * 1000 + 199919991999 };
end
 
Տող 148 ⟶ 155՝
end
 
--[[
Преобразует строку в булевое значение
 
Տող 155 ⟶ 162՝
]]
local function toBoolean( valueToParse, defaultValue )
if ( valueToParse ~= nil ) then
if valueToParse == false or valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
return false
end
return true
end
return defaultValue;
end
 
--[[
Обрачивает отформатированное значение в тег
Функция для получения сущности (еntity) для текущей страницы
Подробнее о сущностях см. d:Wikidata:Glossary/ru
Принимает: строковое значение, строку с атрибутами (может отсутствовать)
Возвращает: строковое значение, значения с блочными тегами остаются блоком, текст встраиваем в строку
]]
local function wrapFormatProperty( value, attributes )
local tagName = 'span';
local spacer = '';
if ( string.match( value, '\n' )
or string.match( value, '<t[dhr][ >]' )
or string.match( value, '<div[ >]' )
or string.find( value, 'UNIQ%-%-imagemap' ) ) then
tagName = 'div';
spacer = '\n'
end
return '<' .. tagName .. ' ' .. ( attributes or '' ) .. '>' .. spacer .. value .. '</' .. tagName .. '>';
end
 
--[[
Принимает: строковый индентификатор (типа P18, Q42)
Функция для получения сущности (еntity) для текущей страницы
Возвращает: объект таблицу, элементы которой индексируются с нуля
Подробнее о сущностях см. d:Wikidata:Glossary/ru
 
Принимает: строковый индентификатор (типа P18, Q42)
Возвращает: объект таблицу, элементы которой индексируются с нуля
]]
local function getEntityFromId( id )
local entity;
if id then
local wbStatus;
return mw.wikibase.getEntityObject( id )
 
end
if id then
return mw.wikibase.getEntityObject();
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
end
 
return entity;
end
 
--[[
Внутрення функция для формирования сообщения об ошибке
 
Принимает: ключ элемента в таблице i18nconfig.errors (например entity-not-found)
Возвращает: строку сообщения
]]
local function throwError( key )
error( i18n.getConfig( 'errors[', key] ) );
end
 
--[[
Функция для получения идентификатора сущностей
 
Принимает: объект таблицу сущности
Возвращает: строковый индентификатор (типа P18, Q42)
]]
local function getEntityIdFromValue( value )
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'Q'
elseif value['entity-type'] == 'property' then
prefix = 'P'
else
throwError( 'unknown-entity-type' )
end
return prefix .. value['numeric-id']
end
 
-- проверка на наличие специилизированной функции в опциях
local function getUserFunction( options, prefix, defaultFunction )
-- проверка на указание специализированных обработчиков в параметрах,
-- переданных при вызове
if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then
-- проверка на пустые строки в параметрах или их отсутствие
if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then
throwError( 'unknown-' .. prefix .. '-module' );
end
-- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require( ('Module:' .. options[ prefix .. '-module' ] );
if formatter == nil then
throwError( prefix .. '-module-not-found' )
end
local fun = formatter[ options[ prefix .. '-function' ] ]
if fun == nil then
throwError( prefix .. '-function-not-found' )
end
return fun;
end
 
return defaultFunction;
end
 
Տող 239 ⟶ 271՝
result = WDS.filter( options.entity.claims, propertySelector );
 
if ( not result or #result == 0 ) then
return nil;
end
 
if options.limit and options.limit ~= '' and options.limit ~= '-' then
Տող 250 ⟶ 282՝
end
 
return result;
end
 
--[[
Функция для получения значения свойства элемента в заданный момент времени.
 
Принимает: контекст, элемент, временные границы, таблица ID свойства
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entityentityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
 
local results = {};
 
Տող 266 ⟶ 300՝
end
 
for _, propertyId in ipairs( propertyIds ) do
if entity.claims then
local selector = selectors[_];
for _, propertyId in ipairs( propertyIds ) do
local filteredClaimspropertyClaims = WDSmw.filterwikibase.getAllStatements( entity.claimsentityId, propertyId .. '[rank:preferred, rank:normal]' );
local fakeAllClaims = {};
if filteredClaims then
fakeAllClaims[propertyId] = propertyClaims;
for _, claim in pairs( filteredClaims ) do
if not boundaries or not propertyIds or #propertyIds == 0 then
local filteredClaims = WDS.filter( fakeAllClaims, selector .. '[rank:preferred, rank:normal]' );
if filteredClaims then
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]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) 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]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
table.insert( results, claim.mainsnak );
end
end
end
end
end
 
if #results > 0 then
break;
end
end
end
Տող 294 ⟶ 331՝
end
 
--[[
TODO
]]
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
Տող 317 ⟶ 354՝
end
 
--[[
TODO
]]
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
Տող 324 ⟶ 361՝
qualifierIds = { 'P582', 'P580', 'P585' };
end
 
for _, qualifierId in ipairs( qualifierIds ) do
local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId );
Տող 335 ⟶ 372՝
end
 
local CONTENT_LANGUAGE_CODE = mw.language.getContentLanguage():getCode();
--[[
local getLabelWithLang_DEFAULT_PROPERTIES = { "P1813", "P1448", "P1705" };
Функция для получения метки элемента в заданный момент времени.
local getLabelWithLang_DEFAULT_SELECTORS = {
'P1813[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1448[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1705[language:' .. CONTENT_LANGUAGE_CODE .. ']'
};
 
--[[
Принимает: контекст, элемент, временные границы
Функция для получения метки элемента в заданный момент времени.
Возвращает: текстовую метку элемента, язык метки
 
Принимает: контекст, элемент, временные границы
Возвращает: текстовую метку элемента, язык метки
]]
local function getLabelWithLang( context, options, entityentityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
if not entity then
if not entityId then
return nil;
end
 
local langlangCode = mw.language.getContentLanguage()CONTENT_LANGUAGE_CODE;
local langCode = lang:getCode();
 
-- name from label
local label = nil;
if ( options.text and options.text ~= '' ) then
label = options.text;
else
label, langCode = entity:getLabelWithLang();
if not langCode then
return nil;
end
if not propertyIds then
propertyIds = {getLabelWithLang_DEFAULT_PROPERTIES;
selectors = getLabelWithLang_DEFAULT_SELECTORS;
'P1813[language:' .. langCode .. ']',
'P1448[language:' .. langCode .. ']',
'P1705[language:' .. langCode .. ']'
};
end
 
-- name from properties
local results = getPropertyInBoundaries( context, entityentityId, boundaries, propertyIds, selectors );
 
for _, result in pairs( results ) do
if result.datavalue and result.datavalue.value then
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
label = result.datavalue.value.text;
langlangCode = result.datavalue.value.language;
break;
elseif result.datavalue.type == 'string' then
Տող 381 ⟶ 417՝
break;
end
end
end
if (not label) then
label, langCode = mw.wikibase.getLabelWithLang( entityId );
if not langCode then
return nil;
end
end
Տող 388 ⟶ 431՝
end
 
local function formatPropertyDefault( context, options )
--[[
if ( not context ) then error( 'context not specified' ); end;
Функция для оформления утверждений (statement)
if ( not options ) then error( 'options not specified' ); end;
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
if ( not options.entity ) then error( 'options.entity missing' ); end;
 
local claims;
Принимает: таблицу параметров
if options.property then -- TODO: Почему тут может не быть property?
Возвращает: строку оформленного текста, предназначенного для отображения в статье
claims = context.selectClaims( options, options.property );
end
if claims == nil then
return '' --TODO error?
end
 
-- Обход всех заявлений утверждения и с накоплением оформленых предпочтительных
-- заявлений в таблице
local formattedClaims = {}
 
for i, claim in ipairs(claims) do
local formattedStatement = context.formatStatement( options, claim )
-- здесь может вернуться либо оформленный текст заявления, либо строка ошибки, либо nil
if ( formattedStatement and formattedStatement ~= '' ) then
formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
table.insert( formattedClaims, formattedStatement )
end
end
 
-- создание текстовой строки со списком оформленых заявлений из таблицы
local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
if out ~= '' then
if options.before then
out = options.before .. out
end
if options.after then
out = out .. options.after
end
end
 
return out
end
 
--[[
Функция для оформления утверждений (statement)
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
 
Принимает: таблицу параметров
Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
local function formatProperty( options )
-- Получение сущности по идентификатору
local entity = getEntityFromId( options.entityId )
if not entity then
return -- throwError( 'entity-not-found' )
end
-- проверка на присутсвие у сущности заявлений (claim)
-- подробнее о заявлениях см. d:Викиданные:Глоссарий
if (entity.claims == nil) then
return '' --TODO error?
end
 
-- improve options
Տող 415 ⟶ 498՝
 
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
 
Տող 433 ⟶ 516՝
options.entity = entity;
newOptions.entity = entity;
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
 
return newOptions;
end;
context.formatProperty = function( options )
local func = getUserFunction( options, 'property', context.formatPropertyDefault );
return func( context, options )
Տող 443 ⟶ 527՝
context.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end;
context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;
 
context.parseTimeFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) then
Տող 462 ⟶ 546՝
end
 
--[[
function formatPropertyDefault( context, options )
Функция для оформления одного утверждения (statement)
if ( not context ) then error( 'context not specified' ); end;
if ( not options ) then error( 'options not specified' ); end;
if ( not options.entity ) then error( 'options.entity missing' ); end;
 
local claims;
if options.property then -- TODO: Почему тут может не быть property?
claims = context.selectClaims( options, options.property );
end
if claims == nil then
return '' --TODO error?
end
 
-- Обход всех заявлений утверждения и с накоплением оформленых предпочтительных
-- заявлений в таблице
local formattedClaims = {}
 
for i, claim in ipairs(claims) do
local formattedStatement = context.formatStatement( options, claim )
-- здесь может вернуться либо оформленный текст заявления
-- либо строка ошибки nil похоже никогда не возвращается
if (formattedStatement) then
formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
table.insert( formattedClaims, formattedStatement )
end
end
 
-- создание текстовой строки со списком оформленых заявлений из таблицы
local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
if out ~= '' then
if options.before then
out = options.before .. out
end
if options.after then
out = out .. options.after
end
end
 
return out
end
 
--[[
Функция для оформления одного утверждения (statement)
 
Принимает: объект-таблицу утверждение и таблицу параметров
Возвращает: строку оформленного текста с заявлением (claim)
]]
function formatStatement( context, options, statement )
Տող 513 ⟶ 556՝
error( 'statement is not specified or nil' );
end
if not statement.type or statement.type ~= 'statement' then
throwError( 'unknown-claim-type' )
end
 
local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault );
return functionToCall( context, options, statement );
end
 
Տող 533 ⟶ 576՝
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
local circumstance =table.insert(circumstances, qualifier.datavalue.value.id;)
if ( 'Q5727902' == circumstance ) then
circumstances.circa = true;
end
if ( 'Q18122778' == circumstance ) then
circumstances.presumably = true;
end
end
end
Տող 546 ⟶ 583՝
end
 
--[[
Функция для оформления одного утверждения (statement)
 
Принимает: объект-таблицу утверждение, таблицу параметров,
объект-функцию оформления внутренних структур утверждения (snak) и
объект-функцию оформления ссылки на источники (reference)
Возвращает: строку оформленного текста с заявлением (claim)
]]
function formatStatementDefault( context, options, statement )
Տող 563 ⟶ 600՝
options.qualifiers = statement.qualifiers;
 
local result = context.formatSnak( options, statement.mainsnak, circumstances );
if ( options.references ) then
return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
else
returnqualConfig context.formatSnak= getPropertyParams( options.qualifier, statement.mainsnaknil, circumstances {});
if options.i18n then qualConfig.i18n = options.i18n end
local qualifierValues = {};
for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
local snakValue = context.formatSnak( qualConfig, qualifierSnak );
if snakValue and snakValue ~= '' then
table.insert( qualifierValues, snakValue );
end
end
if ( result and result ~= '' and #qualifierValues ) then
if qualConfig.invisible then
result = result .. table.concat( qualifierValues, ', ' );
else
result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
end
end
end
 
if ( result and result ~= '' and options.references ) then
result = result .. context.formatRefs( options, statement );
end
 
return result;
end
 
--[[
Функция для оформления части утверждения (snak)
Подробнее о snak см. d:Викиданные:Глоссарий
 
Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций
Возвращает: строку оформленного викитекста
]]
function formatSnak( context, options, snak, circumstances )
Տող 590 ⟶ 648՝
local after = '</span>'
 
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
result return before ..= options['somevalue'] .. after;
else
end
result return before ..= options.i18n['somevalue'] .. after;
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
return before .. options['novalue'] .. after;
end
return before .. options.i18n['novalue'] .. after;
elseif snak.snaktype == 'value' then
if ( circumstances.presumably ) then
before = before .. options.i18n.presumably;
end
elseif snak.snaktype == 'novalue' then
if ( circumstances.circa ) then
if ( options['novalue'] and options['novalue'] ~= '' ) then
before = before .. options.i18n.circa;
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
 
return before .. formatDatavalue( context, options, snak.datavalue, snak.datatype )result .. after;
else
throwError( 'unknown-snak-type' );
end
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}}
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or '' -- TODO
local lat = {}
local globe = options.globe or ''
lat['abs'] = math.abs(value['latitude'])
if globe == lat['ns'] =and value['latitudeglobe'] >= 0 and 'N' or 'S'then
globes = require( 'Module:Wikidata/Globes' )
lat['d'] = math.floor(lat['abs'] + eps)
globe = globes[value['globe']] or ''
lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
end
lat['s'] = math.max(0, ((lat['abs'] - lat['d']) * 60 - lat['m']) * 60 + eps)
local lon = {}
local display = 'inline'
lon['abs'] = math.abs(value['longitude'])
if options.display and options.display ~= '' then
lon['ew'] = value['longitude'] >= 0 and 'E' or 'W'
display = options.display
lon['d'] = math.floor(lon['abs'] + eps)
elseif ( options.property:upper() == 'P625' ) then
lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
display = 'title'
lon['s'] = math.max(0, ((lon['abs'] - lon['d']) * 60 - lon['m']) * 60 + eps)
end
-- TODO: round seconds with precision
local coord = '{{coord'
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display }
if (value['precision'] == nil) or (value['precision'] < 1/60) then -- по умолчанию с точностью до секунды
coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['s'] .. '|' .. lat['ns']
return coord_mod.coord(g_frame)
coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['s'] .. '|' .. lon['ew']
end
elseif value['precision'] < 1 then
coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['ns']
coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['ew']
else
coord = coord .. '|' .. lat['d'] .. '|' .. lat['ns']
coord = coord .. '|' .. lon['d'] .. '|' .. lon['ew']
end
coord = coord .. '|globe:' .. globe
if options['type'] and options['type'] ~= '' then
coord = coord .. '|type=' .. options.type
end
if options['display'] and options['display'] ~= '' then
coord = coord .. '|display=' .. options.display
else
coord = coord .. '|display=title'
end
coord = coord .. '}}'
 
return g_frame:preprocess(coord)
end
end
 
--[[
Функция для оформления объектов-значений с файлами с Викисклада
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
local function formatCommonsMedia( value, options )
local image = value;
 
local caption = '';
if options[ 'caption' ] and options[ 'caption' ] ~= '' then
caption = options[ 'caption' ];
elseif options[ 'description' ] and options[ 'description' ] ~= '' then
caption = options[ 'description' ];
end
if caption ~= '' then
caption = wrapFormatProperty( caption, '<spanclass="media-caption" data-wikidata-qualifier-id="P2096" style="display:block;">' .. caption .. '</span>');
end
 
if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
-- если в value не содержится викикод или imagemap, то викифицируем имя файла
image = '[[File:' .. value
-- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[PHAB:T28213]]
if options['border'] and options['border'] ~= '' then
image = image'[[File:' .. value .. '|borderframeless';
if options[ 'border' ] and options[ 'border' ] ~= '' then
end
image = image .. '|border';
end
local size = options['size']
 
if size and size ~= '' then
local size = options[ 'size' ];
if not string.match( size, 'px$' )
if size and size ~= '' then
if not string.match( size, 'px$' )
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
then
size = size .. 'px'
end
else
size = fileDefaultSize;
end
image = image .. '|' .. size;
 
if options[ 'alt' ] and options[ 'alt' ] ~= '' then
image = image .. '|' .. options[ 'alt' ];
end
image = image .. ']]';
 
if caption ~= '' then
image = image .. '<br>' .. caption;
end
 
if captionoptions[ 'local_caption' ] and options[ 'local_caption' ] ~= '' then
image = image .. getCategoryByCode( '<br>media-contains-local-caption' .. caption)
end
else
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
end
if options.entity and options.fixdouble then
return image
local page = mw.title.getCurrentTitle()
local txt = page:getContent()
if txt and txt:match(':' .. value) and mw.title.getCurrentTitle():inNamespace(0) then image = image .. getCategoryByCode( 'media-contains-local-double' ) end
end
return image
end
 
--[[
Fonction for render math formulas
Функция для оформления внешних идентификаторов
 
@param string Value.
Принимает: объект-значение и таблицу параметров,
@param table Parameters.
Возвращает: строку оформленного текста
@return string Formatted string.
]]
local function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
end
 
--[[
Функция для оформления внешних идентификаторов
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
local function formatExternalId( value, options )
local formatter = options.formatter;
 
if not formatter or formatter == '' then
local entitywbStatus, propertyEntity = pcall( mw.wikibase.getEntity(, options.property:upper() )
if entitywbStatus == true and propertyEntity then
local statementsisGoodFormat = entity:getBestStatements( 'P1630' )false;
local statements = propertyEntity:getBestStatements( 'P1793' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
formatterlocal pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' );
break
if ( string.find( pattern, '|' ) or string.find( pattern, '%)%?' )
or mw.ustring.match( value, '^' .. pattern .. '$' ) ~= nil ) then
isGoodFormat = true;
break;
end
end
end
 
if ( isGoodFormat == true ) then
statements = propertyEntity:getBestStatements( 'P1630' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
formatter = statement.mainsnak.datavalue.value;
break
end
end
end
Տող 750 ⟶ 834՝
 
if formatter and formatter ~= '' then
local link = mw.ustring.gsub(
mw.ustring.gsub( formatter, '$1', value ), '.',
{ [' '] = '%20', ['+'] = '%2b' } )
 
local title = options.title
Տող 764 ⟶ 850՝
end
 
--[[
Функция для оформления числовых значений
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
local function formatQuantity( value, options )
-- диапазон значений
local amount = string.gsub( value['amount'], '^%+', '' );
local lang = mw.language.getContentLanguage();
local langCode = lang:getCode();
local function formatNum( number )
-- округление до 13 знаков после запятой, на 14-м возникает ошибка в точности
local mult = 10^13
number = math.floor( number * mult + 0.5 ) / mult
 
local function return lang:formatNum( number, sigfig )
sigfig = sigfig or 12 -- округление до 12 знаков после запятой, на 13-м возникает ошибка в точности
local mult = 10^sigfig;
number = math.floor( number * mult + 0.5 ) / mult;
return string.gsub( lang:formatNum( number ), '^-', '−' );
end
local out = formatNum( tonumber( amount ) );
if value.upperBound then
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
out = out .. '±' .. formatNum( diff )
end
end
 
local out = formatNum( tonumber( amount ) );
if options.unit and options.unit ~= '' then
if optionsvalue.unit ~= '-'upperBound then
local diff = tonumber( value.upperBound ) - tonumber( amount )
out = out .. ' ' .. options.unit
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
end
-- Пробуем понять до какого знака округлять
elseif value.unit and string.match( value.unit, 'http://www.wikidata.org/entity/' ) then
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
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 unitEntity = mw.wikibase.getEntity( unitEntityId );
local wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
if unitEntity then
if wbStatus == true and unitEntity then
local writingSystemElementId = 'Q11932';
if unitEntity.claims.P2370 and
local langElementId = 'Q180945';
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
local label = getLabelWithLang( context, options, unitEntity, nil, {
not value.upperBound and
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
options.siConversion == true
'P558[!P282][!P407]'
} ); then
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
out = out .. ' ' .. label;
-- Если не степени десятки (переводить сантиметры в метры не надо!)
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;
end
 
local DATATYPE_CACHE = {}
 
--[[
Get property datatype by ID.
 
@param string Property ID, e.g. 'P123'.
@return string Property datatype, e.g. 'commonsMedia', 'time' or 'url'.
Տող 825 ⟶ 959՝
end
local propertyEntitycached = mw.wikibase.getEntity( DATATYPE_CACHE[propertyId )];
if (cached ~= nil) then return cached; end
if not propertyEntity then
 
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
if wbStatus ~= true or not propertyEntity then
return nil;
end
mw.log("Loaded datatype " .. propertyEntity.datatype .. " of " .. propertyId .. ' from wikidata, consider passing datatype argument to formatProperty call or to Wikidata/config' )
 
DATATYPE_CACHE[propertyId] = propertyEntity.datatype;
return propertyEntity.datatype;
end
 
local function formatLangRefs( options )
local langRefs = ''
if ( options.qualifiers and options.qualifiers.P407 ) then
for i, qualifier in pairs( options.qualifiers.P407 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'wikibase-entityid' ) then
local langRefEntity = getEntityFromId( qualifier.datavalue.value.id )
if ( langRefEntity and langRefEntity.claims ) then
local langRefCodeClaims = WDS.filter( langRefEntity.claims, 'P218' )
if langRefCodeClaims then
for _, claim in pairs( langRefCodeClaims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'string' ) then
local langRefCode = claim.mainsnak.datavalue.value
langRefs = langRefs .. '&#8203;' .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
end
end
end
end
end
end
end
 
return langRefs
end
 
local function getDefaultValueFunction( datavalue, datatype )
-- вызов обработчиков по умолчанию для известных типов значений
if datavalue.type == 'wikibase-entityid' then
-- Entity ID
return function( context, options, value ) return formatEntityId( context, options, getEntityIdFromValue( value ) ) end;
elseif datavalue.type == 'string' then
-- String
if datatype and datatype == 'commonsMedia' then
-- Media
return function( context, options, value )
if ( not options.caption orand options.caption =~= '' )then
and ( not options.descriptionlocal_caption or= options.description == '' )caption;
andelseif options.qualifiersdescription and options.qualifiers.P2096description ~= '' then
options.local_caption = options.description;
for i, qualifier in pairs( options.qualifiers.P2096 ) do
end
options.caption = ''
options.description = ''
if options.qualifiers and options.qualifiers.P2096 then
for i, qualifier in pairs( options.qualifiers.P2096 ) do
if ( qualifier
and qualifier.datavalue
Տող 857 ⟶ 1030՝
end
end
end
if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
return formatCommonsMedia( value, options )
local moment = formatDatavalue (context, options, options.qualifiers.P585[1].datavalue, 'time')
end;
if not options.caption or options.caption == '' then
elseif datatype and datatype == 'external-id' then
options.caption = moment
-- External ID
options.description = moment
return function( context, options, value )
else
options.caption = options.caption .. ', ' .. moment
options.description = options.description .. ', ' .. moment
end
end
return formatCommonsMedia( value, options )
end;
elseif datatype and datatype == 'external-id' then
-- External ID
return function( context, options, value )
return formatExternalId( value, options )
end
elseif datatype and datatype == 'urlmath' then
-- URLMath formula
return function( context, options, value )
return formatMath( value, options )
end
elseif datatype and datatype == 'url' then
-- URL
return function( context, options, value )
local moduleUrl = require( 'Module:URL' )
local langRefs = formatLangRefs( options )
if not options.length or options.length == '' then
options.length = math.max( 18, 25 - #langRefs )
end
return moduleUrl.formatUrlSingle( context, options, value ); .. langRefs
end
end
return function( context, options, value ) return value end;
elseif datavalue.type == 'monolingualtext' then
-- моноязычный текст (строка с указанием языка)
return function( context, options, value )
if ( options.monolingualLangTemplate == 'lang' ) then
if ( value.language == contentLanguageCode ) then
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
return value.text;
elseif ( options.monolingualLangTemplate == 'ref' ) then
end
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
else
elseif ( options.monolingualLangTemplate == 'ref' ) then
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
end
else
end;
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
elseif datavalue.type == 'globecoordinate' then
end
-- географические координаты
end;
return function( context, options, value ) return formatGlobeCoordinate( value, options ) end;
elseif datavalue.type == 'quantityglobecoordinate' then
-- географические координаты
return function( context, options, value ) return formatQuantity( value, options ) end;
return function( context, options, value ) return formatGlobeCoordinate( value, options ) end;
elseif datavalue.type == 'time' then
elseif datavalue.type == 'quantity' then
return function( context, options, value )
return function( context, options, value ) return formatQuantity( value, options ) end;
elseif datavalue.type == 'time' then
return function( context, options, value )
local moduleDate = require( 'Module:Wikidata/date' )
return moduleDate.formatDate( context, options, value );
end;
else
-- во всех стальных случаях возвращаем ошибку
throwError( 'unknown-datavalue-type' )
end
end
 
--[[
Функция для оформления значений (value)
Подробнее о значениях см. d:Wikidata:Glossary/ru
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatDatavalue( context, options, datavalue, datatype )
Տող 916 ⟶ 1108՝
if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;
 
-- проверка на указание специализированных обработчиков в параметрах,
-- переданных при вызове
context.formatValueDefault = getDefaultValueFunction( datavalue, datatype );
local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
return functionToCall( context, options, datavalue.value );
end
 
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
--[[
Функция для оформления идентификатора сущности
 
--[[
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Функция для оформления идентификатора сущности
Возвращает: строку оформленного текста
 
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local entity = mw.wikibase.getEntity( entityId )
local boundaries = nil
local cat = nil;
if options.qualifiers then
boundaries = p.getTimeBoundariesFromQualifiers( frame, context, { qualifiers = options.qualifiers } )
end
if not boundaries then
local label, labelLanguageCode = getLabelWithLang( context, options, entity, boundaries )
boundaries = DEFAULT_BOUNDARIES;
if (labelLanguageCode == 'en') then
end
cat = '[[Ստորոգութիւն:Ուիքիպետիա:Ուիքիտուեալների անգլերեն պիտակով տարրեր պարունակող էջեր]]';
elseif local label, (labelLanguageCode == 'hyw')getLabelWithLang( thencontext, options, entityId, boundaries )
 
cat = '[[Ստորոգութիւն:Ուիքիպետիա:Ուիքիտուեալների արեւելահայերէն պիտակով տարրեր պարունակող էջեր]]';
elseif (labelLanguageCode == nil) then
cat = categoryLinksToEntitiesWithMissingLabel;
else
cat = '';
end
-- определение соответствующей показываемому элементу категории
local category = ''p.extractCategory( context, options, { id = entityId } )
 
if ( options.category ) then
-- получение ссылки по идентификатору
local claims = WDS.filter( entity.claims, options.category );
local link = mw.wikibase.sitelink( entityId )
if ( claims ) then
if link then
for _, claim in pairs( claims ) do
-- ссылка на категорию, а не добавление страницы в неё
if ( claim.mainsnak
if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
and claim.mainsnak
link = ':' .. link
and claim.mainsnak.datavalue
end
and claim.mainsnak.datavalue.type == 'wikibase-entityid' ) then
if label and not options.rawArticle then
local catEntityId = claim.mainsnak.datavalue.value.id;
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
local catEntity = mw.wikibase.getEntity( catEntityId );
if ( catEntitycontentLanguageCode and~= catEntity:getSitelink()labelLanguageCode ) then
return a .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
category = '[[' .. catEntity:getSitelink() .. ']]';
endelse
return a .. category;
end
end
else
return '[[' .. link .. ']]' .. category;
end
end
local help = '<span class="wikidata-missing-label" style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="Վիքիդատայում այս տարրը չունի հայերեն նկարագրություն: Դուք կարող եք օգնել՝ նշելով տարրի հայերեն թարգմանությունը:">?</span>'
 
-- получение ссылки по идентификатору
local link = mw.wikibase.sitelink( entityId )
if link then
if label then
return '[[' .. link .. '|' .. label .. ']]' .. cat
else
return '[[' .. link .. ']]' .. cat
end
end
 
if label then
if ( contentLanguageCode == labelLanguageCode ) then
return '[[:d:' .. entityId .. '|' .. label .. ']]' .. cat
return '[[:d:' .. entityId .. '|' .. label .. ']]' .. category;
else
return '[[:d:' .. entityId .. '|' .. label .. ']]' .. help .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
end
end
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[d:' .. entityId .. '|' .. entityId .. ']]' .. help .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="Վիքիդատայում այս տարրը չունի հայերեն նկարագրություն: Դուք կարող եք օգնել՝ նշելով տարրի հայերեն թարգմանությունը:">?</span>' .. cat;
end
 
--[[
Функция для формирования категории на основе wikidata/config
]]
function p.extractCategory( context, options, value )
if ( not options.category or options.nocat ) then
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
-- getting sitelink of a given wiki
function p.getSiteLink(frame)
Տող 999 ⟶ 1214՝
return link
end
--[[
Функция для оформления утверждений (statement)
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
 
Принимает: таблицу параметров
Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
-- устаревшее имя, не использовать
Տող 1012 ⟶ 1227՝
 
--[[
Получение параметров, которые обычно используются для вывода свойства.
]]
function getPropertyParams( propertyId, datatype, params )
local config = requiregetConfig( 'Module:Wikidata/config' );
if not config then
return {};
end
 
-- Различные уровни настройки параметров, по убыванию приоритета
Տող 1025 ⟶ 1237՝
-- 1. Параметры, указанные явно при вызове
if params then
localfor tplParamskey, =value mw.clonein pairs( params ); do
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[ key ] = value;
end
end
Տող 1034 ⟶ 1245՝
 
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
localfor selfParamskey, =value mw.clonein pairs( config[ 'properties' ][ propertyId ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( selfParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
end
 
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
and config[ 'presets' ][ propertyParams[ 'preset'] ] ]
then
localfor presetParamskey, =value mw.clonein pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( presetParams ) do
if propertyParams[ key ] == nil thenvalue;
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
localfor datatypeParamskey, =value mw.clonein pairs( config[ 'datatypes' ][ datatype ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( datatypeParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
Տող 1065 ⟶ 1279՝
 
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
localfor globalParamskey, =value mw.clonein pairs( config[ 'global' ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( globalParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
Տող 1078 ⟶ 1291՝
 
function p.formatProperty( frame )
local args = frame.args
 
-- проверка на отсутствие обязательного параметра property
if not args.property then
throwError( 'property-param-not-provided' )
end
local override;
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '([^Pp0-9].*)$', function(w)
local datatype = getPropertyDatatype( propertyId );
if string.sub( w, 1, 1 ) == '~' then override = w; end
args = getPropertyParams( propertyId, datatype, args );
return '';
end ) )
args = getPropertyParams( propertyId, nil, args );
if (override) then
args[override:match('[,~]([^=]*)=')] = override:match('=(.*)')
args['property'] = propertyId
end
 
local datatype = args.datatype;
-- проброс всех параметров из шаблона {wikidata}
 
local p_frame = frame:getParent();
-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args= );frame
while p_frame do
if p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args, true );
end
if p_frame.args and p_frame.args.from and p_frame.args.from ~= '' then
args.entityId = p_frame.args.from;
end
p_frame = p_frame:getParent();
end
 
args.plain = toBoolean( args.plain, false );
args.nocat = toBoolean( args.nocat, false );
args.noagereferences = toBoolean( args.noagereferences, falsetrue );
args.references = toBoolean( args.references, true );
 
-- если значение передано в параметрах вызова то выводим только его
if args.value and args.value ~= '' then
-- специальное значение для скрытия Викиданных
if args.value == '-' then
return ''
end
local value = args.value
 
-- опция, запрещающая оформление значения, поэтому никак не трогаем
if args.plain then
return value
end
 
-- обработчики по типу значения
Տող 1122 ⟶ 1349՝
wrapperExtraArgs = wrapperExtraArgs .. ' data-wikidata-external-id="' .. mw.text.encode( value ).. '"';
value = formatExternalId( value, args );
elseif datatype == 'math' then
value = formatMath( value, args );
elseif datatype == 'url' then
local moduleUrl = require( 'Module:URL' );
if not args.length or args.length == '' then
value = moduleUrl.formatUrlSingle( nil, args, value );
args.length = 25
end
value = moduleUrl.formatUrlSingle( nil, args, value );
end
 
-- оборачиваем в тег для JS-функций
if string.match( propertyId, '^P%d+$' ) then
value = mw.text.trim( value )
 
-- временная штрафная категория для исправления табличных вставок
if ( propertyId ~= 'P166'
and string.match( value, '<t[dr][ >]' )
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. getCategoryByCode( 'value-contains-table' )
value = value .. '[[Категория:Википедия:Статьи с табличной вставкой в карточке]]'
else
value = wrapFormatProperty( value, 'class="no-wikidata"'
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
if ( string.match( value, '\n' )
.. propertyId .. '"' );
or string.match( value, '<t[dhr][ >]' )
end
or string.match( value, '<div[ >]' ) ) then
end
value = '<div class="no-wikidata"' .. wrapperExtraArgs
.. ' data-wikidata-property-id="' .. propertyId .. '">\n'
.. value .. '</div>'
else
value = '<span class="no-wikidata"' .. wrapperExtraArgs
.. ' data-wikidata-property-id="' .. propertyId .. '">'
.. value .. '</span>'
end
end
end
 
-- добавляем категорию-маркер
if not args.nocat then
local pageTitle = mw.title.getCurrentTitle();
value = value .. categoryLocalValuePresent;
if pageTitle.namespace == 0 then
value = value .. getCategoryByCode( 'local-value-present' );
end
end
 
return value
end
 
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
local callArgs = { propertyId };
return frame:callParserFunction( '#property', propertyId );
if args.entityId then
end
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
 
g_frame = frame
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
return formatProperty( args )
end
 
--[[
Функция оформления ссылок на источники (reference)
Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru
 
Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
 
Принимает: объект-таблицу утверждение
Возвращает: строку оформленных ссылок для отображения в статье
]]
function formatRefs( context, options, statement )
Տող 1190 ⟶ 1420՝
end
 
local resultreferences = ''{};
if ( statement.references ) then
 
local allReferences = statement.references;
local hasPreferredhasNotDeprecated = false;
local displayCount = 0;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
Տող 1202 ⟶ 1433՝
and reference.snaks.P248[1].datavalue.value.id ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
if ( preferredSourcesnot deprecatedSources[entityId] ) then
hasPreferredhasNotDeprecated = true;
end
end
Տող 1210 ⟶ 1441՝
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasPreferredhasNotDeprecated ) then
if ( reference.snaks
and reference.snaks.P248
Տող 1222 ⟶ 1453՝
end
end
if ( displaydisplayCount > 2 ) then
if ( options.entity and options.property ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( options.property ) .. '|[…]]]</sup>';
table.insert( references, moreReferences );
end
break;
end
if ( display == true ) then
local refText = moduleSources.renderReference( g_frame, options.entity, reference );
if ( refText ~= '' ) then
table.insert( references, refText );
displayCount = displayCount + 1;
end
end
end
end
return resulttable.concat( references );
end