Модуль:Wikidata — Версийн башхалла
[теллина верси] | [теллина верси] |
Чулацам дӀабаьккхина Чулацам тӀетоьхна
Юхадаьккхина декъашхочун Takhirgeran Umar (дийц.) нисдар 4979468 Билгало: йухайаккхар |
Нисдарах лаьцна йаздина дац |
||
МогӀа 1:
-- settings, may differ from project to project
local fileDefaultSize = '267x400px';
local outputReferences = true;
МогӀа 35 ⟶ 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
};
МогӀа 49 ⟶ 22 :
local contentLanguageCode = mw.getContentLanguage():getCode();
local p = {};
local config = nil;
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
МогӀа 55 ⟶ 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;
МогӀа 72 ⟶ 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
МогӀа 134 ⟶ 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
МогӀа 164 ⟶ 169 :
end
return 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
МогӀа 179 ⟶ 203 :
if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
end
return entity;
МогӀа 188 ⟶ 213 :
Внутрення функция для формирования сообщения об ошибке
Принимает: ключ элемента в таблице
Возвращает: строку сообщения
]]
local function throwError( key )
error(
end
МогӀа 223 ⟶ 248 :
end
-- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require
if formatter == nil then
throwError( prefix .. '-module-not-found' )
МогӀа 266 ⟶ 291 :
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context,
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
local results = {};
МогӀа 273 ⟶ 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
МогӀа 341 ⟶ 371 :
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 .. ']'
};
--[[
МогӀа 348 ⟶ 386 :
Возвращает: текстовую метку элемента, язык метки
]]
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
МогӀа 361 ⟶ 399 :
label = options.text;
else
if not propertyIds then
propertyIds =
selectors = getLabelWithLang_DEFAULT_SELECTORS;
end
-- name from properties
local results = getPropertyInBoundaries( context,
for _, result in pairs( results ) do
МогӀа 382 ⟶ 411 :
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
label = result.datavalue.value.text;
break;
elseif result.datavalue.type == 'string' then
МогӀа 388 ⟶ 417 :
break;
end
end
end
if (not label) then
label, langCode = mw.wikibase.getLabelWithLang( entityId );
if not langCode then
return nil;
end
end
МогӀа 393 ⟶ 429 :
return label, langCode;
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
МогӀа 422 ⟶ 498 :
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
МогӀа 440 ⟶ 516 :
options.entity = entity;
newOptions.entity = entity;
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
return newOptions;
МогӀа 467 ⟶ 544 :
return context.formatProperty( options );
end
МогӀа 540 ⟶ 576 :
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
end
end
МогӀа 570 ⟶ 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
qualConfig = getPropertyParams( options.qualifier, nil, {})
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
МогӀа 599 ⟶ 650 :
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
else
result = options.i18n['somevalue'];
end
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
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
return before .. result .. after;
end
МогӀа 627 ⟶ 684 :
Возвращает: строку оформленного текста
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
МогӀа 641 ⟶ 698 :
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or ''
globes = require( 'Module:Wikidata/Globes' )
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
МогӀа 688 ⟶ 726 :
Возвращает: строку оформленного текста
]]
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$' )
МогӀа 717 ⟶ 757 :
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
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
МогӀа 741 ⟶ 802 :
]]
local function formatExternalId( value, options )
local formatter = options.formatter;
if not formatter or formatter == '' then
local wbStatus,
if wbStatus == true and
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
МогӀа 757 ⟶ 834 :
if formatter and formatter ~= '' then
local link = mw.ustring.gsub(
mw.ustring.gsub( formatter, '$1', value ), '.', { [' '] = '%20', ['+'] = '%2b' } )
local title = options.title
МогӀа 783 ⟶ 862 :
local langCode = lang:getCode();
local function formatNum( number, sigfig )
sigfig = sigfig or 12 -- округление до
local mult = 10^
number = math.floor( number * mult + 0.5 ) / mult;
return string.gsub( lang:formatNum( number ), '^-', '−' );
end
МогӀа 795 ⟶ 873 :
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
МогӀа 805 ⟶ 897 :
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
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
МогӀа 820 ⟶ 945 :
return out;
end
local DATATYPE_CACHE = {}
--[[
МогӀа 831 ⟶ 958 :
return nil;
end
local cached = DATATYPE_CACHE[propertyId];
if (cached ~= nil) then return cached; end
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
МогӀа 836 ⟶ 966 :
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
МогӀа 850 ⟶ 1011 :
-- Media
return function( context, options, value )
if
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
МогӀа 863 ⟶ 1029 :
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
МогӀа 871 ⟶ 1047 :
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
МогӀа 876 ⟶ 1057 :
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 )
end
end
МогӀа 887 ⟶ 1069 :
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
МогӀа 929 ⟶ 1114 :
return functionToCall( context, options, datavalue.value );
end
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
--[[
МогӀа 938 ⟶ 1125 :
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 label, labelLanguageCode = getLabelWithLang( context, options, entityId, boundaries )
-- определение соответствующей показываемому элементу категории
local category =
-- получение ссылки по идентификатору
МогӀа 975 ⟶ 1144 :
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
if ( contentLanguageCode ~= labelLanguageCode ) then
return
else
return
end
else
МогӀа 991 ⟶ 1161 :
local title = mw.title.new( label );
if title and not title.exists and options.frame then
local redLink = options.frame:expandTemplate{ title='Ш:Красная ссылка с рыбой', args = { entityId, label } };
return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
МогӀа 1009 ⟶ 1180 :
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' ..
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
--[[
Функция для оформления утверждений (statement)
МогӀа 1028 ⟶ 1231 :
]]
function getPropertyParams( propertyId, datatype, params )
local config =
-- Различные уровни настройки параметров, по убыванию приоритета
МогӀа 1038 ⟶ 1238 :
-- 1. Параметры, указанные явно при вызове
if params then
if value ~= '' then
propertyParams[ key ] = value;
end
end
МогӀа 1047 ⟶ 1246 :
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
if propertyParams[ key ] == nil then
end
end
МогӀа 1057 ⟶ 1255 :
-- 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
МогӀа 1078 ⟶ 1280 :
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
if propertyParams[ key ] == nil then
end
end
МогӀа 1097 ⟶ 1298 :
throwError( 'property-param-not-provided' )
end
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
МогӀа 1134 ⟶ 1350 :
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
МогӀа 1148 ⟶ 1369 :
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. getCategoryByCode( 'value-contains-table' )
else
value = wrapFormatProperty( value, 'class="no-wikidata"'
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
end
end
МогӀа 1169 ⟶ 1381 :
local pageTitle = mw.title.getCurrentTitle();
if pageTitle.namespace == 0 then
value = value ..
end
end
МогӀа 1177 ⟶ 1389 :
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
МогӀа 1205 ⟶ 1421 :
end
local
if ( statement.references ) then
local allReferences = statement.references;
local
local displayCount = 0;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
МогӀа 1217 ⟶ 1434 :
and reference.snaks.P248[1].datavalue.value.id ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
if (
end
end
МогӀа 1225 ⟶ 1442 :
for _, reference in pairs( statement.references ) do
local display = true;
if (
if ( reference.snaks
and reference.snaks.P248
МогӀа 1237 ⟶ 1454 :
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
|