Модуль:Wikidata — различия между версиями

Материал из Wikipedia PC-SUPP
Перейти к: навигация, поиск
 
Строка 1: Строка 1:
-- vim: set noexpandtab ft=lua ts=4 sw=4:
+
-- settings, may differ from project to project
require('Module:No globals')
+
local fileDefaultSize = '267x400px';
 +
local outputReferences = true;
  
local p = {}
+
-- sources that shall be omitted if any preffered sources exists
local debug = false
+
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 WDS = require( 'Module:WikidataSelectors' );
  
------------------------------------------------------------------------------
+
-- Константы
-- module local variables and functions
+
local contentLanguageCode = mw.getContentLanguage():getCode();
  
local wiki =
+
local p = {};
{
+
local config = nil;
langcode = mw.language.getContentLanguage().code
 
}
 
  
-- internationalisation
+
local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
local i18n =
+
formatStatementDefault, formatProperty, getSourcingCircumstances,
{
+
getPropertyDatatype, getPropertyParams, throwError, toBoolean;
["errors"] =
 
{
 
["property-not-found"] = "Property not found.",
 
["entity-not-found"] = "Wikidata entity not found.",
 
["unknown-claim-type"] = "Unknown claim type.",
 
["unknown-entity-type"] = "Unknown entity type.",
 
["qualifier-not-found"] = "Qualifier not found.",
 
["site-not-found"] = "Wikimedia project not found.",
 
["unknown-datetime-format"] = "Unknown datetime format.",
 
["local-article-not-found"] = "Article is not yet available in this wiki."
 
},
 
["datetime"] =
 
{
 
-- $1 is a placeholder for the actual number
 
[0] = "$1 billion years", -- precision: billion years
 
[1] = "$100 million years", -- precision: hundred million years
 
[2] = "$10 million years", -- precision: ten million years
 
[3] = "$1 million years", -- precision: million years
 
[4] = "$100,000 years", -- precision: hundred thousand years
 
[5] = "$10,000 years", -- precision: ten thousand years
 
[6] = "$1 millennium", -- precision: millennium
 
[7] = "$1 century", -- precision: century
 
[8] = "$1s", -- precision: decade
 
-- the following use the format of #time parser function
 
[9]  = "Y", -- precision: year,
 
[10] = "F Y", -- precision: month
 
[11] = "F j, Y", -- precision: day
 
[12] = "F j, Y ga", -- precision: hour
 
[13] = "F j, Y g:ia", -- precision: minute
 
[14] = "F j, Y g:i:sa", -- precision: second
 
["beforenow"] = "$1 BCE", -- how to format negative numbers for precisions 0 to 5
 
["afternow"] = "$1 CE", -- how to format positive numbers for precisions 0 to 5
 
["bc"] = '$1 "BCE"', -- how print negative years
 
["ad"] = "$1", -- how print positive years
 
-- the following are for function getDateValue() and getQualifierDateValue()
 
["default-format"] = "dmy", -- default value of the #3 (getDateValue) or
 
-- #4 (getQualifierDateValue) argument
 
["default-addon"] = "BC", -- default value of the #4 (getDateValue) or
 
-- #5 (getQualifierDateValue) argument
 
["prefix-addon"] = false, -- set to true for languages put "BC" in front of the
 
-- datetime string; or the addon will be suffixed
 
["addon-sep"] = " ", -- separator between datetime string and addon (or inverse)
 
["format"] = -- options of the 3rd argument
 
{
 
["mdy"] = "F j, Y",
 
["my"] = "F Y",
 
["y"] = "Y",
 
["dmy"] = "j F Y",
 
["ymd"] = "Y-m-d",
 
["ym"] = "Y-m"
 
}
 
},
 
["monolingualtext"] = '<span lang="%language">%text</span>',
 
["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
 
["ordinal"] =
 
{
 
[1] = "st",
 
[2] = "nd",
 
[3] = "rd",
 
["default"] = "th"
 
}
 
}
 
  
-- Credit to http://stackoverflow.com/a/1283608/2644759
+
local function copyTo( obj, target, skipEmpty )
-- cc-by-sa 3.0
+
for k, v in pairs( obj ) do
local function tableMerge(t1, t2)
+
if skipEmpty ~= true or ( v ~= nil and v ~= '' ) then
for k,v in pairs(t2) do
+
target[k] = v;
if type(v) == "table" then
 
if type(t1[k] or false) == "table" then
 
tableMerge(t1[k] or {}, t2[k] or {})
 
else
 
t1[k] = v
 
end
 
else
 
t1[k] = v
 
 
end
 
end
 
end
 
end
return t1
+
return target;
 +
end
 +
 
 +
local function min( prev, next )
 +
if ( prev == nil ) then return next;
 +
elseif ( prev > next ) then return next;
 +
else return prev; end
 
end
 
end
  
local function loadI18n()
+
local function max( prev, next )
local exist, res = pcall(require, "Module:Wikidata/i18n")
+
if ( prev == nil ) then return next;
if exist and next(res) ~= nil then
+
elseif ( prev < next ) then return next;
tableMerge(i18n, res.i18n)
+
else return prev; end
end
 
 
end
 
end
  
loadI18n()
+
local function getConfig( section, code )
 +
if config == nil then
 +
config = require( 'Module:Wikidata/config' );
 +
end;
 +
if not config then
 +
config = {};
 +
end
  
-- this function needs to be internationalised along with the above:
+
if not section then
-- takes cardinal numer as a numeric and returns the ordinal as a string
+
return config;
-- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc.
 
local function makeOrdinal (cardinal)
 
local ordsuffix = i18n.ordinal.default
 
if cardinal % 10 == 1 then
 
ordsuffix = i18n.ordinal[1]
 
elseif cardinal % 10 == 2 then
 
ordsuffix = i18n.ordinal[2]
 
elseif cardinal % 10 == 3 then
 
ordsuffix = i18n.ordinal[3]
 
 
end
 
end
-- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th'
+
if not code then
-- similarly for 12 and 13, etc.
+
return config[ section ] or {};
if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then
+
end
ordsuffix = i18n.ordinal.default
+
 
 +
if not config[ section ] then
 +
return nil;
 
end
 
end
return tostring(cardinal) .. ordsuffix
+
return config[ section ][ code ];
 
end
 
end
  
local function printError(code)
+
local function getCategoryByCode( code )
return '<span class="error">' .. (i18n.errors[code] or code) .. '</span>'
+
local value = getConfig( 'categories', code );
 +
if not value or value == '' then
 +
return '';
 +
end
 +
return '[[Category:' .. value .. ']]';
 
end
 
end
  
local function parseDateValue(timestamp, date_format, date_addon)
+
local function splitISO8601(str)
local prefix_addon = i18n["datetime"]["prefix-addon"]
+
if 'table' == type(str) then
local addon_sep = i18n["datetime"]["addon-sep"]
+
if str.args and str.args[1] then
local addon = ""
+
str = '' .. str.args[1]
 
 
-- check for negative date
 
if string.sub(timestamp, 1, 1) == '-' then
 
timestamp = '+' .. string.sub(timestamp, 2)
 
addon = date_addon
 
end
 
local function d(f)
 
local year_suffix
 
local tstr = ""
 
local lang_obj = mw.language.new(wiki.langcode)
 
local f_parts = mw.text.split(f, 'Y', true)
 
for idx, f_part in pairs(f_parts) do
 
year_suffix = ''
 
if string.match(f_part, "x[mijkot]$") then
 
-- for non-Gregorian year
 
f_part = f_part .. 'Y'
 
elseif idx < #f_parts then
 
-- supress leading zeros in year
 
year_suffix = lang_obj:formatDate('Y', timestamp)
 
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
 
end
 
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
 
end
 
if addon ~= "" and prefix_addon then
 
return addon .. addon_sep .. tstr
 
elseif addon ~= "" then
 
return tstr .. addon_sep .. addon
 
 
else
 
else
return tstr
+
return 'unknown argument type: ' .. type( str ) .. ': ' .. table.tostring( str )
 
end
 
end
 
end
 
end
local _date_format = i18n["datetime"]["format"][date_format]
+
local Y, M, D = (function(str)
if _date_format ~= nil then
+
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
return d(_date_format)
+
local Y, M, D = mw.ustring.match( str, pattern )
else
+
return tonumber(Y), tonumber(M), tonumber(D)
return printError("unknown-datetime-format")
+
end) (str);
end
+
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
 
end
  
-- This local function combines the year/month/day/BC/BCE handling of parseDateValue{}
+
local function parseTimeBoundaries( time, precision )
-- with the millennium/century/decade handling of formatDate()
+
local s = splitISO8601( time );
local function parseDateFull(timestamp, precision, date_format, date_addon)
+
if (not s) then return nil; end
local prefix_addon = i18n["datetime"]["prefix-addon"]
 
local addon_sep = i18n["datetime"]["addon-sep"]
 
local addon = ""
 
  
-- check for negative date
+
if ( precision >= 0 and precision <= 8 ) then
if string.sub(timestamp, 1, 1) == '-' then
+
local powers = { 1000000000 , 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10 }
timestamp = '+' .. string.sub(timestamp, 2)
+
local power = powers[ precision + 1 ];
addon = date_addon
+
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
 
end
  
-- get the next four characters after the + (should be the year now in all cases)
+
if ( precision == 9 ) then
-- ok, so this is dirty, but let's get it working first
+
return { tonumber(os.time( {year=s.year, month=1, day=1, hour=0, min=0, sec=0} )) * 1000,
local intyear = tonumber(string.sub(timestamp, 2, 5))
+
tonumber(os.time( {year=s.year, month=12, day=31, hour=23, min=59, sec=58} )) * 1000 + 1999 };
if intyear == 0 and precision <= 9 then
 
return ""
 
 
end
 
end
  
-- precision is 10000 years or more
+
if ( precision == 10 ) then
if precision <= 5 then
+
local lastDays = {31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
local factor = 10 ^ ((5 - precision) + 4)
+
local lastDay = lastDays[s.month];
local y2 = math.ceil(math.abs(intyear) / factor)
+
return { tonumber(os.time( {year=s.year, month=s.month, day=1, hour=0, min=0, sec=0} )) * 1000,
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
+
tonumber(os.time( {year=s.year, month=s.month, day=lastDay, hour=23, min=59, sec=58} )) * 1000 + 1999 };
if addon ~= "" then
+
end
-- negative date
+
 
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
+
if ( precision == 11 ) then
else
+
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=0, min=0, sec=0} )) * 1000,
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
+
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=23, min=59, sec=58} )) * 1000 + 1999 };
end
 
return relative
 
 
end
 
end
  
-- precision is decades (8), centuries (7) and millennia (6)
+
if ( precision == 12 ) then
local era, card
+
return { tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=0, sec=0} )) * 1000,
if precision == 6 then
+
tonumber(os.time( {year=s.year, month=s.month, day=s.day, hour=s.hour, min=59, sec=58} )) * 1000 + 19991999 };
card = math.floor((intyear - 1) / 1000) + 1
 
era = mw.ustring.gsub(i18n.datetime[6], "$1", makeOrdinal(card))
 
 
end
 
end
if precision == 7 then
+
 
card = math.floor((intyear - 1) / 100) + 1
+
if ( precision == 13 ) then
era = mw.ustring.gsub(i18n.datetime[7], "$1", makeOrdinal(card))
+
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
 
end
if precision == 8 then
+
 
era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(intyear) / 10) * 10))
+
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
 
end
if era then
+
 
if addon ~= "" then
+
error('Unsupported precision: ' .. precision );
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
+
end
else
+
 
