Modul:Wikidata
Bu modul uchun Modul:Wikidata/doc nomli hujjat sahifasini yaratishingiz mumkin
local i18n = { ["errors"] = { ["property-param-not-provided"] = "Xossa koʻrsatkichi berilmagan", ["entity-not-found"] = "Obyekt topilmadi.", ["unknown-claim-type"] = "Noma’lum da’vo turi.", ["unknown-snak-type"] = "Noma’lum snek turi.", ["unknown-datavalue-type"] = "Nomaʼlum maʼlumotlar qiymati turi.", ["unknown-entity-type"] = "Nomaʼlum obyekt turi.", ["unknown-property-module"] = "Siz ham property-moduleni, ham property-functionni oʻrnatishingiz kerak.", ["unknown-claim-module"] = "Siz ham claim-moduleni, ham claim-functionni oʻrnatishingiz kerak.", ["unknown-value-module"] = "Siz ham value-moduleni, ham value-functionni oʻrnatishingiz kerak.", ["property-module-not-found"] = "Xossalarni koʻrsatish uchun modul topilmadi", ["property-function-not-found"] = "Xossalarni koʻrsatish uchun funksiya topilmadi", ["claim-module-not-found"] = "Tasdiqni koʻrsatish uchun modul topilmadi.", ["claim-function-not-found"] = "Tasdiqni koʻrsatish uchun funksiya topilmadi.", ["value-module-not-found"] = "Qiymatni koʻrsatish uchun modul topilmadi.", ["value-function-not-found"] = "Qiymatni koʻrsatish uchun funksiya topilmadi." }, ["somevalue"] = "''nomaʼlum''", ["novalue"] = "", ["approximate"] = '<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 projectlocal categoryLinksToEntitiesWithMissingLabel = '';local categoryLocalValuePresent = '[[Turkum:Vikipediya:Vikimaʼlumotlarda qayta aniqlash maqolalari]]';local outputReferences = true;-- sources that shall be omitted if any preffered sources existslocal deprecatedSources = {Q36578 = true, -- Gemeinsame NormdateiQ63056 = true, -- Find a GraveQ15222191 = true, -- BNF};local preferredSources = {Q5375741 = true, -- Encyclopædia Britannica OnlineQ17378135 = true, -- Great Soviet Encyclopedia (1969—1978)};local moduleSources = require('Module:Sources')local p = {}local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement, formatStatementDefault, formatProperty, getSourcingCircumstances, loadCacheSafe, throwError, toBoolean;local function copyTo( obj, target )for k, v in pairs( obj ) dotarget[k] = vendreturn target;endlocal function loadCacheSafe( entityId )local status, result = pcall( function() return mw.loadData( 'Module:WikidataCache/' .. entityId ) end );if ( status == true ) thenreturn result;endreturn nil;endlocal function parseISO8601(str)if 'table' == type(str) thenif str.args and str.args[1] thenstr = '' .. str.args[1]elsereturn 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )endendlocal Y, M, D = (function(str) local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"local Y, M, D = mw.ustring.match( str, pattern )return tonumber(Y), tonumber(M), tonumber(D)end) (str);local h, m, s = (function(str) local pattern = "T(%d+):(%d+):(%d+)%Z";local H, M, S = mw.ustring.match( str, pattern);return tonumber(H), tonumber(M), tonumber(S);end) (str);local oh,om = ( function(str)if str:sub(-1)=="Z" then return 0,0 end; -- ends with Z, Zulu time-- matches ±hh:mm, ±hhmm or ±hh; else returns nilslocal pattern = "([-+])(%d%d):?(%d?%d?)$";local sign, oh, om = mw.ustring.match( str, pattern);sign, oh, om = sign or "+", oh or "00", om or "00";return tonumber(sign .. oh), tonumber(sign .. om);end )(str)return tonumber(os.time({year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s})) * 1000;endlocal function toBoolean( valueToParse, defaultValue ) if ( valueToParse ) then if valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then return false end return true end return defaultValue;endlocal function getEntityFromId( id ) if id then local cached = loadCacheSafe( id ); if ( cached ) then return cached; end return mw.wikibase.getEntityObject( id ) end local entity = mw.wikibase.getEntityObject(); if ( entity ) then local cached = loadCacheSafe( entity.id ); if ( cached ) then return cached; endend return entity;endlocal function throwError( key ) error( i18n.errors[key] );endlocal function getEntityIdFromValue( value ) local prefix = '' if value['entity-type'] == 'item' then prefix = 'Q' elseif value['entity-type'] == 'property' then prefix = 'P' else throwError( 'unknown-entity-type' ) end return prefix .. value['numeric-id']endlocal function getUserFunction( options, prefix, defaultFunction ) if options[ prefix .. '-module' ] or options[ prefix .. '-function' ] then if not options[ prefix .. '-module' ] or not options[ prefix .. '-function' ] then throwError( 'unknown-' .. prefix .. '-module' ); end local formatter = require ('Module:' .. options[ prefix .. '-module' ]); if formatter == nil then throwError( prefix .. '-module-not-found' ) end local fun = formatter[ options[ prefix .. '-function' ] ] if fun == nil then throwError( prefix .. '-function-not-found' ) end return fun; end return defaultFunction;endlocal function selectClaims( context, options, propertySelector )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 is missing'); end;if ( not propertySelector ) then error( 'propertySelector not specified'); end;local WDS = require('Module:WikidataSelectors')result = WDS.filter(options.entity.claims, propertySelector) if ( not result or #result == 0 ) then return nil; end if options.limit and options.limit ~= '' and options.limit ~= '-' thenlocal limit = tonumber( options.limit, 10 );while #result > limit dotable.remove( result );endend return result;endlocal function formatProperty( options ) -- Получение сущности по идентификатору local entity = getEntityFromId( options.entityId ) if not entity then return -- throwError( 'entity-not-found' ) end-- проверка на присутсвие у сущности заявлений (claim)-- подробнее о заявлениях см. d:Викиданные:Глоссарий if (entity.claims == nil) then return '' --TODO error? end-- improve optionsoptions.frame = g_frame;options.entity = entity;options.extends = function( self, newOptions )return copyTo( newOptions, copyTo( self, {} ) )endif ( options.i18n ) thenoptions.i18n = copyTo( options.i18n, copyTo( i18n, {} ) );elseoptions.i18n = i18n;end-- create contextlocal context = { formatSnak = formatSnak, formatPropertyDefault = formatPropertyDefault, formatStatementDefault = formatStatementDefault }context.formatProperty = function( options ) local func = getUserFunction( options, 'property', context.formatPropertyDefault );return func( context, options )end;context.formatStatement = function( options, statement ) return formatStatement( context, options, statement ) end;context.formatSnak = function( options, snak, circumstances ) return formatSnak( context, options, snak, circumstances ) end;context.formatRefs = function( options, statement ) return formatRefs( context, options, statement ) end;context.parseTimeFromSnak = function( snak )if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time ) thenlocal timeISO6801 = tostring( snak.datavalue.value.time )return parseISO8601( timeISO6801 );endreturn nil;endcontext.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end;context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;return context.formatProperty( options );endfunction 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 = context.selectClaims( options, options.property ); if (claims == nil) then return '' --TODO error? end local formattedClaims = {} for i, claim in ipairs(claims) do local formattedStatement = context.formatStatement( options, claim ) 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 ) end end return mw.text.listToText( formattedClaims, options.separator, options.conjunction )endfunction formatStatement( context, options, statement )if ( not statement ) thenerror( 'statement is not specified or nil' );end if not statement.type or statement.type ~= 'statement' then throwError( 'unknown-claim-type' ) end local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault ); return functionToCall( context, options, statement );endfunction getSourcingCircumstances( statement )if (not statement) then error('statement is not specified') end;local circumstances = {};if ( statement.qualifiersand statement.qualifiers.P1480 ) thenfor i, qualifier in pairs( statement.qualifiers.P1480 ) doif ( qualifierand qualifier.datavalueand qualifier.datavalue.type == 'wikibase-entityid'and qualifier.datavalue.valueand qualifier.datavalue.value["entity-type"] == 'item' ) thenlocal circumstance = 'Q' .. qualifier.datavalue.value["numeric-id"];if ( 'Q18086598' == circumstance ) thencircumstances.approximate = true;endif ( 'Q18122778' == circumstance ) thencircumstances.presumably = true;endendendendreturn circumstances;endfunction formatStatementDefault( context, options, statement )if (not context) then error('context is not specified') end;if (not options) then error('options is not specified') end;if (not statement) then error('statement is not specified') end;local circumstances = context.getSourcingCircumstances( statement );if ( options.references ) then return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement ); else return context.formatSnak( options, statement.mainsnak, circumstances ); endendfunction formatSnak( context, options, snak, circumstances )circumstances = circumstances or {};local hash = '';local mainSnakClass = '';if ( snak.hash ) thenhash = ' data-wikidata-hash="' .. snak.hash .. '"';elsemainSnakClass = ' wikidata-main-snak';endlocal before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'local after = '</span>' if snak.snaktype == 'somevalue' then return before .. options.i18n['somevalue'] .. after; elseif snak.snaktype == 'novalue' then return before .. options.i18n['novalue'] .. after; elseif snak.snaktype == 'value' thenif ( circumstances.presumably ) thenbefore = before .. options.i18n.presumably;endif ( circumstances.approximate ) thenbefore = before .. options.i18n.approximate;end return before .. formatDatavalue( context, options, snak.datavalue ) .. after; else throwError( 'unknown-snak-type' ); endendfunction formatGlobeCoordinate( value, options )-- проверка на требование в параметрах вызова на возврат сырого значения if options['subvalue'] == 'latitude' then -- широты return value['latitude'] elseif options['subvalue'] == 'longitude' then -- долготы return value['longitude'] else -- в противном случае формируются параметры для вызова шаблона {{coord}} -- нужно дописать в документации шаблона, что он отсюда вызывается, и что -- любое изменние его парамеров должно быть согласовано с кодом тут 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) endendlocal function getDefaultValueFunction( datavalue ) if datavalue.type == 'wikibase-entityid' then return function( context, options, value ) return formatEntityId( getEntityIdFromValue( value ), options ) end; elseif datavalue.type == 'string' then return function( context, options, value ) return value end; elseif datavalue.type == 'monolingualtext' then return function( context, options, value ) if ( options.monolingualLangTemplate == 'lang' ) then return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } }; elseif ( options.monolingualLangTemplate == 'ref' ) then return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>' .. options.frame:expandTemplate{ title = 'ref-' .. value.language }; else return '<span class="lang" lang="' .. value.language .. '">' .. value.text .. '</span>'; end end; elseif datavalue.type == 'globecoordinate' then -- geografik koordinatalar return function( context, options, value ) return formatGlobeCoordinate( value, options ) end; elseif datavalue.type == 'quantity' then return function( context, options, value ) local amount = string.gsub(value['amount'], '^%+', '') local lang = mw.language.new( 'ru' ) return lang:formatNum( tonumber( amount ) ) end; elseif datavalue.type == 'time' then return function( context, options, value )local moduleDate = require('Module:Wikidata/date') return moduleDate.formatDate( context, options, value ); end; else throwError( 'unknown-datavalue-type' ) endend function formatDatavalue( context, options, datavalue )if ( not context ) then error( 'context not specified' ); end;if ( not options ) then error( 'options not specified' ); end;if ( not datavalue ) then error( 'datavalue not specified' ); end;if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end; context.formatValueDefault = getDefaultValueFunction( datavalue ); local functionToCall = getUserFunction( options, 'value', context.formatValueDefault ); return functionToCall( context, options, datavalue.value );end-- local simpleReplaces = {Q30 = '[[AQSh]]',Q148 = '[[Xitoy Xalq Respublikasi|Xitoy]]',Q183 = '[[Germaniya]]',Q258 = '[[JAR]]',Q423 = '[[Koreya Xalq Demokratik Respublikasi|KXDR]]',Q2184 = '[[Rossiya Sovet Federativ Sotsialistik Respublikasi|Rossiya SFSR]]',Q2895 = '[[Belorussiya Sovet Sotsialistik Respublikasi|Belorus SSR]]',Q15180 = '[[Sovet Sotsialistik Respublikalari Ittifoqi|SSSR]]',Q16957 = '[[Germaniya Demokratik Respublikasi|GDR]]',Q130229 = '[[Gruziya Sovet Sotsialistik Respublikasi|Gruziya SSR]]',Q130280 = '[[Estoniya Sovet Sotsialistik Respublikasi|Estoniya SSR]]',Q131337 = '[[Ozarbayjon Sovet Sotsialistik Respublikasi|Ozarbayjon SSR]]',Q132856 = '[[Armaniston Sovet Sotsialistik Respublikasi|Armaniston SSR]]',Q133356 = '[[Ukraina Sovet Sotsialistik Respublikasi|Ukraina SSR]]',Q168811 = '[[Qozogʻiston Sovet Sotsialistik Respublikasi|Qozogʻiston SSR]]',Q170895 = '[[Moldova Sovet Sotsialistik Respublikasi|Moldova SSR]]',Q173761 = '[[Litva Sovet Sotsialistik Respublikasi|Litva SSR]]',Q192180 = '[[Latviya Sovet Sotsialistik Respublikasi|Latviya SSR]]',Q199707 = '[[Turkmaniston Sovet Sotsialistik Respublikasi|Turkmaniston SSR]]',Q199711 = '[[Tojikiston Sovet Sotsialistik Respublikasi|Tojikiston SSR]]',Q484578 = '[[Oʻzbekiston Sovet Sotsialistik Respublikasi|Oʻzbekiston SSR]]',}function formatEntityId( entityId, options )-- получение локализованного названия local label = nil; if ( options.text and options.text ~= '' ) then label = options.text else if ( simpleReplaces[entityId] ) thenreturn simpleReplaces[entityId];endlabel = 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 -- сообщение об отсутвии локализованного названия -- not good, but better than nothing return '[[d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. categoryLinksToEntitiesWithMissingLabel;end--[[ Функция для оформления утверждений (statement) Подробнее о утверждениях см. d:Wikidata:Glossary/ru Принимает: таблицу параметров Возвращает: строку оформленного текста, предназначенного для отображения в статье]]-- устаревшее имя, не использоватьfunction p.formatStatements( frame )return p.formatProperty( frame );endfunction p.formatProperty( 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 not frame.args.property then throwError( 'property-param-not-provided' ) end p_frame = framewhile p_frame doif p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' thencopyTo( p_frame.args, args, true );endif p_frame.args and p_frame.args.from and p_frame.args.from ~= '' thenargs.entityId = p_frame.args.from;endp_frame = p_frame:getParent();end if frame.args.value and frame.args.value ~= '' then if plain or frame.args.nocat or frame:callParserFunction( '#property', frame.args.property )=='' then return frame.args.value else return args.value .. categoryLocalValuePresent; end end if ( plain ) then return frame:callParserFunction( '#property', frame.args.property ); endg_frame = frame return formatProperty( frame.args )endfunction formatRefs( context, options, statement )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;if ( not statement ) then error( 'statement not specified' ); end;if ( not outputReferences ) thenreturn '';endlocal result = '';if ( statement.references ) thenlocal allReferences = statement.references;local hasPreferred = false;for _, reference in pairs( statement.references ) doif ( reference.snaksand reference.snaks.P248and reference.snaks.P248[1]and reference.snaks.P248[1].datavalueand reference.snaks.P248[1].datavalue.value["numeric-id"] ) thenlocal entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];if ( preferredSources[entityId] ) thenhasPreferred = true;endendendfor _, reference in pairs( statement.references ) dolocal display = true;if ( hasPreferred ) thenif ( reference.snaksand reference.snaks.P248and reference.snaks.P248[1]and reference.snaks.P248[1].datavalueand reference.snaks.P248[1].datavalue.value["numeric-id"] ) thenlocal entityId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];if ( deprecatedSources[entityId] ) thendisplay = false;endendendif ( display ) thenresult = result .. moduleSources.renderReference( g_frame, options.entity, reference );endendendreturn resultendreturn p
🔥 Top keywords: Maxsus:SearchBosh SahifaBirinchi yordamSayyoraAmir TemurVoleybolKoinotAlisher NavoiyBasketbolBotir ZokirovOʻzbekistonFeʼlAbdurauf FitratAbu Rayhon BeruniyJadidchilikFutbolHalima XudoyberdiyevaBirlashgan Millatlar TashkilotiKitobIslomIkkinchi jahon urushiNaqshFalsafaQoraqalpogʻistonTasviriy sanʼatYozAbu Ali ibn SinoOrol dengiziUslubDunyo aholisiAmerika Qoʻshma ShtatlariMicrosoft ExcelPoliz ekinlariInternetFutbol maydoniBirinchi jahon urushiTinish belgilariGʻarbiy frontda oʻzgarish yoʻqAllohning 99 nomi