Модуль:Wikidata: відмінності між версіями

[неперевірена версія][перевірена версія]
Вилучено вміст Додано вміст
Shmurak (обговорення | внесок)
у вашій версії в статтях помилки модуля
Мітка: Скасування
Скасування редагування № 23299605 користувача Shmurak (обговорення): Для перевірки
Мітка: Скасування
Рядок 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-module, не знайдений.",
["property-function-not-found"] = "Функція, вказана у property-function, не знайдена.",
["claim-module-not-found"] = "Модуль, вказаний у claim-module, не знайдений.",
["claim-function-not-found"] = "Функція, вказана у claim-function, не знайдена.",
["value-module-not-found"] = "Модуль, вказаний у value-module, не знайдений.",
["value-function-not-found"] = "Функція, вказана у value-function, не знайдена."
},
["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 fileDefaultSize = '267x400px';
local categoryLocalValuePresent = '[[Категорія:Вікіпедія:Статті з іншим значенням на Вікіданих]]';
local outputReferences = true;
 
Рядок 14 ⟶ 39:
};
 
-- Ссылки на используемые модули, которые потребуются в 99% случаев загрузки страниц (чтобы иметь на виду при переименовании)
local moduleSources = require( 'Module:Sources' )
local moduleSources = require('Module:Sources')
local WDS = require( 'Module:WikidataSelectors' );
 
local p = {}
-- Сталі
local contentLanguageCode = mw.getContentLanguage():getCode();
 
local p = {};
local config = nil;
 
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
formatStatementDefault, formatProperty, getSourcingCircumstances,
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
 
local function copyTo( obj, target, skipEmpty )
for k, v in pairs( obj ) do
target[k] = v
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
target[k] = v;
end
end
return target;
Рядок 46 ⟶ 66:
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
 
Рядок 153 ⟶ 144:
end
 
local function parseISO8601(str)
--[[
if 'table' == type(str) then
Перетворює рядок в логічне значення
if str.args and str.args[1] then
str = '' .. str.args[1]
else
return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )
end
end
local Y, M, D = (function(str)
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
local Y, M, D = mw.ustring.match( str, pattern )
return tonumber(Y), tonumber(M), tonumber(D)
end) (str);
local h, m, s = (function(str)
local pattern = "T(%d+):(%d+):(%d+)%Z";
local H, M, S = mw.ustring.match( str, pattern);
return tonumber(H), tonumber(M), tonumber(S);
end) (str);
local oh,om = ( function(str)
if str:sub(-1)=="Z" then return 0,0 end; -- ends with Z, Zulu time
-- matches ±hh:mm, ±hhmm or ±hh; else returns nils
local pattern = "([-+])(%d%d):?(%d?%d?)$";
local sign, oh, om = mw.ustring.match( str, pattern);
sign, oh, om = sign or "+", oh or "00", om or "00";
return tonumber(sign .. oh), tonumber(sign .. om);
end )(str)
return tonumber(os.time({year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s}))
end
 
--[[
Преобразует строку в булевое значение
 
Принимает: строковое значение (может отсутствовать)
Приймає: строкове значення (може бути відсутнім)
Возвращает: булевое значение true или false, если получается распознать значение, или defaultValue во всех остальных случаях
Повертає: логічне значення true або false, якщо виходить розпізнати значення, чи defaultValue у всіх інших випадках
]]
local function toBoolean( valueToParse, defaultValue )
Рядок 169 ⟶ 189:
end
 
--[[
Функція Функция для отриманняполучения сутностісущности (еntity) для поточноїтекущей сторінкистраницы
Детальніше про сутностіПодробнее диво сущностях см. d:Wikidata:Glossary/ukru
 
Принимает: строковый индентификатор (типа P18, Q42)
Возвращает: объект таблицу, элементы которой индексируются с нуля
]]
local function getEntityFromId( id )
Рядок 189 ⟶ 209:
end
 
--[[
Внутрення функция для формирования сообщения об ошибке
 
Принимает: ключ элемента в таблице config.errorsi18n (например entity-not-found)
Возвращает: строку сообщения
]]
local function throwError( key )
error( getConfig( 'i18n.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
 
Рядок 264 ⟶ 284:
end
 
--[[
Функция для оформления утверждений (statement)
Функция для получения значения свойства элемента в заданный момент времени.
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
 
Принимает: таблицу параметров
Принимает: контекст, элемент, временные границы, таблица ID свойства
Возвращает: строку оформленного текста, предназначенного для отображения в статье
Возвращает: таблицу соответствующих значений свойства
]]
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
 
local results = {};
 
if not propertyIds or #propertyIds == 0 then
return results;
end
 
for _, propertyId in ipairs( propertyIds ) do
local selector = selectors[_];
local propertyClaims = mw.wikibase.getAllStatements( entityId, propertyId );
local fakeAllClaims = {};
fakeAllClaims[propertyId] = propertyClaims;
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 );
end
end
end
end
 
if #results > 0 then
break;
end
end
 
return results;
end
 
--[[
TODO
]]
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
-- only support exact date so far, but need improvment
local left = nil;
local right = nil;
if ( statement.qualifiers and statement.qualifiers[qualifierId] ) then
for _, qualifier in pairs( statement.qualifiers[qualifierId] ) do
local boundaries = context.parseTimeBoundariesFromSnak( qualifier );
if ( not boundaries ) then return nil; end
left = min( left, boundaries[1] );
right = max( right, boundaries[2] );
end
end
 
if ( not left or not right ) then
return nil;
end
 
return { left, right };
end
 
--[[
TODO
]]
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
if not qualifierIds then
qualifierIds = { 'P582', 'P580', 'P585' };
end
 
for _, qualifierId in ipairs( qualifierIds ) do
local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId );
if result then
return result;
end
end
 
return nil;
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 .. ']'
};
 