era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era)
+
--[[
 +
Преобразует строку в булевое значение
 +
 
 +
Принимает: строковое значение (может отсутствовать)
 +
Возвращает: булевое значение 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
 
end
return era
+
return true
 
end
 
end
 +
return defaultValue;
 +
end
 +
 +
--[[
 +
Функция для получения сущности (еntity) для текущей страницы
 +
Подробнее о сущностях см. d:Wikidata:Glossary/ru
 +
 +
Принимает: строковый индентификатор (типа P18, Q42)
 +
Возвращает: объект таблицу, элементы которой индексируются с нуля
 +
]]
 +
local function getEntityFromId( id )
 +
local entity;
 +
local wbStatus;
  
local _date_format = i18n["datetime"]["format"][date_format]
+
if id then
if _date_format ~= nil then
+
wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
-- check for precision is year and override supplied date_format
+
else
if precision == 9 then
+
wbStatus, entity = pcall( mw.wikibase.getEntityObject );
_date_format = i18n["datetime"][9]
+
end
 +
 
 +
return entity;
 +
end
 +
 
 +
--[[
 +
Внутрення функция для формирования сообщения об ошибке
 +
 
 +
Принимает: ключ элемента в таблице config.errors (например entity-not-found)
 +
Возвращает: строку сообщения
 +
]]
 +
local function throwError( key )
 +
error( getConfig( '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
 
end
local year_suffix
+
-- динамическая загруза модуля с обработчиком указанным в параметре
local tstr = ""
+
local formatter = require( 'Module:' .. options[ prefix .. '-module' ] );
local lang_obj = mw.language.new(wiki.langcode)
+
if formatter == nil then
local f_parts = mw.text.split(_date_format, 'Y', true)
+
throwError( prefix .. '-module-not-found' )
for idx, f_part in pairs(f_parts) do
 
year_suffix = ''
 
if string.match(f_part, "x[mijkot]$") then
 
-- for non-Gregorian year
 
f_part = f_part .. 'Y'
 
elseif idx < #f_parts then
 
-- supress leading zeros in year
 
year_suffix = lang_obj:formatDate('Y', timestamp)
 
year_suffix = string.gsub(year_suffix, '^0+', '', 1)
 
end
 
tstr = tstr .. lang_obj:formatDate(f_part, timestamp) .. year_suffix
 
 
end
 
end
local fdate
+
local fun = formatter[ options[ prefix .. '-function' ] ]
if addon ~= "" and prefix_addon then
+
if fun == nil then
fdate = addon .. addon_sep .. tstr
+
throwError( prefix .. '-function-not-found' )
elseif addon ~= "" then
 
fdate = tstr .. addon_sep .. addon
 
else
 
fdate = tstr
 
 
end
 
end
 +
return fun;
 +
end
  
return fdate
+
return defaultFunction;
else
 
return printError("unknown-datetime-format")
 
end
 
 
end
 
end
  
-- the "qualifiers" and "snaks" field have a respective "qualifiers-order" and "snaks-order" field
+
-- Выбирает свойства по property id, дополнительно фильтруя их по рангу
-- use these as the second parameter and this function instead of the built-in "pairs" function
+
local function selectClaims( context, options, propertySelector )
-- to iterate over all qualifiers and snaks in the intended order.
+
if ( not context ) then error( 'context not specified' ); end;
local function orderedpairs(array, order)
+
if ( not options ) then error( 'options not specified' ); end;
if not order then return pairs(array) end
+
if ( not options.entity ) then error( 'options.entity is missing' ); end;
 +
if ( not propertySelector ) then error( 'propertySelector not specified' ); end;
  
-- return iterator function
+
result = WDS.filter( options.entity.claims, propertySelector );
local i = 0
+
 
return function()
+
if ( not result or #result == 0 ) then
i = i + 1
+
return nil;
if order[i] then
+
end
return order[i], array[order[i]]
+
 
 +
if options.limit and options.limit ~= '' and options.limit ~= '-'  then
 +
local limit = tonumber( options.limit, 10 );
 +
while #result > limit do
 +
table.remove( result );
 
end
 
end
 
end
 
end
 +
 +
return result;
 
end
 
end
  
-- precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
+
--[[
local function normalizeDate(date)
+
Функция для получения значения свойства элемента в заданный момент времени.
date = mw.text.trim(date, "+")
+
 
-- extract year
+
Принимает: контекст, элемент, временные границы, таблица ID свойства
local yearstr = mw.ustring.match(date, "^\-?%d+")
+
Возвращает: таблицу соответствующих значений свойства
local year = tonumber(yearstr)
+
]]
-- remove leading zeros of year
+
local function getPropertyInBoundaries( context, entity, boundaries, propertyIds )
return year .. mw.ustring.sub(date, #yearstr + 1), year
+
local results = {};
end
+
 
 +
if not propertyIds or #propertyIds == 0 then
 +
return results;
 +
end
  
local function formatDate(date, precision, timezone)
+
if entity.claims then
precision = precision or 11
+
for _, propertyId in ipairs( propertyIds ) do
local date, year = normalizeDate(date)
+
local filteredClaims = WDS.filter( entity.claims, propertyId .. '[rank:preferred, rank:normal]' );
if year == 0 and precision <= 9 then return "" end
+
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' );
  
-- precision is 10000 years or more
+
if ( (startBoundaries == nil or ( startBoundaries[2] <= boundaries[1]))
if precision <= 5 then
+
and (endBoundaries == nil or ( endBoundaries[1] >= boundaries[2]))) then
local factor = 10 ^ ((5 - precision) + 4)
+
table.insert( results, claim.mainsnak );
local y2 = math.ceil(math.abs(year) / factor)
+
end
local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
+
end
if year < 0 then
+
end
relative = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
+
end
else
+
 
relative = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
+
if #results > 0 then
 +
break;
 +
end
 
end
 
end
return relative
 
 
end
 
end
  
-- precision is decades, centuries and millennia
+
return results;
local era
+
end
if precision == 6 then era = mw.ustring.gsub(i18n.datetime[6], "$1", tostring(math.floor((math.abs(year) - 1) / 1000) + 1)) end
+
 
if precision == 7 then era = mw.ustring.gsub(i18n.datetime[7], "$1", tostring(math.floor((math.abs(year) - 1) / 100) + 1)) end
+
--[[
if precision == 8 then era = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(year) / 10) * 10)) end
+
TODO
if era then
+
]]
if year < 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.bc, '"', ""), "$1", era)
+
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
elseif year > 0 then era = mw.ustring.gsub(mw.ustring.gsub(i18n.datetime.ad, '"', ""), "$1", era) end
+
-- only support exact date so far, but need improvment
return era
+
local left = nil;
 +
local right = nil;
 +
if ( statement.qualifiers and statement.qualifiers[qualifierId] ) then
 +
for _, qualifier in pairs( statement.qualifiers[qualifierId] ) do
 +
local boundaries = context.parseTimeBoundariesFromSnak( qualifier );
 +
if ( not boundaries ) then return nil; end
 +
left = min( left, boundaries[1] );
 +
right = max( right, boundaries[2] );
 +
end
 
end
 
end
  
-- precision is year
+
if ( not left or not right ) then
if precision == 9 then
+
return nil;
return year
 
 
end
 
end
  
-- precision is less than years
+
return { left, right };
if precision > 9 then
+
end
--[[ the following code replaces the UTC suffix with the given negated timezone to convert the global time to the given local time
+
 
timezone = tonumber(timezone)
+
--[[
if timezone and timezone ~= 0 then
+
TODO
timezone = -timezone
+
]]
timezone = string.format("%.2d%.2d", timezone / 60, timezone % 60)
+
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
if timezone[1] ~= '-' then timezone = "+" .. timezone end
+
if not qualifierIds then
date = mw.text.trim(date, "Z") .. " " .. timezone
+
qualifierIds = { 'P582', 'P580', 'P585' };
end
+
end
]]--
 
  
local formatstr = i18n.datetime[precision]
+
for _, qualifierId in ipairs( qualifierIds ) do
if year == 0 then formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], "")
+
local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId );
elseif year < 0 then
+
if result then
-- Mediawiki formatDate doesn't support negative years
+
return result;
date = mw.ustring.sub(date, 2)
 
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.bc, "$1", i18n.datetime[9]))
 
elseif year > 0 and i18n.datetime.ad ~= "$1" then
 
formatstr = mw.ustring.gsub(formatstr, i18n.datetime[9], mw.ustring.gsub(i18n.datetime.ad, "$1", i18n.datetime[9]))
 
 
end
 
end
return mw.language.new(wiki.langcode):formatDate(formatstr, date)
 
 
end
 
end
 +
 +
return nil;
 
end
 
end
  
local function printDatavalueEntity(data, parameter)
+
--[[
-- data fields: entity-type [string], numeric-id [int, Wikidata id]
+
Функция для получения метки элемента в заданный момент времени.
local id
 
  
if data["entity-type"] == "item" then id = "Q" .. data["numeric-id"]
+
Принимает: контекст, элемент, временные границы
elseif data["entity-type"] == "property" then id = "P" .. data["numeric-id"]
+
Возвращает: текстовую метку элемента, язык метки
else return printError("unknown-entity-type")
+
]]
 +
function getLabelWithLang( context, options, entity, boundaries, propertyIds )
 +
if not entity then
 +
return nil;
 
end
 
end
  
if parameter then
+
local lang = mw.language.getContentLanguage();
if parameter == "link" then
+
local langCode = lang:getCode();
local linkTarget = mw.wikibase.sitelink(id)
+
 
local linkName = mw.wikibase.label(id)
+
-- name from label
if linkTarget then
+
local label = nil;
-- if there is a local Wikipedia article link to it using the label or the article title
+
if ( options.text and options.text ~= '' ) then
return "[[" .. linkTarget .. "|" .. (linkName or linkTarget) .. "]]"
+
label = options.text;
else
+
else
-- if there is no local Wikipedia article output the label or link to the Wikidata object to let the user input a proper label
+
label, langCode = entity:getLabelWithLang();
if linkName then return linkName else return "[[:d:" .. id .. "|" .. id .. "]]" end
+
 
 +
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, entity, boundaries, propertyIds );
 +
 
 +
for _, result in pairs( results ) do
 +
if result.datavalue and result.datavalue.value then
 +
if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
 +
label = result.datavalue.value.text;
 +
lang = result.datavalue.value.language;
 +
break;
 +
elseif result.datavalue.type == 'string' then
 +
label = result.datavalue.value;
 +
break;
 +
end
 
end
 
end
else
 
return data[parameter]
 
 
end
 
end
else
 
return mw.wikibase.label(id) or id
 
 
end
 
end
 +
 +
return label, langCode;
 
end
 
end
  
local function printDatavalueTime(data, parameter)
+
--[[
-- data fields: time [ISO 8601 time], timezone [int in minutes], before [int], after [int], precision [int], calendarmodel [wikidata URI]
+
Функция для оформления утверждений (statement)
--   precision: 0 - billion years, 1 - hundred million years, ..., 6 - millennia, 7 - century, 8 - decade, 9 - year, 10 - month, 11 - day, 12 - hour, 13 - minute, 14 - second
+
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
--   calendarmodel: e.g. http://www.wikidata.org/entity/Q1985727 for the proleptic Gregorian calendar or http://www.wikidata.org/wiki/Q11184 for the Julian calendar]
+
 
if parameter then
+
Принимает: таблицу параметров
if parameter == "calendarmodel" then data.calendarmodel = mw.ustring.match(data.calendarmodel, "Q%d+") -- extract entity id from the calendar model URI
+
Возвращает: строку оформленного текста, предназначенного для отображения в статье
elseif parameter == "time" then data.time = normalizeDate(data.time) end
+
]]
return data[parameter]
+
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
 +
 
 +
