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

Контент бетерелгән Контент өстәлгән
кТөзәтмә аңлатмасы юк
к Ilnur efende үзгәртүләре (бәхәс) Takhirgeran Umar юрамасына кадәр кире кайтарылды
Тамга: кире кайтару
Юл номеры - 3:
local outputReferences = true;
 
-- sources that shall be omitted if any preferredpreffered sources exists
local deprecatedSources = {
Q36578 = true, -- Gemeinsame Normdatei
Q63056 = true, -- Find a Grave
Q1798125 = true, -- LIBRIS
Q15222191 = true, -- BNF
};
Q15241312 = true, -- Freebase
local preferredSources = {
Q29861311 = true, -- SNAC
Q86999151Q5375741 = true, -- WeChangEdEncyclopædia Britannica Online
Q17378135 = true, -- Great Soviet Encyclopedia (1969—1978)
Q523660 = true, -- International Music Score Library Project by https://ru.wikipedia.org/?diff=107090748
};
 
Строка 52 ⟶ 51 :
local function getConfig( section, code )
if config == nil then
config = require( 'Module:WikidataWikidata2/config' );
end;
if not config then
Строка 139 ⟶ 138 :
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 + 199919991999 };
end
 
Строка 169 ⟶ 168 :
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
 
Строка 386 ⟶ 366 :
Возвращает: текстовую метку элемента, язык метки
]]
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
Строка 429 ⟶ 409 :
 
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
 
Строка 548 ⟶ 484 :
 
return context.formatProperty( options );
end
 
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
 
Строка 580 ⟶ 556 :
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
table.insert(circumstances,local circumstance = qualifier.datavalue.value.id);
if ( 'Q5727902' == circumstance ) then
circumstances.circa = true;
end
if ( 'Q18122778' == circumstance ) then
circumstances.presumably = true;
end
end
end
Строка 607 ⟶ 589 :
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( qualConfigoptions, qualifierSnak );
if snakValue and snakValue ~= '' then
table.insert( qualifierValues, snakValuecontext.formatSnak( options, qualifierSnak ) );
end
end
if ( result and result ~= '' and #qualifierValues ) then
result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
if qualConfig.invisible then
result = result .. table.concat( qualifierValues, ', ' );
else
result = result .. ' (' .. table.concat( qualifierValues, ', ' ) .. ')';
end
end
end
Строка 666 ⟶ 642 :
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
 
for _, item in pairs(circumstances) do
if options( circumstances.i18n[item]presumably ) then
result = options.i18n[item].presumably .. result;
end
if ( circumstances.circa ) then
result = options.i18n.circa .. result;
end
else
Строка 688 ⟶ 666 :
Возвращает: строку оформленного текста
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
Строка 702 ⟶ 680 :
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or ''
if globe == '' and value['globe'] then
globes = require( 'Module:WikidataWikidata2/Globes' )
globe = globes[value['globe']] or ''
end
local displaylat = 'inline'{}
lat['abs'] = math.abs(value['latitude'])
if options.display and options.display ~= '' then
lat['ns'] = value['latitude'] >= 0 and 'N' or 'S'
display = options.display
lat['d'] = math.floor(lat['abs'] + eps)
elseif ( options.property:upper() == 'P625' ) then
lat['m'] = math.floor((lat['abs'] - lat['d']) * 60 + eps)
display = 'title'
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
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display }
coord = coord .. '|type=' .. options.type
end
return coord_mod.coord(g_frame)
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
Строка 730 ⟶ 733 :
Возвращает: строку оформленного текста
]]
local function formatCommonsMedia( value, options )
local image = value;
 
Строка 740 ⟶ 743 :
end
if caption ~= '' then
caption = wrapFormatProperty( caption, 'class="media-caption"<span data-wikidata-qualifier-id="P2096" style="display:block;">' ).. caption .. '</span>';
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
Строка 770 ⟶ 771 :
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
Строка 795 ⟶ 786 :
@return string Formatted string.
]]
local function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
end
Строка 838 ⟶ 829 :
 
if formatter and formatter ~= '' then
local link = mw.ustring.gsub( mw.ustring.gsub( formatter, '$1', value ), ' ', '%%20' )
mw.ustring.gsub( formatter, '$1', value ), '.',
{ [' '] = '%20', ['+'] = '%2b' } )
 
local title = options.title
Строка 870 ⟶ 859 :
local mult = 10^sigfig;
number = math.floor( number * mult + 0.5 ) / mult;
 
return string.gsub( lang:formatNum( number ), '^-', '−' );
end
Строка 877 ⟶ 867 :
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
out = out .. ' ± ' .. formatNum( diff )
-- Пробуем понять до какого знака округлять
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
Строка 907 ⟶ 883 :
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, '^%+', '' );
Строка 1015 ⟶ 991 :
-- 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
Строка 1090 ⟶ 1061 :
elseif datavalue.type == 'time' then
return function( context, options, value )
local moduleDate = require( 'Module:WikidataWikidata2/date' )
return moduleDate.formatDate( context, options, value );
end;
Строка 1148 ⟶ 1119 :
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
if ( contentLanguageCode ~= labelLanguageCode ) then
Строка 1165 ⟶ 1136 :
local title = mw.title.new( label );
if title and not title.exists and options.frame then
local templateText = "{{Универсальная карточка|" .. entityId .. "}}%0A'''" .. label .. "''' — %0A%0A== Примечания ==%0A{{примечания}}%0A";
local redLink = options.frame:expandTemplate{ title='Ш:Красная ссылка с рыбой', args = { entityId, label } };
local templateText = templateText .. "[[Категория:Википедия:Связать с элементом Викиданных|" .. entityId .. "]]";
return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
local preloadUrl = tostring( mw.uri.canonicalUrl( label, 'action=edit&preload=Ш:Preload/Викиданные&preloadparams[]=' .. templateText ));
local redLink = options.frame:expandTemplate{ title='цветная ссылка', args = { '#0645AD', preloadUrl, label }};
return '<span class="plainlinks">' .. redLink .. '</span><sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
 
Строка 1191 ⟶ 1165 :
]]
function p.extractCategory( context, options, value )
local wbStatus, entity = pcall( mw.wikibase.getEntity, value.id )
if ( not options.category or options.nocat ) then
local category = ''
return '';
if ( options.category ) then
end
local propertyIdclaims = stringWDS.gsubfilter( optionsentity.categoryclaims, '([^Pp0-9]options.*)$',category '');
if ( claims ) then
local wbStatus, claims = pcall( mw.wikibase.getAllStatements, value.id, propertyId );
if for (_, wbStatusclaim ~=in true or notpairs( claims ) then return ''; enddo
if ( claim.mainsnak
allClaims = {}
and claim.mainsnak
allClaims[ propertyId ] = claims
and claim.mainsnak.datavalue
claims = WDS.filter( allClaims, options.category )
and claim.mainsnak.datavalue.type == 'wikibase-entityid' ) then
if not claims then return ''; end
local catEntityId = claim.mainsnak.datavalue.value.id;
local wbStatus, catEntity = pcall( mw.wikibase.getEntity, catEntityId );
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 catSiteLinkcatEntity ) then
if catEntity:getSitelink() then
return '[[' .. catSiteLink .. ']]';
category = '[[' .. catEntity:getSitelink() .. ']]';
end
end
end
end
end
end
return category;
 
return '';
end
 
--[[
Функция для оформления утверждений (statement)
Строка 1302 ⟶ 1273 :
throwError( 'property-param-not-provided' )
end
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
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;
 
Строка 1318 ⟶ 1280 :
p_frame = frame
while p_frame do
if p_frame:getTitle() == mw.site.namespaces[10].name .. ':WikidataWikidata2' then
copyTo( p_frame.args, args, true );
end
Строка 1375 ⟶ 1337 :
value = value .. getCategoryByCode( 'value-contains-table' )
else
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
value = wrapFormatProperty( value, 'class="no-wikidata"'
if ( string.match( value, '\n' )
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
or string..match( propertyIdvalue, ..'<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
Строка 1429 ⟶ 1400 :
 
local allReferences = statement.references;
local hasNotDeprecatedhasPreferred = false;
local displayCount = 0;
for _, reference in pairs( statement.references ) do
Строка 1438 ⟶ 1409 :
and reference.snaks.P248[1].datavalue.value.id ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
if ( not deprecatedSourcespreferredSources[entityId] ) then
hasNotDeprecatedhasPreferred = true;
end
end
Строка 1446 ⟶ 1417 :
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasNotDeprecatedhasPreferred ) then
if ( reference.snaks
and reference.snaks.P248
Строка 1457 ⟶ 1428 :
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
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