Модуль:Wikidata — Версийн башхалла

[теллина верси][теллина верси]
Чулацам дӀабаьккхина Чулацам тӀетоьхна
Юхадаьккхина декъашхочун Takhirgeran Umar (дийц.) нисдар 5054628
Билгало: йухайаккхар
Нисдарах лаьцна йаздина дац
Билгало: Куьйга йухайерзор
МогӀа 1:
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"] = '<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 project
local categoryLinksToEntitiesWithMissingLabel = '[[Категори:Википеди:Викихаамаш чохь элементаш тӀе куьг доцу хьажоргаш йолу яззамаш]]';
local categoryLinksToEntitiesWithWikibaseError = '[[Категори:Википеди:Викихаамаш чохь скриптийн гӀалаташ долу яззамаш]]';
local categoryLinksToEntitiesWithMissingLocalLanguageLabel = '[[Категори:Википеди:Викихаамаш чохь элементаш тӀе нохчийн куьг доцу хьажоргаш йолу яззамаш]]';
local categoryLocalValuePresent = '[[Категори:Википеди:Викихаамаш чохь маьӀнаш карладаьхна яззамаш]]';
local fileDefaultSize = '267x400px';
local outputReferences = true;
МогӀа 35 ⟶ 7 :
Q36578 = true, -- Gemeinsame Normdatei
Q63056 = true, -- Find a Grave
Q1798125 = true, -- LIBRIS
Q15222191 = true, -- BNF
Q15241312 = true, -- Freebase
};
Q29861311 = true, -- SNAC
local preferredSources = {
Q5375741 Q86999151 = true, -- Encyclopædia Britannica OnlineWeChangEd
Q523660 = true, -- International Music Score Library Project by https://ru.wikipedia.org/?diff=107090748
Q17378135 = true, -- Great Soviet Encyclopedia (1969—1978)
};
 
МогӀа 49 ⟶ 22 :
local contentLanguageCode = mw.getContentLanguage():getCode();
 
local p = {};
local config = nil;
 
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
МогӀа 55 ⟶ 29 :
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
 
local function copyTo( obj, target, skipEmpty )
for k, v in pairs( obj ) do
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
target[k] = v
target[k] = v;
end
end
return target;
МогӀа 72 ⟶ 48 :
elseif ( prev < next ) then return next;
else return prev; end
end
 
local function getConfig( section, code )
if config == nil then
config = require( 'Module:Wikidata/config' );
end;
if not config then
config = {};
end
 
if not section then
return config;
end
if not code then
return config[ section ] or {};
end
 
if not config[ section ] then
return nil;
end
return config[ section ][ code ];
end
 
local function getCategoryByCode( code )
local value = getConfig( 'categories', code );
if not value or value == '' then
return '';
end
return '[[Category:' .. value .. ']]';
end
 
МогӀа 134 ⟶ 139 :
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
 
МогӀа 164 ⟶ 169 :
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
 
МогӀа 179 ⟶ 203 :
if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
else
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
end
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
 
return entity;
МогӀа 188 ⟶ 213 :
Внутрення функция для формирования сообщения об ошибке
 
Принимает: ключ элемента в таблице i18nconfig.errors (например entity-not-found)
Возвращает: строку сообщения
]]
local function throwError( key )
error( i18n.getConfig( 'errors[', key] ) );
end
 
МогӀа 223 ⟶ 248 :
end
-- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require ( 'Module:' .. options[ prefix .. '-module' ] );
if formatter == nil then
throwError( prefix .. '-module-not-found' )
МогӀа 266 ⟶ 291 :
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entityentityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
 
local results = {};
 
МогӀа 273 ⟶ 300 :
end
 
for _, propertyId in ipairs( propertyIds ) do
if entity.claims then
local selector = selectors[_];
for _, propertyId in ipairs( propertyIds ) do
local filteredClaimspropertyClaims = WDSmw.filterwikibase.getAllStatements( entity.claimsentityId, propertyId .. '[rank:preferred, rank:normal]' );
local fakeAllClaims = {};
if filteredClaims then
fakeAllClaims[propertyId] = propertyClaims;
for _, claim in pairs( filteredClaims ) do
if not boundaries or not propertyIds or #propertyIds == 0 then
local filteredClaims = WDS.filter( fakeAllClaims, selector .. '[rank:preferred, rank:normal]' );
if filteredClaims then
for _, claim in pairs( filteredClaims ) do
if not boundaries then
table.insert( results, claim.mainsnak );
else
local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' );
 
if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
table.insert( results, claim.mainsnak );
else
local startBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P580' );
local endBoundaries = p.getTimeBoundariesFromQualifier( context.frame, context, claim, 'P582' );
 
if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
table.insert( results, claim.mainsnak );
end
end
end
end
end
 
if #results > 0 then
break;
end
end
end
МогӀа 341 ⟶ 371 :
return nil;
end
 
local CONTENT_LANGUAGE_CODE = mw.language.getContentLanguage():getCode();
local getLabelWithLang_DEFAULT_PROPERTIES = { "P1813", "P1448", "P1705" };
local getLabelWithLang_DEFAULT_SELECTORS = {
'P1813[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1448[language:' .. CONTENT_LANGUAGE_CODE .. ']',
'P1705[language:' .. CONTENT_LANGUAGE_CODE .. ']'
};
 
--[[
МогӀа 348 ⟶ 386 :
Возвращает: текстовую метку элемента, язык метки
]]
local function getLabelWithLang( context, options, entityentityId, boundaries, propertyIds, selectors )
if (type(entityId) ~= 'string') then error('type of entityId argument expected string, but was ' .. type(entityId)); end
if not entity then
if not entityId then
return nil;
end
 
local langlangCode = mw.language.getContentLanguage()CONTENT_LANGUAGE_CODE;
local langCode = lang:getCode();
 
-- name from label
МогӀа 361 ⟶ 399 :
label = options.text;
else
label, langCode = entity:getLabelWithLang();
 
if not langCode then
return nil;
end
 
if not propertyIds then
propertyIds = {getLabelWithLang_DEFAULT_PROPERTIES;
selectors = getLabelWithLang_DEFAULT_SELECTORS;
'P1813[language:' .. langCode .. ']',
'P1448[language:' .. langCode .. ']',
'P1705[language:' .. langCode .. ']'
};
end
 
-- name from properties
local results = getPropertyInBoundaries( context, entityentityId, boundaries, propertyIds, selectors );
 
for _, result in pairs( results ) do
МогӀа 382 ⟶ 411 :
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
label = result.datavalue.value.text;
langlangCode = result.datavalue.value.language;
break;
elseif result.datavalue.type == 'string' then
МогӀа 388 ⟶ 417 :
break;
end
end
end
if (not label) then
label, langCode = mw.wikibase.getLabelWithLang( entityId );
if not langCode then
return nil;
end
end
МогӀа 393 ⟶ 429 :
 
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?
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
 
МогӀа 422 ⟶ 498 :
 
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo( getConfig( 'i18n' ), {} ) );
else
options.i18n = getConfig( 'i18n' );
end
 
МогӀа 440 ⟶ 516 :
options.entity = entity;
newOptions.entity = entity;
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
 
return newOptions;
МогӀа 467 ⟶ 544 :
 
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 = '<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
 
МогӀа 540 ⟶ 576 :
and qualifier.datavalue.value
and qualifier.datavalue.value['entity-type'] == 'item' ) then
local circumstance =table.insert(circumstances, qualifier.datavalue.value.id;)
if ( 'Q5727902' == circumstance ) then
circumstances.circa = true;
end
if ( 'Q18122778' == circumstance ) then
circumstances.presumably = true;
end
end
end
МогӀа 570 ⟶ 600 :
options.qualifiers = statement.qualifiers;
 
local result = context.formatSnak( options, statement.mainsnak, circumstances );
if ( options.references ) then
return context.formatSnak( options, statement.mainsnak, circumstances ) .. context.formatRefs( options, statement );
if ( options.qualifier and statement.qualifiers and statement.qualifiers[ options.qualifier ] ) then
else
qualConfig = getPropertyParams( options.qualifier, nil, {})
return context.formatSnak( options, statement.mainsnak, circumstances );
if options.i18n then qualConfig.i18n = options.i18n end
local qualifierValues = {};
for _, qualifierSnak in pairs( statement.qualifiers[ options.qualifier ] ) do
local snakValue = context.formatSnak( qualConfig, qualifierSnak );
if snakValue and snakValue ~= '' then
table.insert( qualifierValues, snakValue );
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
 
if ( result and result ~= '' and options.references ) then
result = result .. context.formatRefs( options, statement );
end
 
return result;
end
 
МогӀа 599 ⟶ 650 :
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
returnresult before ..= options['somevalue'] .. after;
else
result = options.i18n['somevalue'];
end
return before .. options.i18n['somevalue'] .. after;
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
returnresult before ..= options['novalue'] .. after;
else
result = options.i18n['novalue'];
end
return before .. options.i18n['novalue'] .. after;
elseif snak.snaktype == 'value' then
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
if ( circumstances.presumably ) then
for _, item in pairs(circumstances) do
before = before .. options.i18n.presumably;
if options.i18n[item] then
result = options.i18n[item] .. result;
end
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
if ( not result or result == '' ) then
return nil;
end
 
return before .. result .. after;
end
 
МогӀа 627 ⟶ 684 :
Возвращает: строку оформленного текста
]]
local function formatGlobeCoordinate( value, options )
-- проверка на требование в параметрах вызова на возврат сырого значения
if options['subvalue'] == 'latitude' then -- широты
МогӀа 641 ⟶ 698 :
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
coord_mod = require( "Module:Coordinates" );
local globe = options.globe or '' -- TODO
local lat = {}
local globe = options.globe or ''
lat['abs'] = math.abs(value['latitude'])
lat['ns']if globe == value['latitude'] >= 0 and value['Nglobe'] or 'S'then
globes = require( 'Module:Wikidata/Globes' )
lat['d'] = math.floor(lat['abs'] + eps)
lat['m'] globe = math.floor((latglobes[value['absglobe']] -or 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
local display = 'inline'
if options['type'] and options['type'] ~= '' then
if options.display and options.display ~= '' then
coord = coord .. '|type=' .. options.type
display = options.display
elseif ( options.property:upper() == 'P625' ) then
display = 'title'
end
if options['display'] and options['display'] ~= '' then
g_frame.args = {tostring(value['latitude']), tostring(value['longitude']), globe = globe, type = options.type and options.type or '', display = display }
coord = coord .. '|display=' .. options.display
else
return coord_mod.coord(g_frame)
coord = coord .. '|display=title'
end
coord = coord .. '}}'
 
return g_frame:preprocess(coord)
end
end
МогӀа 688 ⟶ 726 :
Возвращает: строку оформленного текста
]]
local function formatCommonsMedia( value, options )
local image = value;
 
local caption = '';
if options[ 'caption' ] and options[ 'caption' ] ~= '' then
caption = options[ 'caption' ];
elseif options[ 'description' ] and options[ 'description' ] ~= '' then
caption = options[ 'description' ];
end
if caption ~= '' then
caption = wrapFormatProperty( caption, '<spanclass="media-caption" 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, то викифицируем имя файла
image = '[[File:' .. value
-- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[PHAB:T28213]]
if options['border'] and options['border'] ~= '' then
image = image'[[File:' .. value .. '|borderframeless';
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$' )
МогӀа 717 ⟶ 757 :
size = fileDefaultSize;
end
image = image .. '|' .. size;
 
if options[ 'alt' ] and options[ 'alt' ] ~= '' then
image = image .. '|' .. options[ 'alt' ];
end
image = image .. ']]';
 
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
 
--[[
Fonction for render math formulas
 
@param string Value.
@param table Parameters.
@return string Formatted string.
]]
local function formatMath( value, options )
return options.frame:extensionTag{ name = 'math', content = value };
end
 
МогӀа 741 ⟶ 802 :
]]
local function formatExternalId( value, options )
local formatter = options.formatter;
 
if not formatter or formatter == '' then
local wbStatus, entitypropertyEntity = pcall( mw.wikibase.getEntity, options.property:upper() )
if wbStatus == true and entitypropertyEntity then
local statementsisGoodFormat = entity:getBestStatements( 'P1630' )false;
local statements = propertyEntity:getBestStatements( 'P1793' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
formatterlocal pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' );
break
if ( string.find( pattern, '|' ) or string.find( pattern, '%)%?' )
or mw.ustring.match( value, '^' .. pattern .. '$' ) ~= nil ) then
isGoodFormat = true;
break;
end
end
end
 
if ( isGoodFormat == true ) then
statements = propertyEntity:getBestStatements( 'P1630' );
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
formatter = statement.mainsnak.datavalue.value;
break
end
end
end
МогӀа 757 ⟶ 834 :
 
if formatter and formatter ~= '' then
local link = mw.ustring.gsub(
mw.ustring.gsub( formatter, '$1', value ), '.',
{ [' '] = '%20', ['+'] = '%2b' } )
 
local title = options.title
МогӀа 783 ⟶ 862 :
local langCode = lang:getCode();
 
local function formatNum( number, sigfig )
sigfig = sigfig or 12 -- округление до 1312 знаков после запятой, на 1413-м возникает ошибка в точности
local mult = 10^13sigfig;
number = math.floor( number * mult + 0.5 ) / mult;
return string.gsub( lang:formatNum( number ), '^-', '−' );
 
return lang:formatNum( number )
end
 
МогӀа 795 ⟶ 873 :
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
МогӀа 805 ⟶ 897 :
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/', '' );
if unitEntityId ~= 'undefined' then
local wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
if local wbStatus, unitEntity == truepcall( andmw.wikibase.getEntity, unitEntityunitEntityId then);
if wbStatus == true and unitEntity then
local writingSystemElementId = 'Q8209';
if unitEntity.claims.P2370 and
local langElementId = 'Q7737';
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
local label = getLabelWithLang( context, options, unitEntity, nil, {
not value.upperBound and
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
options.siConversion == true
'P558[!P282][!P407]'
} ); then
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
 
if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
out = out .. ' ' .. label;
-- Если не степени десятки (переводить сантиметры в метры не надо!)
outValue = tonumber( amount ) * conversionToSIunit
if ( outValue > 0 ) then
-- Пробуем понять до какого знака округлять
local integer, dot, decimals, expstr = amount:match( '^(%d*)(%.?)(%d*)(.*)' )
local prec
if dot == '' then
prec = -integer:match('0*$'):len()
else
prec = #decimals
end
local adjust = math.log10( math.abs( conversionToSIunit )) + math.log10( 2 )
local minprec = 1 - math.floor( math.log10( outValue ) + 2e-14 );
out = formatNum( outValue, math.max( math.floor( prec + adjust ), minprec ));
else
out = formatNum( outValue, 0 )
end
unitEntityId = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.unit, 'http://www.wikidata.org/entity/', '' );
wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
end
end
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
local label = getLabelWithLang( context, options, unitEntity.id, nil, { "P5061", "P558", "P558" }, {
'P5061[language:' .. langCode .. ']',
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
'P558[!P282][!P407]'
} );
out = out .. ' ' .. label;
end
end
end
МогӀа 820 ⟶ 945 :
return out;
end
 
local DATATYPE_CACHE = {}
 
--[[
МогӀа 831 ⟶ 958 :
return nil;
end
local cached = DATATYPE_CACHE[propertyId];
if (cached ~= nil) then return cached; end
 
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
МогӀа 836 ⟶ 966 :
return nil;
end
mw.log("Loaded datatype " .. propertyEntity.datatype .. " of " .. propertyId .. ' from wikidata, consider passing datatype argument to formatProperty call or to Wikidata/config' )
 
DATATYPE_CACHE[propertyId] = propertyEntity.datatype;
return propertyEntity.datatype;
end
 
local function formatLangRefs( options )
local langRefs = ''
if ( options.qualifiers and options.qualifiers.P407 ) then
for i, qualifier in pairs( options.qualifiers.P407 ) do
if ( qualifier
and qualifier.datavalue
and qualifier.datavalue.type == 'wikibase-entityid' ) then
local langRefEntity = getEntityFromId( qualifier.datavalue.value.id )
if ( langRefEntity and langRefEntity.claims ) then
local langRefCodeClaims = WDS.filter( langRefEntity.claims, 'P218' )
if langRefCodeClaims then
for _, claim in pairs( langRefCodeClaims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'string' ) then
local langRefCode = claim.mainsnak.datavalue.value
langRefs = langRefs .. '&#8203;' .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
end
end
end
end
end
end
end
 
return langRefs
end
 
МогӀа 850 ⟶ 1011 :
-- Media
return function( context, options, value )
if ( not options.caption orand options.caption =~= '' )then
and ( not options.descriptionlocal_caption or= options.description == '' )caption;
andelseif options.qualifiersdescription and options.qualifiers.P2096description ~= '' 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
МогӀа 863 ⟶ 1029 :
break
end
end
end
if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
local moment = formatDatavalue (context, options, options.qualifiers.P585[1].datavalue, 'time')
if not options.caption or options.caption == '' then
options.caption = moment
options.description = moment
else
options.caption = options.caption .. ', ' .. moment
options.description = options.description .. ', ' .. moment
end
end
МогӀа 871 ⟶ 1047 :
return function( context, options, value )
return formatExternalId( value, options )
end
elseif datatype and datatype == 'math' then
-- Math formula
return function( context, options, value )
return formatMath( value, options )
end
elseif datatype and datatype == 'url' then
МогӀа 876 ⟶ 1057 :
return function( context, options, value )
local moduleUrl = require( 'Module:URL' )
local langRefs = formatLangRefs( options )
if not options.length or options.length == '' then
options.length = math.max( 18, 25 - #langRefs )
end
return moduleUrl.formatUrlSingle( context, options, value ); .. langRefs
end
end
МогӀа 887 ⟶ 1069 :
return function( context, options, value )
if ( options.monolingualLangTemplate == 'lang' ) then
if ( value.language == contentLanguageCode ) then
return value.text;
end
return options.frame:expandTemplate{ title = 'lang-' .. value.language, args = { value.text } };
elseif ( options.monolingualLangTemplate == 'ref' ) then
МогӀа 929 ⟶ 1114 :
return functionToCall( context, options, datavalue.value );
end
 
local DEFAULT_BOUNDARIES = { os.time() * 1000, os.time() * 1000};
 
--[[
МогӀа 938 ⟶ 1125 :
function formatEntityId( context, options, entityId )
-- получение локализованного названия
local wbStatus, entity = pcall( mw.wikibase.getEntity, entityId )
if wbStatus ~= true then
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="color:#b32424; border-bottom: 1px dotted #b32424; cursor: help; white-space: nowrap" title="Ошибка получения элемента из Викиданных.">×</span>' .. categoryLinksToEntitiesWithWikibaseError;
end
local boundaries = nil
if options.qualifiers then
boundaries = p.getTimeBoundariesFromQualifiers( frame, context, { qualifiers = options.qualifiers } )
end
if not boundaries then
local label, labelLanguageCode = getLabelWithLang( context, options, entity, boundaries )
boundaries = DEFAULT_BOUNDARIES;
end
local label, labelLanguageCode = getLabelWithLang( context, options, entityId, boundaries )
 
-- определение соответствующей показываемому элементу категории
local category = ''p.extractCategory( context, options, { id = entityId } )
if ( options.category ) then
local claims = WDS.filter( entity.claims, options.category );
if ( claims ) then
for _, claim in pairs( claims ) do
if ( claim.mainsnak
and claim.mainsnak
and claim.mainsnak.datavalue
and claim.mainsnak.datavalue.type == 'wikibase-entityid' ) then
local catEntityId = claim.mainsnak.datavalue.value.id;
local wbStatus, catEntity = pcall( mw.wikibase.getEntity, catEntityId );
if ( wbStatus == true and catEntity and catEntity:getSitelink() ) then
category = '[[' .. catEntity:getSitelink() .. ']]';
end
end
end
end
end
 
-- получение ссылки по идентификатору
МогӀа 975 ⟶ 1144 :
link = ':' .. link
end
if label and not options.rawArticle then
local a = link == label and ('[[' .. link .. ']]') or '[[' .. link .. '|' .. label .. ']]';
if ( contentLanguageCode ~= labelLanguageCode ) then
return '[['a .. link ..getCategoryByCode( '|' .. links-to-entities-with-missing-local-language-label .. ']]' .. categoryLinksToEntitiesWithMissingLocalLanguageLabel) .. category;
else
return '[[' .. link .. '|' .. label .. ']]'a .. category;
end
else
МогӀа 991 ⟶ 1161 :
local title = mw.title.new( label );
if title and not title.exists and options.frame then
local redLink = options.frame:expandTemplate{ title='Ш:Красная ссылка с рыбой', args = { entityId, label } };
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
return redLink .. '<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
 
МогӀа 1009 ⟶ 1180 :
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. categoryLinksToEntitiesWithMissingLabelgetCategoryByCode( 'links-to-entities-with-missing-label' ) .. category;
end
 
--[[
Функция для формирования категории на основе wikidata/config
]]
function p.extractCategory( context, options, value )
if ( not options.category or options.nocat ) then
return '';
end
local propertyId = string.gsub( options.category, '([^Pp0-9].*)$', '');
local wbStatus, claims = pcall( mw.wikibase.getAllStatements, value.id, propertyId );
if ( wbStatus ~= true or not claims ) then return ''; end
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 );
 
if ( wbStatus == true and catSiteLink ) then
return '[[' .. catSiteLink .. ']]';
end
end
end
 
return '';
end
--[[
Функция для оформления утверждений (statement)
МогӀа 1028 ⟶ 1231 :
]]
function getPropertyParams( propertyId, datatype, params )
local config = requiregetConfig( 'Module:Wikidata/config' );
if not config then
return {};
end
 
-- Различные уровни настройки параметров, по убыванию приоритета
МогӀа 1038 ⟶ 1238 :
-- 1. Параметры, указанные явно при вызове
if params then
localfor tplParamskey, =value mw.clonein pairs( params ); do
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[ key ] = value;
end
end
МогӀа 1047 ⟶ 1246 :
 
-- 2. Настройки конкретного параметра
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
localfor selfParamskey, =value mw.clonein pairs( config[ 'properties' ][ propertyId ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( selfParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
МогӀа 1057 ⟶ 1255 :
 
-- 3. Указанный пресет настроек
if propertyParams[ 'preset' ] and config[ 'presets' ] and
and config[ 'presets' ][ propertyParams[ 'preset'] ] ]
then
localfor presetParamskey, =value mw.clonein pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( presetParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
end
 
local datatype = datatype or params.datatype or propertyParams.datatype or getPropertyDatatype( propertyId );
if propertyParams.datatype == nil then
propertyParams.datatype = datatype;
end
 
-- 4. Настройки для типа данных
if datatype and config[ 'datatypes' ] and config[ 'datatypes' ][ datatype ] then
localfor datatypeParamskey, =value mw.clonein pairs( config[ 'datatypes' ][ datatype ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( datatypeParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
МогӀа 1078 ⟶ 1280 :
 
-- 5. Общие настройки для всех свойств
if config[ 'global' ] then
localfor globalParamskey, =value mw.clonein pairs( config[ 'global' ] ); do
if propertyParams[ key ] == nil then
for key, value in pairs( globalParams ) do
if propertyParams[ key ] == nil thenvalue;
propertyParams[key] = value;
end
end
МогӀа 1097 ⟶ 1298 :
throwError( 'property-param-not-provided' )
end
local override;
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '([^Pp0-9].*)$', function(w)
local datatype = getPropertyDatatype( propertyId );
if string.sub( w, 1, 1 ) == '~' then override = w; end
args = getPropertyParams( propertyId, datatype, args );
return '';
end ) )
args = getPropertyParams( propertyId, nil, args );
if (override) then
args[override:match('[,~]([^=]*)=')] = override:match('=(.*)')
args['property'] = propertyId
end
 
local datatype = args.datatype;
-- проброс всех параметров из шаблона {wikidata}
 
local p_frame = frame:getParent();
-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args= );frame
while p_frame do
if p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args, true );
end
if p_frame.args and p_frame.args.from and p_frame.args.from ~= '' then
args.entityId = p_frame.args.from;
end
p_frame = p_frame:getParent();
end
 
МогӀа 1134 ⟶ 1350 :
wrapperExtraArgs = wrapperExtraArgs .. ' data-wikidata-external-id="' .. mw.text.encode( value ).. '"';
value = formatExternalId( value, args );
elseif datatype == 'math' then
value = formatMath( value, args );
elseif datatype == 'url' then
local moduleUrl = require( 'Module:URL' );
if not args.length or args.length == '' then
args.length = 25
end
value = moduleUrl.formatUrlSingle( nil, args, value );
end
МогӀа 1148 ⟶ 1369 :
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. getCategoryByCode( 'value-contains-table' )
value = value .. '[[Категори:Википеди:Карточкин чохь таблицаш йолу агӀонаш]]'
else
value = wrapFormatProperty( value, 'class="no-wikidata"'
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
.. wrapperExtraArgs .. ' data-wikidata-property-id="'
if ( string.match( value, '\n' )
or string.match(. value,propertyId '<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
МогӀа 1169 ⟶ 1381 :
local pageTitle = mw.title.getCurrentTitle();
if pageTitle.namespace == 0 then
value = value .. categoryLocalValuePresentgetCategoryByCode( 'local-value-present' );
end
end
МогӀа 1177 ⟶ 1389 :
 
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
returnlocal frame:callParserFunction(callArgs '#property',= { propertyId )};
if args.entityId then
callArgs.from = args.entityId;
end
return frame:callParserFunction( '#property', callArgs );
end
 
МогӀа 1205 ⟶ 1421 :
end
 
local resultreferences = ''{};
if ( statement.references ) then
 
local allReferences = statement.references;
local hasPreferredhasNotDeprecated = false;
local displayCount = 0;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
МогӀа 1217 ⟶ 1434 :
and reference.snaks.P248[1].datavalue.value.id ) then
local entityId = reference.snaks.P248[1].datavalue.value.id;
if ( preferredSourcesnot deprecatedSources[entityId] ) then
hasPreferredhasNotDeprecated = true;
end
end
МогӀа 1225 ⟶ 1442 :
for _, reference in pairs( statement.references ) do
local display = true;
if ( hasPreferredhasNotDeprecated ) then
if ( reference.snaks
and reference.snaks.P248
МогӀа 1237 ⟶ 1454 :
end
end
if ( displaydisplayCount > 2 ) then
if ( options.entity and options.property ) then
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
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
table.insert( references, refText );
displayCount = displayCount + 1;
end
end
end
end
return resulttable.concat( references );
end