Модуль:Wikidata2: юрамалар арасында аерма

Контент бетерелгән Контент өстәлгән
IanraBot (бәхәс | кертем)
к →‎top: clean up, replaced: неизвестно → билгесез using AWB
Marat-avgust (бәхәс | кертем)
Төзәтмә аңлатмасы юк
Юл номеры - 59:
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
 
Строка 69 ⟶ 81 :
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);
Строка 137 ⟶ 149 :
end
 
--[[
Преобразует строку в булевое значение
 
Строка 144 ⟶ 156 :
]]
local function toBoolean( valueToParse, defaultValue )
if ( valueToParse ~= nil ) then
if valueToParse == false or valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
return false
end
return true
end
return defaultValue;
end
 
--[[
Функция для получения сущности (еntity) для текущей страницы
Подробнее о сущностях см. d:Wikidata:Glossary/ru
 
Принимает: строковый индентификатор (типа P18, Q42)
Возвращает: объект таблицу, элементы которой индексируются с нуля
]]
local function getEntityFromId( id )
local entity;
if id then
local wbStatus;
return mw.wikibase.getEntityObject( id )
 
end
if id then
return mw.wikibase.getEntityObject();
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
end
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
 
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
 
Строка 228 ⟶ 245 :
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
Строка 239 ⟶ 256 :
end
 
return result;
end
 
--[[
Функция для получения значения свойства элемента в заданный момент времени.
 
Принимает: контекст, элемент, временные границы, таблица ID свойства
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entity, boundaries, propertyIds )
Строка 263 ⟶ 280 :
table.insert( results, claim.mainsnak );
else
local startBoundaries = getTimeBoundariesFromQualifiersp.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = getTimeBoundariesFromQualifiersp.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
Строка 283 ⟶ 300 :
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 )
Строка 298 ⟶ 356 :
 
-- name from label
local label = nil;
if ( options.text and options.text ~= '' ) then
label = options.text;
else
label, langCode = entity:getLabelWithLang();
 
if not langCode then
return nil;
end
 
if not propertyIds then
propertyIds = {
Строка 315 ⟶ 373 :
};
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
Строка 336 ⟶ 394 :
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
Строка 374 ⟶ 432 :
formatPropertyDefault = formatPropertyDefault,
formatStatementDefault = formatStatementDefault }
context.formatPropertycloneOptions = function( options )
local entity = options.entity;
options.entity = nil;
 
newOptions = mw.clone( options );
options.entity = entity;
newOptions.entity = entity;
 
return newOptions;
end;
context.formatProperty = function( options )
local func = getUserFunction( options, 'property', context.formatPropertyDefault );
return func( context, options )
Строка 381 ⟶ 449 :
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
Строка 405 ⟶ 473 :
if ( not options.entity ) then error( 'options.entity missing' ); end;
 
local claims;
if options.property then -- TODO: Почему тут может не быть property?
claims = context.selectClaims( options, options.property );
end
if claims == nil then
return '' --TODO error?
end
 
-- Обход всех заявлений утверждения и с накоплением оформленых предпочтительных
-- заявлений в таблице
local formattedClaims = {}
 
for i, claim in ipairs(claims) do
local formattedStatement = context.formatStatement( options, claim )
-- здесь может вернуться либо оформленный текст заявления
-- либо строка ошибки nil похоже никогда не возвращается
if (formattedStatement) then
formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
table.insert( formattedClaims, formattedStatement )
end
end
 
-- создание текстовой строки со списком оформленых заявлений из таблицы
local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
if out ~= '' then
if options.before then
out = options.before .. out
end
if options.after then
out = out .. options.after
end
end
 
return out
end
 
--[[
Функция для оформления одного утверждения (statement)
 
Принимает: объект-таблицу утверждение и таблицу параметров
Возвращает: строку оформленного текста с заявлением (claim)
]]
function formatStatement( context, options, statement )
Строка 451 ⟶ 519 :
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
 
Строка 470 ⟶ 538 :
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;
Строка 484 ⟶ 552 :
end
 
--[[
Функция для оформления одного утверждения (statement)
 
Принимает: объект-таблицу утверждение, таблицу параметров,
объект-функцию оформления внутренних структур утверждения (snak) и
объект-функцию оформления ссылки на источники (reference)
Возвращает: строку оформленного текста с заявлением (claim)
]]
function formatStatementDefault( context, options, statement )
Строка 499 ⟶ 567 :
local circumstances = context.getSourcingCircumstances( statement );
 
ifoptions.qualifiers = statement.qualifiers then;
options.qualifiers = statement.qualifiers;
end
 
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:Викиданные:Глоссарий
 
Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций
Возвращает: строку оформленного викитекста
]]
function formatSnak( context, options, snak, circumstances )
Строка 530 ⟶ 596 :
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;
Строка 548 ⟶ 614 :
end
 
