Module:Wikidata
Көрініс
Бұл модульдің құжаттамасын Module:Wikidata/doc бетінде бастай аласыз
local i18n = {
["errors"] = {
["property-param-not-provided"] = "Қасиет параметрі берілмеген",
["entity-not-found"] = "Нысан табылмады.",
["unknown-claim-type"] = "Өтініштің белгісіз типі.",
["unknown-snak-type"] = "Снэктің белгісіз типі.",
["unknown-datavalue-type"] = "Мәліметтер мәнінің белгісіз типі.",
["unknown-entity-type"] = "Нысанның белгісіз типі.",
["unknown-claim-module"] = "Сіз claim-module, сондай-ақ claim-function орнатуыңыз қажет.",
["unknown-value-module"] = "Сіз value-module, сондай-ақ value-function орнатуыңыз қажет.",
["claim-module-not-found"] = "Мәндер меңзеген модуль табылмады.",
["claim-function-not-found"] = "Мәндер меңзеген әрекет табылмады.",
["value-module-not-found"] = "Мәндер меңзеген модуль табылмады.",
["value-function-not-found"] = "Мәндер меңзеген әрекет табылмады."
},
["somevalue"] = "''белгісіз''",
["novalue"] = ""
}
-- settings, may differ from project to project
local categoryLinksToEntitiesWithMissingLabel = '[[Санат:Уикипедия:Уикидерек элементтеріне сілтемесі бар мақалалар]]';
local outputReferences = true;
-- sources that shall be omitted if any preffered sources exists
local deprecatedSources = {
Q36578 = true, -- Gemeinsame Normdatei
};
local preferredSources = {
Q5375741 = true, -- Encyclopædia Britannica Online
Q17378135 = true, -- Great Soviet Encyclopedia (1969—1978)
};
local moduleSources = require('Module:Sources')
local p = {}
local function toBoolean( valueToParse, defaultValue )
if ( valueToParse ) then
if valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then
return false
end
return true
end
return defaultValue;
end
function loadCacheSafe( entityId )
local status, result = pcall( function() return mw.loadData( 'Module:WikidataCache/' .. entityId ) end );
if ( status == true ) then
return result;
end
return nil;
end
function getEntityFromId( id )
if id then
local cached = loadCacheSafe( id );
if ( cached ) then
return cached;
end
-- в документации [[Extension:Wikibase Client/Lua]]
-- вызов mw.wikibase.getEntity считатеся устаревшей
-- необходимо использовать mw.wikibase.getEntityObject
return mw.wikibase.getEntity( id )
end
-- TODO: replace with entityObject
local entity = mw.wikibase.getEntity();
if ( entity ) then
local cached = loadCacheSafe( entity.id );
if ( cached ) then
return cached;
end
end
return mw.wikibase.getEntity()
end
function getEntityIdFromValue( value )
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'Q'
elseif value['entity-type'] == 'property' then
prefix = 'P'
else
return formatError( 'unknown-entity-type' )
end
return prefix .. value['numeric-id']
end
local function formatError( key )
return '<span class="error">' .. i18n.errors[key] .. '</span>'
end
-- property id бойынша қасиеттерді таңдайды
local function selectClaims( context, propertyId )
local allPropertyClaims = context.entity.claims[ string.upper( propertyId ) ];
if ( not allPropertyClaims ) then
return nil;
end
local requiredRank = 'normal'
if ( allPropertyClaims[0] ) then
for i = 0, #allPropertyClaims do
local statement = allPropertyClaims[i]
if (statement.rank == 'preferred') then
requiredRank = 'preferred';
break
end
end
else
for i, statement in pairs( allPropertyClaims ) do
if (statement.rank == 'preferred') then
requiredRank = 'preferred';
break
end
end
end
local result = {};
if ( allPropertyClaims[0] ) then
for i = 0, #allPropertyClaims do
local statement = allPropertyClaims[i]
if (statement.rank == requiredRank) then
result[ #result + 1 ] = statement;
end
end
else
for i, statement in pairs( allPropertyClaims ) do
if (statement.rank == requiredRank) then
result[ #result + 1 ] = statement;
end
end
end
if ( #result == 0 ) then
return nil;
end
return result;
end
function formatStatements( options )
local entity = getEntityFromId( options.entityId )
if not entity then
return -- formatError( 'entity-not-found' )
end
if (entity.claims == nil) then
return '' --TODO error?
end
local context = { frame = g_frame, entity = entity, options = options, formatSnak = formatSnak, formatStatementDefault = formatStatementDefault }
context.formatStatement = function( statement ) return formatStatement( context, statement ) end;
context.formatRefs = function( statement ) return formatRefs( context, statement ) end;
context.selectClaims = function( propertyId ) return selectClaims( context, propertyId ) end;
local claims = context.selectClaims( options.property );
if (claims == nil) then
return '' --TODO error?
end
local formattedStatements = {}
for i = 1, #claims do
local statement = claims[i]
local formattedStatement = formatStatement( context, statement )
if (formattedStatement) then
formattedStatement = '<span class="wikidata-claim" data-wikidata-claim-id="' .. statement.id .. '">' .. formattedStatement .. '</span>'
table.insert( formattedStatements, formattedStatement )
end
end
return mw.text.listToText( formattedStatements, options.separator, options.conjunction )
end
function formatStatement( context, statement )
if ( not statement ) then
error( 'statement is not specified or nil' );
end
if not statement.type or statement.type ~= 'statement' then
return formatError( 'unknown-claim-type' )
end
local options = context.options;
local claim
if options['claim-module'] or options['claim-function'] then
if not options['claim-module'] or not options['claim-function'] then
return formatError( 'unknown-claim-module' )
end
local formatter = require ('Module:' .. options['claim-module'])
if formatter == nil then
return formatError( 'claim-module-not-found' )
end
local fun = formatter[options['claim-function']]
if fun == nil then
return formatError( 'claim-function-not-found' )
end
claim = fun( context, statement )
else
claim = context.formatStatementDefault( context, statement )
end
return claim
end
function formatStatementDefault( context, statement )
if ( context.options.references ) then
return context.formatSnak( statement.mainsnak, context.options ) .. context.formatRefs( statement );
else
return context.formatSnak( statement.mainsnak, context.options );
end
end
function formatSnak( snak, options )
local hash = '';
local mainSnakClass = '';
if ( snak.hash ) then
hash = ' data-wikidata-hash="' .. snak.hash .. '"';
else
mainSnakClass = ' wikidata-main-snak';
end
local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
local after = '</span>'
if snak.snaktype == 'somevalue' then
return before .. (options['somevalue'] or i18n['somevalue']) .. after;
elseif snak.snaktype == 'novalue' then
return before .. (options['novalue'] or i18n['novalue']) .. after;
elseif snak.snaktype == 'value' then
return before .. formatDatavalue( snak.datavalue, options ) .. after;
else
return before .. formatError( 'unknown-snak-type' ) .. after;
end
end
function formatGlobeCoordinate( value, options )
if options['subvalue'] == 'latitude' then
return value['latitude']
elseif options['subvalue'] == 'longitude' then
return value['longitude']
else
local eps = 0.0000001 -- < 1/360000
local globe = '' -- 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)
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)
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['display'] then
coord = coord .. '|display=' .. options.display
else
coord = coord .. '|display=title'
end
coord = coord .. '}}'
return g_frame:preprocess(coord)
end
end
function formatDatavalue( datavalue, options )
if options['value-module'] or options['value-function'] then
if not options['value-module'] or not options['value-function'] then
return formatError( 'unknown-value-module' )
end
local formatter = require ('Module:' .. options['value-module'])
if formatter == nil then
return formatError( 'value-module-not-found' )
end
local fun = formatter[options['value-function']]
if fun == nil then
return formatError( 'value-function-not-found' )
end
return fun( datavalue.value, options )
end
if datavalue.type == 'wikibase-entityid' then
return formatEntityId( getEntityIdFromValue( datavalue.value ), options )
elseif datavalue.type == 'string' then
return datavalue.value --TODO ids + media
elseif datavalue.type == 'monolingualtext' then
return '<span class="lang" lang="' .. datavalue.value.language .. '">' .. datavalue.value.text .. '</span>'
elseif datavalue.type == 'globecoordinate' then
return formatGlobeCoordinate( datavalue.value, options )
elseif datavalue.type == 'quantity' then
local value = string.gsub(datavalue.value['amount'], '^%+', '')
local lang = mw.language.new( 'ru' )
return lang:formatNum( tonumber( value ) )
elseif datavalue.type == 'time' then
local moduleDate = require('Module:Wikidata/date')
return moduleDate.formatDate( datavalue.value, options );
else
return formatError( 'unknown-datavalue-type' )
end
end
local simpleReplaces = {
Q30 = '[[Америка Құрама Штаттары|АҚШ]]',
Q148 = '[[Қытай Халық Республикасы|ҚХР]]',
Q258 = '[[Оңтүстік Африка Республикасы|ОАР]]',
Q423 = '[[Корей Халық Демократиялық Республикасы|КХДР]]',
Q2184 = '[[Ресей Кеңестік Федерациялық Социалистік Республикасы|РКФСР]]',
Q15180 = '[[Кеңестік Социалистік Республикалар Одағы|КСРО]]',
Q133356 = '[[Украин Кеңестік Социалистік Республикасы|Украин КСР]]',
}
function formatEntityId( entityId, options )
local label = nil;
if ( options.text and options.text ~= '' ) then
label = options.text
else
if ( simpleReplaces[entityId] ) then
return simpleReplaces[entityId];
end
label = mw.wikibase.label( entityId );
end
local link = mw.wikibase.sitelink( entityId )
if link then
if label then
return '[[' .. link .. '|' .. label .. ']]'
else
return '[[' .. link .. ']]'
end
end
if label then
return label
end
return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;
end
function p.formatStatements( frame )
local args = frame.args
local plain = toBoolean( frame.args.plain, false );
frame.args.nocat = toBoolean( frame.args.nocat, false );
frame.args.references = toBoolean( frame.args.references, true );
if args.value and args.value ~= '' then
if ( plain ) then
return args.value
else
return args.value .. categoryLocalValuePresent;
end
end
if not frame.args.property then
return formatError( 'property-param-not-provided' );
end
if ( plain ) then
return frame:callParserFunction( '#property', frame.args.property );
end
g_frame = frame
return formatStatements( frame.args )
end
function formatRefs( context, statement )
if ( not outputReferences ) then
return '';
end
local result = '';
if ( statement.references ) then
local allReferences = statement.references;
local hasPreferred = false;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
and reference.snaks.p248
and reference.snaks.p248[0]
and reference.snaks.p248[0].datavalue
and reference.snaks.p248[0].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.p248[0].datavalue.value["numeric-id"];
if ( preferredSources[entityId] ) then
hasPreferred = true;
end
end
end
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasPreferred ) then
if ( reference.snaks
and reference.snaks.p248
and reference.snaks.p248[0]
and reference.snaks.p248[0].datavalue
and reference.snaks.p248[0].datavalue.value["numeric-id"] ) then
local entityId = "Q" .. reference.snaks.p248[0].datavalue.value["numeric-id"];
if ( deprecatedSources[entityId] ) then
display = false;
end
end
end
if ( display ) then
result = result .. moduleSources.renderReference( g_frame, context.entity, reference );
end
end
end
return result
end
return p