Модуль:Wikidata — Версийн башхалла
[теллина верси] | [теллина верси] |
Чулацам дӀабаьккхина Чулацам тӀетоьхна
Нисдарах лаьцна йаздина дац |
Нисдарах лаьцна йаздина дац |
||
МогӀа 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;
МогӀа 21 ⟶ 49 :
local contentLanguageCode = mw.getContentLanguage():getCode();
local p = {}
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
МогӀа 28 ⟶ 55 :
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
local function copyTo( obj, target
for k, v in pairs( obj ) do
target[k] = v
end
return target;
МогӀа 47 ⟶ 72 :
elseif ( prev < next ) then return next;
else return prev; end
end
МогӀа 183 ⟶ 179 :
if id then
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
end
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
return entity;
МогӀа 193 ⟶ 188 :
Внутрення функция для формирования сообщения об ошибке
Принимает: ключ элемента в таблице
Возвращает: строку сообщения
]]
local function throwError( key )
error(
end
МогӀа 228 ⟶ 223 :
end
-- динамическая загруза модуля с обработчиком указанным в параметре
local formatter = require
if formatter == nil then
throwError( prefix .. '-module-not-found' )
МогӀа 271 ⟶ 266 :
Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context,
local results = {};
МогӀа 280 ⟶ 273 :
end
if entity.claims then
for _, propertyId in ipairs( propertyIds ) do
local
if filteredClaims then
for _, claim in pairs( filteredClaims ) do
if not boundaries or not propertyIds or #propertyIds == 0 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
if #results > 0 then
break;
end
end
end
МогӀа 351 ⟶ 341 :
return nil;
end
--[[
МогӀа 366 ⟶ 348 :
Возвращает: текстовую метку элемента, язык метки
]]
function getLabelWithLang( context, options,
if not entity then
return nil;
end
local
local langCode = lang:getCode();
-- name from label
МогӀа 379 ⟶ 361 :
label = options.text;
else
label, langCode = entity:getLabelWithLang();
if not langCode then
return nil;
end
if not propertyIds then
propertyIds =
'P1813[language:' .. langCode .. ']',
'P1448[language:' .. langCode .. ']',
'P1705[language:' .. langCode .. ']'
};
end
-- name from properties
local results = getPropertyInBoundaries( context,
for _, result in pairs( results ) do
МогӀа 391 ⟶ 382 :
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
label = result.datavalue.value.text;
break;
elseif result.datavalue.type == 'string' then
МогӀа 397 ⟶ 388 :
break;
end
end
end
МогӀа 438 ⟶ 422 :
if ( options.i18n ) then
options.i18n = copyTo( options.i18n, copyTo(
else
options.i18n =
end
МогӀа 456 ⟶ 440 :
options.entity = entity;
newOptions.entity = entity;
return newOptions;
МогӀа 505 ⟶ 488 :
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 )
МогӀа 586 ⟶ 570 :
options.qualifiers = statement.qualifiers;
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
МогӀа 630 ⟶ 599 :
if snak.snaktype == 'somevalue' then
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
end
return before .. options.i18n['somevalue'] .. after;
elseif snak.snaktype == 'novalue' then
if ( options['novalue'] and options['novalue'] ~= '' ) then
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
end
return before .. formatDatavalue( context, options, snak.datavalue, snak.datatype ) .. after;
else
throwError( 'unknown-snak-type' );
end
end
МогӀа 680 ⟶ 641 :
-- нужно дописать в документации шаблона, что он отсюда вызывается, и что
-- любое изменние его парамеров должно быть согласовано с кодом тут
local eps = 0.0000001 -- < 1/360000
local globe = options.globe or '' -- TODO
local lat = {}
lat['abs'] = math.abs(value['latitude'])
lat['d'] = math.floor(lat['abs'] + 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
МогӀа 709 ⟶ 689 :
]]
function formatCommonsMedia( value, options )
local image = value
local caption = ''
if options[
caption = options[
elseif options[
caption = options[
end
if caption ~= '' then
caption = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>'
end
if not string.find( value, '[%[%]%{%}]' ) then
image = '[[File:' .. value
if options[
image = image .. '|border'
end
local size = options[
if size and size ~= '' then
if not string.match( size, 'px$' )
МогӀа 737 ⟶ 717 :
size = fileDefaultSize;
end
image = image .. '|' .. size
if options[
image = image .. '|' .. options[
end
image = image .. ']]'
if caption ~= '' then
image = image .. '<br>' .. caption
end
else
image = image .. caption
end
return image
end
МогӀа 776 ⟶ 741 :
]]
local function formatExternalId( value, options )
local formatter = options.formatter
if not formatter or formatter == '' then
local wbStatus,
if wbStatus == true and
local
for _, statement in pairs( statements ) do
if statement.mainsnak.snaktype == 'value' then
break
end
end
МогӀа 808 ⟶ 757 :
if formatter and formatter ~= '' then
local link =
local title = options.title
МогӀа 834 ⟶ 783 :
local langCode = lang:getCode();
local function formatNum( number
local mult = 10^
number = math.floor( number * mult + 0.5 ) / mult
return
end
МогӀа 846 ⟶ 795 :
local diff = tonumber( value.upperBound ) - tonumber( amount )
if diff > 0 then -- временная провека, пока у большинства значений не будет убрано ±0
out = out .. '
end
end
МогӀа 856 ⟶ 805 :
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 wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
local writingSystemElementId = 'Q8209';
local langElementId = 'Q7737';
local label = getLabelWithLang( context, options, unitEntity, nil, {
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
'P558[!P282][!P407]'
out = out .. ' ' .. label;
end
end
МогӀа 904 ⟶ 820 :
return out;
end
--[[
МогӀа 917 ⟶ 831 :
return nil;
end
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
МогӀа 925 ⟶ 836 :
return nil;
end
return propertyEntity.datatype;
end
МогӀа 970 ⟶ 850 :
-- Media
return function( context, options, value )
if ( not options.caption
and ( not options.
for i, qualifier in pairs( options.qualifiers.P2096 ) do
if ( qualifier
МогӀа 988 ⟶ 863 :
break
end
end
end
МогӀа 1006 ⟶ 871 :
return function( context, options, value )
return formatExternalId( value, options )
end
elseif datatype and datatype == 'url' then
МогӀа 1016 ⟶ 876 :
return function( context, options, value )
local moduleUrl = require( 'Module:URL' )
if not options.length or options.length == '' then
options.length =
end
return moduleUrl.formatUrlSingle( context, options, value )
end
end
МогӀа 1028 ⟶ 887 :
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
МогӀа 1073 ⟶ 929 :
return functionToCall( context, options, datavalue.value );
end
--[[
МогӀа 1084 ⟶ 938 :
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
local label, labelLanguageCode = getLabelWithLang( context, options, entity, boundaries )
-- определение соответствующей показываемому элементу категории
local category =
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
-- получение ссылки по идентификатору
МогӀа 1103 ⟶ 975 :
link = ':' .. link
end
if label
if ( contentLanguageCode ~= labelLanguageCode ) then
return
else
return
end
else
МогӀа 1120 ⟶ 991 :
local title = mw.title.new( label );
if title and not title.exists and options.frame then
return '[[' .. label .. ']]<sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
end
МогӀа 1142 ⟶ 1009 :
-- сообщение об отсутвии локализованного названия
-- not good, but better than nothing
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' ..
end
--[[
Функция для оформления утверждений (statement)
МогӀа 1191 ⟶ 1028 :
]]
function getPropertyParams( propertyId, datatype, params )
local config =
if not config then
return {};
end
-- Различные уровни настройки параметров, по убыванию приоритета
МогӀа 1198 ⟶ 1038 :
-- 1. Параметры, указанные явно при вызове
if params then
for key, value in pairs( tplParams ) do
if value ~= '' then
propertyParams[
end
end
МогӀа 1206 ⟶ 1047 :
-- 2. Настройки конкретного параметра
if config[
for key, value in pairs( selfParams ) do
propertyParams[key] = value;
end
end
МогӀа 1215 ⟶ 1057 :
-- 3. Указанный пресет настроек
if propertyParams[
and config[
local presetParams = mw.clone( config['presets'][propertyParams['preset']] );
for key, value in pairs(
if propertyParams[
propertyParams[
end
end
end
-- 4. Настройки для типа данных
if datatype and config[
for key, value in pairs( datatypeParams ) do
propertyParams[key] = value;
end
end
МогӀа 1240 ⟶ 1078 :
-- 5. Общие настройки для всех свойств
if config[
for key, value in pairs( globalParams ) do
propertyParams[key] = value;
end
end
МогӀа 1259 ⟶ 1098 :
end
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
args = getPropertyParams( propertyId, datatype, args );
-- проброс всех параметров из шаблона {wikidata}
local p_frame = frame:getParent();
if p_frame and p_frame:getTitle() == mw.site.namespaces[10].name .. ':Wikidata' then
copyTo( p_frame.args, args );
end
МогӀа 1301 ⟶ 1134 :
wrapperExtraArgs = wrapperExtraArgs .. ' data-wikidata-external-id="' .. mw.text.encode( value ).. '"';
value = formatExternalId( value, args );
elseif datatype == 'url' then
local moduleUrl = require( 'Module:URL' );
value = moduleUrl.formatUrlSingle( nil, args, value );
end
МогӀа 1320 ⟶ 1148 :
and not string.match( value, '<table >]' )
and not string.match( value, '^%{%|' ) ) then
value = value .. '[[Категори:Википеди:Карточкин чохь таблицаш йолу агӀонаш]]'
else
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
МогӀа 1341 ⟶ 1169 :
local pageTitle = mw.title.getCurrentTitle();
if pageTitle.namespace == 0 then
value = value ..
end
end
МогӀа 1349 ⟶ 1177 :
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
end
МогӀа 1381 ⟶ 1205 :
end
local
if ( statement.references ) then
local allReferences = statement.references;
local hasPreferred = false;
for _, reference in pairs( statement.references ) do
if ( reference.snaks
МогӀа 1414 ⟶ 1237 :
end
end
if ( display
result = result .. moduleSources.renderReference( g_frame, options.entity, reference );
end
end
end
return
end
|