«Մոդուլ:Wikidata» խմբագրումներու միջեւ տարբերութիւն
Content deleted Content added
No edit summary |
No edit summary |
||
Տող 1.
-- settings, may differ from project to project
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
Q523660 = true, -- International Music Score Library Project by https://ru.wikipedia.org/?diff=107090748
};
Տող 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;
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 +
end
Տող 148 ⟶ 155՝
end
--[[
Преобразует строку в булевое значение
Տող 155 ⟶ 162՝
]]
local function toBoolean( valueToParse, defaultValue )
end
--[[
Обрачивает отформатированное значение в тег
Принимает: строковое значение, строку с атрибутами (может отсутствовать)
Возвращает: строковое значение, значения с блочными тегами остаются блоком, текст встраиваем в строку
]]
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
--[[
Функция для получения сущности (еntity) для текущей страницы
Подробнее о сущностях см. d:Wikidata:Glossary/ru
Принимает: строковый индентификатор (типа 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
--[[
]]
local function throwError( key )
end
--[[
]]
local function getEntityIdFromValue( value )
end
-- проверка на наличие специилизированной функции в опциях
local function getUserFunction( options, prefix, defaultFunction )
end
Տող 239 ⟶ 271՝
result = WDS.filter( options.entity.claims, propertySelector );
if options.limit and options.limit ~= '' and options.limit ~= '-' then
Տող 250 ⟶ 282՝
end
end
--[[
]]
local function getPropertyInBoundaries( context,
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
local selector = selectors[_];
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
end
end
Տող 294 ⟶ 331՝
end
--[[
]]
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
Տող 317 ⟶ 354՝
end
--[[
]]
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,
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
-- name from label
if not propertyIds then
propertyIds =
selectors = getLabelWithLang_DEFAULT_SELECTORS;
end
-- name from properties
local results = getPropertyInBoundaries( context,
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;
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;
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 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 )
-- проверка на присутсвие у сущности заявлений (claim)
-- подробнее о заявлениях см. d:Викиданные:Глоссарий
-- 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
--[[
Функция для оформления одного утверждения (statement)
]]
function formatStatement( context, options, statement )
Տող 513 ⟶ 556՝
error( 'statement is not specified or nil' );
end
end
Տող 533 ⟶ 576՝
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
end
end
Տող 546 ⟶ 583՝
end
--[[
]]
function formatStatementDefault( context, options, statement )
Տող 563 ⟶ 600՝
options.qualifiers = statement.qualifiers;
local result = context.formatSnak( options, statement.mainsnak, circumstances );
if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
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
--[[
]]
function formatSnak( context, options, snak, circumstances )
Տող 590 ⟶ 648՝
local after = '</span>'
result
else
result
end
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
result = options['novalue'];
else
result = options.i18n['novalue'];
end
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
for _, item in pairs(circumstances) do
if options.i18n[item] then
result = options.i18n[item] .. result;
end
end
else
throwError( 'unknown-snak-type' );
end
if ( not result or result == '' ) then
return nil;
end
end
--[[
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or ''
if globe ==
globes = require( 'Module:Wikidata/Globes' )
globe = globes[value['globe']] or ''
end
local display = 'inline'
if options.display and options.display ~= '' then
display = options.display
elseif ( options.property:upper() == 'P625' ) then
display = 'title'
end
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display }
return coord_mod.coord(g_frame)
end
end
--[[
]]
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, '
end
if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
-- если в value не содержится викикод или imagemap, то викифицируем имя файла
-- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[PHAB:T28213]]
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
else
size = fileDefaultSize;
image = image .. '|' .. size;
image = image .. ']]';
if caption ~= '' then
image = image .. '<br>' .. caption;
end
if
image = image .. getCategoryByCode( '
end
else
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
end
if options.entity and options.fixdouble then
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
if
local
local statements = propertyEntity:getBestStatements( 'P1793' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
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
Տող 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 function
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 ) );
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
-- Пробуем понять до какого знака округлять
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 wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
if wbStatus == true and unitEntity then
if unitEntity.claims.P2370 and
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
not value.upperBound and
options.siConversion == true
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
-- Если не степени десятки (переводить сантиметры в метры не надо!)
outValue = tonumber( amount ) * conversionToSIunit
if ( outValue > 0 ) then
-- Пробуем понять до какого знака округлять
local integer, dot, decimals, expstr = amount:match( '^(%d*)(%.?)(%d*)(.*)' )
local prec
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
local adjust = math.log10( math.abs( conversionToSIunit )) + math.log10( 2 )
local minprec = 1 - math.floor( math.log10( outValue ) + 2e-14 );
out = formatNum( outValue, math.max( math.floor( prec + adjust ), minprec ));
else
out = formatNum( outValue, 0 )
end
unitEntityId = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.unit, 'http://www.wikidata.org/entity/', '' );
wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
end
end
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
local label = getLabelWithLang( context, options, unitEntity.id, nil, { "P5061", "P558", "P558" }, {
'P5061[language:' .. langCode .. ']',
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
'P558[!P282][!P407]'
} );
out = out .. ' ' .. label;
end
end
end
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
if (cached ~= nil) then return cached; end
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 .. '​' .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
end
end
end
end
end
end
end
return langRefs
end
local function getDefaultValueFunction( datavalue, datatype )
options.local_caption = options.description;
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
if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
local moment = formatDatavalue (context, options, options.qualifiers.P585[1].datavalue, 'time')
if not options.caption or options.caption == '' then
options.caption = moment
options.description = moment
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 )
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
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;
-- географические координаты
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' )
end
--[[
]]
function formatDatavalue( context, options, datavalue, datatype )
Տող 916 ⟶ 1108՝
if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;
end
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
--[[
Функция для оформления идентификатора сущности
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local boundaries = nil
if options.qualifiers then
boundaries = p.getTimeBoundariesFromQualifiers( frame, context, { qualifiers = options.qualifiers } )
end
if not boundaries then
boundaries = DEFAULT_BOUNDARIES;
end
-- определение соответствующей показываемому элементу категории
local category =
-- получение ссылки по идентификатору
local link = mw.wikibase.sitelink( entityId )
if link then
-- ссылка на категорию, а не добавление страницы в неё
if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
return a .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
return a .. category;
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>'
if label then
if ( contentLanguageCode == labelLanguageCode ) then
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;
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
--[[
]]
-- устаревшее имя, не использовать
Տող 1012 ⟶ 1227՝
--[[
]]
function getPropertyParams( propertyId, datatype, params )
local config =
-- Различные уровни настройки параметров, по убыванию приоритета
Տող 1025 ⟶ 1237՝
-- 1. Параметры, указанные явно при вызове
if params then
if value ~= '' then
propertyParams[ key ] = value;
end
end
Տող 1034 ⟶ 1245՝
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
if propertyParams[ key ] == nil then
end
end
end
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
then if propertyParams[ key ] == nil then
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
if propertyParams[ key ] == nil then
end
end
Տող 1065 ⟶ 1279՝
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
if propertyParams[ key ] == nil then
end
end
Տող 1078 ⟶ 1291՝
function p.formatProperty( frame )
local override;
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '([^Pp0-9].*)$', function(w)
if string.sub( w, 1, 1 ) == '~' then override = w; end
return '';
end ) )
args = getPropertyParams( propertyId, nil, args );
if (override) then
args[override:match('[,~]([^=]*)=')] = override:match('=(.*)')
args['property'] = propertyId
end
local datatype = args.datatype;
-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
while p_frame do
if p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args, true );
end
if p_frame.args and p_frame.args.from and p_frame.args.from ~= '' then
args.entityId = p_frame.args.from;
end
p_frame = p_frame:getParent();
end
-- если значение передано в параметрах вызова то выводим только его
local value = args.value
-- обработчики по типу значения
Տող 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
args.length = 25
end
value = moduleUrl.formatUrlSingle( nil, args, value );
end
value = value .. getCategoryByCode( 'value-contains-table' )
value = wrapFormatProperty( value, 'class="no-wikidata"'
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
.. propertyId .. '"' );
end
end
local pageTitle = mw.title.getCurrentTitle();
if pageTitle.namespace == 0 then
value = value .. getCategoryByCode( 'local-value-present' );
end
end
local callArgs = { propertyId };
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
g_frame = frame
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
end
--[[
]]
function formatRefs( context, options, statement )
Տող 1190 ⟶ 1420՝
end
local
if ( statement.references ) then
local allReferences = statement.references;
local
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 (
end
end
Տող 1210 ⟶ 1441՝
for _, reference in pairs( statement.references ) do
local display = true;
if (
if ( reference.snaks
and reference.snaks.P248
Տող 1222 ⟶ 1453՝
end
end
if (
if ( options.entity and options.property ) then
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
end
|