return before .. formatDatavalue( 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']
elseif options['nocoord'] and options['nocoord'] ~= '' then
-- если передан параметр nocoord, то не выводить координаты
-- обычно это делается при использовании нескольких карточек на странице
return ''
else
-- в противном случае формируются параметры для вызова шаблона {{coord}}
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
local globe = options.globe or '' -- TODO
local lat = {}
lat['abs'] = math.abs(value['latitude'])
lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
lat['d'] = math.floor(lat['abs'] + eps)
lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
lat['s'] = math.max(0, ((lat['abs'] - lat['d']) * 60 - lat['m']) * 60 + eps)
local lon = {}
lon['abs'] = math.abs(value['longitude'])
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 -- по умолчанию с точностью до секунды
coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['s'] .. '|' .. lat['ns']
coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['s'] .. '|' .. lon['ew']
elseif value['precision'] < 1 then
coord = coord .. '|' .. lat['d'] .. '|' .. lat['m'] .. '|' .. lat['ns']
coord = coord .. '|' .. lon['d'] .. '|' .. lon['m'] .. '|' .. lon['ew']
else
coord = coord .. '|' .. lat['d'] .. '|' .. lat['ns']
coord = coord .. '|' .. lon['d'] .. '|' .. lon['ew']
end
coord = coord .. '|globe:' .. globe
if options['type'] and options['type'] ~= '' then
coord = coord .. '|type=' .. options.type
end
if options['display'] and options['display'] ~= '' then
coord = coord .. '|display=' .. options.display
else
coord = coord .. '|display=title'
end
coord = coord .. '}}'
 
return g_frame:preprocess(coord)
end
end
 
--[[
Функция для оформления объектов-значений с файлами с Викисклада
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatCommonsMedia( value, options )
local image = '[[File:' .. value
if options['border'] and options['border'] ~= '' then
image = image .. '|border'
end
 
local sizecaption = options['size']
if sizeoptions['caption'] and sizeoptions['caption'] ~= '' then
caption = options['caption']
if not string.match( size, 'px$' )
elseif options['description'] and options['description'] ~= '' then
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
caption = options['description']
then
end
size = size .. 'px'
if caption ~= '' then
end
caption = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>'
else
end
size = fileDefaultSize;
end
image = image .. '|' .. size
 
if not string.find( value, '[%[%]%{%}]' ) then
if options['alt'] and options['alt'] ~= '' then
image = image .. '|[[File:' .. options['alt']value
if options['border'] and options['border'] ~= '' then
end
image = image .. ']]|border'
end
 
if options['description'] and options['description'] ~= '' then
imagelocal size = image .. '<br>' .. options['descriptionsize']
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
image = image .. caption
end
 
return image
end
 
--[[
Функция для оформления внешних идентификаторов
 
Принимает: объект-значение и таблицу параметров,
Возвращает: строку оформленного текста
]]
local function formatExternalId( value, options )
local formatter = options.formatter
 
if not formatter or formatter == '' then
local wbStatus, entity = pcall( mw.wikibase.getEntity(, options.property:upper() )
if wbStatus == true and entity then
local statements = entity:getBestStatements( 'P1630' )
for _, statement in pairs( statements ) do
Строка 688 ⟶ 770 :
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
 
local out = formatNum( tonumber( amount ) );
if options.unit and options.unit ~= '' then
if optionsvalue.unit ~= '-'upperBound then
local diff = tonumber( value.upperBound ) - tonumber( amount )
out = out .. ' ' .. options.unit
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
end
out = out .. '±' .. formatNum( diff )
elseif value.unit and string.match( value.unit, 'http://www.wikidata.org/entity/' ) then
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
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
Строка 730 ⟶ 812 :
'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'.
Строка 748 ⟶ 830 :
return nil;
end
 
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity(, propertyId );
if wbStatus ~= true or not propertyEntity then
return nil;
end
Строка 758 ⟶ 840 :
 
local function getDefaultValueFunction( datavalue, datatype )
-- вызов обработчиков по умолчанию для известных типов значений
if datavalue.type == 'wikibase-entityid' then
-- Entity ID
return function( context, options, value ) return formatEntityId( context, options, getEntityIdFromValue( value ) ) end;
elseif datavalue.type == 'string' then
-- String
if datatype and datatype == 'commonsMedia' then
-- Media
return function( context, options, value )
if ( not options.descriptioncaption or options.descriptioncaption == '' )
and ( not options.qualifiersdescription andor options.qualifiers.P2096description == '' then)
for and i,options.qualifiers qualifier in pairs(and options.qualifiers.P2096 ) dothen
for i, qualifier in pairs( options.qualifiers.P2096 ) do
if ( qualifier
and qualifier.datavalue
Строка 775 ⟶ 858 :
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;
elseif datatype and datatype == 'external-id' then
-- External ID
return function( context, options, value )
return formatExternalId( value, options )
end
elseif datatype and datatype == 'url' then
-- URL
return function( context, options, value )
local moduleUrl = require( 'Module:URL' )
if not options.length or options.length == '' then
options.length = 25
end
return moduleUrl.formatUrlSingle( context, options, value );
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
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 )
Строка 838 ⟶ 922 :
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
 
--[[
Функция для оформления идентификатора сущности
 
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
Возвращает: строку оформленного текста
]]
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local wbStatus, entity = pcall( mw.wikibase.getEntity(, entityId )
if wbStatus ~= true then
local label, labelLanguageCode = getLabelWithLang( context, options, entity )
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="color:#b32424; border-bottom: 1px dotted #b32424; cursor: help; white-space: nowrap" title="Ошибка получения элемента из Викиданных.">×</span>' .. categoryLinksToEntitiesWithWikibaseError;
end
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 = claim.mainsnak.datavalue.value.id;
local wbStatus, catEntity = pcall( mw.wikibase.getEntity, catEntityId );
if ( wbStatus == true and 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 mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
link = ':' .. link
end
if label then
if ( contentLanguageCode ~= labelLanguageCode ) then
return '[[' .. link .. '|' .. label .. ']]' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel .. category;
else
return '[[' .. link .. '|' .. label .. ']]' .. category;
end
end
else
return '[[' .. link .. ']]' .. category;
end
end
 
if label then
-- красная ссылка
-- TODO: разобраться, почему не всегда есть options.frame
local title if not= mw.title.new( label ).exists and options.frame then;
if title and not title.exists and options.frame then
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>';
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
end
 
-- TODO: перенести до проверки на существование статьи
Строка 885 ⟶ 1001 :
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>' .. categoryLinksToEntitiesWithMissingLabel .. category;
end
 
--[[
Функция для оформления утверждений (statement)
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
 
Принимает: таблицу параметров
Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
-- устаревшее имя, не использовать
Строка 908 ⟶ 1024 :
 
--[[
Получение параметров, которые обычно используются для вывода свойства.
]]
function getPropertyParams( propertyId, datatype, params )
Строка 939 ⟶ 1055 :
end
 
-- 3. Указанный пресет настроек
if propertyParams['preset'] and config['presets']
and config['presets'][propertyParams['preset']] then
Строка 974 ⟶ 1090 :
 
function p.formatProperty( frame )
local plainargs = toBoolean( frame.args.plain, false );
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 );
Строка 991 ⟶ 1106 :
end
 
args.nocatplain = toBoolean( args.nocatplain, false );
args.referencesnocat = toBoolean( args.referencesnocat, truefalse );
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
 
-- обработчики по типу значения
Строка 1012 ⟶ 1128 :
local func = getUserFunction( args, 'value' );
value = func( {}, args, value );
elseif datatype == 'commonsMedia' and not string.find( value, '[%[%]%{%}]' ) then
value = formatCommonsMedia( value, args );
elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then
Строка 1019 ⟶ 1135 :
elseif datatype == 'url' then
local moduleUrl = require( 'Module:URL' );
value = moduleUrl.formatUrlSingle( nil, args, value );
end
 
-- оборачиваем в тег для JS-функций
if string.match( propertyId, '^P%d+$' ) then
value = mw.text.trim( value )
 
-- временная штрафная категория для исправления табличных вставок
if ( propertyId ~= 'P166'
and string.match( value, '<t[dr][ >]' )
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. '[[Категория:Википедия:Статьи с табличной вставкой в карточке]]'
else
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
if ( string.match( value, '\n' )
or string.match( value, '<t[dhr][ >]' )
or string.match( value, '<div[ >]' ) ) then
value = '<div class="no-wikidata"' .. wrapperExtraArgs
.. ' data-wikidata-property-id="' .. propertyId .. '">\n'
.. value .. '</div>'
else
value = '<span class="no-wikidata"' .. wrapperExtraArgs
.. ' data-wikidata-property-id="' .. propertyId .. '">'
.. value .. '</span>'
end
end
end
 
-- добавляем категорию-маркер
if not args.nocat then
local pageTitle = mw.title.getCurrentTitle();
value = value .. categoryLocalValuePresent;
if pageTitle.namespace == 0 then
value = value .. categoryLocalValuePresent;
end
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/ru
 
Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
 
Принимает: объект-таблицу утверждение
Возвращает: строку оформленных ссылок для отображения в статье
]]
function formatRefs( context, options, statement )
Строка 1095 ⟶ 1214 :
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;
Строка 1110 ⟶ 1229 :
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;