-- 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( getConfig( 'i18n' ), {} ) );
 
else
 
else
return formatDate(data.time, data.precision, data.timezone)
+
options.i18n = getConfig( 'i18n' );
 
end
 
end
 +
 +
-- create context
 +
local context = {
 +
entity = options.entity,
 +
formatSnak = formatSnak,
 +
formatPropertyDefault = formatPropertyDefault,
 +
formatStatementDefault = formatStatementDefault }
 +
context.cloneOptions = function( options )
 +
local entity = options.entity;
 +
options.entity = nil;
 +
 +
newOptions = mw.clone( options );
 +
options.entity = entity;
 +
newOptions.entity = entity;
 +
newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()
 +
 +
return newOptions;
 +
end;
 +
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
 
end
  
local function printDatavalueMonolingualText(data, parameter)
+
function formatPropertyDefault( context, options )
-- data fields: language [string], text [string]
+
if ( not context ) then error( 'context not specified' ); end;
if parameter then
+
if ( not options ) then error( 'options not specified' ); end;
return data[parameter]
+
if ( not options.entity ) then error( 'options.entity missing' ); end;
else
+
 
local result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
+
local claims;
return result
+
if options.property then -- TODO: Почему тут может не быть property?
 +
claims = context.selectClaims( options, options.property );
 +
end
 +
if claims == nil then
 +
return '' --TODO error?
 
end
 
end
end
 
  
local function findClaims(entity, property)
+
-- Обход всех заявлений утверждения и с накоплением оформленых предпочтительных
if not property or not entity or not entity.claims then return end
+
-- заявлений в таблице
return entity:getAllStatements(property)
+
local formattedClaims = {}
end
 
  
local function getSnakValue(snak, parameter)
+
for i, claim in ipairs(claims) do
if snak.snaktype == "value" then
+
local formattedStatement = context.formatStatement( options, claim )
-- call the respective snak parser
+
-- здесь может вернуться либо оформленный текст заявления, либо строка ошибки, либо nil
if snak.datavalue.type == "string" then return snak.datavalue.value
+
if ( formattedStatement and formattedStatement ~= '' ) then
elseif snak.datavalue.type == "globecoordinate" then return printDatavalueCoordinate(snak.datavalue.value, parameter)
+
formattedStatement = '<span class="wikidata-claim" data-wikidata-property-id="' .. string.upper( options.property ) .. '" data-wikidata-claim-id="' .. claim.id .. '">' .. formattedStatement .. '</span>'
elseif snak.datavalue.type == "quantity" then return printDatavalueQuantity(snak.datavalue.value, parameter)
+
table.insert( formattedClaims, formattedStatement )
elseif snak.datavalue.type == "time" then return printDatavalueTime(snak.datavalue.value, parameter)
 
elseif snak.datavalue.type == "wikibase-entityid" then return printDatavalueEntity(snak.datavalue.value, parameter)
 
elseif snak.datavalue.type == "monolingualtext" then return printDatavalueMonolingualText(snak.datavalue.value, parameter)
 
 
end
 
end
 
end
 
end
return mw.wikibase.renderSnak(snak)
 
end
 
  
local function getQualifierSnak(claim, qualifierId)
+
-- создание текстовой строки со списком оформленых заявлений из таблицы
-- a "snak" is Wikidata terminology for a typed key/value pair
+
local out = mw.text.listToText( formattedClaims, options.separator, options.conjunction )
-- a claim consists of a main snak holding the main information of this claim,
+
if out ~= '' then
-- as well as a list of attribute snaks and a list of references snaks
+
if options.before then
if qualifierId then
+
out = options.before .. out
-- search the attribute snak with the given qualifier as key
+
end
if claim.qualifiers then
+
if options.after then
local qualifier = claim.qualifiers[qualifierId]
+
out = out .. options.after
if qualifier then return qualifier[1] end
 
 
end
 
end
return nil, printError("qualifier-not-found")
 
else
 
-- otherwise return the main snak
 
return claim.mainsnak
 
 
end
 
end
 +
 +
return out
 
end
 
end
  
local function getValueOfClaim(claim, qualifierId, parameter)
+
--[[
local error
+
Функция для оформления одного утверждения (statement)
local snak
+
 
snak, error = getQualifierSnak(claim, qualifierId)
+
Принимает: объект-таблицу утверждение и таблицу параметров
if snak then
+
Возвращает: строку оформленного текста с заявлением (claim)
return getSnakValue(snak, parameter)
+
]]
else
+
function formatStatement( context, options, statement )
return nil, error
+
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
 
end
 +
 +
local functionToCall = getUserFunction( options, 'claim', context.formatStatementDefault );
 +
return functionToCall( context, options, statement );
 
end
 
end
  
local function getReferences(frame, claim)
+
function getSourcingCircumstances( statement )
local result = ""
+
if (not statement) then error('statement is not specified') end;
-- traverse through all references
+
 
for ref in pairs(claim.references or {}) do
+
local circumstances = {};
local refparts
+
if ( statement.qualifiers
-- traverse through all parts of the current reference
+
and statement.qualifiers.P1480 ) then
for snakkey, snakval in orderedpairs(claim.references[ref].snaks or {}, claim.references[ref]["snaks-order"]) do
+
for i, qualifier in pairs( statement.qualifiers.P1480 ) do
if refparts then refparts = refparts .. ", " else refparts = "" end
+
if ( qualifier
-- output the label of the property of the reference part, e.g. "imported from" for P143
+
and qualifier.datavalue
refparts = refparts .. tostring(mw.wikibase.label(snakkey)) .. ": "
+
and qualifier.datavalue.type == 'wikibase-entityid'
-- output all values of this reference part, e.g. "German Wikipedia" and "English Wikipedia" if the referenced claim was imported from both sites
+
and qualifier.datavalue.value
for snakidx = 1, #snakval do
+
and qualifier.datavalue.value['entity-type'] == 'item' ) then
if snakidx > 1 then refparts = refparts .. ", " end
+
local circumstance = qualifier.datavalue.value.id;
refparts = refparts .. getSnakValue(snakval[snakidx])
+
if ( 'Q5727902' == circumstance ) then
 +
circumstances.circa = true;
 +
end
 +
if ( 'Q18122778' == circumstance ) then
 +
circumstances.presumably = true;
 +
end
 
end
 
end
 
end
 
end
if refparts then result = result .. frame:extensionTag("ref", refparts) end
 
 
end
 
end
return result
+
return circumstances;
 
end
 
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 );
  
------------------------------------------------------------------------------
+
options.qualifiers = statement.qualifiers;
-- module global functions
 
  
if debug then
+
local result = context.formatSnak( options, statement.mainsnak, circumstances );
function p.inspectI18n(frame)
+
if ( result and result ~= '' and options.references ) then
local val = i18n
+
result = result .. context.formatRefs( options, statement );
for _, key in pairs(frame.args) do
 
key = mw.text.trim(key)
 
val = val[key]
 
end
 
return val
 
 
end
 
end
 +
 +
return result;
 
end
 
end
  
function p.descriptionIn(frame)
+
--[[
local langcode = frame.args[1]
+
Функция для оформления части утверждения (snak)
local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
+
Подробнее о snak см. d:Викиданные:Глоссарий
-- return description of a Wikidata entity in the given language or the default language of this Wikipedia site
+
 
return mw.wikibase.getEntityObject(id).descriptions[langcode or wiki.langcode].value
+
Принимает: таблицу snak объекта (main snak или же snak от квалификатора) и таблицу опций
end
+
Возвращает: строку оформленного викитекста
 +
]]
 +
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
  
function p.labelIn(frame)
+
local before = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
local langcode = frame.args[1]
+
local after = '</span>'
local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
 
-- return label of a Wikidata entity in the given language or the default language of this Wikipedia site
 
return mw.wikibase.getEntityObject(id).labels[langcode or wiki.langcode].value
 
end
 
  
-- This is used to get a value, or a comma separated list of them if multiple values exist
+
if snak.snaktype == 'somevalue' then
p.getValue = function(frame)
+
if ( options['somevalue'] and options['somevalue'] ~= '' ) then
local propertyID = mw.text.trim(frame.args[1] or "")
+
result = options['somevalue'];
local input_parm = mw.text.trim(frame.args[2] or "")
+
else
if input_parm == "FETCH_WIKIDATA" then
+
result = options.i18n['somevalue'];
local entity = mw.wikibase.getEntityObject()
+
end
local claims
+
elseif snak.snaktype == 'novalue' then
if entity and entity.claims then
+
if ( options['novalue'] and options['novalue'] ~= '' ) then
claims = entity.claims[propertyID]
+
result = options['novalue'];
 +
else
 +
result = options.i18n['novalue'];
 
end
 
end
if claims then
+
elseif snak.snaktype == 'value' then
-- if wiki-linked value output as link if possible
+
result = formatDatavalue( context, options, snak.datavalue, snak.datatype );
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
 
local out = {}
 
for k, v in pairs(claims) do
 
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
 
local label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"])
 
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
  
if sitelink then
+
if ( circumstances.presumably ) then
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
+
result = options.i18n.presumably .. result;
else
+
end
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
+
if ( circumstances.circa ) then
end
+
result = options.i18n.circa .. result;
end
 
return table.concat(out, ", ")
 
else
 
-- just return best values
 
return entity:formatPropertyValues(propertyID).value
 
end
 
else
 
return ""
 
 
end
 
end
 
else
 
else
return input_parm
+
throwError( 'unknown-snak-type' );
 
end
 
end
 +
 +
if ( not result or result == '' ) then
 +
return nil;
 +
end
 +
 +
return before .. result .. after;
 
end
 
end
  
-- Same as above, but uses the short name property for label if available.
+
--[[
p.getValueShortName = function(frame)
+
Функция для оформления объектов-значений с географическими координатами
local propertyID = mw.text.trim(frame.args[1] or "")
+
 
local input_parm = mw.text.trim(frame.args[2] or "")
+
Принимает: объект-значение и таблицу параметров,
if input_parm == "FETCH_WIKIDATA" then
+
Возвращает: строку оформленного текста
local entity = mw.wikibase.getEntityObject()
+
]]
local claims
+
function formatGlobeCoordinate( value, options )
if entity and entity.claims then
+
-- проверка на требование в параметрах вызова на возврат сырого значения
claims = entity.claims[propertyID]
+
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
 
end
if claims then
+
coord = coord .. '|globe:' .. globe
-- if wiki-linked value output as link if possible
+
if options['type'] and options['type'] ~= '' then
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
+
coord = coord .. '|type=' .. options.type
local out = {}
+
end
for k, v in pairs(claims) do
+
if options['display'] and options['display'] ~= '' then
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
+
coord = coord .. '|display=' .. options.display
local label
 
local claimEntity = mw.wikibase.getEntity("Q" .. v.mainsnak.datavalue.value["numeric-id"])
 
if claimEntity ~= nil then
 
if claimEntity.claims.P1813 then
 
for k2, v2 in pairs(claimEntity.claims.P1813) do
 
if v2.mainsnak.datavalue.value.language == "en" then
 
label = v2.mainsnak.datavalue.value.text
 
end
 
end
 
end
 
end
 
if label == nil or label == "" then label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"]) end
 
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
 
 
if sitelink then
 
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
 
else
 
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
 
end
 
end
 
return table.concat(out, ", ")
 
else
 
-- just return best vakues
 
return entity:formatPropertyValues(propertyID).value
 
end
 
 
else
 
else
return ""
+
coord = coord .. '|display=title'
 
end
 
end
else
+
coord = coord .. '}}'
return input_parm
+
 
 +
