Модуль:Вікізьвесткі
Перайсьці да навігацыі
Перайсьці да пошуку
Дакумэнтацыю да гэтага модуля можна стварыць у Модуль:Вікізьвесткі/Дакумэнтацыя
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>',
}
-- налады, могуць адрозьнівацца ў розных праектах
local categoryLinksToEntitiesWithMissingLocalLanguageLabel = '[[Катэгорыя:Вікіпэдыя:Артыкулы з элемэнтамі зь Вікізьвестак, якія патрабуюць перакладу]]';
local outputReferences = true;
-- крыніцы, якія могуць быць прапушчаныя, калі існуюць лепшыя крыніцы
local deprecatedSources = {
Q36578 = true, -- Gemeinsame Normdatei
Q63056 = true, -- Find a Grave
Q15222191 = true, -- BNF
};
local preferredSources = {
Q5375741 = true, -- Encyclopædia Britannica Online
Q17378135 = true, -- Great Soviet Encyclopedia (1969—1978)
};
-- Спасылкі на выкарыстаныя модулі, неабходныя ў 99% выпадках загрузкі старонак (каб мець на ўвазе пры перайменаваньні)
local moduleSources = require( 'Модуль:Крыніцы' )
local WDS = require( 'Модуль:Сьцьверджаньні Вікізьвестак' );
-- Канстанты
local contentLanguageCode = mw.getContentLanguage():getCode();
local p = {}
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
formatStatementDefault, formatProperty, getSourcingCircumstances,
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
local function copyTo( obj, target )
for k, v in pairs( obj ) do
target[k] = v
end
return target;
end
local function min( prev, next )
if ( prev == nil ) then return next;
elseif ( prev > next ) then return next;
else return prev; end
end
local function max( prev, next )
if ( prev == nil ) then return next;
elseif ( prev < next ) then return next;
else return prev; end
end
local function splitISO8601(str)
if 'table' == type(str) then
if str.args and str.args[1] then
str = '' .. str.args[1]
else
return 'невядомы тып аргумэнту: ' .. 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; -- сканчаем на Z, час Zulu
-- супадае з ±hh:mm, ±hhmm або ±hh; інакш вяртаем пустое
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 {year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s};
end
local function parseTimeBoundaries( time, precision )
local s = splitISO8601( time );
if (not s) then return nil; end
if ( precision >= 0 and precision <= 8 ) then
local powers = { 1000000000 , 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 }
local power = powers[ precision + 1 ];
local left = s.year - ( s.year % power );
return { tonumber(os.time( {year=left, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
tonumber(os.time( {year=left + power - 1, month=12, day=31, hour=29, min=59, sec=58} )) * 1000 + 1999 };
end
if ( precision == 9 ) then
return { tonumber(os.time( {year=s.year, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
tonumber(os.time( {year=s.year, month=12, day=31, hour=23, min=59, sec=58} )) * 1000 + 1999 };
end
if ( precision == 10 ) then
local lastDays = {31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
local lastDay = lastDays[s.month];
return { tonumber(os.time( {year=s.year, month=s.month, day=1, hour=0, min=0, sec=0} )) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=lastDay, hour=23, min=59, sec=58} )) * 1000 + 1999 };
end
if ( precision == 11 ) then
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=0, min=0, sec=0} )) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=23, min=59, sec=58} )) * 1000 + 1999 };
end
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 + 19991999 };
end
if ( precision == 13 ) then
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} )) * 1000,
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=58} )) * 1000 + 1999 };
end
if ( precision == 14 ) then
local t = tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} ) );
return { t * 1000, t * 1000 + 999 };
end
error('Дакладнасьць не падтрымліваецца: ' .. precision );
end
--[[
Перамяняе радок ў булевае значэньне
Атрымлівае: радковае значэньне (можа адсутнічаць)
Вяртае: булевае значэньне true ці false, калі магчыма распазнаць значэньне, або defaultValue ва ўсіх астатніх выпадках
]]
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
Атрымлівае: радковы ідэнтыфікатар (накшталт P18, Q42)
Вяртае: аб’ект-табліцу, элемэнты якой праіндэксаваныя з нулю
]]
local function getEntityFromId( id )
local entity;
local wbStatus;
if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
end
return entity;
end
--[[
Унутраная функцыя дзеля фармаваньня паведамленьня пра памылку
Атрымлівае: ключ элемэнта ў табліцы i18n (напрыклад, entity-not-found)
Вяртае: радок паведамленьня
]]
local function throwError( key )
error( 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
-- праверка на наяўнасьць спэцыялізаванай функцыі ў можнасьцях
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
-- Выбірае ўласьцівасьці па property id, дадаткова фільтруючы іх паводле рангу
local function selectClaims( context, options, propertySelector )
if ( not context ) then error( 'кантэкст не зададзены' ); end;
if ( not options ) then error( 'парамэтры не зададзеныя' ); end;
if ( not options.entity ) then error( 'адсутнічае options.entity' ); end;
if ( not propertySelector ) then error( 'propertySelector не зададзены' ); end;
result = WDS.filter( options.entity.claims, propertySelector );
if ( not result or #result == 0 ) then
return nil;
end
if options.limit and options.limit ~= '' and options.limit ~= '-' then
local limit = tonumber( options.limit, 10 );
while #result > limit do
table.remove( result );
end
end
return result;
end
--[[
Функция для получения значения свойства элемента в заданный момент времени.
Принимает: контекст, элемент, временные границы, таблица ID свойства
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entity, boundaries, propertyIds )
local results = {};
if not propertyIds or #propertyIds == 0 then
return results;
end
if entity.claims then
for _, propertyId in ipairs( propertyIds ) do
local filteredClaims = WDS.filter( entity.claims, propertyId .. '[rank:preferred, rank:normal]' );
if filteredClaims then
for _, claim in pairs( filteredClaims ) do
if not boundaries or not propertyIds or #propertyIds == 0 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
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
--[[
Функция для получения метки элемента в заданный момент времени.
Принимает: контекст, элемент, временные границы
Возвращает: текстовую метку элемента, язык метки
]]
function getLabelWithLang( context, options, entity, boundaries, propertyIds )
if not entity then
return nil;
end
local lang = mw.language.getContentLanguage();
local langCode = lang:getCode();
-- назва зь меткі
local label = nil;
if ( options.text and options.text ~= '' ) then
label, langCode = entity:getLabelWithLang();
label = options.text;
else
label, langCode = entity:getLabelWithLang();
if not langCode then
return nil;
end
if not propertyIds then
propertyIds = {
'P1813[language:' .. langCode .. ']',
'P1448[language:' .. langCode .. ']',
'P1705[language:' .. langCode .. ']'
};
end
-- name from properties
local results = getPropertyInBoundaries( context, entity, boundaries, propertyIds );
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;
lang = result.datavalue.value.language;
break;
elseif result.datavalue.type == 'string' then
label = result.datavalue.value;
break;
end
end
end
end
return label, langCode;
end
--[[
Функцыя дзеля афармленьня сьцьверджаньняў (statement)
Падрабязьней пра сьцьверджаньні гл. d:Wikidata:Glossary
Атрымлівае: табліцу парамэтраў
Вяртае: радок аформленага тэксту, прызначанага дзеля вываду ў артыкуле
]]
local function formatProperty( options )
-- Атрыманьне элемэнту па ідэнтыфікатары
local entity = getEntityFromId( options.entityId )
if not entity then
return -- throwError( 'entity-not-found' )
end
-- праверка на прысутнасьць у элемэнту заяваў (claim)
-- падрабязьней пра заявы гл. d:Wikidata:Glossary
if (entity.claims == nil) then
return '' --TODO error?
end
-- improve options
options.frame = g_frame;
options.entity = entity;
options.extends = function( self, newOptions )
return copyTo( newOptions, copyTo( self, {} ) )
end
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( i18n, {} ) );
else
options.i18n = i18n;
end
-- стварыць кантэкст
local context = {
entity = options.entity,
formatSnak = formatSnak,
formatPropertyDefault = formatPropertyDefault,
formatStatementDefault = formatStatementDefault }
context.formatProperty = function( options )
local func = getUserFunction( options, 'property', context.formatPropertyDefault );
return func( context, options )
end;
context.formatStatement = function( options, statement ) return formatStatement( context, options, statement ) end;
context.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end;
context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;
context.parseTimeFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) then
return tonumber(os.time( splitISO8601( tostring( snak.datavalue.value.time ) ) ) ) * 1000;
end
return nil;
end
context.parseTimeBoundariesFromSnak = function( snak )
if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time and snak.datavalue.value.precision ) then
return parseTimeBoundaries( snak.datavalue.value.time, snak.datavalue.value.precision );
end
return nil;
end
context.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end;
context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;
return context.formatProperty( options );
end
function formatPropertyDefault( context, options )
if ( not context ) then error( 'кантэкст не зададзены' ); end;
if ( not options ) then error( 'парамэтры не зададзеныя' ); end;
if ( not options.entity ) then error( 'адсутнічае options.entity' ); end;
local claims;
if options.property then -- TODO: Чаму тут можа ня быць property?
claims = context.selectClaims( options, options.property );
end
if claims == nil then
return '' --TODO памылка?
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 )
if ( not statement ) then
error( 'statement is not specified or nil' );
end
if not statement.type or statement.type ~= 'statement' then
throwError( 'unknown-claim-type' )
end
local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault );
return functionToCall( context, options, statement );
end
function getSourcingCircumstances( statement )
if (not statement) then error('statement is not specified') end;
local circumstances = {};
if ( statement.qualifiers
and statement.qualifiers.P1480 ) then
for i, qualifier in pairs( statement.qualifiers.P1480 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'wikibase-entityid'
and qualifier.datavalue.value
and qualifier.datavalue.value["entity-type"] == 'item' ) then
local circumstance = 'Q' .. qualifier.datavalue.value["numeric-id"];
if ( 'Q5727902' == circumstance ) then
circumstances.circa = true;
end
if ( 'Q18122778' == circumstance ) then
circumstances.presumably = true;
end
end
end
end
return circumstances;
end
--[[
Функцыя дзеля афармленьня аднаго сьцьверджаньня (statement)
Атрымлівае: аб’ект-табліцу сьцьверджаньне, табліцу парамэтраў,
аб’ект-функцыю афармленьня ўнутраных структураў сьцьверджаньня (snak) і
аб’ект-функцыю афармленьня спасылкі на крыніцы (reference)
Вяртае: радок аформленага тэксту з сьцьверджаньнем (claim)
]]
function formatStatementDefault( context, options, statement )
if (not context) then error('кантэкст не зададзены') end;
if (not options) then error('парамэтры не зададзеныя') end;
if (not statement) then error('сьцьверджаньне не зададзенае') end;
local circumstances = context.getSourcingCircumstances( statement );
options.qualifiers = statement.qualifiers;
if ( options.references ) then
return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
else
return context.formatSnak( options, statement.mainsnak, circumstances );
end
end
--[[
Функция для оформления части утверждения (snak)
Подробнее о snak см. d:Wikidata:Glossary
Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций
Возвращает: строку оформленного викитекста
]]
function formatSnak( context, options, snak, circumstances )
circumstances = circumstances or {};
local hash = '';
local mainSnakClass = '';
if ( snak.hash ) then
hash = ' data-wikidata-hash="' .. snak.hash .. '"';
else
mainSnakClass = ' wikidata-main-snak';
end
local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
local after = '</span>'
if snak.snaktype == 'somevalue' then
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;
end
if ( circumstances.circa ) then
before = before .. options.i18n.circa;
end
return before .. formatDatavalue( context, options, snak.datavalue, snak.datatype ) .. after;
else
throwError( 'unknown-snak-type' );
end
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
return 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 unitEntity = mw.wikibase.getEntity( unitEntityId );
if unitEntity then
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
local label = getLabelWithLang( context, options, unitEntity, nil, {
'P5061[language:be-tarask]',
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
'P558[!P282][!P407]'
} );
out = out .. ' ' .. label;
end
end
return out;
end
--[[
Get property datatype by ID.
@param string Property ID, e.g. 'P123'.
@return string Property datatype, e.g. 'commonsMedia', 'time' or 'url'.
]]
local function getPropertyDatatype( propertyId )
if not propertyId or not string.match( propertyId, '^P%d+$' ) then
return nil;
end
local propertyEntity = mw.wikibase.getEntity( propertyId );
if not propertyEntity then
return nil;
end
return propertyEntity.datatype;
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
-- Радок
if datatype and datatype == 'commonsMedia' then
-- Мэдыя
return function( context, options, value )
if ( not options.caption or options.caption == '' )
and ( 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 == contentLanguageCode ) then
options.caption = qualifier.datavalue.value.text
options.description = qualifier.datavalue.value.text
break
end
end
end
return formatCommonsMedia( value, options )
end;
end
return function( context, options, value ) return value end;
elseif datavalue.type == 'monolingualtext' then
-- аднамоўны тэкст (радок з пазначэньнем мовы)
return function( context, options, value )
if ( options.monolingualLangTemplate == 'мова' ) then
return options.frame:expandTemplate{ title = 'мова-' .. 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 == '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:Вікізьвесткі/дата' )
return moduleDate.formatDate( context, options, value );
end;
else
-- ва ўсіх астатніх выпадках вяртаем памылку
throwError( 'unknown-datavalue-type' )
end
end
--[[
Функцыя дзеля афармленьня значэньняў (value)
Падрабязьней пра значэньні гл. d:Wikidata:Glossary
Атрымлівае: аб’ект-значэньне і табліцу парамэтраў,
Вяртае: радок аформленага тэксту
]]
function formatDatavalue( context, options, datavalue, datatype )
if ( not context ) then error( 'кантэкст не зададзены' ); end;
if ( not options ) then error( 'парамэтры не зададзеныя' ); end;
if ( not datavalue ) then error( 'значэньне даты не зададзенае' ); end;
if ( not datavalue.value ) then error( 'адсутнічае datavalue.value' ); end;
-- праверка на пазначэньне спэцыялізаваных апрацоўнікаў у парамэтрах,
-- перададзеных пры выкліку
context.formatValueDefault = getDefaultValueFunction( datavalue, datatype );
local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
return functionToCall( context, options, datavalue.value );
end
--[[
Функция для оформления идентификатора сущности
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local entity = mw.wikibase.getEntity( entityId )
local boundaries = nil
if options.qualifiers then
boundaries = p.getTimeBoundariesFromQualifiers( frame, context, { qualifiers = options.qualifiers } )
end
local label, labelLanguageCode = getLabelWithLang( context, options, entity, boundaries )
-- определение соответствующей показываемому элементу категории
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 = 'Q' .. claim.mainsnak.datavalue.value["numeric-id"];
local catEntity = mw.wikibase.getEntity( catEntityId );
if ( catEntity and catEntity:getSitelink() ) then
category = '[[' .. catEntity:getSitelink() .. ']]';
end
end
end
end
end
-- здабыцьцё спасылкі па ідэнтыфікатары
local link = mw.wikibase.sitelink( entityId )
if link then
if label then
if ( contentLanguageCode ~= labelLanguageCode ) then
return '[[' .. link .. '|' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel .. category;
else
return '[[' .. link .. '|' .. label .. ']]' .. category;
end
else
return '[[' .. link .. ']]' .. category;
end
end
if label then
-- чырвоная спасылка
-- TODO: высьветліць, чаму не заўжды ёсьць options.frame
if not mw.title.new( label ).exists and options.frame then
if ( contentLanguageCode ~= labelLanguageCode ) then
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel .. category;
else
return '[[' .. label .. ']]' .. category;
end
end
-- TODO: перанесьці да праверкі на існаваньне артыкулу
local sup = '';
if ( not options.format or options.format ~= 'text' )
and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: перапісаць на format=text
then
sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d]]</sup>'
end
-- одноимённая статья уже существует - выводится текст и ссылка на ВД
return '<span class="iw" data-title="' .. label .. '">' .. label
.. sup
.. '</span>' .. category
end
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="У Вікізьвестках няма беларускай меткі элемэнту. Вы можаце дапамагчы даданьнем беларускага варыянту меткі.">?</span>' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel .. category;
end
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 not string.find( value, '[%[%]%{%}]' ) then
image = '[[File:' .. value
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, 'пкс$' )
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
image = image .. caption
end
return image
end
--[[
Функцыя дзеля афармленьня сьцьверджаньняў (statement)
Падрабязьней пра сьцьверджаньні гл. d:Wikidata:Glossary
Атрымлівае: табліцу парамэтраў
Вяртае: радок аформленага тэкста, прызначанага дзеля адлюстраваньня ў артыкуле
]]
-- састарэлае імя, не выкарыстоўваць
function p.formatStatements( frame )
return p.formatProperty( frame );
end
--[[
Атрыманьне парамэтраў, якія звычайна выкарыстоўваюцца для вываду ўласьцівасьці.
]]
function getPropertyParams( propertyId, datatype, params )
local config = require( 'Модуль:Вікізьвесткі/канфігурацыя' );
if not config then
return {};
end
-- Розныя ўзроўні налады парамэтраў, паводле зьмяншэньня прыярытэту
local propertyParams = {};
-- 1. Парамэтры, зададзеныя вачавіста пры выкліку
if params then
local tplParams = mw.clone( params );
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[key] = value;
end
end
end
-- 2. Налады канкрэтнага парамэтру
if config['properties'] and config['properties'][propertyId] then
local selfParams = mw.clone( config['properties'][propertyId] );
for key, value in pairs( selfParams ) do
if propertyParams[key] == nil then
propertyParams[key] = value;
end
end
end
-- 3. Пазначаная нарыхтоўка наладаў
if propertyParams['preset'] and config['presets']
and config['presets'][propertyParams['preset']] then
local presetParams = mw.clone( config['presets'][propertyParams['preset']] );
for key, value in pairs( presetParams ) do
if propertyParams[key] == nil then
propertyParams[key] = value;
end
end
end
-- 4. Налады для тыпу зьвестак
if datatype and config['datatypes'] and config['datatypes'][datatype] then
local datatypeParams = mw.clone( config['datatypes'][datatype] );
for key, value in pairs( datatypeParams ) do
if propertyParams[key] == nil then
propertyParams[key] = value;
end
end
end
-- 5. Агульныя налады для ўсіх уласьцівасьцей
if config['global'] then
local globalParams = mw.clone( config['global'] );
for key, value in pairs( globalParams ) do
if propertyParams[key] == nil then
propertyParams[key] = value;
end
end
end
return propertyParams;
end
function p.formatProperty( frame )
local args = frame.args
-- праверка на адсутнасьць абавязковага парамэтру property
if not args.property then
throwError( 'property-param-not-provided' )
end
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
local datatype = getPropertyDatatype( propertyId );
args = getPropertyParams( propertyId, datatype, args );
-- пракід усіх парамэтраў з шаблёну {{Вікізьвесткі}}
local p_frame = frame:getParent();
if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Вікізьвесткі' then
copyTo( p_frame.args, args );
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
return value
end
if ( args.plain ) then -- выклік стандартнага апрацоўніка без афармленьня, асьлі перададзены парамэтар plain
return frame:callParserFunction( '#property', propertyId );
end
g_frame = frame
-- пасьля праверкі ўсіх аргумэнтаў — выклік функцыі афармленьня для ўласьцівасьці (набору сьцьверджаньняў)
return formatProperty( args )
end
--[[
Функцыя афармленьня спасылак на крыніцы (reference)
Падрабязьней пра спасылкі на крыніцы гл. d:Wikidata:Glossary
Экспартуецца ў якасьці зарэзэрваванага пункту для выкліку з функцый-пашырэньня выгляду 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 result = '';
if ( statement.references ) then
local allReferences = statement.references;
local hasPreferred = false;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
if ( preferredSources[entityId] ) then
hasPreferred = true;
end
end
end
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasPreferred ) then
if ( reference.snaks
and reference.snaks.P248
and reference.snaks.P248[1]
and reference.snaks.P248[1].datavalue
and reference.snaks.P248[1].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];
if ( deprecatedSources[entityId] ) then
display = false;
end
end
end
if ( display ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
end
end
end
return result
end
return p