--[[
Функция для получения метки элемента в заданный момент времени.
 
Принимает: контекст, элемент, временные границы
Возвращает: текстовую метку элемента, язык метки
]]
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 = nil;
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
local results = getPropertyInBoundaries( context, entityId, 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;
langCode = result.datavalue.value.language;
break;
elseif result.datavalue.type == 'string' then
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;
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
Рядок 437 ⟶ 311:
 
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
 
Рядок 448 ⟶ 322:
formatPropertyDefault = formatPropertyDefault,
formatStatementDefault = formatStatementDefault }
context.cloneOptionsformatProperty = function( options )
local entity = options.entity;
options.entity = nil;
 
newOptions = mw.clone( options );
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 )
Рядок 466 ⟶ 329:
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
Рядок 490 ⟶ 353:
if ( not options.entity ) then error( 'options.entity missing' ); end;
 
local claims = context.selectClaims( options, options.property );
local claims;
if (claims == nil) then
if options.property then -- TODO: Почему тут может не быть property?
return '' --TODO error?
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
-- либо строка ошибки nil похоже никогда не возвращается
if ( formattedStatement and formattedStatement ~= '' ) then
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
 
-- создание текстовой строки со списком оформленых заявлений из таблицы
Рядок 568 ⟶ 428:
end
 