return g_frame:preprocess(coord)
 
end
 
end
 
end
 
end
  
-- This is used to get a value, or a comma separated list of them if multiple values exist
+
--[[
-- from an arbitrary entry by using its QID.
+
Функция для оформления объектов-значений с файлами с Викисклада
-- Use : {{#invoke:Wikidata|getValueFromID|<ID>|<Property>|FETCH_WIKIDATA}}
+
 
-- E.g.: {{#invoke:Wikidata|getValueFromID|Q151973|P26|FETCH_WIKIDATA}} - to fetch value of 'spouse' (P26) from 'Richard Burton' (Q151973)
+
Принимает: объект-значение и таблицу параметров,
-- Please use sparingly - this is an *expensive call*.
+
Возвращает: строку оформленного текста
p.getValueFromID = function(frame)
+
]]
local itemID = mw.text.trim(frame.args[1] or "")
+
function formatCommonsMedia( value, options )
local propertyID = mw.text.trim(frame.args[2] or "")
+
local image = value;
local input_parm = mw.text.trim(frame.args[3] or "")
+
 
if input_parm == "FETCH_WIKIDATA" then
+
local caption = '';
local entity = mw.wikibase.getEntity(itemID)
+
if options[ 'caption' ] and options[ 'caption' ] ~= '' then
local claims
+
caption = options[ 'caption' ];
if entity and entity.claims then
+
elseif options[ 'description' ] and options[ 'description' ] ~= '' then
claims = entity.claims[propertyID]
+
caption = options[ 'description' ];
 +
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 .. '|frameless';
 +
if options[ 'border' ] and options[ 'border' ] ~= '' then
 +
image = image .. '|border';
 
end
 
end
if claims then
 
-- if wiki-linked value output as link if possible
 
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "wikibase-entityid") then
 
local out = {}
 
for k, v in pairs(claims) do
 
local sitelink = mw.wikibase.sitelink("Q" .. v.mainsnak.datavalue.value["numeric-id"])
 
local label = mw.wikibase.label("Q" .. v.mainsnak.datavalue.value["numeric-id"])
 
if label == nil then label = "Q" .. v.mainsnak.datavalue.value["numeric-id"] end
 
  
if sitelink then
+
local size = options[ 'size' ];
out[#out + 1] = "[[" .. sitelink .. "|" .. label .. "]]"
+
if size and size ~= '' then
else
+
if not string.match( size, 'px$' )
out[#out + 1] = "[[:d:Q" .. v.mainsnak.datavalue.value["numeric-id"] .. "|" .. label .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
+
and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
end
+
then
end
+
size = size .. 'px'
return table.concat(out, ", ")
 
else
 
return entity:formatPropertyValues(propertyID).value
 
 
end
 
end
 
else
 
else
return ""
+
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
 
end
 
else
 
else
return input_parm
+
image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
 
end
 
end
 +
 +
return image
 
end
 
end
  
p.getQualifierValue = function(frame)
+
--[[
local propertyID = mw.text.trim(frame.args[1] or "")
+
Fonction for render math formulas
local qualifierID = mw.text.trim(frame.args[2] or "")
+
 
local input_parm = mw.text.trim(frame.args[3] or "")
+
@param string Value.
if input_parm == "FETCH_WIKIDATA" then
+
@param table Parameters.
local entity = mw.wikibase.getEntityObject()
+
@return string Formatted string.
if entity.claims[propertyID] ~= nil then
+
]]
local out = {}
+
function formatMath( value, options )
for k, v in pairs(entity.claims[propertyID]) do
+
return options.frame:extensionTag{ name = 'math', content = value };
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
+
end
if v2.snaktype == 'value' then
+
 
if (mw.wikibase.sitelink("Q" .. v2.datavalue.value["numeric-id"])) then
+
--[[
out[#out + 1] = "[[" .. mw.wikibase.sitelink("Q" .. v2.datavalue.value["numeric-id"]) .. "]]"
+
Функция для оформления внешних идентификаторов
else
+
 
out[#out + 1] = "[[:d:Q" .. v2.datavalue.value["numeric-id"] .. "|" .. mw.wikibase.label("Q" .. v2.datavalue.value["numeric-id"]) .. "]]<abbr title='" .. i18n["errors"]["local-article-not-found"] .. "'>[*]</abbr>"
+
Принимает: объект-значение и таблицу параметров,
end
+
Возвращает: строку оформленного текста
 +
]]
 +
local function formatExternalId( value, options )
 +
local formatter = options.formatter;
 +
 
 +
if not formatter or formatter == '' then
 +
local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, options.property:upper() )
 +
if wbStatus == true and propertyEntity then
 +
local isGoodFormat = false;
 +
local statements = propertyEntity:getBestStatements( 'P1793' );
 +
for _, statement in pairs( statements ) do
 +
if statement.mainsnak.snaktype == 'value' then
 +
local pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
 +
pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' );
 +
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
 
end
 
end
 
end
return table.concat(out, ", ")
 
else
 
return ""
 
 
end
 
end
else
 
return input_parm
 
 
end
 
end
end
 
  
-- This is used to get a value like 'male' (for property p21) which won't be linked and numbers without the thousand separators
+
if formatter and formatter ~= '' then
p.getRawValue = function(frame)
+
local link = mw.ustring.gsub( mw.ustring.gsub( formatter, '$1', value ), ' ', '%%20' )
local propertyID = mw.text.trim(frame.args[1] or "")
 
local input_parm = mw.text.trim(frame.args[2] or "")
 
if input_parm == "FETCH_WIKIDATA" then
 
local entity = mw.wikibase.getEntityObject()
 
local claims
 
if entity and entity.claims then claims = entity.claims[propertyID] end
 
if claims then
 
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
 
  
-- if number type: remove thousand separators, bounds and units
+
local title = options.title
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
+
if not title or title == '' then
result = mw.ustring.gsub(result, "(%d),(%d)", "%1%2")
+
title = '$1'
result = mw.ustring.gsub(result, "(%d)±.*", "%1")
 
end
 
return result
 
else
 
return ""
 
 
end
 
end
else
+
title = mw.ustring.gsub( title, '$1', value )
return input_parm
+
 
 +
return '[' .. link .. ' ' .. title .. ']'
 
end
 
end
 +
 +
return value
 
end
 
end
  
-- This is used to get the unit name for the numeric value returned by getRawValue
+
--[[
p.getUnits = function(frame)
+
Функция для оформления числовых значений
local propertyID = mw.text.trim(frame.args[1] or "")
+
 
local input_parm = mw.text.trim(frame.args[2] or "")
+
Принимает: объект-значение и таблицу параметров,
if input_parm == "FETCH_WIKIDATA" then
+
Возвращает: строку оформленного текста
local entity = mw.wikibase.getEntityObject()
+
]]
local claims
+
local function formatQuantity( value, options )
if entity and entity.claims then claims = entity.claims[propertyID] end
+
-- диапазон значений
if claims then
+
local amount = string.gsub( value['amount'], '^%+', '' );
local result = entity:formatPropertyValues(propertyID, mw.wikibase.entity.claimRanks).value
+
local lang = mw.language.getContentLanguage();
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
+
local langCode = lang:getCode();
result = mw.ustring.sub(result, mw.ustring.find(result, " ")+1, -1)
+
 
end
+
local function formatNum( number, sigfig )
return result
+
sigfig = sigfig or 12 -- округление до 12 знаков после запятой, на 13-м возникает ошибка в точности
else
+
local mult = 10^sigfig;
return ""
+
number = math.floor( number * mult + 0.5 ) / mult;
 +
 
 +
return string.gsub( 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
else
 
return input_parm
 
 
end
 
end
end
 
  
-- This is used to get the unit's QID to use with the numeric value returned by getRawValue
+
if options.unit and options.unit ~= '' then
p.getUnitID = function(frame)
+
if options.unit ~= '-' then
local propertyID = mw.text.trim(frame.args[1] or "")
+
out = out .. ' ' .. options.unit
local input_parm = mw.text.trim(frame.args[2] or "")
 
if input_parm == "FETCH_WIKIDATA" then
 
local entity = mw.wikibase.getEntityObject()
 
local claims
 
if entity and entity.claims then claims = entity.claims[propertyID] end
 
if claims then
 
local result
 
if (claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity") then
 
-- get the url for the unit entry on Wikidata:
 
result = claims[1].mainsnak.datavalue.value.unit
 
-- and just reurn the last bit from "Q" to the end (which is the QID):
 
result = mw.ustring.sub(result, mw.ustring.find(result, "Q"), -1)
 
end
 
return result
 
else
 
return ""
 
 
end
 
end
else
+
elseif value.unit and string.match( value.unit, 'http://www.wikidata.org/entity/' ) then
return input_parm
+
local unitEntityId = string.gsub( value.unit, 'http://www.wikidata.org/entity/', '' );
end
+
local wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
end
+
if wbStatus == true and unitEntity then
 +
if unitEntity.claims.P2370 and
 +
unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
 +
not value.upperBound and
 +
options.siConversion
 +
then
 +
conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
 +
if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
 +
-- Если не степени десятки (переводить сантиметры в метры не надо!)
 +
outValue = tonumber( amount ) * conversionToSIunit
  
p.getRawQualifierValue = function(frame)
+
if ( outValue > 0 ) then
local propertyID = mw.text.trim(frame.args[1] or "")
+
-- Пробуем понять до какого знака округлять
local qualifierID = mw.text.trim(frame.args[2] or "")
+
local integer, dot, decimals, expstr = amount:match( '^(%d*)(%.?)(%d*)(.*)' )
local input_parm = mw.text.trim(frame.args[3] or "")
+
local prec
if input_parm == "FETCH_WIKIDATA" then
+
if dot == '' then
local entity = mw.wikibase.getEntityObject()
+
prec = -integer:match('0*$'):len()
if entity.claims[propertyID] ~= nil then
 
local out = {}
 
for k, v in pairs(entity.claims[propertyID]) do
 
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
 
if v2.snaktype == 'value' then
 
if v2.datavalue.value["numeric-id"] then
 
out[#out + 1] = mw.wikibase.label("Q" .. v2.datavalue.value["numeric-id"])
 
 
else
 
else
out[#out + 1] = v2.datavalue.value
+
prec = #decimals
 
end
 
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
 
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
 
end
 
end
local ret = table.concat(out, ", ")
+
 
return string.upper(string.sub(ret, 1, 1)) .. string.sub(ret, 2)
+
local writingSystemElementId = 'Q8209';
else
+
local langElementId = 'Q7737';
return ""
+
local label = getLabelWithLang( context, options, unitEntity, nil, {
 +
'P5061[language:' .. langCode .. ']',
 +
'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
 +
'P558[!P282][!P407]'
 +
} );
 +
 
 +
out = out .. ' ' .. label;
 
end
 
end
else
 
return input_parm
 
 
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 wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
 +
if wbStatus ~= true or not propertyEntity then
 +
return nil;
 +
end
 +
 +
return propertyEntity.datatype;
 
end
 
end
  
-- This is used to get a date value for date_of_birth (P569), etc. which won't be linked
+
local function formatLangRefs( options )
-- Dates and times are stored in ISO 8601 format (sort of).
+
local langRefs = ''
-- At present the local formatDate(date, precision, timezone) function doesn't handle timezone
+
if ( options.qualifiers and options.qualifiers.P407 ) then
-- So I'll just supply "Z" in the call to formatDate below:
+
for i, qualifier in pairs( options.qualifiers.P407 ) do
p.getDateValue = function(frame)
+
if ( qualifier
local propertyID = mw.text.trim(frame.args[1] or "")
+
and qualifier.datavalue
local input_parm = mw.text.trim(frame.args[2] or "")
+
and qualifier.datavalue.type == 'wikibase-entityid' ) then
local date_format = mw.text.trim(frame.args[3] or i18n["datetime"]["default-format"])
+
local langRefEntity = getEntityFromId( qualifier.datavalue.value.id )
local date_addon = mw.text.trim(frame.args[4] or i18n["datetime"]["default-addon"])
+
if ( langRefEntity and langRefEntity.claims ) then
if input_parm == "FETCH_WIKIDATA" then
+
local langRefCodeClaims = WDS.filter( langRefEntity.claims, 'P218' )
local entity = mw.wikibase.getEntityObject()
+
if langRefCodeClaims then
if entity.claims[propertyID] ~= nil then
+
for _, claim in pairs( langRefCodeClaims ) do
local out = {}
+
if ( claim.mainsnak
for k, v in pairs(entity.claims[propertyID]) do
+
and claim.mainsnak
if v.mainsnak.datavalue.type == 'time' then
+
and claim.mainsnak.datavalue
local timestamp = v.mainsnak.datavalue.value.time
+
and claim.mainsnak.datavalue.type == 'string' ) then
local dateprecision = v.mainsnak.datavalue.value.precision
+
local langRefCode = claim.mainsnak.datavalue.value
-- A year can be stored like this: "+1872-00-00T00:00:00Z",
+
langRefs = langRefs .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
-- which is processed here as if it were the day before "+1872-01-01T00:00:00Z",
+
end
-- and that's the last day of 1871, so the year is wrong.
+
end
-- So fix the month 0, day 0 timestamp to become 1 January instead:
+
end
timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
 
out[#out + 1] = parseDateFull(timestamp, dateprecision, date_format, date_addon)
 
 
end
 
end
 
end
 
end
return table.concat(out, ", ")
 
else
 
return ""
 
 
end
 
end
else
 
return input_parm
 
 
end
 
end
 +
 +
return langRefs
 
end
 
end
  
p.getQualifierDateValue = function(frame)
+
local function getDefaultValueFunction( datavalue, datatype )
local propertyID = mw.text.trim(frame.args[1] or "")
+
-- вызов обработчиков по умолчанию для известных типов значений
local qualifierID = mw.text.trim(frame.args[2] or "")
+
if datavalue.type == 'wikibase-entityid' then
local input_parm = mw.text.trim(frame.args[3] or "")
+
-- Entity ID
local date_format = mw.text.trim(frame.args[4] or i18n["datetime"]["default-format"])
+
return function( context, options, value ) return formatEntityId( context, options, getEntityIdFromValue( value ) ) end;
local date_addon = mw.text.trim(frame.args[5] or i18n["datetime"]["default-addon"])
+
elseif datavalue.type == 'string' then
if input_parm == "FETCH_WIKIDATA" then
+
-- String
local entity = mw.wikibase.getEntityObject()
+
if datatype and datatype == 'commonsMedia' then
if entity.claims[propertyID] ~= nil then
+
-- Media
local out = {}
+
return function( context, options, value )
for k, v in pairs(entity.claims[propertyID]) do
+
if ( not options.caption or options.caption == '' )
for k2, v2 in pairs(v.qualifiers[qualifierID]) do
+
and ( not options.description or options.description == '' )
if v2.snaktype == 'value' then
+
and options.qualifiers and options.qualifiers.P2096 then
local timestamp = v2.datavalue.value.time
+
for i, qualifier in pairs( options.qualifiers.P2096 ) do
out[#out + 1] = parseDateValue(timestamp, date_format, date_addon)
+
if ( qualifier
 +
and qualifier.datavalue
 +
and qualifier.datavalue.type == 'monolingualtext'
 +
and qualifier.datavalue.value
 +
and qualifier.datavalue.value.language == contentLanguageCode ) then
 +
options.caption = qualifier.datavalue.value.text
 +
options.description = qualifier.datavalue.value.text
 +
break
 +
end
 
end
 
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
 +
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 == 'math' then
 +
-- Math formula
 +
return function( context, options, value )
 +
return formatMath( value, options )
 +
end
 +
elseif datatype and datatype == 'url' then
 +
-- URL
 +
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
return table.concat(out, ", ")
 
else
 
return ""
 
 
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
 +
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
 +
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
 +
-- географические координаты
 +
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
 
else
return input_parm
+
-- во всех стальных случаях возвращаем ошибку
 +
throwError( 'unknown-datavalue-type' )
 
end
 
end
 
end
 
end
  
-- This is used to fetch all of the images with a particular property, e.g. image (P18), Gene Atlas Image (P692), etc.
+
--[[
-- Parameters are | propertyID | value / FETCH_WIKIDATA / nil | separator (default=space) | size (default=frameless)
+
Функция для оформления значений (value)
-- It will return a standard wiki-markup [[File:Filename | size]] for each image with a selectable size and separator (which may be html)
+
Подробнее о значениях  см. d:Wikidata:Glossary/ru
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA}}
+
 
-- e.g. {{#invoke:Wikidata|getImages|P18|FETCH_WIKIDATA|<br>|250px}}
+
Принимает: объект-значение и таблицу параметров,
-- If a property is chosen that is not of type "commonsMedia", it will return empty text.
+
Возвращает: строку оформленного текста
p.getImages = function(frame)
+
]]
local propertyID = mw.text.trim(frame.args[1] or "")
+
function formatDatavalue( context, options, datavalue, datatype )
local input_parm = mw.text.trim(frame.args[2] or "")
+
if ( not context ) then error( 'context not specified' ); end;
local sep = mw.text.trim(frame.args[3] or " ")
+
if ( not options ) then error( 'options not specified' ); end;
local imgsize = mw.text.trim(frame.args[4] or "frameless")
+
if ( not datavalue ) then error( 'datavalue not specified' ); end;
if input_parm == "FETCH_WIKIDATA" then
+
if ( not datavalue.value ) then error( 'datavalue.value is missng' ); end;
local entity = mw.wikibase.getEntityObject()
+
 
local claims
+
-- проверка на указание специализированных обработчиков в параметрах,
if entity and entity.claims then
+
-- переданных при вызове
claims = entity.claims[propertyID]
+
context.formatValueDefault = getDefaultValueFunction( datavalue, datatype );
 +
local functionToCall = getUserFunction( options, 'value', context.formatValueDefault );
 +
return functionToCall( context, options, datavalue.value );
 +
end
 +
 
 +
--[[
 +
Функция для оформления идентификатора сущности
 +
 
 +
Принимает: строку индентификатора (типа Q42) и таблицу параметров,
 +
Возвращает: строку оформленного текста
 +
]]
 +
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>' .. getCategoryByCode( 'links-to-entities-with-wikibase-error' );
 +
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 = p.extractCategory( context, options, { id = entityId } )
 +
 
 +
-- получение ссылки по идентификатору
 +
local link = mw.wikibase.sitelink( entityId )
 +
if link then
 +
-- ссылка на категорию, а не добавление страницы в неё
 +
if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
 +
link = ':' .. link
 
end
 
end
if claims then
+
if label then
if (claims[1] and claims[1].mainsnak.datatype == "commonsMedia") then
+
if ( contentLanguageCode ~= labelLanguageCode ) then
local out = {}
+
return '[[' .. link .. '|' .. label .. ']]' .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
for k, v in pairs(claims) do
 
local filename = v.mainsnak.datavalue.value
 
out[#out + 1] = "[[File:" .. filename .. "|" .. imgsize .. "]]"
 
end
 
return table.concat(out, sep)
 
 
else
 
else
return ""
+
return '[[' .. link .. '|' .. label .. ']]' .. category;
 
end
 
end
 
else
 
else
return ""
+
return '[[' .. link .. ']]' .. category;
 
end
 
end
else
 
return input_parm
 
 
end
 
end
 +
 +
if label then
 +
-- красная ссылка
 +
-- TODO: разобраться, почему не всегда есть options.frame
 +
local title = mw.title.new( label );
 +
if title and not title.exists and options.frame then
 +
local templateText = "{{Универсальная карточка|" .. entityId .. "}}%0A'''" .. label .. "''' — %0A%0A== Примечания ==%0A{{примечания}}%0A";
 +
local templateText = templateText .. "[[Категория:Википедия:Связать с элементом Викиданных|" .. entityId .. "]]";
 +
local preloadUrl = tostring( mw.uri.canonicalUrl( label, 'action=edit&preload=Ш:Preload/Викиданные&preloadparams[]=' .. templateText ));
 +
local redLink = options.frame:expandTemplate{ title='цветная ссылка', args = { '#ba0000', preloadUrl, label }};
 +
return '<span class="plainlinks">' .. redLink .. '</span><sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
 +
end
 +
 +
-- TODO: перенести до проверки на существование статьи
 +
local sup = '';
 +
if ( not options.format or options.format ~= 'text' )
 +
and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: переписать на format=text
 +
then
 +
sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d&#x5d;]</sup>'
 +
end
 +
 +
-- одноимённая статья уже существует - выводится текст и ссылка на ВД
 +
return '<span class="iw" data-title="' .. label .. '">' .. label
 +
.. sup
 +
.. '</span>' .. category
 +
end
 +
-- сообщение об отсутвии локализованного названия
 +
-- not good, but better than nothing
 +
return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' ) .. category;
 
end
 
end
  
-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
+
--[[
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
+
Функция для формирования категории на основе wikidata/config
-- uses the newer mw.wikibase calls instead of directly using the snaks
+
]]
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
+
function p.extractCategory( context, options, value )
p.getTAValue = function(frame)
+
local wbStatus, entity = pcall( mw.wikibase.getEntity, value.id )
local ent = mw.wikibase.getEntityObject()
+
local category = ''
local props = ent:formatPropertyValues('P1323')
+
if ( options.category ) then
local out = {}
+
local claims = WDS.filter( entity.claims, options.category );
local t = {}
+
if ( claims ) then
for k, v in pairs(props) do
+
for _, claim in pairs( claims ) do
if k == 'value' then
+
if ( claim.mainsnak
t = mw.text.split( v, ", ")
+
and claim.mainsnak
for k2, v2 in pairs(t) do
+
and claim.mainsnak.datavalue
out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
+
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 ) then
 +
if catEntity:getSitelink() then
 +
category = '[[' .. catEntity:getSitelink() .. ']]';
 +
end
 +
end
 +
end
 
end
 
end
 
end
 
end
 
end
 
end
local ret = table.concat(out, "<br> ")
+
return category;
if #ret == 0 then
 
ret = "Invalid TA"
 
end
 
return ret
 
 
end
 
end
  
 
--[[
 
--[[
This is used to return an image legend from Wikidata
+
Функция для оформления утверждений (statement)
image is property P18
+
Подробнее о утверждениях см. d:Wikidata:Glossary/ru
image legend is property P2096
 
  
Call as {{#invoke:Wikidata |getImageLegend | <PARAMETER> | lang=<ISO-639code> |id=<QID>}}
+
Принимает: таблицу параметров
Returns PARAMETER, unless it is equal to "FETCH_WIKIDATA", from Item QID (expensive call)
+
Возвращает: строку оформленного текста, предназначенного для отображения в статье
If QID is omitted or blank, the current article is used (not an expensive call)
+
]]
If lang is omitted, it uses the local wiki language, otherwise it uses the provided ISO-639 language code
+
-- устаревшее имя, не использовать
ISO-639: https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html#wp1252447
+
function p.formatStatements( frame )
 +
return p.formatProperty( frame );
 +
end
  
Ranks are: 'preferred' > 'normal'
+
--[[
This returns the label from the first image with 'preferred' rank
+
Получение параметров, которые обычно используются для вывода свойства.
Or the label from the first image with 'normal' rank if preferred returns nothing
 
Ranks: https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
 
 
]]
 
]]
 +
function getPropertyParams( propertyId, datatype, params )
 +
local config = getConfig();
 +
 +
-- Различные уровни настройки параметров, по убыванию приоритета
 +
local propertyParams = {};
  
p.getImageLegend = function(frame)
+
-- 1. Параметры, указанные явно при вызове
-- look for named parameter id; if it's blank make it nil
+
if params then
local id = frame.args.id
+
for key, value in pairs( params ) do
if id and (#id == 0) then
+
if value ~= '' then
id = nil
+
propertyParams[ key ] = value;
 +
end
 +
end
 
end
 
end
  
-- look for named parameter lang
+
-- 2. Настройки конкретного параметра
-- it should contain a two-character ISO-639 language code
+
if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
-- if it's blank fetch the language of the local wiki
+
for key, value in pairs( config[ 'properties' ][ propertyId ] ) do
local lang = frame.args.lang
+
if propertyParams[ key ] == nil then
if (not lang) or (#lang < 2) then
+
propertyParams[ key ] = value;
lang = mw.language.getContentLanguage().code
+
end
 +
end
 
end
 
end
  
-- first unnamed parameter is the local parameter, if supplied
+
-- 3. Указанный пресет настроек
local input_parm = mw.text.trim(frame.args[1] or "")
+
if propertyParams[ 'preset' ] and config[ 'presets' ] and
if input_parm == "FETCH_WIKIDATA" then
+
config[ 'presets' ][ propertyParams[ 'preset' ] ]
local ent = mw.wikibase.getEntityObject(id)
+
then
local imgs
+
for key, value in pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ] ) do
if ent and ent.claims then
+
if propertyParams[ key ] == nil then
imgs = ent.claims.P18
+
propertyParams[ key ] = value;
 +
end
 
end
 
end
local imglbl
+
end
if imgs then
+
 
-- look for an image with 'preferred' rank
+
-- 4. Настройки для типа данных
for k1, v1 in pairs(imgs) do
+
if datatype and config[ 'datatypes' ] and config[ 'datatypes' ][ datatype ] then
if v1.rank == "preferred" and v1.qualifiers and v1.qualifiers.P2096 then
+
for key, value in pairs( config[ 'datatypes' ][ datatype ] ) do
local imglbls = v1.qualifiers.P2096
+
if propertyParams[ key ] == nil then
for k2, v2 in pairs(imglbls) do
+
propertyParams[ key ] = value;
if v2.datavalue.value.language == lang then
 
imglbl = v2.datavalue.value.text
 
break
 
end
 
end
 
end
 
end
 
-- if we don't find one, look for an image with 'normal' rank
 
if (not imglbl) then
 
for k1, v1 in pairs(imgs) do
 
if v1.rank == "normal" and v1.qualifiers and v1.qualifiers.P2096 then
 
local imglbls = v1.qualifiers.P2096
 
for k2, v2 in pairs(imglbls) do
 
if v2.datavalue.value.language == lang then
 
imglbl = v2.datavalue.value.text
 
break
 
end
 
end
 
end
 
end
 
 
end
 
end
 
end
 
end
return imglbl
 
else
 
return input_parm
 
 
end
 
end
end
 
 
-- This is used to get the QIDs of all of the values of a property, as a comma separated list if multiple values exist
 
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |FETCH_WIKIDATA}}
 
-- Usage: {{#invoke:Wikidata |getPropertyIDs |<PropertyID> |<InputParameter> |qid=<QID>}}
 
  
p.getPropertyIDs = function(frame)
+
-- 5. Общие настройки для всех свойств
local propertyID = mw.text.trim(frame.args[1] or "")
+
if config[ 'global' ] then
local input_parm = mw.text.trim(frame.args[2] or "")
+
for key, value in pairs( config[ 'global' ] ) do
-- can take a named parameter |qid which is the Wikidata ID for the article. This will not normally be used.
+
if propertyParams[ key ] == nil then
local qid = frame.args.qid
+
propertyParams[ key ] = value;
if qid and (#qid == 0) then qid = nil end
 
if input_parm == "FETCH_WIKIDATA" then
 
local entity = mw.wikibase.getEntityObject(qid)
 
local propclaims
 
if entity and entity.claims then
 
propclaims = entity.claims[propertyID]
 
end
 
if propclaims then
 
-- if wiki-linked value collect the QID in a table
 
if (propclaims[1] and propclaims[1].mainsnak.snaktype == "value" and propclaims[1].mainsnak.datavalue.type == "wikibase-entityid") then
 
local out = {}
 
for k, v in pairs(propclaims) do
 
out[#out + 1] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
 
end
 
return table.concat(out, ", ")
 
else
 
-- not a wikibase-entityid, so return empty
 
return ""
 
 
end
 
end
else
 
-- no claim, so return empty
 
return ""
 
 
end
 
end
else
 
return input_parm
 
 
end
 
end
end
 
  
-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
+
return propertyParams;
function p.pageId(frame)
 
return mw.wikibase.getEntityIdForCurrentPage()
 
 
end
 
end
  
function p.claim(frame)
+
function p.formatProperty( frame )
local property = frame.args[1] or ""
+
local args = frame.args
local id = frame.args["id"] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration
 
local qualifierId = frame.args["qualifier"]
 
local parameter = frame.args["parameter"]
 
local list = frame.args["list"]
 
local references = frame.args["references"]
 
local showerrors = frame.args["showerrors"]
 
local default = frame.args["default"]
 
if default then showerrors = nil end
 
  
-- get wikidata entity
+
-- проверка на отсутствие обязательного параметра property
local entity = mw.wikibase.getEntityObject(id)
+
if not args.property then
if not entity then
+
throwError( 'property-param-not-provided' )
if showerrors then return printError("entity-not-found") else return default end
 
 
end
 
end
-- fetch the first claim of satisfying the given property
+
local propertyId = mw.language.getContentLanguage():ucfirst( string.gsub( args.property, '%[.*$', '' ) )
local claims = findClaims(entity, property)
+
local datatype = getPropertyDatatype( propertyId );
if not claims or not claims[1] then
+
args = getPropertyParams( propertyId, datatype, args );
if showerrors then return printError("property-not-found") else return default end
+
 
 +
-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
 +
p_frame = 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
 
end
  
-- get initial sort indices
+
args.plain = toBoolean( args.plain, false );
local sortindices = {}
+
args.nocat = toBoolean( args.nocat, false );
for idx in pairs(claims) do
+
args.references = toBoolean( args.references, true );
sortindices[#sortindices + 1] = idx
+
 
end
+
-- если значение передано в параметрах вызова то выводим только его
-- sort by claim rank
+
if args.value and args.value ~= '' then
local comparator = function(a, b)
+
-- специальное значение для скрытия Викиданных
local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
+
if args.value == '-' then
local ranka = rankmap[claims[a].rank or "normal"] .. string.format("%08d", a)
+
return ''
local rankb = rankmap[claims[b].rank or "normal"] .. string.format("%08d", b)
+
end
return ranka < rankb
+
local value = args.value
end
 
table.sort(sortindices, comparator)
 
  
local result
+
-- опция, запрещающая оформление значения, поэтому никак не трогаем
local error
+
if args.plain then
if list then
+
return value
local value
 
-- iterate over all elements and return their value (if existing)
 
result = {}
 
for idx in pairs(claims) do
 
local claim = claims[sortindices[idx]]
 
value, error = getValueOfClaim(claim, qualifierId, parameter)
 
if not value and showerrors then value = error end
 
if value and references then value = value .. getReferences(frame, claim) end
 
result[#result + 1] = value
 
 
end
 
end
result = table.concat(result, list)
 
else
 
-- return first element
 
local claim = claims[sortindices[1]]
 
result, error = getValueOfClaim(claim, qualifierId, parameter)
 
if result and references then result = result .. getReferences(frame, claim) end
 
end
 
  
if result then return result else
+
-- обработчики по типу значения
if showerrors then return error else return default end
+
local wrapperExtraArgs = ''
end
+
if args['value-module'] and args['value-function'] and not string.find( value, '[%[%]%{%}]' ) then
end
+
local func = getUserFunction( args, 'value' );
 +
value = func( {}, args, value );
 +
elseif datatype == 'commonsMedia' then
 +
value = formatCommonsMedia( value, args );
 +
elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then
 +
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
  
-- look into entity object
+
-- оборачиваем в тег для JS-функций
function p.ViewSomething(frame)
+
if string.match( propertyId, '^P%d+$' ) then
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
+
value = mw.text.trim( value )
local id = f.args.id
 
if id and (#id == 0) then
 
id = nil
 
end
 
local data = mw.wikibase.getEntityObject(id)
 
if not data then
 
return nil
 
end
 
  
local i = 1
+
-- временная штрафная категория для исправления табличных вставок
while true do
+
if ( propertyId ~= 'P166'
local index = f.args[i]
+
and string.match( value, '<t[dr][ >]' )
if not index then
+
and not string.match( value, '<table >]' )
if type(data) == "table" then
+
and not string.match( value, '^%{%|' ) ) then
return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
+
value = value .. getCategoryByCode( 'value-contains-table' )
 
else
 
else
return tostring(data)
+
-- значений с блочными тегами остаются блоком, текст встраиваем в строку
 +
if ( string.match( value, '\n' )
 +
or string.match( value, '<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
 
end
 
end
  
data = data[index] or data[tonumber(index)]
+
-- добавляем категорию-маркер
if not data then
+
if not args.nocat then
return
+
local pageTitle = mw.title.getCurrentTitle();
 +
if pageTitle.namespace == 0 then
 +
value = value .. getCategoryByCode( 'local-value-present' );
 +
end
 
end
 
end
  
i = i + 1
+
return value
 
end
 
end
end
 
  
-- getting sitelink of a given wiki
+
if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
function p.getSiteLink(frame)
+
local callArgs = { propertyId };
local f = frame.args[1]
+
if args.entityId then
local entity = mw.wikibase.getEntity()
+
callArgs.from = args.entityId;
if not entity then
+
end
return
+
return frame:callParserFunction( '#property', callArgs );
 
end
 
end
local link = entity:getSitelink( f )
+
 
if not link then
+
g_frame = frame
return
+
-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
end
+
return formatProperty( args )
return link
 
 
end
 
end
  
function p.Dump(frame)
+
--[[
local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
+
Функция оформления ссылок на источники (reference)
local data = mw.wikibase.getEntityObject(f.args.id)
+
Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru
if not data then
+
 
return i18n.warnDump
+
Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
 +
Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).
 +
 
 +
Принимает: объект-таблицу утверждение
 +
Возвращает: строку оформленных ссылок для отображения в статье
 +
]]
 +
function 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 ) then
 +
return '';
 
end
 
end
  
local i = 1
+
local references = {};
while true do
+
if ( statement.references ) then
local index = f.args[i]
+
 
if not index then
+
local allReferences = statement.references;
return "<pre>"..mw.dumpObject(data).."</pre>".. i18n.warnDump
+
local hasPreferred = false;
 +
local displayCount = 0;
 +
for _, reference in pairs( statement.references ) do
 +
if ( reference.snaks
 +
and reference.snaks.P248
 +
and reference.snaks.P248[1]
 +
and reference.snaks.P248[1].datavalue
 +
and reference.snaks.P248[1].datavalue.value.id ) then
 +
local entityId = reference.snaks.P248[1].datavalue.value.id;
 +
if ( preferredSources[entityId] ) then
 +
hasPreferred = true;
 +
end
 +
end
 
end
 
end
  
data = data[index] or data[tonumber(index)]
+
for _, reference in pairs( statement.references ) do
if not data then
+
local display = true;
return i18n.warnDump
+
if ( hasPreferred ) then
 +
if ( reference.snaks
 +
and reference.snaks.P248
 +
and reference.snaks.P248[1]
 +
and reference.snaks.P248[1].datavalue
 +
and reference.snaks.P248[1].datavalue.value.id ) then
 +
local entityId = reference.snaks.P248[1].datavalue.value.id;
 +
if ( deprecatedSources[entityId] ) then
 +
display = false;
 +
end
 +
end
 +
end
 +
if ( display == true ) then
 +
if ( displayCount > 2 ) then
 +
if ( options.entity and options.property ) then
 +
table.remove( references );
 +
local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( options.property ) .. '|[…]]]</sup>';
 +
table.insert( references, moreReferences );
 +
end
 +
break;
 +
end;
 +
local refText = moduleSources.renderReference( g_frame, options.entity, reference );
 +
if ( refText ~= '' ) then
 +
table.insert( references, refText );
 +
displayCount = displayCount + 1;
 +
end
 +
end
 
end
 
end
 
i = i + 1
 
 
end
 
end
 +
return table.concat( references );
 
end
 
end
  
 
return p
 
return p

Текущая версия на 15:30, 3 июля 2018


Используется в {{Wikidata}}.

Функции данного модуля не предназначены для прямого вызова из шаблонов карточек или других модулей, не являющихся функциями расширения данного. Для вызова из шаблонов карточек используйте шаблон {{wikidata}} или один из специализированных шаблонов для свойств. Для вызова функций Викиданных предназначенных для отображения чаще всего достаточно вызова frame:expandTemplate{} с вызовом шаблона, ответственного за отрисовку свойства. С другой стороны, вызов определённых функций модуля (в основном это касается getEntityObject()) может в будущем стать предпочтительным. Данный Lua-функционал в любом случае стоит рассматривать как unstable с точки зрения сохранения совместимости на уровне кода (вместе с соответствующими функциями API для Wikibase Client).

Далее описывается внутренняя документация. Названия функций и параметров могут изменяться. При их изменении автор изменений обязан обновить шаблон {{wikidata}} и специализированные шаблоны свойств. Изменения в других местах, если кто-то всё-таки вызывает функции модуля напрямую, остаются на совести автора «костыля». Итак, при вызове шаблона {{wikidata}} или специализированного шаблона свойства управление отдаётся на функцию formatStatements, которая принимает frame. Из frame достаются следующие опции, которые так или иначе передаются в остальные функции:

  • plain — булевый переключатель (по умолчанию false). Если true, результат совпадает с обычным вызовом {{#property:pNNN}} (по факту им и будет являться)
  • references — булевый переключатель (по умолчанию true). Если true, после вывода значения параметра дополнительно выводит ссылки на источники, указанные в Викиданных. Для вывода используется Модуль:Sources. Обычно отключается для тех свойств, которые являются «самоописываемыми», например, внешними идентификаторами или ссылками (когда такая ссылка является доказательством своей актуальности), например, идентификаторы IMDb.
  • value — значение, которое надо выводить вместо значений из Викиданных (используется, если что-то задано уже в карточке в виде т. н. локального свойства)

По умолчанию модуль поддерживает вывод следующих значений без дополнительных настроек:

  • географические координаты (coordinates)
  • количественные значения (quantity)
  • моноязычный текст (monolingualtext)
  • строки (string)
  • даты (time)

Остальные типы данных требуют указания функции форматирования значения.

Поддерживаются три типа параметров-функций, которые дополнительно указывают, как надо форматировать значения:

  • property-module, property-function — название модуля и функции модуля, которые отвечают за форматирование вывода массива значений свойства (statements, claims) с учётом квалификаторов, ссылок и прочего. Например, оформляет множество выводов в таблицу или график. Характерные примеры:
    Спецификация функции: function p.…( context, options ), поведение по умолчанию: Модуль:Wikidata#formatPropertyDefault.
  • claim-module, claim-function — название модуля и функции модуля, которые отвечают за форматирование вывода значения свойства (statement, claim) с учётом квалификаторов, ссылок и прочего. Может, например, дополнительно к основному значению (main snak) вывести значения квалификаторов. Характерные примеры:
    Спецификация функции: function p.…( context, statement )
  • value-module, value-function — название модуля и функции модуля, которые отвечают за форматирование значения (snak, snak data value), в зависимости от контекста, как значений свойства, так и значений квалификатора (если вызывается из claim-module/claim-function). Необходимо для изменения отображения свойства, например, генерации викиссылки вместо простой строки или даже вставки изображения вместо отображения имени файла изображения (так как ссылки на изображения хранятся как строки). Характерные примеры:
    Спецификация функции: function p.…( value, options )



-- settings, may differ from project to project
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 WDS = require( 'Module:WikidataSelectors' );

-- Константы
local contentLanguageCode = mw.getContentLanguage():getCode();

local p = {};
local config = nil;

local formatDatavalue, formatEntityId, formatRefs, formatSnak, formatStatement,
	formatStatementDefault, formatProperty, getSourcingCircumstances,
	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;
		end
	end
	return target;
end

local function min( prev, next )
	if ( prev == nil ) then return next;
	elseif ( prev > next ) then return next;
	else return prev; end
end

local function max( prev, next )
	if ( prev == nil ) then return next;
	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

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 )
	local entity;
	local wbStatus;

	if id then
		wbStatus, entity = pcall( mw.wikibase.getEntityObject, id )
	else
		wbStatus, entity = pcall( mw.wikibase.getEntityObject );
	end

	return entity;
end

--[[
	Внутрення функция для формирования сообщения об ошибке

	Принимает: ключ элемента в таблице config.errors (например entity-not-found)
	Возвращает: строку сообщения
]]
local function throwError( key )
	error( getConfig( '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;

	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 ~= '-'  then
		local limit = tonumber( options.limit, 10 );
		while #result > limit do
			table.remove( result );
		end
	end

	return result;
end

--[[
	Функция для получения значения свойства элемента в заданный момент времени.

	Принимает: контекст, элемент, временные границы, таблица ID свойства
	Возвращает: таблицу соответствующих значений свойства
]]
local function getPropertyInBoundaries( context, entity, boundaries, propertyIds )
	local results = {};

	if not propertyIds or #propertyIds == 0 then
		return results;
	end

	if entity.claims then
		for _, propertyId in ipairs( propertyIds ) do
			local filteredClaims = WDS.filter( entity.claims, propertyId .. '[rank:preferred, rank:normal]' );
			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

	return results;
end

--[[
	TODO
]]
function p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId )
	-- only support exact date so far, but need improvment
	local left = nil;
	local right = nil;
	if ( statement.qualifiers and statement.qualifiers[qualifierId] ) then
		for _, qualifier in pairs( statement.qualifiers[qualifierId] ) do
			local boundaries = context.parseTimeBoundariesFromSnak( qualifier );
			if ( not boundaries ) then return nil; end
			left = min( left, boundaries[1] );
			right = max( right, boundaries[2] );
		end
	end

	if ( not left or not right ) then
		return nil;
	end

	return { left, right };
end

--[[
	TODO
]]
function p.getTimeBoundariesFromQualifiers( frame, context, statement, qualifierIds )
	if not qualifierIds then
		qualifierIds = { 'P582', 'P580', 'P585' };
	end

	for _, qualifierId in ipairs( qualifierIds ) do
		local result = p.getTimeBoundariesFromQualifier( frame, context, statement, qualifierId );
		if result then
			return result;
		end
	end

	return nil;
end

--[[
	Функция для получения метки элемента в заданный момент времени.

	Принимает: контекст, элемент, временные границы
	Возвращает: текстовую метку элемента, язык метки
]]
function getLabelWithLang( context, options, entity, boundaries, propertyIds )
	if not entity then
		return nil;
	end

	local lang = mw.language.getContentLanguage();
	local langCode = lang:getCode();

	-- name from label
	local label = nil;
	if ( options.text and options.text ~= '' ) then
		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, entity, boundaries, propertyIds );

		for _, result in pairs( results ) do
			if result.datavalue and result.datavalue.value then
				if result.datavalue.type == 'monolingualtext' and result.datavalue.value.text then
					label = result.datavalue.value.text;
					lang = result.datavalue.value.language;
					break;
				elseif result.datavalue.type == 'string' then
					label = result.datavalue.value;
					break;
				end
			end
		end
	end

	return label, langCode;
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

	-- 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( getConfig( 'i18n' ), {} ) );
	else
		options.i18n = getConfig( 'i18n' );
	end

	-- create context
	local context = {
		entity = options.entity,
		formatSnak = formatSnak,
		formatPropertyDefault = formatPropertyDefault,
		formatStatementDefault = formatStatementDefault }
	context.cloneOptions = function( options )
		local entity = options.entity;
		options.entity = nil;

		newOptions = mw.clone( options );
		options.entity = entity;
		newOptions.entity = entity;
		newOptions.frame = options.frame; -- На склонированном фрейме frame:expandTemplate()

		return newOptions;
	end;
	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 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

--[[
	Функция для оформления одного утверждения (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 = qualifier.datavalue.value.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 );

	options.qualifiers = statement.qualifiers;

	local result = context.formatSnak( options, statement.mainsnak, circumstances );
	if ( result and result ~= '' and options.references ) then
		result = result .. context.formatRefs( options, statement );
	end

	return result;
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 = '<span class="wikidata-snak ' .. mainSnakClass .. '"' .. hash .. '>'
	local after = '</span>'

	if snak.snaktype == 'somevalue' then
		if ( options['somevalue'] and options['somevalue'] ~= '' ) then
			result = options['somevalue'];
		else
			result = options.i18n['somevalue'];
		end
	elseif snak.snaktype == 'novalue' then
		if ( options['novalue'] and options['novalue'] ~= '' ) then
			result = options['novalue'];
		else
			result = options.i18n['novalue'];
		end
	elseif snak.snaktype == 'value' then
		result = formatDatavalue( context, options, snak.datavalue, snak.datatype );

		if ( circumstances.presumably ) then
			result = options.i18n.presumably .. result;
		end
		if ( circumstances.circa ) then
			result = options.i18n.circa .. result;
		end
	else
		throwError( 'unknown-snak-type' );
	end
	
	if ( not result or result == '' ) then
		return nil;
	end

	return before .. result .. after;
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 = 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 = '<span data-wikidata-qualifier-id="P2096" style="display:block">' .. caption .. '</span>';
	end

	if not string.find( value, '[%[%]%{%}]' ) then
		image = '[[File:' .. value .. '|frameless';
		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 caption ~= '' then
			image = image .. '<br>' .. caption;
		end
	else
		image = image .. caption .. getCategoryByCode( 'media-contains-markup' );
	end

	return image
end

--[[
	Fonction for render math formulas

	@param string Value.
	@param table Parameters.
	@return string Formatted string.
]]
function formatMath( value, options )
	return options.frame:extensionTag{ name = 'math', content = value };
end

--[[
	Функция для оформления внешних идентификаторов

	Принимает: объект-значение и таблицу параметров,
	Возвращает: строку оформленного текста
]]
local function formatExternalId( value, options )
	local formatter = options.formatter;

	if not formatter or formatter == '' then
		local wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, options.property:upper() )
		if wbStatus == true and propertyEntity then
			local isGoodFormat = false;
			local statements = propertyEntity:getBestStatements( 'P1793' );
			for _, statement in pairs( statements ) do
				if statement.mainsnak.snaktype == 'value' then
					local pattern = mw.ustring.gsub( statement.mainsnak.datavalue.value, '\\', '%' );
					pattern = mw.ustring.gsub( pattern, '{%d+,?%d*}', '+' );
					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
		end
	end

	if formatter and formatter ~= '' then
		local link = mw.ustring.gsub( mw.ustring.gsub( formatter, '$1', value ), ' ', '%%20' )

		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, sigfig )
		sigfig = sigfig or 12 -- округление до 12 знаков после запятой, на 13-м возникает ошибка в точности
		local mult = 10^sigfig;
		number = math.floor( number * mult + 0.5 ) / mult;

		return string.gsub( 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 wbStatus, unitEntity = pcall( mw.wikibase.getEntity, unitEntityId );
		if wbStatus == true and unitEntity then
			if unitEntity.claims.P2370 and
				unitEntity.claims.P2370[1].mainsnak.snaktype == 'value' and
				not value.upperBound and
				options.siConversion
			then
				conversionToSIunit = string.gsub( unitEntity.claims.P2370[1].mainsnak.datavalue.value.amount, '^%+', '' );
				if math.floor( math.log10( conversionToSIunit )) ~= math.log10( conversionToSIunit ) then
					-- Если не степени десятки (переводить сантиметры в метры не надо!)
					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, nil, {
				'P5061[language:' .. langCode .. ']',
				'P558[P282:' .. writingSystemElementId .. ', P407:' .. langElementId .. ']',
				'P558[!P282][!P407]'
			} );

			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 wbStatus, propertyEntity = pcall( mw.wikibase.getEntity, propertyId );
	if wbStatus ~= true or not propertyEntity then
		return nil;
	end

	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 .. options.frame:expandTemplate{ title = 'ref-' ..langRefCode }
							end
						end
					end
				end
			end
		end
	end

	return langRefs
end

local function getDefaultValueFunction( datavalue, datatype )
	-- вызов обработчиков по умолчанию для известных типов значений
	if datavalue.type == 'wikibase-entityid' then
		-- Entity ID
		return function( context, options, value ) return formatEntityId( context, options, getEntityIdFromValue( value ) ) end;
	elseif datavalue.type == 'string' then
		-- String
		if datatype and datatype == 'commonsMedia' then
			-- Media
			return function( context, options, value )
				if ( not options.caption or options.caption == '' )
						and ( 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.caption = qualifier.datavalue.value.text
							options.description = qualifier.datavalue.value.text
							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
				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 == 'math' then
			-- Math formula
			return function( context, options, value )
				return formatMath( value, options )
			end
		elseif datatype and datatype == 'url' then
			-- URL
			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
		return function( context, options, value ) return value end;
	elseif datavalue.type == 'monolingualtext' then
		-- моноязычный текст (строка с указанием языка)
		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
				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
		-- географические координаты
		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

--[[
	Функция для оформления идентификатора сущности

	Принимает: строку индентификатора (типа Q42) и таблицу параметров,
	Возвращает: строку оформленного текста
]]
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>' .. getCategoryByCode( 'links-to-entities-with-wikibase-error' );
	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 = p.extractCategory( context, options, { id = entityId } )

	-- получение ссылки по идентификатору
	local link = mw.wikibase.sitelink( entityId )
	if link then
		-- ссылка на категорию, а не добавление страницы в неё
		if mw.ustring.match( link, '^' .. mw.site.namespaces[ 14 ].name .. ':' ) then
			link = ':' .. link
		end
		if label then
			if ( contentLanguageCode ~= labelLanguageCode ) then
				return '[[' .. link .. '|' .. label .. ']]' .. getCategoryByCode( 'links-to-entities-with-missing-local-language-label' ) .. category;
			else
				return '[[' .. link .. '|' .. label .. ']]' .. category;
			end
		else
			return '[[' .. link .. ']]' .. category;
		end
	end

	if label then
		-- красная ссылка
		-- TODO: разобраться, почему не всегда есть options.frame
		local title = mw.title.new( label );
		if title and not title.exists and options.frame then
			local templateText = "{{Универсальная карточка|" .. entityId .. "}}%0A'''" .. label .. "''' — %0A%0A== Примечания ==%0A{{примечания}}%0A";
			local templateText = templateText .. "[[Категория:Википедия:Связать с элементом Викиданных|" .. entityId .. "]]";
			local preloadUrl = tostring( mw.uri.canonicalUrl( label, 'action=edit&preload=Ш:Preload/Викиданные&preloadparams[]=' .. templateText ));
			local redLink = options.frame:expandTemplate{ title='цветная ссылка', args = { '#ba0000', preloadUrl, label }};
			return '<span class="plainlinks">' .. redLink .. '</span><sup>[[:d:' .. entityId .. '|[d]]]</sup>' .. category;
		end

		-- TODO: перенести до проверки на существование статьи
		local sup = '';
		if ( not options.format or options.format ~= 'text' )
				and entityId ~= 'Q6581072' and entityId ~= 'Q6581097' -- TODO: переписать на format=text
				then
			sup = '<sup class="plainlinks noprint">[//www.wikidata.org/wiki/' .. entityId .. '?uselang=' .. contentLanguageCode .. ' [d&#x5d;]</sup>'
		end

		-- одноимённая статья уже существует - выводится текст и ссылка на ВД
		return '<span class="iw" data-title="' .. label .. '">' .. label
			.. sup
			.. '</span>' .. category
	end
	-- сообщение об отсутвии локализованного названия
	-- not good, but better than nothing
	return '[[:d:' .. entityId .. '|' .. entityId .. ']]<span style="border-bottom: 1px dotted; cursor: help; white-space: nowrap" title="В Викиданных нет русской подписи к элементу. Вы можете помочь, указав русский вариант подписи.">?</span>' .. getCategoryByCode( 'links-to-entities-with-missing-label' ) .. category;
end

--[[
	Функция для формирования категории на основе wikidata/config
]]
function p.extractCategory( context, options, value )
	local wbStatus, entity = pcall( mw.wikibase.getEntity, value.id )
	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 ) then
						if catEntity:getSitelink() then
							category = '[[' .. catEntity:getSitelink() .. ']]';
						end
					end
				end
			end
		end
	end
	return category;
end

--[[
	Функция для оформления утверждений (statement)
	Подробнее о утверждениях см. d:Wikidata:Glossary/ru

	Принимает: таблицу параметров
	Возвращает: строку оформленного текста, предназначенного для отображения в статье
]]
-- устаревшее имя, не использовать
function p.formatStatements( frame )
	return p.formatProperty( frame );
end

--[[
	Получение параметров, которые обычно используются для вывода свойства.
]]
function getPropertyParams( propertyId, datatype, params )
	local config = getConfig();

	-- Различные уровни настройки параметров, по убыванию приоритета
	local propertyParams = {};

	-- 1. Параметры, указанные явно при вызове
	if params then
		for key, value in pairs( params ) do
			if value ~= '' then
				propertyParams[ key ] = value;
			end
		end
	end

	-- 2. Настройки конкретного параметра
	if config[ 'properties' ] and config[ 'properties' ][ propertyId ] then
		for key, value in pairs( config[ 'properties' ][ propertyId ] ) 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
		for key, value in pairs( config[ 'presets' ][ propertyParams[ 'preset' ] ] ) do
			if propertyParams[ key ] == nil then
				propertyParams[ key ] = value;
			end
		end
	end

	-- 4. Настройки для типа данных
	if datatype and config[ 'datatypes' ] and config[ 'datatypes' ][ datatype ] then
		for key, value in pairs( config[ 'datatypes' ][ datatype ] ) do
			if propertyParams[ key ] == nil then
				propertyParams[ key ] = value;
			end
		end
	end

	-- 5. Общие настройки для всех свойств
	if config[ 'global' ] then
		for key, value in pairs( config[ 'global' ] ) do
			if propertyParams[ key ] == nil then
				propertyParams[ key ] = value;
			end
		end
	end

	return propertyParams;
end

function p.formatProperty( frame )
	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 );

	-- проброс всех параметров из шаблона {wikidata} и параметра from откуда угодно
	p_frame = 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

	args.plain = toBoolean( args.plain, false );
	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 args.plain then
			return value
		end

		-- обработчики по типу значения
		local wrapperExtraArgs = ''
		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' then
			value = formatCommonsMedia( value, args );
		elseif datatype == 'external-id' and not string.find( value, '[%[%]%{%}]' ) then
			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

		-- оборачиваем в тег для JS-функций
		if string.match( propertyId, '^P%d+$' ) then
			value = mw.text.trim( value )

			-- временная штрафная категория для исправления табличных вставок
			if ( propertyId ~= 'P166'
					and string.match( value, '<t[dr][ >]' )
					and not string.match( value, '<table >]' )
					and not string.match( value, '^%{%|' ) ) then
				value = value .. getCategoryByCode( 'value-contains-table' )
			else
				-- значений с блочными тегами остаются блоком, текст встраиваем в строку
				if ( string.match( value, '\n' )
						or string.match( value, '<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

		-- добавляем категорию-маркер
		if not args.nocat then
			local pageTitle = mw.title.getCurrentTitle();
			if pageTitle.namespace == 0 then
				value = value .. getCategoryByCode( 'local-value-present' );
			end
		end

		return value
	end

	if ( args.plain ) then -- вызова стандартного обработчика без оформления, если передана опция plain
		local callArgs = { propertyId };
		if args.entityId then
			callArgs.from = args.entityId;
		end
		return frame:callParserFunction( '#property', callArgs );
	end

	g_frame = frame
	-- после проверки всех аргументов -- вызов функции оформления для свойства (набора утверждений)
	return formatProperty( args )
end

--[[
	Функция оформления ссылок на источники (reference)
	Подробнее о ссылках на источники см. d:Wikidata:Glossary/ru

	Экспортируется в качестве зарезервированной точки для вызова из функций-расширения вида claim-module/claim-function через context
	Вызов из других модулей напрямую осуществляться не должен (используйте frame:expandTemplate вместе с одним из специлизированных шаблонов вывода значения свойства).

	Принимает: объект-таблицу утверждение
	Возвращает: строку оформленных ссылок для отображения в статье
]]
function 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 ) then
		return '';
	end

	local references = {};
	if ( statement.references ) then

		local allReferences = statement.references;
		local hasPreferred = false;
		local displayCount = 0;
		for _, reference in pairs( statement.references ) do
			if ( reference.snaks
					and reference.snaks.P248
					and reference.snaks.P248[1]
					and reference.snaks.P248[1].datavalue
					and reference.snaks.P248[1].datavalue.value.id ) then
				local entityId = reference.snaks.P248[1].datavalue.value.id;
				if ( preferredSources[entityId] ) then
					hasPreferred = true;
				end
			end
		end

		for _, reference in pairs( statement.references ) do
			local display = true;
			if ( hasPreferred ) then
				if ( reference.snaks
						and reference.snaks.P248
						and reference.snaks.P248[1]
						and reference.snaks.P248[1].datavalue
						and reference.snaks.P248[1].datavalue.value.id ) then
					local entityId = reference.snaks.P248[1].datavalue.value.id;
					if ( deprecatedSources[entityId] ) then
						display = false;
					end
				end
			end
			if ( display == true ) then
				if ( displayCount > 2 ) then
					if ( options.entity and options.property ) then
						table.remove( references );
						local moreReferences = '<sup>[[d:' .. options.entity.id .. '#' .. string.upper( options.property ) .. '|[…]]]</sup>';
						table.insert( references, moreReferences );
					end
					break;
				end;
				local refText = moduleSources.renderReference( g_frame, options.entity, reference );
				if ( refText ~= '' ) then
					table.insert( references, refText );
					displayCount = displayCount + 1;
				end
			end
		end
	end
	return table.concat( references );
end

return p