wikidata

Documentation for this module may be created at 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-property-module"] = "Вы должны установить и property-module, и property-function.",         ["unknown-claim-module"] = "Вы должны установить и claim-module, и claim-function.",         ["unknown-value-module"] = "Вы должны установить и value-module, и value-function.",         ["property-module-not-found"] = "Модуль для отображения свойства не найден",         ["property-function-not-found"] = "Функция для отображения свойства не найдена",         ["claim-module-not-found"] = "Модуль для отображения утверждения не найден.",         ["claim-function-not-found"] = "Функция для отображения утверждения не найдена.",         ["value-module-not-found"] = "Модуль для отображения значения не найден.",         ["value-function-not-found"] = "Функция для отображения значения не найдена."     },     ["somevalue"] = "''неизвестно''",     ["novalue"] = "",     ["circa"] = 'прибл. ',     ["presumably"] = 'предп. ', }  -- settings, may differ from project to project local categoryLinksToEntitiesWithMissingLabel = '[[Категория:Википедия:Статьи со ссылками на элементы Викиданных без подписи]]'; local categoryLinksToEntitiesWithMissingLocalLanguageLabel = '[[Категория:Википедия:Статьи со ссылками на элементы Викиданных без русской подписи]]'; local categoryLocalValuePresent = '[[Категория:Википедия:Статьи с переопределением значения из Викиданных]]'; local fileDefaultSize = '267x400px'; local outputReferences = true;  -- sources that shall be omitted if any preffered sources exists local deprecatedSources = { Q36578 = true, -- Gemeinsame Normdatei Q63056 = true, -- Find a Grave Q15222191 = true, -- BNF }; local preferredSources = { Q5375741  = true, -- Encyclopædia Britannica Online Q17378135  = true, -- Great Soviet Encyclopedia (1969—1978) };  -- Ссылки на используемые модули, которые потребуются в 99% случаев загрузки страниц (чтобы иметь на виду при переименовании) local moduleSources = require( 'Module:Sources' )  -- Константы local contentLanguageCode = mw.getContentLanguage():getCode();  local p = {}  local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement, formatStatementDefault, formatProperty, getSourcingCircumstances, getPropertyDatatype, getPropertyParams, loadCacheSafe, throwError, toBoolean;  local function copyTo( obj, target ) for k, v in pairs( obj ) do target[k] = v end return target; end  local function loadCacheSafe( entityId ) -- TODO: Вернуть mw.loadData() local status, result = pcall( function() return require( 'Module:WikidataCache/' .. entityId ) end ); if ( status == true ) then return result; end return nil; end  local function splitISO8601(str) if 'table' == type(str) then if str.args and str.args[1] then str = '' .. str.args[1] else return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str ) end end local 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 nils local 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 {year=Y, month=M, day=D, hour=(h+oh), min=(m+om), sec=s}; end  local function parseTimeBoundaries( time, precision ) local s = splitISO8601( time ); if (not s) then return nil; end  if ( precision >= 0 and precision <= 8 ) then local powers = { 1000000000 , 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 } local power = powers[ precision + 1 ]; local left = s.year - ( s.year % power ); return { tonumber(os.time( {year=left, month=1, day=1, hour=0, min=0, sec=0} )) * 1000, tonumber(os.time( {year=left + power - 1, month=12, day=31, hour=29, min=59, sec=58} )) * 1000 + 1999 }; end  if ( precision == 9 ) then return { tonumber(os.time( {year=s.year, month=1, day=1, hour=0, min=0, sec=0} )) * 1000, tonumber(os.time( {year=s.year, month=12, day=31, hour=23, min=59, sec=58} )) * 1000 + 1999 }; end  if ( precision == 10 ) then local lastDays = {31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; local lastDay = lastDays[s.month]; return { tonumber(os.time( {year=s.year, month=s.month, day=1, hour=0, min=0, sec=0} )) * 1000, tonumber(os.time( {year=s.year, month=s.month, day=lastDay, hour=23, min=59, sec=58} )) * 1000 + 1999 }; end  if ( precision == 11 ) then return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=0, min=0, sec=0} )) * 1000, tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=23, min=59, sec=58} )) * 1000 + 1999 }; end  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 + 19991999 }; end  if ( precision == 13 ) then return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} )) * 1000, tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=58} )) * 1000 + 1999 }; end  if ( precision == 14 ) then local t = tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=s.min, sec=0} ) ); return { t * 1000, t * 1000 + 999 }; end  error('Unsupported precision: ' .. precision ); end  --[[   Преобразует строку в булевое значение   Принимает: строковое значение (может отсутствовать)  Возвращает: булевое значение true или false, если получается распознать значение, или defaultValue во всех остальных  случаях ]] local function toBoolean( valueToParse, defaultValue )     if ( valueToParse ~= nil ) then         if valueToParse == false or valueToParse == '' or valueToParse == 'false' or valueToParse == '0' then             return false         end         return true     end     return defaultValue; end  --[[    Функция для получения сущности (еntity) для текущей страницы   Подробнее о сущностях см. d:Wikidata:Glossary/ru    Принимает: строковый индентификатор (типа P18, Q42)   Возвращает: объект таблицу, элементы которой индексируются с нуля ]] local 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;     end end     return entity; end  --[[    Внутрення функция для формирования сообщения об ошибке     Принимает: ключ элемента в таблице i18n (например entity-not-found)   Возвращает: строку сообщения ]] local function throwError( key )     error( i18n.errors[key] ); end  --[[    Функция для получения идентификатора сущностей     Принимает: объект таблицу сущности   Возвращает: строковый индентификатор (типа P18, Q42) ]] local 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'] end  -- проверка на наличие специилизированной функции в опциях local 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; end  -- Выбирает свойства по property id, дополнительно фильтруя их по рангу local 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      return result; end  --[[    Функция для оформления утверждений (statement)   Подробнее о утверждениях см. d:Wikidata:Glossary/ru    Принимает: таблицу параметров   Возвращает: строку оформленного текста, предназначенного для отображения в статье ]] local 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  -- проброс всех параметров из шаблона {wikidata} local p_frame = g_frame:getParent(); if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then copyTo( p_frame.args, options ); end  -- improve options options.frame = g_frame; options.entity = entity; options.extends = function( self, newOptions ) return copyTo( newOptions, copyTo( self, {} ) ) end  if ( options.i18n ) then options.i18n = copyTo( options.i18n, copyTo( i18n, {} ) ); else options.i18n = i18n; end  -- create context local context = { entity = options.entity, 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 ) then return tonumber(os.time( splitISO8601( tostring( snak.datavalue.value.time ) ) ) ) * 1000; end return nil; end context.parseTimeBoundariesFromSnak = function( snak ) if ( snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.time and snak.datavalue.value.precision ) then return parseTimeBoundaries( snak.datavalue.value.time, snak.datavalue.value.precision ); end return nil; end context.getSourcingCircumstances = function( statement ) return getSourcingCircumstances( statement ) end; context.selectClaims = function( options, propertyId ) return selectClaims( context, options, propertyId ) end;  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) then             formattedStatement = '.. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. ''             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  --[[    Функция для оформления одного утверждения (statement)    Принимает: объект-таблицу утверждение и таблицу параметров   Возвращает: строку оформленного текста с заявлением (claim) ]] function formatStatement( context, options, statement ) if ( not statement ) then error( '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 ); end  function getSourcingCircumstances( statement ) if (not statement) then error('statement is not specified') end;  local circumstances = {}; if ( statement.qualifiers and statement.qualifiers.P1480 ) then for i, qualifier in pairs( statement.qualifiers.P1480 ) do if ( qualifier and qualifier.datavalue and qualifier.datavalue.type == 'wikibase-entityid' and qualifier.datavalue.value and qualifier.datavalue.value["entity-type"] == 'item' ) then local circumstance = 'Q' .. qualifier.datavalue.value["numeric-id"]; if ( 'Q5727902' == circumstance ) then circumstances.circa = true; end if ( 'Q18122778' == circumstance ) then circumstances.presumably = true; end end end end return circumstances; end  --[[    Функция для оформления одного утверждения (statement)    Принимает: объект-таблицу утверждение, таблицу параметров,   объект-функцию оформления внутренних структур утверждения (snak) и   объект-функцию оформления ссылки на источники (reference)   Возвращает: строку оформленного текста с заявлением (claim) ]] function 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 statement.qualifiers then options.qualifiers = statement.qualifiers; end  if ( options.references ) then     return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );     else     return context.formatSnak( options, statement.mainsnak, circumstances );     end end  --[[    Функция для оформления части утверждения (snak)   Подробнее о snak см. d:Викиданные:Глоссарий    Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций   Возвращает: строку оформленного викитекста ]] function formatSnak( context, options, snak, circumstances ) circumstances = circumstances or {}; local hash = ''; local mainSnakClass = ''; if ( snak.hash ) then hash = ' data-wikidata-hash="' .. snak.hash .. '"'; else mainSnakClass = ' wikidata-main-snak'; end  local before = '.. mainSnakClass .. '"' .. hash .. '>' local after = ''      if snak.snaktype == 'somevalue' then         if ( options['somevalue'] and options['somevalue'] ~= '' ) then             return before .. options['somevalue'] .. after;         end         return before .. options.i18n['somevalue'] .. after;     elseif snak.snaktype == 'novalue' then         if ( options['novalue'] and options['novalue'] ~= '' ) then             return before .. options['novalue'] .. after;         end         return before .. options.i18n['novalue'] .. after;     elseif snak.snaktype == 'value' then if ( circumstances.presumably ) then before = before .. options.i18n.presumably; end if ( circumstances.circa ) then before = before .. options.i18n.circa; end          return before .. formatDatavalue( context, options, snak.datavalue, snak.datatype ) .. after;     else         throwError( 'unknown-snak-type' );     end end  --[[    Функция для оформления объектов-значений с географическими координатами    Принимает: объект-значение и таблицу параметров,   Возвращает: строку оформленного текста ]] function formatGlobeCoordinate( value, options ) -- проверка на требование в параметрах вызова на возврат сырого значения      if options['subvalue'] == 'latitude' then -- широты         return value['latitude']     elseif options['subvalue'] == 'longitude' then -- долготы         return value['longitude']     elseif options['nocoord'] and options['nocoord'] ~= '' then     -- если передан параметр nocoord, то не выводить координаты     -- обычно это делается при использовании нескольких карточек на странице     return ''     else     -- в противном случае формируются параметры для вызова шаблона {{coord}}     -- нужно дописать в документации шаблона, что он отсюда вызывается, и что     -- любое изменние его парамеров  должно быть согласовано с кодом тут         local eps = 0.0000001 -- < 1/360000         local globe = options.globe or '' -- 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 + 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         coord = coord .. '|type=' .. options.type     end         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  --[[    Функция для оформления объектов-значений с файлами с Викисклада    Принимает: объект-значение и таблицу параметров,   Возвращает: строку оформленного текста ]] function formatCommonsMedia( value, options ) local image = '[[File:' .. value 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$' ) and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики  then     size = size .. 'px'     end else size = fileDefaultSize;     end image = image .. '|' .. size      if options['alt'] and options['alt'] ~= '' then     image = image .. '|' .. options['alt']     end image = image .. ']]'  if options['description'] and options['description'] ~= '' then image = image .. '
'
.. options['description'] end return image end --[[ Функция для оформления внешних идентификаторов Принимает: объект-значение и таблицу параметров, Возвращает: строку оформленного текста ]] local function formatExternalId( value, options ) local formatter = options.formatter if not formatter or formatter == '' then local entity = mw.wikibase.getEntity( options.property:upper() ) if entity then local statements = entity:getBestStatements( 'P1630' ) for _, statement in pairs( statements ) do if statement.mainsnak.snaktype == 'value' then formatter = statement.mainsnak.datavalue.value break end end end end if formatter and formatter ~= '' then local link = mw.ustring.gsub( formatter, '$1', value ) local title = options.title if not title or title == '' then title = '$1' end title = mw.ustring.gsub( title, '$1', value ) return '[' .. link .. ' ' .. title .. ']' end return value end --[[ Функция для оформления числовых значений Принимает: объект-значение и таблицу параметров, Возвращает: строку оформленного текста ]] local function formatQuantity( value, options ) -- диапазон значений local amount = string.gsub( value['amount'], '^%+', '' ); local lang = mw.language.getContentLanguage(); local langCode = lang:getCode(); local function formatNum( number ) -- округление до 13 знаков после запятой, на 14-м возникает ошибка в точности local mult = 10^13 number = math.floor( number * mult + 0.5 ) / mult return lang:formatNum( number ) end local out = formatNum( tonumber( amount ) ); if value.upperBound then local diff = tonumber( value.upperBound ) - tonumber( amount ) if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0 out = out .. '±' .. formatNum( diff ) end end if options.unit and options.unit ~= '' then if options.unit ~= '-' then out = out .. ' ' .. options.unit end 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/', '' ); local unitEntity = mw.wikibase.getEntity( unitEntityId ); if unitEntity then -- name from label -- TODO: lang:getFallbackLanguages() local label = nil; if unitEntity.labels then if unitEntity.labels[langCode] and unitEntity.labels[langCode].value then label = unitEntity.labels[langCode].value; elseif unitEntity.labels.en and unitEntity.labels.en.value then label = unitEntity.labels.en.value; end end -- name from properties if unitEntity.claims and unitEntity.claims.P558 then local writingSystemElementId = 'Q8209'; local langElementId = 'Q7737'; local WDS = require( 'Module:WikidataSelectors' ); local labelFilter = 'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']'; local labelClaims = WDS.filter( unitEntity.claims, labelFilter ); if #labelClaims == 0 then labelFilter = 'P558[!P282][!P407]'; labelClaims = WDS.filter( unitEntity.claims, labelFilter ); end for r, claim in pairs( labelClaims ) do if claim.mainsnak and claim.mainsnak.datavalue and claim.mainsnak.datavalue.type == 'string' and claim.mainsnak.datavalue.value ~= '' then label = claim.mainsnak.datavalue.value; break; end end end out = out .. ' ' .. label; end end return out; end --[[ Get property datatype by ID. @param string Property ID, e.g. 'P123'. @return string Property datatype, e.g. 'commonsMedia', 'time' or 'url'. ]] local function getPropertyDatatype( propertyId ) if not propertyId or not string.match( propertyId, '^P%d+$' ) then return nil; end local propertyEntity = mw.wikibase.getEntity( propertyId ); if not propertyEntity then return nil; end return propertyEntity.datatype; end local function getDefaultValueFunction( datavalue, datatype ) -- вызов обработчиков по умолчанию для известных типов значений if datavalue.type == 'wikibase-entityid' then -- Entity ID return function( context, options, value ) return formatEntityId( getEntityIdFromValue( value ), options ) end; elseif datavalue.type == 'string' then -- String if datatype and datatype == 'commonsMedia' then -- Media return function( context, options, value ) if ( not options.description or options.description == '' ) and options.qualifiers and options.qualifiers.P2096 then for i, qualifier in pairs( options.qualifiers.P2096 ) do if ( qualifier and qualifier.datavalue and qualifier.datavalue.type == 'monolingualtext' and qualifier.datavalue.value and qualifier.datavalue.value.language == contentLanguageCode ) then options.description = qualifier.datavalue.value.text break end end end return formatCommonsMedia( value, options ) end; elseif datatype and datatype == 'external-id' then -- External ID return function( context, options, value ) return formatExternalId( value, options ) end elseif datatype and datatype == 'url' then -- URL return function( context, options, value ) local moduleUrl = require( 'Module:URL' ) if not options.length or options.length == '' then options.length = 25 end return moduleUrl.formatUrlSingle( context, options, value ); end end 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 '.. value.language .. '">' .. value.text .. '' .. options.frame:expandTemplate{ title = 'ref-' .. value.language }; else return '.. value.language .. '">' .. value.text .. ''; end end; elseif datavalue.type == 'globecoordinate' then -- географические координаты return function( context, options, value ) return formatGlobeCoordinate( value, options ) end; elseif datavalue.type == 'quantity' then return function( context, options, value ) return formatQuantity( value, options ) 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' ) end end --[[ Функция для оформления значений (value) Подробнее о значениях см. d:Wikidata:Glossary/ru Принимает: объект-значение и таблицу параметров, Возвращает: строку оформленного текста ]] function formatDatavalue( context, options, datavalue, datatype ) 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, datatype ); local functionToCall = getUserFunction( options, 'value', context.formatValueDefault ); return functionToCall( context, options, datavalue.value ); end -- Небольшой словарь упрощенного отображения (TODO: надо сделать расширенный с учётом даты) local simpleReplaces = {} --[[ Функция для оформления идентификатора сущности Принимает: строку индентификатора (типа Q42) и таблицу параметров, Возвращает: строку оформленного текста ]] function formatEntityId( entityId, options ) -- получение локализованного названия local label = nil; local labelLanguageCode = contentLanguageCode; if ( options.text and options.text ~= '' ) then label = options.text else if ( simpleReplaces[entityId] ) then return simpleReplaces[entityId]; end label, lang = mw.wikibase.getLabelWithLang( entityId ); end -- получение ссылки по идентификатору local link = mw.wikibase.sitelink( entityId ) if link then if label then if ( contentLanguageCode ~= labelLanguageCode ) then return '[[' .. link .. '|' .. label .. ']]' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel; else return '[[' .. link .. '|' .. label .. ']]'; end else return '[[' .. link .. ']]'; end end if label then -- красная ссылка -- TODO: разобраться, почему не всегда есть options.frame if not mw.title.new( label ).exists and options.frame then return '[[' .. label .. ']][[:d:' .. entityId .. '|[d]]]'; end -- TODO: перенести до проверки на существование статьи local sup = ''; if ( not options.format or options.format ~= 'text' ) and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: переписать на format=text then sup = '[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d]]' end -- одноимённая статья уже существует - выводится текст и ссылка на ВД return '.. label .. '">' .. label .. sup .. '' end -- сообщение об отсутвии локализованного названия -- not good, but better than nothing return '[[:d:' .. entityId .. '|' .. entityId .. ']]?' .. categoryLinksToEntitiesWithMissingLabel; end --[[ Функция для оформления утверждений (statement) Подробнее о утверждениях см. d:Wikidata:Glossary/ru Принимает: таблицу параметров Возвращает: строку оформленного текста, предназначенного для отображения в статье ]] -- устаревшее имя, не использовать function p.formatStatements( frame ) return p.formatProperty( frame ); end --[[ Получение параметров, которые обычно используются для вывода свойства. ]] function getPropertyParams( propertyId, datatype, params ) local config = require( 'Module:Wikidata/config' ); if not config then return {}; end -- Различные уровни настройки параметров, по убыванию приоритета local propertyParams = {}; -- 1. Параметры, указанные явно при вызове if params then local tplParams = mw.clone( params ); for key, value in pairs( tplParams ) do if value ~= '' then propertyParams[key] = value; end end end -- 2. Настройки конкретного параметра if config['properties'] and config['properties'][propertyId] then local selfParams = mw.clone( config['properties'][propertyId] ); for key, value in pairs( selfParams ) do if propertyParams[key] == nil then propertyParams[key] = value; end end end -- 3. Указанный пресет настроек if propertyParams['preset'] and config['presets'] and config['presets'][propertyParams['preset']] then local presetParams = mw.clone( config['presets'][propertyParams['preset']] ); for key, value in pairs( presetParams ) do if propertyParams[key] == nil then propertyParams[key] = value; end end end -- 4. Настройки для типа данных if datatype and config['datatypes'] and config['datatypes'][datatype] then local datatypeParams = mw.clone( config['datatypes'][datatype] ); for key, value in pairs( datatypeParams ) do if propertyParams[key] == nil then propertyParams[key] = value; end end end -- 5. Общие настройки для всех свойств if config['global'] then local globalParams = mw.clone( config['global'] ); for key, value in pairs( globalParams ) do if propertyParams[key] == nil then propertyParams[key] = value; end end end return propertyParams; end function p.formatProperty( frame ) local plain = toBoolean( frame.args.plain, false ); local args = frame.args -- проверка на отсутствие обязательного параметра property if not args.property then throwError( 'property-param-not-provided' ) end local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) ) local datatype = getPropertyDatatype( propertyId ); args = getPropertyParams( propertyId, datatype, args ); args.nocat = toBoolean( args.nocat, false ); args.references = toBoolean( args.references, true ); -- если значение передано в параметрах вызова то выводим только его if args.value and args.value ~= '' then -- специальное значение для скрытия Викиданных if args.value == '-' then return '' end local value = args.value -- опция, запрещающая оформление значения, поэтому никак не трогаем if plain then return value end -- обработчики по типу значения if args['value-module'] and args['value-function'] and not string.find( value, '[%[%]%{%}]' ) then local func = getUserFunction( args, 'value' ); value = func( {}, args, value ); elseif datatype == 'commonsMedia' and not string.find( value, '[%[%]%{%}]' ) then value = formatCommonsMedia( value, args ); elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then value = formatExternalId( value, args ); elseif datatype == 'url' then local moduleUrl = require( 'Module:URL' ); value = moduleUrl.formatUrlSingle( nil, args, value ); end -- оборачиваем в тег для JS-функций if string.match( propertyId, '^P%d+$' ) then value = mw.text.trim( value ) -- временная штрафная категория для исправления табличных вставок if ( propertyId ~= 'P166' and string.match( value, ']' ) and not string.match( value, ']')andnotstring.match(value,'^%{%|'))thenvalue=value..'[[Категория:Википедия:Статьи с табличной вставкой в карточке]]'else-- значений с блочными тегами остаются блоком, текст встраиваем в строкуif(string.match(value,'\n')orstring.match(value,']')orstring.match(value,']'))thenvalue='
.. 'data-wikidata-property-id="' .. propertyId .. '">\n' .. value .. '
'
elsevalue=' .. 'data-wikidata-property-id="' .. propertyId .. '">' ..value..''endendend-- добавляем категорию-маркерifnotargs.nocatthenvalue=value..categoryLocalValuePresent;endreturnvalueendif(plain)then-- вызова стандартного обработчика без оформления, если передана опция plainreturnframe:callParserFunction('#property',propertyId);endg_frame=frame-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)returnformatProperty(args)end--[[ Функция оформления ссылок на источники (reference) Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства). Принимает: объект-таблицу утверждение Возвращает: строку оформленных ссылок для отображения в статье]]functionformatRefs(context,options,statement)if(notcontext)thenerror('context not specified');end;if(notoptions)thenerror('options not specified');end;if(notoptions.entity)thenerror('options.entity missing');end;if(notstatement)thenerror('statement not specified');end;if(notoutputReferences)thenreturn'';endlocalresult='';if(statement.references)thenlocalallReferences=statement.references;localhasPreferred=false;for_,referenceinpairs(statement.references)doif(reference.snaksandreference.snaks.P248andreference.snaks.P248[1]andreference.snaks.P248[1].datavalueandreference.snaks.P248[1].datavalue.value["numeric-id"])thenlocalentityId="Q"..reference.snaks.P248[1].datavalue.value["numeric-id"];if(preferredSources[entityId])thenhasPreferred=true;endendendfor_,referenceinpairs(statement.references)dolocaldisplay=true;if(hasPreferred)thenif(reference.snaksandreference.snaks.P248andreference.snaks.P248[1]andreference.snaks.P248[1].datavalueandreference.snaks.P248[1].datavalue.value["numeric-id"])thenlocalentityId="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);endendendreturnresultendreturnp

Tags: