Модуль:Wikidata — Версийн башхалла

[теллина верси][теллина верси]
Чулацам дӀабаьккхина Чулацам тӀетоьхна
Нисдарах лаьцна йаздина дац
Нисдарах лаьцна йаздина дац
МогӀа 1:
local i18n = {
["errors"] = {
["property-param-not-provided"] = "Не дан параметр свойства",
["entity-not-found"] = "Сущность не найдена.",
["unknown-claim-type"] = "Неизвестный тип заявления.",
["unknown-snak-type"] = "Неизвестный тип снэка.",
["unknown-datavalue-type"] = "Неизвестный тип значения данных.",
["unknown-entity-type"] = "Неизвестный тип сущности.",
["unknown-property-module"] = "Вы должны установить и property-module, и property-function.",
["unknown-claim-module"] = "Вы должны установить и claim-module, и claim-function.",
["unknown-value-module"] = "Вы должны установить и value-module, и value-function.",
["property-module-not-found"] = "Модуль для отображения свойства не найден",
["property-function-not-found"] = "Функция для отображения свойства не найдена",
["claim-module-not-found"] = "Модуль для отображения утверждения не найден.",
["claim-function-not-found"] = "Функция для отображения утверждения не найдена.",
["value-module-not-found"] = "Модуль для отображения значения не найден.",
["value-function-not-found"] = "Функция для отображения значения не найдена."
},
["somevalue"] = "''неизвестно''",
["novalue"] = "",
["circa"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="около, приблизительно">прибл. </span>',
["presumably"] = '<span style="border-bottom: 1px dotted; cursor: help;" title="предположительно">предп. </span>',
}
 
-- settings, may differ from project to project
local categoryLinksToEntitiesWithMissingLabel = '[[Категори:Википеди:Викихаамаш чохь элементаш тӀе куьг доцу хьажоргаш йолу яззамаш]]';
local categoryLinksToEntitiesWithWikibaseError = '[[Категори:Википеди:Викихаамаш чохь скриптийн гӀалаташ долу яззамаш]]';
local categoryLinksToEntitiesWithMissingLocalLanguageLabel = '[[Категори:Википеди:Викихаамаш чохь элементаш тӀе нохчийн куьг доцу хьажоргаш йолу яззамаш]]';
local categoryLocalValuePresent = '[[Категори:Википеди:Викихаамаш чохь маьӀнаш карладаьхна яззамаш]]';
local fileDefaultSize = '267x400px';
local outputReferences = true;
МогӀа 21 ⟶ 49 :
local contentLanguageCode = mw.getContentLanguage():getCode();
 
local p = {};
local config = nil;
 
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
МогӀа 28 ⟶ 55 :
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
 
local function copyTo( obj, target, skipEmpty )
for k, v in pairs( obj ) do
target[k] = v
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
target[k] = v;
end
end
return target;
МогӀа 47 ⟶ 72 :
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
 
МогӀа 183 ⟶ 179 :
if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
end
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
 
return entity;
МогӀа 193 ⟶ 188 :
Внутрення функция для формирования сообщения об ошибке
 
Принимает: ключ элемента в таблице config.errorsi18n (например entity-not-found)
Возвращает: строку сообщения
]]
local function throwError( key )
error( getConfig( 'i18n.errors', [key )] );
end
 