--[[
Функция для оформления одного утверждения (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 =if statement.qualifiers; then
options.qualifiers = statement.qualifiers;
end
 
if ( options.references ) then
local result = context.formatSnak( options, statement.mainsnak, circumstances );
return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
else
if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
return context.formatSnak( options, statement.mainsnak, circumstances );
local qualifierValues = {};
for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
local snakValue = context.formatSnak( options, qualifierSnak );
if snakValue and snakValue ~= '' then
table.insert( qualifierValues, context.formatSnak( options, qualifierSnak ) );
end
end
if ( #qualifierValues ) then
result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
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 )
Рядок 624 ⟶ 471:
end
 
local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
local after = '</span>'
 
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
result = options['somevalue'];
else
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 );
 
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
return before .. options['somevalue'] .. after;
end
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;
result = options.i18n.presumably .. result;
end
if ( circumstances.circa ) then
resultbefore = optionsbefore .i18n.circa options.i18n. resultcirca;
end
else
throwError( 'unknown-snak-type' );
end
if ( not result or result == '' ) then
return nil;
end
 
return before .. resultformatDatavalue( context, options, snak.datavalue, snak.datatype ) .. after;
else
throwError( 'unknown-snak-type' );
end
end
 
--[[
Функция для оформления объектов-значений с географическими координатами
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
return value['latitude']
elseif options['subvalue'] == 'longitude' then -- долготы
return value['longitude']
else
elseif options['nocoord'] and options['nocoord'] ~= '' then
-- в противном случае формируются параметры для вызова шаблона {{coord}}
-- если передан параметр nocoord, то не выводить координаты
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- обычно это делается при использовании нескольких карточек на странице
-- любое изменние его парамеров должно быть согласовано с кодом тут
return ''
local eps = 0.0000001 -- < 1/360000
else
local globe = '' -- TODO
-- в противном случае формируются параметры для вызова шаблона {{coord}}
local lat = {}
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
lat['abs'] = math.abs(value['latitude'])
-- любое изменние его парамеров должно быть согласовано с кодом тут
lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
local eps = 0.0000001 -- < 1/360000
lat['d'] = math.floor(lat['abs'] + eps)
local globe = options.globe or '' -- TODO
lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
local lat = {}
lat['abss'] = math.absmax(value0, ((lat['latitudeabs'] - lat['d']) * 60 - lat['m']) * 60)
local lon = {}
lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
lat lon['dabs'] = math.floorabs(latvalue['abslongitude'] + eps)
lat lon['mew'] = math.floor((latvalue['abslongitude'] ->= 0 and lat['dE']) *or 60 + eps)'W'
lat['s'] = math.max(0, ((lat['abs'] - lat lon['d']) *= 60 - latmath.floor(lon['mabs']) * 60 + eps)
lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
local lon = {}
lon['abss'] = math.absmax(value0, ((lon['longitudeabs'] - lon['d']) * 60 - lon['m']) * 60)
lon['ew'] = value['longitude'] >= 0 and 'E' or 'W'
lon['d'] = math.floor(lon['abs'] + eps)
lon['m'] = math.floor((lon['abs'] - lon['d']) * 60 + eps)
lon['s'] = math.max(0, ((lon['abs'] - lon['d']) * 60 - lon['m']) * 60 + eps)
-- TODO: round seconds with precision
local coord = '{{coord'
if (value['precision'] == nil) or (value['precision'] < 1/60) then -- по умолчанию с точностью до секунды
Рядок 717 ⟶ 551:
end
 
--[[
Функция для оформления объектов-значений с файлами с Викисклада
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatCommonsMedia( value, options )
local image = '[[File:' .. value;
if options['border'] and options['border'] ~= '' then
image = image .. '|border'
end
 
local captionsize = options['size';]
if options[ 'caption' ] andif options[size 'caption'and ]size ~= '' then
if not string.match( size, 'px$' )
caption = options[ 'caption' ];
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
elseif options[ 'description' ] and options[ 'description' ] ~= '' then
then
caption = options[ 'description' ];
size = size .. 'px'
end
end
if caption ~= '' then
caption = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>';
end
 
if not string.find( value, '[%[%]%{%}]' ) then
image = '[[File:' .. value .. '|frameless';
if options[ 'border' ] and options[ 'border' ] ~= '' then
image = image .. '|border';
end
 
local size = options[ 'size' ];
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
else
size = '250x350px' -- TODO: вынести в настройки
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
end
image = image .. '|' .. size
 
if options['alt'] and options['alt'] ~= '' then
return image
image = image .. '|' .. options['alt']
end
end
 
image = image .. ']]'
--[[
Fonction for render math formulas
 
@param string Value.
@param table Parameters.
@return string Formatted string.
]]
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 wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, options.property:upper() )
if wbStatus == true and propertyEntity then
local isGoodFormat = false;
local statements = propertyEntity:getBestStatements( 'P1793' );
for _, statement in pairs( statements ) 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
 
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
end
end
 
if formatter and formatter ~= '' then
local link = mw.ustring.gsub( mw.ustring.gsub( formatter, '$1', value ), ' ', '%%20' )
 
local title = options.title
if not title or title == '' then
title = '$1'
end
title = mw.ustring.gsub( title, '$1', value )
 
if options['description'] and options['description'] ~= '' then
return '[' .. link .. ' ' .. title .. ']'
image = image .. '<br>' .. options['description']
end
 
return valueimage
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, 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
 
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/', '' );
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
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
 
return out;
end
 
Рядок 931 ⟶ 604:
 
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 ), options ) end;
elseif datavalue.type == 'string' then
-- String
if datatype and datatype == 'commonsMedia' then
-- Media
return function( context, options, value )
local lang = mw.language.getContentLanguage()
if ( not options.caption or options.caption == '' )
andif ( not options.description or options.description == '' )
and options.qualifiers and options.qualifiers.P2096 then
for i, qualifier in pairs( options.qualifiers.P2096 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'monolingualtext'
and qualifier.datavalue.value
and qualifier.datavalue.value.language == contentLanguageCodelang:getCode() ) then
options.caption = qualifier.datavalue.value.text
options.description = qualifier.datavalue.value.text
break
end
end
end
return formatCommonsMedia( value, options )
if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
end;
local moment = formatDatavalue (context, options, options.qualifiers.P585[1].datavalue, 'time')
end
if not options.caption or options.caption == '' then
return function( context, options, value ) return value end;
options.caption = moment
elseif datavalue.type == 'monolingualtext' then
options.description = moment
-- моноязычный текст (строка с указанием языка)
else
return function( context, options, value )
options.caption = options.caption .. ', ' .. moment
if ( options.monolingualLangTemplate == 'lang' ) then
options.description = options.description .. ', ' .. moment
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 };
return formatCommonsMedia( value, options )
else
end;
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
elseif datatype and datatype == 'external-id' then
end
-- External ID
end;
return function( context, options, value )
elseif datavalue.type == 'globecoordinate' then
return formatExternalId( value, options )
-- географические координаты
end
return function( context, options, value ) return formatGlobeCoordinate( value, options ) end;
elseif datatype and datatype == 'math' then
elseif datavalue.type == 'quantity' then
-- Math formula
return function( context, options, value )
-- диапазон значений
return formatMath( value, options )
local amount = string.gsub(value['amount'], '^%+', '')
end
local lang = mw.language.getContentLanguage()
elseif datatype and datatype == 'url' then
return lang:formatNum( tonumber( amount ) )
-- URL
end;
return function( context, options, value )
elseif datavalue.type == 'time' then
local moduleUrl = require( 'Module:URL' )
local langRefs = formatLangRefs return function( context, options, value )
local moduleDate = require('Module:Wikidata/date')
if not options.length or options.length == '' then
return moduleDate.formatDate( context, options, value );
options.length = math.max( 18, 25 - #langRefs )
end;
else
return moduleUrl.formatUrlSingle( context, options, value ) .. langRefs
-- во всех стальных случаях возвращаем ошибку
end
throwError( 'unknown-datavalue-type' )
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 value.text;
end
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
elseif ( options.monolingualLangTemplate == 'ref' ) then
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language };
else
return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>';
end
end;
elseif datavalue.type == 'globecoordinate' then
-- географические координаты
return function( context, options, value ) return formatGlobeCoordinate( value, options ) end;
elseif datavalue.type == 'quantity' then
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 )
Рядок 1064 ⟶ 679:
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
 
-- Небольшой словарь упрощенного отображения (TODO: надо сделать расширенный с учётом даты)
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
local simpleReplaces = {
Q30 = '[[Сполучені Штати Америки|США]]',
Q148 = '[[Китайська Народна Республіка|КНР]]',
Q258 = '[[Південно-Африканська Республіка|ПАР]]',
Q423 = '[[Корейська Народно-Демократична Республіка|КНДР]]',
Q2184 = '[[Російська Радянська Федеративна Соціалістична Республіка|РРФСР]]',
Q2895 = '[[Білоруська Радянська Соціалістична Республіка|Білоруська РСР]]',
Q15180 = '[[Союз Радянських Соціалістичних Республік|СРСР]]',
Q16957 = '[[Німецька Демократична Республіка|НДР]]',
Q130229 = '[[Грузинська Радянська Соціалістична Республіка|Грузинська РСР]]',
Q133356 = '[[Українська Радянська Соціалістична Республіка|Українська РСР]]',
}
 
--[[
Функция для оформления идентификатора сущности
 
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Возвращает: строку оформленного текста
]]
 
function formatEntityId( context, options, entityId )
function formatEntityId( entityId, options )
-- получение локализованного названия
local label = nil;
Рядок 1085 ⟶ 713:
label = options.text
else
if ( simpleReplaces[entityId] ) then
return simpleReplaces[entityId];
end
label = mw.wikibase.label( entityId );
end
Рядок 1123 ⟶ 754:
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="вікідані не мають української назви елемента. Ви можете помогти, вказавши її.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;
end
 
--[[
Функция для формирования категории на основе wikidata/config
]]
function p.extractCategory( context, options, value )
local wbStatus, entity = pcall( mw.wikibase.getEntity, value.id )
local category = ''
if ( options.category ) then
local claims = WDS.filter( entity.claims, options.category );
if ( claims ) then
for _, claim in pairs( claims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'wikibase-entityid' ) then
local catEntityId = claim.mainsnak.datavalue.value.id;
local wbStatus, catEntity = pcall( mw.wikibase.getEntity, catEntityId );
 
if ( wbStatus == true and catEntity ) then
if catEntity:getSitelink() then
category = '[[' .. catEntity:getSitelink() .. ']]';
end
end
end
end
end
end
return category;
end
 
Рядок 1168 ⟶ 770:
 
function getPropertyParams( propertyId, datatype, params )
local config = getConfigrequire( 'Module:Wikidata/config' );
if not config then
return {};
end
 
-- Различные уровни настройки параметров, по убыванию приоритета
Рядок 1175 ⟶ 780:
-- 1. Параметры, указанные явно при вызове
if params then
forlocal key,tplParams value= in pairsmw.clone( params ) do;
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[ key ] = value;
end
end
Рядок 1183 ⟶ 789:
 
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
forlocal key,selfParams value= in pairsmw.clone( config[ 'properties' ][ propertyId ] ) do;
for key, value in pairs( selfParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
Рядок 1192 ⟶ 799:
 
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
and config[ 'presets' ][ propertyParams[ 'preset' ] ] then
local presetParams = mw.clone( config['presets'][propertyParams['preset']] );
then
for key, value in pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ]presetParams ) 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
forlocal key,datatypeParams value= in pairsmw.clone( config[ 'datatypes' ][ datatype ] ) do;
for key, value in pairs( datatypeParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
Рядок 1217 ⟶ 820:
 
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
forlocal key,globalParams value= in pairsmw.clone( config[ 'global' ] ) do;
for key, value in pairs( globalParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
Рядок 1229 ⟶ 833:
 
function p.formatProperty( frame )
local argsplain = toBoolean( frame.args.plain, false );
frame.args.nocat = toBoolean( frame.args.nocat, false );
 
frame.args.microformatClass = toBoolean(frame.args.microformatClass, false);
-- проверка на отсутствие обязательного параметра property
frame.args.references = toBoolean( frame.args.references, true );
if not args.property then
local args = frame.args
throwError( 'property-param-not-provided' )
args = getPropertyParams( propertyId, datatype, args );
end
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
-- проверка на отсутствие обязательного параметра property
args = getPropertyParams( propertyId, nil, args );
if not args.property then
local datatype = args.datatype;
throwError( 'property-param-not-provided' )
end
p_frame = frame
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
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.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
 
-- опция, запрещающая оформление значения, поэтому никак не трогаем
if plain then
return value
end
-- обробка за типом значення
local datatype = getPropertyDatatype( propertyId );
if args['value-module']datatype and== args['value-functioncommonsMedia'] and not string.find( value, '[%[%]%{%}]' ) then
local func = getUserFunction( args, 'value' );
value = func( {}, args, value );
elseif datatype == 'commonsMedia' and not string.find( value, '[%[%]%{%}]' ) then
value = formatCommonsMedia( 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
args.length = 25
end
value = moduleUrl.formatUrlSingle( nil, args, value );
end
 
-- если трогать всё-таки можно, добавляем категорию-маркер
if (not args.nocat) and (not frame:callParserFunction( '#property', args.property )=='') then
value = value .. categoryLocalValuePresent;
end
-- оборачиваем в тег для JS-функций
if string.match( propertyId, '^P%d+$' ) then
Рядок 1299 ⟶ 888:
end
 
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
return frame:callParserFunction( '#property', propertyId );
local callArgs = { propertyId };
end
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
 
g_frame = frame
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
return formatProperty( frame.args )
end
 
--[[
Функция оформления ссылок на источники (reference)
Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru
 
Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
 
Принимает: объект-таблицу утверждение
Возвращает: строку оформленных ссылок для отображения в статье
]]
function formatRefs( context, options, statement )
if ( not context ) then error( 'context not specified' ); end;
if ( not options ) then error( 'options not specified' ); end;
if ( not options.entity ) then error( 'options.entity missing' ); end;
if ( not statement ) then error( 'statement not specified' ); end;
 
if ( not outputReferences ) then
return '';
end
 
local referencesresult = {}'';
if ( statement.references ) then
 
local allReferences = statement.references;
local hasPreferred = false;
for _, reference in pairs( statement.references ) do
local displayCount = 0;
if ( reference.snaks
for _, reference in pairs( statement.references ) do
if ( and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
and local entityId = "Q" .. reference.snaks.P248[1].datavalue.value.["numeric-id ) then"];
if ( preferredSources[entityId] ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
hasPreferred = true;
if ( preferredSources[entityId] ) then
end
hasPreferred = true;
end
end
end
end
 
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasPreferred ) then
if ( reference.snaks
and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value.["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.P248[1].datavalue.value.["numeric-id"];
if ( deprecatedSources[entityId] ) then
display = false;
end
end
end
end
end
end
if ( display == true ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
if ( displayCount > 2 ) then
end
if ( options.entity and options.property ) then
end
table.remove( references );
end
local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( options.property ) .. '|[…]]]</sup>';
return result
table.insert( references, moreReferences );
end
 
break;
function p.entityName(frame)
end;
return formatEntityId(frame.args[1], frame.args)
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