45
правок
Ilnur efende (бәхәс | кертем) к (Ilnur efende үзгәртүләре (бәхәс) Takhirgeran Umar юрамасына кадәр кире кайтарылды) Тамга: кире кайтару |
(update from ru:Модуль:Wikidata) |
||
local outputReferences = true;
-- sources that shall be omitted if any
local deprecatedSources = {
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
};
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
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
Возвращает: текстовую метку элемента, язык метки
]]
local function getLabelWithLang( context, options, entityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
if not entityId then
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?
if options.rank then -- передать настройки ранга из конфига
claims = context.selectClaims( options, options.property .. options.rank );
else
claims = context.selectClaims( options, options.property );
end
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
return context.formatProperty( options );
end
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
end
end
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(
if snakValue and snakValue ~= '' then
table.insert( qualifierValues,
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
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
for _, item in pairs(circumstances) do
if
result = options.i18n
end
end
else
Возвращает: строку оформленного текста
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or ''
end
local
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;
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]]
image = '[[File:' .. value .. '|frameless';
if options[ 'border' ] and options[ 'border' ] ~= '' then
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
@return string Formatted string.
]]
local function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
end
if formatter and formatter ~= '' then
local link = mw.ustring.gsub(
mw.ustring.gsub( formatter, '$1', value ), '.',
{ [' '] = '%20', ['+'] = '%2b' } )
local title = options.title
local mult = 10^sigfig;
number = math.floor( number * mult + 0.5 ) / mult;
return string.gsub( lang:formatNum( number ), '^-', '−' );
end
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
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
not value.upperBound and
options.siConversion == true
then
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
-- 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
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
if ( contentLanguageCode ~= labelLanguageCode ) then
local title = mw.title.new( label );
if title and not title.exists and options.frame then
local redLink = '[[' .. label .. ']]';
return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
]]
function p.extractCategory( context, options, value )
if ( not options.category or options.nocat ) then
return '';
end
local wbStatus, claims = pcall( mw.wikibase.getAllStatements, value.id, propertyId );
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 );
return '[[' .. catSiteLink .. ']]';
end
end
end
return '';
end
--[[
Функция для оформления утверждений (statement)
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;
value = value .. getCategoryByCode( 'value-contains-table' )
else
value = wrapFormatProperty( value, 'class="no-wikidata"'
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
end
end
local allReferences = statement.references;
local
local displayCount = 0;
for _, reference in pairs( statement.references ) do
and reference.snaks.P248[1].datavalue.value.id ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
if (
end
end
for _, reference in pairs( statement.references ) do
local display = true;
if (
if ( reference.snaks
and reference.snaks.P248
end
end
end
if ( displayCount > 2 ) then
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
|
правок