МогӀа 228 ⟶ 223 :
end
-- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require( ('Module:' .. options[ prefix .. '-module' ] );
if formatter == nil then
throwError( prefix .. '-module-not-found' )
МогӀа 271 ⟶ 266 :
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entityIdentity, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
 
local results = {};
 
МогӀа 280 ⟶ 273 :
end
 
if entity.claims then
for _, propertyId in ipairs( propertyIds ) do
for _, propertyId in ipairs( propertyIds ) do
local selector = selectors[_];
local propertyClaimsfilteredClaims = mwWDS.wikibase.getAllStatementsfilter( entityIdentity.claims, propertyId .. '[rank:preferred, rank:normal]' );
if filteredClaims then
local fakeAllClaims = {};
for _, claim in pairs( filteredClaims ) do
fakeAllClaims[propertyId] = propertyClaims;
if not boundaries or not propertyIds or #propertyIds == 0 then
local filteredClaims = WDS.filter( fakeAllClaims, selector .. '[rank:preferred, rank:normal]' );
if filteredClaims then
for _, claim in pairs( filteredClaims ) do
if not boundaries then
table.insert( results, claim.mainsnak );
else
local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' );
 
if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
table.insert( results, claim.mainsnak );
else
local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' );
 
if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
table.insert( results, claim.mainsnak );
end
end
end
end
end
 
if #results > 0 then
break;
end
end
end
МогӀа 351 ⟶ 341 :
return nil;
end
 
local CONTENT_LANGUAGE_CODE = mw.language.getContentLanguage():getCode();
local getLabelWithLang_DEFAULT_PROPERTIES = { "P1813", "P1448", "P1705" };
local getLabelWithLang_DEFAULT_SELECTORS = {
'P1813[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1448[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1705[language:' .. CONTENT_LANGUAGE_CODE .. ']'
};
 
--[[
МогӀа 366 ⟶ 348 :
Возвращает: текстовую метку элемента, язык метки
]]
function getLabelWithLang( context, options, entityIdentity, boundaries, propertyIds, selectors )
if not entity then
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 langCodelang = CONTENT_LANGUAGE_CODEmw.language.getContentLanguage();
local langCode = lang:getCode();
 
-- name from label
МогӀа 379 ⟶ 361 :
label = options.text;
else
label, langCode = entity:getLabelWithLang();
 
if not langCode then
return nil;
end
 
if not propertyIds then
propertyIds = getLabelWithLang_DEFAULT_PROPERTIES;{
'P1813[language:' .. langCode .. ']',
selectors = getLabelWithLang_DEFAULT_SELECTORS;
'P1448[language:' .. langCode .. ']',
'P1705[language:' .. langCode .. ']'
};
end
 
-- name from properties
local results = getPropertyInBoundaries( context, entityIdentity, boundaries, propertyIds, selectors );
 
for _, result in pairs( results ) do
МогӀа 391 ⟶ 382 :
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
label = result.datavalue.value.text;
langCodelang = result.datavalue.value.language;
break;
elseif result.datavalue.type == 'string' then
МогӀа 397 ⟶ 388 :
break;
end
end
end
if (not label) then
label, langCode = mw.wikibase.getLabelWithLang( entityId );
if not langCode then
return nil;
end
end
МогӀа 438 ⟶ 422 :
 
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
 
МогӀа 456 ⟶ 440 :
options.entity = entity;
newOptions.entity = entity;
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
 
return newOptions;
МогӀа 505 ⟶ 488 :
for i, claim in ipairs(claims) do
local formattedStatement = context.formatStatement( options, claim )
-- здесь может вернуться либо оформленный текст заявления, либо строка ошибки, либо nil
-- либо строка ошибки nil похоже никогда не возвращается
if ( formattedStatement and formattedStatement ~= '' ) then
if (formattedStatement) then
formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
table.insert( formattedClaims, formattedStatement )
МогӀа 586 ⟶ 570 :
options.qualifiers = statement.qualifiers;
 
if ( options.references ) then
local result = context.formatSnak( options, statement.mainsnak, circumstances );
return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
else
if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
return context.formatSnak( options, statement.mainsnak, circumstances );
local qualifierValues = {};
for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
local snakValue = context.formatSnak( options, qualifierSnak );
if snakValue and snakValue ~= '' then
table.insert( qualifierValues, context.formatSnak( options, qualifierSnak ) );
end
end
if ( #qualifierValues ) then
result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
end
end
 
if ( result and result ~= '' and options.references ) then
result = result .. context.formatRefs( options, statement );
end
 
return result;
end
 
МогӀа 630 ⟶ 599 :
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
resultreturn =before .. options['somevalue'] .. after;
else
result = options.i18n['somevalue'];
end
return before .. options.i18n['somevalue'] .. after;
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
resultreturn =before .. options['novalue'] .. after;
else
result = options.i18n['novalue'];
end
return before .. options.i18n['novalue'] .. after;
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
 
if ( circumstances.presumably ) then
before = before .. options.i18n.presumably;
result = options.i18n.presumably .. result;
end
if ( circumstances.circa ) then
resultbefore = optionsbefore .i18n.circa options.i18n. resultcirca;
end
 
return before .. formatDatavalue( context, options, snak.datavalue, snak.datatype ) .. after;
else
throwError( 'unknown-snak-type' );
end
if ( not result or result == '' ) then
return nil;
end
 
return before .. result .. after;
end
 
МогӀа 680 ⟶ 641 :
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
local globe = options.globe or '' -- TODO
coord_mod = require( "Module:Coordinates" );
local lat = {}
lat['abs'] = math.abs(value['latitude'])
local globe = options.globe or ''
if globelat['ns'] == value['latitude'] >= 0 and value['globeN'] thenor 'S'
lat['d'] = math.floor(lat['abs'] + eps)
globes = require( 'Module:Wikidata/Globes' )
globelat['m'] = globes[valuemath.floor((lat['globeabs']] or- 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
local display = 'inline'
coord = coord .. '|type=' .. options.type
if options.display and options.display ~= '' then
display = options.display
elseif ( options.property:upper() == 'P625' ) then
display = 'title'
end
if options['display'] and options['display'] ~= '' then
coord = coord .. '|display=' .. options.display
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display }
else
coord = coord .. '|display=title'
return coord_mod.coord(g_frame)
end
coord = coord .. '}}'
 
return g_frame:preprocess(coord)
end
end
МогӀа 709 ⟶ 689 :
]]
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 = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>';
end
 
if not string.find( value, '[%[%]%{%}]' ) then
image = '[[File:' .. value .. '|frameless';
if options[ 'border' ] and options[ 'border' ] ~= '' then
image = image .. '|border';
end
 
local size = options[ 'size' ];
if size and size ~= '' then
if not string.match( size, 'px$' )
МогӀа 737 ⟶ 717 :
size = fileDefaultSize;
end
image = image .. '|' .. size;
 
if options[ 'alt' ] and options[ 'alt' ] ~= '' then
image = image .. '|' .. options[ 'alt' ];
end
image = image .. ']]';
 
if caption ~= '' then
image = image .. '<br>' .. caption;
end
 
if options[ 'local_caption' ] and options[ 'local_caption' ] ~= '' then
image = image .. getCategoryByCode( 'media-contains-local-caption' )
end
else
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
end
 
return image
end
 
--[[
Fonction for render math formulas
 
@param string Value.
@param table Parameters.
@return string Formatted string.
]]
function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
end
 
МогӀа 776 ⟶ 741 :
]]
local function formatExternalId( value, options )
local formatter = options.formatter;
 
if not formatter or formatter == '' then
local wbStatus, propertyEntityentity = pcall( mw.wikibase.getEntity, options.property:upper() )
if wbStatus == true and propertyEntityentity then
local isGoodFormatstatements = false;entity:getBestStatements( 'P1630' )
local statements = propertyEntity:getBestStatements( 'P1793' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
local patternformatter = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
break
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
МогӀа 808 ⟶ 757 :
 
if formatter and formatter ~= '' then
local link = mw.ustring.gsub( mw.ustring.gsub( formatter, '$1', value ), ' ', '%%20' )
 
local title = options.title
МогӀа 834 ⟶ 783 :
local langCode = lang:getCode();
 
local function formatNum( number, sigfig )
sigfig = sigfig or 12 -- округление до 1213 знаков после запятой, на 1314-м возникает ошибка в точности
local mult = 10^sigfig;13
number = math.floor( number * mult + 0.5 ) / mult;
 
return string.gsub( lang:formatNum( number ), '^-', '−' );
end
 
МогӀа 846 ⟶ 795 :
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
out = out .. ' ± ' .. formatNum( diff )
end
end
МогӀа 856 ⟶ 805 :
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 unitEntityId ~= 'undefined' then
localif wbStatus, unitEntity == pcall(true mw.wikibase.getEntity,and unitEntityIdunitEntity );then
local writingSystemElementId = 'Q8209';
if wbStatus == true and unitEntity then
local langElementId = 'Q7737';
if unitEntity.claims.P2370 and
local label = getLabelWithLang( context, options, unitEntity, nil, {
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
not value.upperBound and
'P558[!P282][!P407]'
options.siConversion
then} );
 
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
out = out .. ' ' .. label;
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
МогӀа 904 ⟶ 820 :
return out;
end
 
local DATATYPE_CACHE = {}
 
--[[
МогӀа 917 ⟶ 831 :
return nil;
end
local cached = DATATYPE_CACHE[propertyId];
if (cached ~= nil) then return cached; end
 
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
МогӀа 925 ⟶ 836 :
return nil;
end
mw.log("Loaded datatype " .. propertyEntity.datatype .. " of " .. propertyId .. ' from wikidata, consider passing datatype argument to formatProperty call or to Wikidata/config' )
 
DATATYPE_CACHE[propertyId] = propertyEntity.datatype;
return propertyEntity.datatype;
end
 
local function formatLangRefs( options )
local langRefs = ''
if ( options.qualifiers and options.qualifiers.P407 ) then
for i, qualifier in pairs( options.qualifiers.P407 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'wikibase-entityid' ) then
local langRefEntity = getEntityFromId( qualifier.datavalue.value.id )
if ( langRefEntity and langRefEntity.claims ) then
local langRefCodeClaims = WDS.filter( langRefEntity.claims, 'P218' )
if langRefCodeClaims then
for _, claim in pairs( langRefCodeClaims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'string' ) then
local langRefCode = claim.mainsnak.datavalue.value
langRefs = langRefs .. '&#8203;' .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
end
end
end
end
end
end
end
 
return langRefs
end
 
МогӀа 970 ⟶ 850 :
-- Media
return function( context, options, value )
if ( not options.caption andor options.caption ~== '' then)
and ( not options.local_captiondescription =or options.caption;description == '' )
elseif and options.descriptionqualifiers and options.description ~= ''qualifiers.P2096 then
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
МогӀа 988 ⟶ 863 :
break
end
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
МогӀа 1006 ⟶ 871 :
return function( context, options, value )
return formatExternalId( value, options )
end
elseif datatype and datatype == 'math' then
-- Math formula
return function( context, options, value )
return formatMath( value, options )
end
elseif datatype and datatype == 'url' then
МогӀа 1016 ⟶ 876 :
return function( context, options, value )
local moduleUrl = require( 'Module:URL' )
local langRefs = formatLangRefs( options )
if not options.length or options.length == '' then
options.length = math.max( 18, 25 - #langRefs )
end
return moduleUrl.formatUrlSingle( context, options, value ) .. langRefs;
end
end
МогӀа 1028 ⟶ 887 :
return function( context, options, value )
if ( options.monolingualLangTemplate == 'lang' ) then
if ( value.language == contentLanguageCode ) then
return value.text;
end
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
elseif ( options.monolingualLangTemplate == 'ref' ) then
МогӀа 1073 ⟶ 929 :
return functionToCall( context, options, datavalue.value );
end
 
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
 
--[[
МогӀа 1084 ⟶ 938 :
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local wbStatus, entity = pcall( mw.wikibase.getEntity, entityId )
if wbStatus ~= true then
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 )
if not boundaries then
boundaries = DEFAULT_BOUNDARIES;
end
local label, labelLanguageCode = getLabelWithLang( context, options, entityId, boundaries )
 
-- определение соответствующей показываемому элементу категории
local category = p.extractCategory( context, options, { id = entityId } )''
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
 
-- получение ссылки по идентификатору
МогӀа 1103 ⟶ 975 :
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
if ( contentLanguageCode ~= labelLanguageCode ) then
return a'[[' .. getCategoryByCode(link .. 'links-to-entities-with-missing-local-language-|' .. label .. ']]' .. )categoryLinksToEntitiesWithMissingLocalLanguageLabel .. category;
else
return a'[[' .. link .. '|' .. label .. ']]' .. category;
end
else
МогӀа 1120 ⟶ 991 :
local title = mw.title.new( label );
if title and not title.exists and options.frame then
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
local templateText = "{{Универсальная карточка|" .. entityId .. "}}%0A'''" .. label .. "''' — %0A%0A== Примечания ==%0A{{примечания}}%0A";
local templateText = templateText .. "[[Категория:Википедия:Связать с элементом Викиданных|" .. entityId .. "]]";
local preloadUrl = tostring( mw.uri.canonicalUrl( label, 'action=edit&preload=Ш:Preload/Викиданные&preloadparams[]=' .. templateText ));
local redLink = options.frame:expandTemplate{ title='цветная ссылка', args = { '#ba0000', preloadUrl, label }};
return '<span class="plainlinks">' .. redLink .. '</span><sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
 
МогӀа 1142 ⟶ 1009 :
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' )categoryLinksToEntitiesWithMissingLabel .. category;
end
 
--[[
Функция для формирования категории на основе wikidata/config
]]
function p.extractCategory( context, options, value )
if ( not options.category ) then
return '';
end
 
local wbStatus, claims = pcall( mw.wikibase.getBestStatements, value.id, options.category );
if ( wbStatus ~= true or 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
--[[
Функция для оформления утверждений (statement)
МогӀа 1191 ⟶ 1028 :
]]
function getPropertyParams( propertyId, datatype, params )
local config = getConfigrequire( 'Module:Wikidata/config' );
if not config then
return {};
end
 
-- Различные уровни настройки параметров, по убыванию приоритета
МогӀа 1198 ⟶ 1038 :
-- 1. Параметры, указанные явно при вызове
if params then
forlocal key,tplParams value= in pairsmw.clone( params ) do;
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[ key ] = value;
end
end
МогӀа 1206 ⟶ 1047 :
 
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
forlocal key,selfParams value= in pairsmw.clone( config[ 'properties' ][ propertyId ] ) do;
for key, value in pairs( selfParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
МогӀа 1215 ⟶ 1057 :
 
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
and config[ 'presets' ][ propertyParams[ 'preset' ] ] then
local presetParams = mw.clone( config['presets'][propertyParams['preset']] );
then
for key, value in pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ]presetParams ) do
if propertyParams[ key ] == nil then
propertyParams[ key ] = value;
end
end
end
 
local datatype = datatype or params.datatype or propertyParams.datatype or getPropertyDatatype( propertyId );
if propertyParams.datatype == nil then
propertyParams.datatype = datatype;
end
 
-- 4. Настройки для типа данных
if datatype and config[ 'datatypes' ] and config[ 'datatypes' ][ datatype ] then
forlocal key,datatypeParams value= in pairsmw.clone( config[ 'datatypes' ][ datatype ] ) do;
for key, value in pairs( datatypeParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
МогӀа 1240 ⟶ 1078 :
 
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
forlocal key,globalParams value= in pairsmw.clone( config[ 'global' ] ) do;
for key, value in pairs( globalParams ) do
if propertyParams[ key ] == nil then
if propertyParams[ key ] == nil value;then
propertyParams[key] = value;
end
end
МогӀа 1259 ⟶ 1098 :
end
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
argslocal datatype = getPropertyParamsgetPropertyDatatype( propertyId, nil, args );
args = getPropertyParams( propertyId, datatype, args );
local datatype = args.datatype;
 
-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
local p_frame = frame:getParent();
if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
while p_frame do
copyTo( p_frame.args, args );
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
 
МогӀа 1301 ⟶ 1134 :
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
МогӀа 1320 ⟶ 1148 :
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. '[[Категори:Википеди:Карточкин чохь таблицаш йолу агӀонаш]]'
value = value .. getCategoryByCode( 'value-contains-table' )
else
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
МогӀа 1341 ⟶ 1169 :
local pageTitle = mw.title.getCurrentTitle();
if pageTitle.namespace == 0 then
value = value .. getCategoryByCode( 'local-value-present' )categoryLocalValuePresent;
end
end
МогӀа 1349 ⟶ 1177 :
 
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
localreturn callArgsframe:callParserFunction( = {'#property', propertyId });
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
 
МогӀа 1381 ⟶ 1205 :
end
 
local referencesresult = {}'';
if ( statement.references ) then
 
local allReferences = statement.references;
local hasPreferred = false;
local displayCount = 0;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
МогӀа 1414 ⟶ 1237 :
end
end
if ( display == true ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
if ( displayCount > 2 ) then
if ( options.entity and options.property ) then
table.remove( references );
local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( options.property ) .. '|[…]]]</sup>';
table.insert( references, moreReferences );
end
break;
end;
local refText = moduleSources.renderReference( g_frame, options.entity, reference );
if ( refText ~= '' ) then
table.insert( references, refText );
displayCount = displayCount + 1;
end
end
end
end
return table.concat( references );result
end