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

Материал из ChronoWiki
Перейти к навигацииПерейти к поиску
 
м (1 версия импортирована)
 
(не показаны 4 промежуточные версии 3 участников)
Строка 1: Строка 1:
local p = {};
+
local p = {}
local u = require('Module:Sources-utils')
 
  
local i18nDefaultLanguage = 'ru';
+
local utils = require('Module:Sources/utils')
  
local i18nEtAlDefault = ' et al.';
+
local i18nDefaultLanguage = 'ru'
 +
 
 +
local i18nEtAlDefault = ' et al.'
 
local i18nEtAl = {
 
local i18nEtAl = {
 
ru = ' и др.',
 
ru = ' и др.',
Строка 16: Строка 17:
 
it = '',
 
it = '',
 
ru = 'под ред. ',
 
ru = 'под ред. ',
 +
}
 +
 +
local i18nTranslators = {
 +
fr = '',
 +
de = '',
 +
es = '',
 +
en = '',
 +
it = '',
 +
ru = 'пер. ',
 
}
 
}
  
Строка 52: Строка 62:
  
  
local monthg = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', "сентября", "октября", "ноября", "декабря"};
+
local monthg = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', "сентября", "октября", "ноября", "декабря"}
  
 
local PREFIX_CITEREF = "CITEREF_";
 
local PREFIX_CITEREF = "CITEREF_";
  
local options_commas = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false };
+
-- Returns formatted pair {Family name(s), First name(s)}
local options_commas_short = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false, short = true };
+
local function tokenizeName( fullName )
local options_commas_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = true, preferids = false };
+
local start = '^%s*' -- matches beginning of the string + arbitrary number of spaces
local options_commas_it = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false };
+
local finish = '%s*$' -- matches end of the string + arbitrary number of spaces
local options_commas_it_short = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false, short = true };
+
local comma = '\,%s+' -- matches comma + single or more spacing character
local options_commas_it_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = true , preferids = false };
+
local space = '%s+' -- matches single or more spacing character
local options_citetypes = { separator = ' ', conjunction = ' ', format = function( src ) return 'citetype_' .. src end, nolinks = true , preferids = true };
+
local name = '(%a[%a\-\']*)\.?' -- matches single name, have to start with letter, can contain apostrophe and hyphen, may end with dot
 
+
local surname = '(%a[%a\-\']*)' -- same as name, but can't end with dot
local options_commas_authors = { separator = ', ', conjunction = ', ', format = personNameToAuthorName, nolinks = false, preferids = false };
+
local options_commas_responsible = { separator = ', ', conjunction = ', ', format = personNameToResponsibleName, nolinks = false, preferids = false };
+
local f, i = mw.ustring.match(fullName, start .. surname .. comma .. name .. finish)
 
+
if f then
local options_arxiv = { separator = '; ', conjunction = '; ', format = function( id ) return '[http://arxiv.org/abs/' .. id .. ' arXiv:' .. id .. ']' end, nolinks = true, preferids = false };
+
mw.log('tokenizeName: «' .. fullName .. '»: have «Fa, Im» match')
local options_doi = { separator = '; ', conjunction = '; ', format = function( doi ) return '[http://dx.doi.org/' .. doi .. ' doi:' .. doi .. ']' end, nolinks = true, preferids = false };
+
return {f, mw.ustring.sub( i, 1, 1 ) .. '.'}
local options_issn = { separator = '; ', conjunction = '; ', format = function( issn ) return '[https://www.worldcat.org/issn/' .. issn .. ' ' .. issn .. ']' end, nolinks = true, preferids = false };
 
local options_pmid = { separator = '; ', conjunction = '; ', format = function( pmid ) return '[https://www.ncbi.nlm.nih.gov/pubmed/?term=' .. pmid .. ' PMID:' .. pmid .. ']' end, nolinks = true, preferids = false };
 
 
 
function renderSource( context, src )
 
options_commas_authors.format = personNameToAuthorName;
 
options_commas_responsible.format = personNameToResponsibleName;
 
 
 
context.lang = getLangCode( getSingle( src.lang ) ) or i18nDefaultLanguage;
 
 
 
preprocessPlaces( src, context.lang );
 
 
 
src.title = src.title or getSingle( src.url ) or '\'\'(unspecified title)\'\''
 
 
 
if ( src.sourceId and not src.url ) then
 
local entity = getEntity( context, src.sourceId );
 
if ( entity.sitelinks and entity.sitelinks[ context.lang .. 'wikisource'] ) then
 
src.url = ':' .. context.lang .. ':s:' .. entity.sitelinks[ context.lang .. 'wikisource' ].title;
 
end
 
 
end
 
end
 
+
if ( not src.year and src.dateOfPublication ) then
+
local f, i, o = mw.ustring.match(fullName, start .. surname .. comma .. name .. space .. name .. finish)
local date = getSingle( src.dateOfPublication );
+
if f then
src.year = mw.ustring.sub( date, 2, 5 );
+
mw.log( 'tokenizeName: «' .. fullName .. '»: have «Fa, Im Ot» match')
 +
return {f, mw.ustring.sub( i, 1, 1 ) .. '. '
 +
.. mw.ustring.sub( o, 1, 1 ) .. '.'}
 
end
 
end
  
if ( not src.year and src.dateOfCreation ) then
+
local f1, f2, i = mw.ustring.match(fullName, start .. surname .. space .. surname .. comma .. name .. finish)
local date = getSingle( src.dateOfCreation );
+
if f1 then
src.year = mw.ustring.sub( date, 2, 5 );
+
mw.log('tokenizeName: «' .. fullName .. '»: have «Fa Fa, Im» match')
 +
return {f1 .. ' ' .. f2, mw.ustring.sub( i, 1, 1 ) .. '.'}
 
end
 
end
 
+
local result;
+
local i, o, f = mw.ustring.match(fullName, start .. name .. space .. name .. space .. 'оглы' .. space .. surname .. finish)
if ( src.author ) then
+
if f then
result = getPeopleAsWikitext( context, src.author, options_commas_authors );
+
mw.log('tokenizeName: «' .. fullName .. '»: have «Im Ot оглы Fa» match')
 +
return {f, mw.ustring.sub(i, 1, 1) .. '. ' .. mw.ustring.sub(o, 1, 1) .. '.'}
 
end
 
end
if ( not isEmpty( result )) then
 
result = '<i class="wef_low_priority_links">' .. result .. '</i> ';
 
else
 
result = '';
 
end
 
 
if ( src.part ) then
 
if ( src.url ) then
 
result = result .. wrapInUrl( src.url, toString( context, src.part, options_commas_nolinks ) );
 
else
 
result = result .. toString( context, src.part, options_commas );
 
end
 
result = result .. ' // ' .. toString( context, src.title, options_commas );
 
else
 
-- title only
 
if ( src.url ) then
 
result = result .. wrapInUrl( src.url, toString( context, src.title, options_commas_nolinks ) );
 
else
 
result = result .. toString( context, src.title, options_commas );
 
end
 
end
 
  
if ( src.subtitle ) then
+
local i1, i2, f = mw.ustring.match(fullName, start .. name .. space .. name .. space .. 'de' .. space .. surname .. finish)
result = result .. ": " .. toString( context, src.subtitle, options_commas );
+
if f then
 +
mw.log('tokenizeName: «' .. fullName .. : have «Im Im de Fa» match')
 +
return {f, mw.ustring.sub( i1, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( i2, 1, 1 ) .. '.'}
 
end
 
end
 
+
if ( src.originaltitle ) then
+
-- Try matching k names + surname
result = result .. ' = ' .. toString( context, src.originaltitle, options_commas );
+
for k = 1, 4 do
end
+
pattern = start .. string.rep(name .. space, k) .. surname .. finish
 
+
matched = {mw.ustring.match(fullName, pattern)}
if ( src.publication ) then
+
if #matched ~= 0 then
if ( type( src.publication.title or '') ~= 'string' ) then error('type of src.publication.title is not string but ' .. type( src.publication.title ) ) end;
+
mw.log('tokenizeName: «' .. fullName .. '»: have «Im (x' .. k .. ') Fa» match')
 
+
for i = 1, k do
result = result .. ' // ' .. toString( context, src.publication, options_commas_it_short );
+
matched[i] = mw.ustring.sub(matched[i], 1, 1)
if ( src.publication.subtitle ) then
 
result = result .. ': ' .. toString( context, src.publication.subtitle, options_commas_it_short );
 
end
 
end
 
 
 
result = result .. '<span class="wef_low_priority_links">';
 
 
 
if ( src.editor ) then
 
local prefix = i18nEditors[ context.lang ] or i18nEditors[ i18nDefaultLanguage ];
 
result = result .. ' / ' .. prefix .. getPeopleAsWikitext( context, src.editor, options_commas_responsible );
 
end
 
 
 
if ( src.edition ) then
 
result = result .. ' — ' .. toString( context, src.edition, options_commas );
 
end
 
 
 
if ( src.place or src.publisher or src.year ) then
 
result = result .. ' — ';
 
if ( src.place ) then
 
result = result .. toString( context, src.place, options_commas_short );
 
if ( src.publisher or src.year ) then
 
result = result .. ': ';
 
end
 
end
 
if ( src.publisher ) then
 
result = result .. toString( context, src.publisher, options_commas_short );
 
if ( src.year ) then
 
result = result .. ', ';
 
 
end
 
end
 +
return {matched[k + 1], table.concat(matched, '.&nbsp;', 1, k) .. '.'}
 
end
 
end
if ( src.year ) then
 
result = result .. toString( context, src.year, options_commas );
 
end
 
result = result .. '.';
 
 
end
 
end
+
if ( src.volume or src.issue ) then
+
mw.log('Unmatched any pattern: «' .. fullName .. '»')
result = result .. ' — ';
+
return {fullName}
if ( src.volume ) then
+
end
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
 
result = result .. letter .. '&nbsp;' .. toString( context, src.volume, options_commas );
 
if ( src.issue ) then
 
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
 
result = result .. ', ' .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
 
else
 
result = result .. '.';
 
end
 
else
 
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
 
result = result .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
 
end
 
end
 
  
if ( src.pages ) then
+
local function personNameToAuthorName( fullName )
local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ];
+
if not fullName then return fullName end
local strPages = toString( context, src.pages, options_commas );
+
local tokenized = tokenizeName(fullName)
strPages = mw.ustring.gsub( strPages, '[-—]', '–' );
+
if #tokenized == 1 then
result = result .. ' — ' .. letter .. '&nbsp;' .. strPages .. '.';
+
return tokenized[1]
 +
else
 +
return tokenized[1] .. '&nbsp;' .. tokenized[2]
 
end
 
end
 +
end
  
if ( src.numberOfPages ) then
+
local function personNameToResponsibleName( fullName )
local letter = i18nNumberOfPages[ context.lang ] or i18nNumberOfPages[ i18nDefaultLanguage ];
+
if not fullName then return fullName end
result = result .. ' — ' .. toString( context, src.numberOfPages, options_commas ) .. '&nbsp;' .. letter;
+
local tokenized = tokenizeName(fullName)
 +
if #tokenized == 1 then
 +
return tokenized[1]
 +
else
 +
return tokenized[2] .. '&nbsp;' .. tokenized[1]
 
end
 
end
 +
end
  
if ( src.bookSeries ) then
 
result = result .. ' — (' .. toString( context, src.bookSeries, options_commas )
 
  
if ( src.bookSeriesVolume or src.bookSeriesIssue ) then
+
local options_commas = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false };
result = result .. '; ';
+
local options_commas_short = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false, short = true };
if ( src.bookSeriesVolume ) then
+
local options_commas_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = true, preferids = false };
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
+
local options_commas_it = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false };
result = result .. letter .. '&nbsp;' .. toString( context, src.bookSeriesVolume, options_commas );
+
local options_commas_it_short = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false, short = true };
if ( src.bookSeriesIssue ) then
+
local options_commas_it_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = true , preferids = false };
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
+
local options_citetypes = { separator = ' ', conjunction = ' ', format = function( src ) return 'citetype_' .. src end, nolinks = true , preferids = true };
result = result .. ', ' .. letter .. '&nbsp;' .. toString( context, src.bookSeriesIssue, options_commas );
 
else
 
result = result;
 
end
 
else
 
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
 
result = result .. letter .. '&nbsp;' .. toString( context, src.bookSeriesIssue, options_commas );
 
end
 
end
 
  
result = result .. ')';
+
local options_commas_authors = { separator = ', ', conjunction = ', ', format = personNameToAuthorName, nolinks = false, preferids = false };
end
+
local options_commas_responsible = { separator = ', ', conjunction = ', ', format = personNameToResponsibleName, nolinks = false, preferids = false };
  
if ( src.tirage ) then
+
local options_arxiv = { separator = '; ', conjunction = '; ', format = function( id ) return '[http://arxiv.org/abs/' .. id .. ' arXiv:' .. id .. ']' end, nolinks = true, preferids = false };
local tirageTemplate = i18nTirage[ context.lang ] or i18nTirage[ i18nDefaultLanguage ];
+
local options_doi = { separator = '; ', conjunction = '; ', format = function( doi ) return '[http://dx.doi.org/' .. doi .. ' doi:' .. doi .. ']' end, nolinks = true, preferids = false };
result = result .. ' ' .. toString( context, src.tirage, { separator = '; ', conjunction = ';', format = function( data ) return mw.ustring.format(tirageTemplate, data) end } );
+
local options_issn = { separator = '; ', conjunction = '; ', format = function( issn ) return '[https://www.worldcat.org/issn/' .. issn .. ' ' .. issn .. ']' end, nolinks = true, preferids = false };
end
+
local options_pmid = { separator = '; ', conjunction = '; ', format = function( pmid ) return '[https://www.ncbi.nlm.nih.gov/pubmed/?term=' .. pmid .. ' PMID:' .. pmid .. ']' end, nolinks = true, preferids = false };
  
if ( src.isbn ) then
+
local function getPersonNameAsLabel( context, entityId, providedLabel, options )
result = result .. ' — ISBN ' .. toString( context, src.isbn, options_commas );
+
-- would custom label provided we don't need to check entity at all
 +
if ( not utils.isEmpty( providedLabel ) ) then
 +
mw.log( 'Custom label provided for ' .. entityId );
 +
return options.format( providedLabel );
 
end
 
end
  
if ( src.issn ) then
+
local entity = utils.getEntity( context, entityId );
result = result .. ' — ISSN ' .. toString( context, src.issn, options_issn );
+
if ( not entity ) then return '\'\'(entity ' .. entityId .. ' is missing)\'\'' end;
end
 
  
if ( src.doi ) then
+
local personName = nil;
result = result .. ' ' .. toString( context, src.doi, options_doi );
+
-- support only labels so far
 +
if ( entity.labels[ context.lang ] ) then
 +
personName = entity.labels[ context.lang ].value;
 +
mw.log('Got person name of ' .. entityId .. ' from label: «' .. personName .. '»' )
 
end
 
end
  
if ( src.pmid ) then
+
if ( not utils.isInstanceOf( entity, 'Q5' ) ) then
result = result .. ' ' .. toString( context, src.pmid, options_pmid );
+
mw.log( 'Entity ' .. entityId .. ' is not a person' );
 +
return personName;
 
end
 
end
  
if ( src.arxiv ) then
+
if ( utils.isEmpty( personName ) ) then
result = result .. ' ' .. toString( context, src.arxiv, options_arxiv );
+
return '\'\'(not translated to ' .. context.lang .. ')\'\'';
 +
else
 +
return options.format( personName );
 
end
 
end
 
if ( src.sourceId ) then
 
if ( src.type and src.sourceId ) then
 
-- wrap into span to target from JS
 
result = '<span class="wikidata_cite ' .. toString( context, src.type, options_citetypes ) .. '" data-entity-id="' .. getSingle( src.sourceId ) .. '">' .. result .. '</span>'
 
else
 
result = '<span class="wikidata_cite citetype_unknown" data-entity-id="' .. getSingle( src.sourceId ) .. '">' .. result .. '</span>'
 
end
 
end
 
 
if ( src.accessdate ) then
 
local date = getSingle( src.accessdate );
 
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T";
 
local y, m, d = mw.ustring.match( date , pattern );
 
y,m,d = tonumber(y),tonumber(m),tonumber(d);
 
result = result .. " <small>Проверено " .. tostring(d) .. " " .. monthg[m]  .. " " .. tostring(y) .. ".</small>";
 
end
 
 
result = result .. '</span>';
 
 
    -- append invisible links to all elements used by source for tracking purposes
 
    local result = result .. '<div style="display:none">';
 
for key, entity in pairs( context.cache ) do
 
result = result .. '<a href="https://wikidata.org' ..  mw.uri.localUrl('Track:' .. key).path .. '"></a>';
 
end
 
    result = result ..'</div>'
 
 
return {text = result, code = src.code};
 
 
end
 
end
  
function renderShortReference( src )
+
local function getPersonNameAsWikitext( context, entityId, customLabel, options )
context = {
+
local personName = getPersonNameAsLabel( context, entityId, customLabel, options);
cache = {},
+
if ( personName == nil ) then
lang = getSingle( src.lang ) or i18nDefaultLanguage;
+
return nil;
};
 
src.title = src.title or '\'\'(unspecified title)\'\''
 
 
 
local result = '[[#' .. PREFIX_CITEREF .. src.code .. '|';
 
if ( src.author ) then
 
result = result .. toString( context, src.author, options_authors_nolinks );
 
else
 
result = result .. toString( context, src.title, options_commas_it_nolinks );
 
end
 
result = result .. ']]'
 
 
 
if ( src.year ) then
 
result = result .. ', ' .. toString( context, src.year, options_commas );
 
end
 
 
 
if ( src.volume ) then
 
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
 
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.volume, options_commas ) .. '.';
 
 
end
 
end
  
if ( src.issue ) then
+
local link = utils.getElementLink( context, entityId, nil );
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
+
return utils.wrapInUrl( link, personName );
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
 
end
 
 
if ( src.pages ) then
 
local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ];
 
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.pages, options_commas ) .. '.';
 
end
 
 
 
end
 
end
  
function getPeopleAsWikitext( context, value, options )
+
local function getPeopleAsWikitext( context, value, options )
if ( type( value ) == 'string' ) then
+
if type( value ) == 'string' then
return options.format( value );
+
return options.format( value )
elseif ( type( value ) == 'table' ) then
+
elseif type( value ) == 'table' then
if ( value.id ) then
+
if value.id then
 
-- this is link
 
-- this is link
if ( options.preferids ) then
+
if options.preferids then
return value.id;
+
return value.id
 
else
 
else
if ( options.nolinks ) then
+
if options.nolinks then
return getPersonNameAsLabel( context, value.id, value.label, options );
+
return getPersonNameAsLabel( context, value.id, value.label, options )
 
else
 
else
return getPersonNameAsWikitext( context, value.id, value.label, options );
+
return getPersonNameAsWikitext( context, value.id, value.label, options )
 
end
 
end
 
end
 
end
 
end
 
end
 
+
local resultList = {};
+
local maxAuthors = 10 -- need some restrictions, as some publications have enormous amount of authors (e.g. 115 authors of Q68951544)
 +
local resultList = {}
 
for i, tableValue in pairs( value ) do
 
for i, tableValue in pairs( value ) do
local nextWikitext = getPeopleAsWikitext( context, tableValue, options );
+
local nextWikitext = getPeopleAsWikitext( context, tableValue, options )
if ( not isEmpty( nextWikitext ) ) then
+
if not utils.isEmpty( nextWikitext ) then
table.insert( resultList, nextWikitext );
+
table.insert( resultList, nextWikitext )
if ( #resultList == 4 ) then
+
if #resultList == maxAuthors + 1 then
-- even 4 is too much, but we preserve 4th to mark that "it's more than 3"
+
-- keep one more to indicate that there are too many
break;
+
break
 
end
 
end
 
end
 
end
 
end
 
end
  
local resultWikitext = '';
+
local resultWikitext = ''
 
for i, wikitext in pairs( resultList ) do
 
for i, wikitext in pairs( resultList ) do
if ( i == 4 ) then
+
if i == maxAuthors + 1 then
resultWikitext = resultWikitext .. ( i18nEtAl[ context.lang ] or i18nEtAlDefault );
+
resultWikitext = resultWikitext .. ( i18nEtAl[ context.lang ] or i18nEtAlDefault )
 
break;
 
break;
 
end
 
end
if ( i ~= 1 ) then
+
if i ~= 1 then
resultWikitext = resultWikitext .. ', ';
+
resultWikitext = resultWikitext .. ', '
 
end
 
end
resultWikitext = resultWikitext .. wikitext;
+
resultWikitext = resultWikitext .. wikitext
 
end
 
end
  
return resultWikitext;
+
return resultWikitext
 
end
 
end
  
return options.format( '(unknown type)' );
+
return options.format( '(unknown type)' )
 
end
 
end
  
function getPersonNameAsWikitext( context, entityId, customLabel, options )
+
local function generateAuthorLinks(context, src)
local personName = getPersonNameAsLabel( context, entityId, customLabel, options);
+
local result = ''
if ( personName == nil ) then
+
if src.author then
return nil;
+
result = getPeopleAsWikitext( context, src.author, options_commas_authors )
 +
result = '<i class="wef_low_priority_links">' .. result .. '</i> '
 
end
 
end
 
+
return result
local link = getElementLink( context, entityId, nil );
 
return wrapInUrl( link, personName );
 
 
end
 
end
  
function getPersonNameAsLabel( context, entityId, providedLabel, options )
+
local function appendProperty(result, context, src, conjunctor, property, url)
-- would custom label provided we don't need to check entity at all
+
if src[property] then
if ( not isEmpty( providedLabel ) ) then
+
if url and src[url] then
mw.log( 'Custom label provided for ' .. entityId );
+
result = result .. conjunctor .. utils.wrapInUrl( src[url], utils.toString( context, src[property], options_commas_nolinks ) )
return options.format( providedLabel );
+
else
 +
result = result .. conjunctor .. utils.toString( context, src[property], options_commas )
 +
end
 
end
 
end
 +
return result
 +
end
  
local entity = getEntity( context, entityId );
+
local function appendTitle(result, context, src)
if ( not entity ) then return '\'\'(entity ' .. entityId .. ' is missing)\'\'' end;
+
conjunctor = ''
 +
if src.part then
 +
result = appendProperty(result, context, src, '', 'part', 'parturl')
 +
conjunctor = ' // '
 +
end
 +
result = appendProperty(result, context, src, conjunctor, 'title', 'url')
 +
return result
 +
end
  
local personName = nil;
+
local function appendLanguage(result, context, src)
-- support only labels so far
+
if context.lang ~= i18nDefaultLanguage then
if ( entity.labels[ context.lang ] ) then
+
local langs = require('Module:Languages')
personName = entity.labels[ context.lang ].value;
+
result = result .. langs.list_ref(p.currentFrame:newChild{ args = {context.lang} })
mw.log('Got person name of ' .. entityId .. ' from label: «' .. personName .. '»' )
 
 
end
 
end
 +
return result
 +
end
  
if ( not isInstanceOf( entity, 'Q5' ) ) then
+
local function appendSubtitle(result, context, src)
mw.log( 'Entity ' .. entityId .. ' is not a person' );
+
return appendProperty(result, context, src, ': ', 'subtitle')
return personName;
+
end
end
 
  
if ( isEmpty( personName ) ) then
+
local function appendOriginalTitle(result, context, src)
return '\'\'(not translated to ' .. context.lang .. ')\'\'';
+
return appendProperty(result, context, src, ' = ', 'originaltitle')
else
 
return options.format( personName );
 
end
 
 
end
 
end
  
function personNameToAuthorName( fullName )
+
local function appendPublication(result, context, src)
if ( not fullName ) then return fullName; end
+
if src.publication then
 
+
if type( src.publication.title or '') ~= 'string' then
local f, i, o = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)\,%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$' );
+
error('type of src.publication.title is not string but ' .. type( src.publication.title ) )
if ( f ) then
+
end
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Fa, I. O.» match' );
+
return f .. '&nbsp;'
+
result = result .. ' // ' .. utils.toString( context, src.publication, options_commas_it_short )
.. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;'
+
if src.publication.subtitle then
.. mw.ustring.sub( o, 1, 1 ) .. '.';
+
result = result .. ': ' .. utils.toString( context, src.publication.subtitle, options_commas_it_short )
 +
end
 
end
 
end
 +
return result
 +
end
  
local f1, f2, i = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)\,%s(%a[%a\-]*)%s*$' );
+
local function appendEditor(result, context, src)
if ( f1 ) then
+
if src.editor or src.translator then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Fa Fa, I» match' );
+
result = result .. ' / '
return f1 .. '&nbsp;' .. f2 .. '&nbsp;'
+
if src.editor then
.. mw.ustring.sub( i, 1, 1 ) .. '.';
+
local prefix = i18nEditors[ context.lang ] or i18nEditors[ i18nDefaultLanguage ]
 +
result = result .. prefix .. getPeopleAsWikitext( context, src.editor, options_commas_responsible )
 +
if src.translator then
 +
result = result .. ', '
 +
end
 +
end
 +
if src.translator then
 +
local prefix = i18nTranslators[ context.lang ] or i18nTranslators[ i18nDefaultLanguage ]
 +
result = result .. prefix .. getPeopleAsWikitext( context, src.translator, options_commas_responsible )
 +
end
 
end
 
end
 +
return result
 +
end
  
local i, o, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
+
local function appendEdition(result, context, src)
if ( f ) then
+
return appendProperty(result, context, src, ' ', 'edition')
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. Fa» match' );
+
end
return f .. '&nbsp;' .. i .. '.&nbsp;' .. o .. '.';
 
end
 
  
local i1, i2, i3, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
+
local function appendPublicationData(result, context, src)
if ( f ) then
+
if src.place or src.publisher or src.year then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
+
result = result .. ' — '
return f .. '&nbsp;' .. i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.';
+
if src.place then
 +
result = result .. utils.toString( context, src.place, options_commas_short )
 +
if src.publisher or src.year then
 +
result = result .. ': '
 +
end
 +
end
 +
if src.publisher then
 +
result = result .. utils.toString( context, src.publisher, options_commas_short )
 +
if src.year then
 +
result = result .. ', '
 +
end
 +
end
 +
if src.year then
 +
result = result .. utils.toString( context, src.year, options_commas )
 +
end
 +
result = result .. '.';
 
end
 
end
 +
return result
 +
end
  
    -- Joel J. P. C. Rodrigues
+
local function appendVolumeAndIssue(result, context, src)
local i1, i2, i3, i4, f = mw.ustring.match( fullName, '^%s*(%a)[%a\-]+%s(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
+
if src.volume or src.issue then
if ( f ) then
+
result = result .. ' — '
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
+
local letter_vol = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ]
return f .. '&nbsp;' .. i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. i4 .. '.';
+
local letter_iss = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ]
end
+
if src.volume then
 +
result = appendProperty(result, context, src, letter_vol .. '&nbsp;', 'volume')
 +
result = appendProperty(result, context, src, ', ' .. letter_iss .. '&nbsp;', 'issue')
 +
else
 +
result = appendProperty(result, context, src, letter_iss .. '&nbsp;', 'issue')
 +
end
 +
result = result .. '.'
 +
end
 +
return result
 +
end
  
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a)\.%s(%a[%a\-]*)%s*$');
+
local function appendPages(result, context, src)
if ( f ) then
+
if src.pages then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im O. Fa» match' );
+
local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ]
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. o .. '.';
+
local strPages = utils.toString( context, src.pages, options_commas )
 +
strPages = mw.ustring.gsub( strPages, '[-—]', '' );
 +
result = result .. ' ' .. letter .. '&nbsp;' .. strPages .. '.'
 
end
 
end
 +
return result
 +
end
  
local i1, i2, i3, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a)\.%s(%a)\.%s(%a[%a\-]*)%s*$');
+
local function appendNumberOfPages(result, context, src)
if ( f ) then
+
if src.numberOfPages then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im I. I. Fa» match' );
+
local letter = i18nNumberOfPages[ context.lang ] or i18nNumberOfPages[ i18nDefaultLanguage ]
return f .. '&nbsp;' .. mw.ustring.sub( i1, 1, 1 ) .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.';
+
result = appendProperty(result, context, src, ' ', 'numberOfPages') .. '&nbsp;' .. letter
 
end
 
end
 +
return result
 +
end
  
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$');
+
local function appendBookSeries(result, context, src)
if ( f ) then
+
if src.bookSeries then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Ot Fa» match' );
+
result = appendProperty(result, context, src, ' (', 'bookSeries')
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.';
+
if src.bookSeriesVolume or src.bookSeriesIssue then
 +
result = result .. '; '
 +
local letter_vol = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ]
 +
local letter_iss = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ]
 +
if ( src.bookSeriesVolume ) then
 +
result = appendProperty(result, context, src, letter_vol .. '&nbsp;', 'bookSeriesVolume')
 +
result = appendProperty(result, context, src, ', ' .. letter_iss .. '&nbsp;', 'bookSeriesIssue')
 +
else
 +
result = appendProperty(result, context, src, letter_iss .. '&nbsp;', 'bookSeriesIssue')
 +
end
 +
end
 +
result = result .. ')'
 
end
 
end
 +
return result
 +
end
  
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]+)%s(%a[%a\-]+)%s+оглы%s+(%a[%a\-]+)%s*$');
+
local function appendTirage(result, context, src)
if ( f ) then
+
if src.tirage then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Ot оглы Fa» match' );
+
local tirageTemplate = i18nTirage[ context.lang ] or i18nTirage[ i18nDefaultLanguage ]
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.';
+
result = result .. ' ' .. utils.toString( context, src.tirage, { separator = '; ', conjunction = '; ', format = function( data ) return mw.ustring.format(tirageTemplate, data) end } )
 
end
 
end
 +
return result
 +
end
  
local i1, i2, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]+)%s(%a[%a\-]+)%s+de%s+(%a[%a\-]+)%s*$');
+
local function appendIdentifiers(result, context, src)
if ( f ) then
+
if src.isbn  then result = result .. ' — ISBN ' .. utils.toString( context, src.isbn, options_commas ) end
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I1 I2 de Fa» match' );
+
if src.issn  then result = result .. ' — ISSN ' .. utils.toString( context, src.issn, options_issn ) end
return f .. '&nbsp;' .. mw.ustring.sub( i1, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( i2, 1, 1 ) .. '.';
+
if src.doi  then result = result .. ' ' .. utils.toString( context, src.doi, options_doi ) end
end
+
if src.pmid  then result = result .. ' ' .. utils.toString( context, src.pmid, options_pmid ) end
 +
if src.arxiv then result = result .. ' — ' .. utils.toString( context, src.arxiv, options_arxiv ) end
 +
return result
 +
end
  
local i, f = mw.ustring.match( fullName, '^%s*(%a[%a\-\']+)%s(%a[%a\-\']+)%s*$');
+
local function appendSourceId(result, context, src)
if ( f ) then
+
if src.sourceId then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Fa» match' );
+
local citetype = src.type and utils.toString(context, src.type, options_citetypes) or 'citetype_unknown'
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.';
+
result = '<span class="wikidata_cite ' .. citetype .. '" data-entity-id="' .. utils.getSingle(src.sourceId) .. '">' .. result .. '</span>'
 
end
 
end
 
+
return result
mw.log( 'Unmatched any pattern: «' .. fullName .. '»' );
 
return fullName;
 
 
end
 
end
  
function personNameToResponsibleName( fullName )
+
local function appendAccessDate(result, context, src)
if ( not fullName ) then return fullName; end
+
if src.accessdate then
 
+
local date = utils.getSingle(src.accessdate)
local f, i, o = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)\,%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$' );
+
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T";
if ( f ) then
+
local y, m, d = mw.ustring.match(date, pattern)
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Fa, I. O.» match' );
+
y, m, d = tonumber(y), tonumber(m), tonumber(d)
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
+
local date_str = (d > 0 and ' ' .. tostring(d) or '')
 +
  .. (m > 0 and ' ' .. monthg[m] or '')
 +
  .. (y > 0 and ' ' .. tostring(y) or '')
 +
result = result .. " <small>Проверено" .. date_str .. ".</small>"
 
end
 
end
 +
return result
 +
end
  
local f1, f2, i = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)\,%s(%a[%a\-]*)%s*$' );
+
local function populateUrl(context, src)
if ( f1 ) then
+
if src.sourceId and not src.url then
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Fa Fa, I» match' );
+
local entity = utils.getEntity(context, src.sourceId)
return  mw.ustring.sub( i, 1, 1 ) .. '&nbsp;' .. f1 .. '&nbsp;' .. f2;
+
if entity.sitelinks and entity.sitelinks[context.lang .. 'wikisource'] then
end
+
src.url = ':' .. context.lang .. ':s:' .. entity.sitelinks[context.lang .. 'wikisource'].title
 
+
end
local i, o, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
 
if ( f ) then
 
mw.log( 'v: «' .. fullName .. '»: have «I. O. Fa» match' );
 
return i .. '.&nbsp;' .. o .. '.&nbsp;' .. f;
 
end
 
 
 
local i1, i2, i3, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
 
if ( f ) then
 
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
 
return  i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. f;
 
end
 
 
 
    -- Joel J. P. C. Rodrigues
 
local i1, i2, i3, i4, f = mw.ustring.match( fullName, '^%s*(%a)[%a\-]+%s(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
 
if ( f ) then
 
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
 
return  i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. i4 .. '.&nbsp;' .. f;
 
end
 
 
 
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a)\.%s(%a[%a\-]*)%s*$');
 
if ( f ) then
 
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im O. Fa» match' );
 
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. o .. '.&nbsp;' .. f;
 
end
 
 
 
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$');
 
if ( f ) then
 
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Ot Fa» match' );
 
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
 
 
end
 
end
 +
end
  
local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]+)%s(%a[%a\-]+)%s+оглы%s+(%a[%a\-]+)%s*$');
+
local function populateYear(src)
if ( f ) then
+
if not src.year and src.dateOfPublication then
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Ot оглы Fa» match' );
+
local date = utils.getSingle(src.dateOfPublication)
return  mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
+
src.year = mw.ustring.sub(date, 2, 5)
 
end
 
end
 
+
if not src.year and src.dateOfCreation then
local i, f = mw.ustring.match( fullName, '^%s*(%a[%a\-\']+)%s(%a[%a\-\']+)%s*$');
+
local date = utils.getSingle(src.dateOfCreation)
if ( f ) then
+
src.year = mw.ustring.sub(date, 2, 5)
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Fa» match' );
 
return  mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. f;
 
 
end
 
end
 
mw.log( 'Unmatched any pattern: «' .. fullName .. '»' );
 
return fullName;
 
 
end
 
end
  
function p.renderSource( frame )
+
local function populateTitle(src)
p.currentFrame = frame;
+
src.title = src.title or utils.getSingle(src.url) or '\'\'(unspecified title)\'\''
 
 
local arg = frame.args[1];
 
local refAnchor = frame.args['ref'];
 
local refAnchorYear = frame.args['ref-year'];
 
local args = {};
 
args.part = frame.args['part'];
 
args.parturl = frame.args['parturl'];
 
args.pages = frame.args['pages'];
 
args.refAnchor = frame.args['ref'];
 
args.refAnchorYear = frame.args['ref-year'];
 
args.url = frame.args['url'];
 
 
 
return p.renderSourceImpl( mw.text.trim( arg ), args );
 
 
end
 
end
  
function p.renderSourceImpl( entityId, args )
+
local function renderSource(context, src)
args = args or {};
+
options_commas_authors.format = personNameToAuthorName
 +
options_commas_responsible.format = personNameToResponsibleName
  
local snaks = {};
+
context.lang = utils.getLangCode(utils.getSingle(src.lang)) or i18nDefaultLanguage
snaks.P248 = { toWikibaseEntityIdSnak( 'P248', entityId ) };
 
snaks.P805 = { toWikibaseEntityIdSnak( 'P805', entityId ) };
 
copyArgsToSnaks( args, snaks );
 
  
local rendered = renderReferenceImpl( mw.wikibase.getEntity(), { snaks = snaks }, args.refAnchor, args.refAnchorYear );
+
utils.preprocessPlaces(src, context.lang)
if ( rendered ) then return rendered.text end;
 
end
 
  
function p.renderReference( frame, currentEntity, reference )
+
populateUrl(context, src)
p.currentFrame = frame;
+
populateTitle(src)
 +
populateYear(src)
  
-- template call
+
local result = generateAuthorLinks(context, src)
if ( frame and not currentEntity and not reference ) then
+
result = appendTitle(result, context, src)
local args = frame.args;
+
result = appendLanguage(result, context, src)
if ( #frame.args == 0 ) then
+
result = appendSubtitle(result, context, src)
args = frame:getParent().args;
+
result = appendOriginalTitle(result, context, src)
end
+
result = appendPublication(result, context, src)
 +
 +
result = result .. '<span class="wef_low_priority_links">'
 +
result = appendEditor(result, context, src) -- Might take current editor instead of actual. Use with caution
 +
result = appendEdition(result, context, src)
 +
result = appendPublicationData(result, context, src)
 +
result = appendVolumeAndIssue(result, context, src)
 +
result = appendPages(result, context, src)
 +
result = appendNumberOfPages(result, context, src)
 +
result = appendBookSeries(result, context, src)
 +
result = appendTirage(result, context, src)
 +
result = appendIdentifiers(result, context, src)
 +
result = appendSourceId(result, context, src)
 +
result = appendAccessDate(result, context, src)
 +
result = result .. '</span>'
  
local snaks = {};
+
return result
 
 
if ( args[1] ) then
 
snaks.P248 = { toWikibaseEntityIdSnak( "P248", args[1] ) };
 
snaks.P805 = { toWikibaseEntityIdSnak( "P805", args[1] ) };
 
end
 
copyArgsToSnaks( args, snaks );
 
 
 
currentEntity = mw.wikibase.getEntity();
 
reference = { snaks = snaks };
 
end
 
 
 
local rendered = renderReferenceImpl( currentEntity, reference );
 
 
 
if ( not rendered ) then
 
return '';
 
end
 
 
 
local result;
 
local code = rendered.code or rendered.text;
 
-- Про выбор алгоритма хеширования см. [[Модуль:Hash]]. Знак подчёркивания в начале позволяет
 
-- исключить ошибку, когда имя сноски — чисто числовое значение, каковыми иногда бывают хеши.
 
result = frame:extensionTag( 'ref', rendered.text, { name = '_' .. mw.hash.hashValue('fnv164', code) } ) .. '[[Category:Википедия:Статьи с источниками из Викиданных]]';
 
 
 
return result;
 
 
end
 
end
  
function renderReferenceImpl( currentEntity, reference, refAnchor, refAnchorYear )
+
local function renderReferenceImpl(currentEntity, reference, refAnchor, refAnchorYear)
if ( not reference.snaks ) then
+
if not reference.snaks then
return nil;
+
return nil
 
end
 
end
  
 
-- контекст, содержит также кеш элементов
 
-- контекст, содержит также кеш элементов
 
local context = {
 
local context = {
cache = {},
+
cache = {}
 
}
 
}
  
 
-- данные в простом формате, согласованном с модулями формирования библиографического описания
 
-- данные в простом формате, согласованном с модулями формирования библиографического описания
local data = {};
+
local data = {}
  
 
     -- забрать данные из reference
 
     -- забрать данные из reference
     populateDataFromClaims( context, nil, reference.snaks, data )
+
     utils.populateDataFromClaims(context, nil, reference.snaks, data)
 +
 
 +
utils.expandSpecials(context, currentEntity, reference, data)
  
-- update ref name with ref-specific properties
+
local sourceEntity = nil
if ( data.code ) then
+
if data.sourceId then
if ( data.part ) then data.code = data.code .. '-' .. getSingle( data.part ) end
+
sourceEntity = utils.getEntity(context, data.sourceId)
if ( data.pages ) then data.code = data.code .. '-' .. getSingle( data.pages ) end
+
if sourceEntity then
if ( data.volume ) then data.code = data.code .. '-' .. getSingle( data.volume ) end
+
utils.populateSourceDataImpl(context, sourceEntity, data)
if ( data.issue ) then data.code = data.code .. '-' .. getSingle( data.issue ) end
+
end
if ( data.url ) then data.code = data.code .. '-' .. getSingle( data.url ) end
 
 
end
 
end
  
expandSpecials( context, currentEntity, reference, data );
+
if data.publication then
 +
utils.expandPublication(context, sourceEntity, data)
 +
end
  
local sourceEntity = nil;
+
utils.expandBookSeries(context, data)
if ( data.sourceId ) then
+
 
sourceEntity = getEntity( context, data.sourceId );
+
if next(data) == nil then
if ( sourceEntity ) then
+
return nil
populateSourceDataImpl( context, sourceEntity, data );
+
end
end
+
 
 +
local rendered = renderSource(context, data)
 +
if mw.ustring.len(rendered) == 0 then
 +
return nil
 
end
 
end
  
if ( data.publication ) then
+
if refAnchor then
expandPublication( context, sourceEntity, data );
+
local anchorValue = 'CITEREF' .. refAnchor .. (utils.coalesce(refAnchorYear, data.year) or '')
 +
rendered = '<span class="citation" id="' .. mw.uri.anchorEncode(anchorValue) .. '">' .. rendered .. '</span>'
 
end
 
end
  
expandBookSeries( context, data );
+
return rendered
 +
end
  
if ( next( data ) == nil ) then
+
local function artificialSnaks(args)
return nil;
+
local snaks = {}
 +
if args[1] then
 +
entityId = mw.text.trim(args[1])
 +
snaks.P248 = {utils.toWikibaseEntityIdSnak("P248", entityId)}
 +
snaks.P805 = {utils.toWikibaseEntityIdSnak("P805", entityId)}
 
end
 
end
 +
utils.copyArgsToSnaks(args, snaks)
 +
return mw.wikibase.getEntity(), {snaks = snaks}
 +
end
  
local rendered;
+
function p.renderReference(frame, currentEntity, reference)
if ( p.short ) then
+
p.currentFrame = frame
rendered = renderShortReference( data );
 
if ( mw.ustring.len( rendered.text ) == 0 ) then
 
return nil;
 
end
 
  
else
+
-- template call
rendered = renderSource( context, data );
+
if frame and not currentEntity and not reference then
if ( mw.ustring.len( rendered.text ) == 0 ) then
+
currentEntity, reference = artificialSnaks(frame.args)
return nil;
+
end
end
 
  
if ( refAnchor ) then
+
local rendered = renderReferenceImpl(currentEntity, reference)
local anchorValue = 'CITEREF' .. refAnchor .. ( coalesce( refAnchorYear, data.year ) or '' );
+
if not rendered then
rendered.text = '<span class="citation" id="' .. mw.uri.anchorEncode( anchorValue ) .. '">' .. rendered.text .. '</span>';
+
return ''
end
 
 
end
 
end
 +
-- Про выбор алгоритма хеширования см. [[Модуль:Hash]]. Знак подчёркивания в начале позволяет
 +
-- исключить ошибку, когда имя сноски — чисто числовое значение, каковыми иногда бывают хеши.
 +
return frame:extensionTag('ref', rendered, {name = '_' .. mw.hash.hashValue('fnv164', rendered)}) .. '[[Category:Википедия:Статьи с источниками из Викиданных]]'
 +
end
  
return rendered;
+
function p.renderSource(frame)
 +
p.currentFrame = frame
 +
currentEntity, reference = artificialSnaks(frame.args)
 +
return renderReferenceImpl(currentEntity, reference, frame.args['ref'], frame.args['ref-year'])
 
end
 
end
  
 
return p;
 
return p;

Текущая версия на 22:47, 29 мая 2021

Для документации этого модуля может быть создана страница Модуль:Sources/doc

local p = {}

local utils = require('Module:Sources/utils')

local i18nDefaultLanguage = 'ru'

local i18nEtAlDefault = ' et al.'
local i18nEtAl = {
	ru	= ' и др.',
}

local i18nEditors = {
	fr	= '',
	de	= 'Hrsg.: ',
	es	= '',
	en	= '',
	it	= '',
	ru	= 'под ред. ',
}

local i18nTranslators = {
	fr	= '',
	de	= '',
	es	= '',
	en	= '',
	it	= '',
	ru	= 'пер. ',
}

local i18nVolume = {
    de  = 'Vol.',
	fr	= 'Vol.',
	es	= 'Vol.',
	en	= 'Vol.',
	it	= 'Vol.',
	ru	= 'Т.',
}

local i18nIssue = {
	en	= 'Iss.',
	ru	= 'вып.',
}

local i18nPages = {
	fr = 'P.',
	de = 'S.',
	es = 'P.',
	en = 'P.',
	it = 'P.',
	ru = 'С.',
}

local i18nNumberOfPages = {
	en = 'p.',
	ru = 'с.',
}

local i18nTirage = {
	en	= 'ed. size: %d',
	ru	= '%d экз.',
}


local monthg = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', "сентября", "октября", "ноября", "декабря"}

local PREFIX_CITEREF = "CITEREF_";

-- Returns formatted pair {Family name(s), First name(s)}
local function tokenizeName( fullName )
	local start = '^%s*' -- matches beginning of the string + arbitrary number of spaces
	local finish = '%s*$' -- matches end of the string + arbitrary number of spaces
	local comma = '\,%s+' -- matches comma + single or more spacing character
	local space = '%s+' -- matches single or more spacing character
	local name = '(%a[%a\-\']*)\.?' -- matches single name, have to start with letter, can contain apostrophe and hyphen, may end with dot
	local surname = '(%a[%a\-\']*)' -- same as name, but can't end with dot
	
	local f, i = mw.ustring.match(fullName, start .. surname .. comma .. name .. finish)
	if f then
		mw.log('tokenizeName: «' .. fullName .. '»: have «Fa, Im» match')
		return {f, mw.ustring.sub( i, 1, 1 ) .. '.'}
	end
	
	local f, i, o = mw.ustring.match(fullName, start .. surname .. comma .. name .. space .. name .. finish)
	if f then
		mw.log( 'tokenizeName: «' .. fullName .. '»: have «Fa, Im Ot» match')
		return {f, mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;'
				.. mw.ustring.sub( o, 1, 1 ) .. '.'}
	end

	local f1, f2, i = mw.ustring.match(fullName, start .. surname .. space .. surname .. comma .. name .. finish)
	if f1 then
		mw.log('tokenizeName: «' .. fullName .. '»: have «Fa Fa, Im» match')
		return {f1 .. '&nbsp;' .. f2, mw.ustring.sub( i, 1, 1 ) .. '.'}
	end
	
	local i, o, f = mw.ustring.match(fullName, start .. name .. space .. name .. space .. 'оглы' .. space .. surname .. finish)
	if f then
		mw.log('tokenizeName: «' .. fullName .. '»: have «Im Ot оглы Fa» match')
		return {f, mw.ustring.sub(i, 1, 1) .. '.&nbsp;' .. mw.ustring.sub(o, 1, 1) .. '.'}
	end

	local i1, i2, f = mw.ustring.match(fullName, start .. name .. space .. name .. space .. 'de' .. space .. surname .. finish)
	if f then
		mw.log('tokenizeName: «' .. fullName .. '»: have «Im Im de Fa» match')
		return {f, mw.ustring.sub( i1, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( i2, 1, 1 ) .. '.'}
	end
	
	-- Try matching k names + surname
	for k = 1, 4 do
		pattern = start .. string.rep(name .. space, k) .. surname .. finish
		matched = {mw.ustring.match(fullName, pattern)}
		if #matched ~= 0 then
			mw.log('tokenizeName: «' .. fullName .. '»: have «Im (x' .. k .. ') Fa» match')
			for i = 1, k do
				matched[i] = mw.ustring.sub(matched[i], 1, 1)
			end
			return {matched[k + 1], table.concat(matched, '.&nbsp;', 1, k) .. '.'}
		end
	end
	
	mw.log('Unmatched any pattern: «' .. fullName .. '»')
	return {fullName}
end

local function personNameToAuthorName( fullName )
	if not fullName then return fullName end
	local tokenized = tokenizeName(fullName)
	if #tokenized == 1 then
		return tokenized[1]
	else
		return tokenized[1] .. '&nbsp;' .. tokenized[2]
	end
end

local function personNameToResponsibleName( fullName )
	if not fullName then return fullName end
	local tokenized = tokenizeName(fullName)
	if #tokenized == 1 then
		return tokenized[1]
	else
		return tokenized[2] .. '&nbsp;' .. tokenized[1]
	end
end


local options_commas = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false };
local options_commas_short = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false, short = true };
local options_commas_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = true, preferids = false };
local options_commas_it = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false };
local options_commas_it_short = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false, short = true };
local options_commas_it_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = true , preferids = false };
local options_citetypes = { separator = ' ', conjunction = ' ', format = function( src ) return 'citetype_' .. src end, nolinks = true , preferids = true };

local options_commas_authors = { separator = ', ', conjunction = ', ', format = personNameToAuthorName, nolinks = false, preferids = false };
local options_commas_responsible = { separator = ', ', conjunction = ', ', format = personNameToResponsibleName, nolinks = false, preferids = false };

local options_arxiv = { separator = '; ', conjunction = '; ', format = function( id ) return '[http://arxiv.org/abs/' .. id .. ' arXiv:' .. id .. ']' end, nolinks = true, preferids = false };
local options_doi = { separator = '; ', conjunction = '; ', format = function( doi ) return '[http://dx.doi.org/' .. doi .. ' doi:' .. doi .. ']' end, nolinks = true, preferids = false };
local options_issn = { separator = '; ', conjunction = '; ', format = function( issn ) return '[https://www.worldcat.org/issn/' .. issn .. ' ' .. issn .. ']' end, nolinks = true, preferids = false };
local options_pmid = { separator = '; ', conjunction = '; ', format = function( pmid ) return '[https://www.ncbi.nlm.nih.gov/pubmed/?term=' .. pmid .. ' PMID:' .. pmid .. ']' end, nolinks = true, preferids = false };

local function getPersonNameAsLabel( context, entityId, providedLabel, options )
	-- would custom label provided we don't need to check entity at all
	if ( not utils.isEmpty( providedLabel ) ) then
		mw.log( 'Custom label provided for ' .. entityId );
		return options.format( providedLabel );
	end

	local entity = utils.getEntity( context, entityId );
	if ( not entity ) then return '\'\'(entity ' .. entityId .. ' is missing)\'\'' end;

	local personName = nil;
	-- support only labels so far
	if ( entity.labels[ context.lang ] ) then
		personName = entity.labels[ context.lang ].value;
		mw.log('Got person name of ' .. entityId .. ' from label: «' .. personName .. '»' )
	end

	if ( not utils.isInstanceOf( entity, 'Q5' ) ) then
		mw.log( 'Entity ' .. entityId .. ' is not a person' );
		return personName;
	end

	if ( utils.isEmpty( personName ) ) then
		return '\'\'(not translated to ' .. context.lang .. ')\'\'';
	else
		return options.format( personName );
	end
end

local function getPersonNameAsWikitext( context, entityId, customLabel, options )
	local personName = getPersonNameAsLabel( context, entityId, customLabel, options);
	if ( personName == nil ) then
		return nil;
	end

	local link = utils.getElementLink( context, entityId, nil );
	return utils.wrapInUrl( link, personName );
end

local function getPeopleAsWikitext( context, value, options )
	if type( value ) == 'string' then
		return options.format( value )
	elseif type( value ) == 'table' then
		if value.id then
			-- this is link
			if options.preferids then
				return value.id
			else
				if options.nolinks then
					return getPersonNameAsLabel( context, value.id, value.label, options )
				else
					return getPersonNameAsWikitext( context, value.id, value.label, options )
				end
			end
		end
		
		local maxAuthors = 10 -- need some restrictions, as some publications have enormous amount of authors (e.g. 115 authors of Q68951544)
		local resultList = {}
		for i, tableValue in pairs( value ) do
			local nextWikitext = getPeopleAsWikitext( context, tableValue, options )
			if not utils.isEmpty( nextWikitext ) then
				table.insert( resultList, nextWikitext )
				if #resultList == maxAuthors + 1 then
					-- keep one more to indicate that there are too many
					break
				end
			end
		end

		local resultWikitext = ''
		for i, wikitext in pairs( resultList ) do
			if i == maxAuthors + 1 then
				resultWikitext = resultWikitext .. ( i18nEtAl[ context.lang ] or i18nEtAlDefault )
				break;
			end
			if i ~= 1 then
				resultWikitext = resultWikitext .. ', '
			end
			resultWikitext = resultWikitext .. wikitext
		end

		return resultWikitext
	end

	return options.format( '(unknown type)' )
end

local function generateAuthorLinks(context, src)
	local result = ''
	if src.author then
		result = getPeopleAsWikitext( context, src.author, options_commas_authors )
		result = '<i class="wef_low_priority_links">' .. result .. '</i> '
	end
	return result
end

local function appendProperty(result, context, src, conjunctor, property, url)
	if src[property] then
		if url and src[url] then
			result = result .. conjunctor .. utils.wrapInUrl( src[url], utils.toString( context, src[property], options_commas_nolinks ) )
		else
			result = result .. conjunctor .. utils.toString( context, src[property], options_commas )
		end
	end
	return result
end

local function appendTitle(result, context, src)
	conjunctor = ''
 	if src.part then
 		result = appendProperty(result, context, src, '', 'part', 'parturl')
 		conjunctor = ' // '
 	end
 	result = appendProperty(result, context, src, conjunctor, 'title', 'url')
 	return result
end

local function appendLanguage(result, context, src)
	if context.lang ~= i18nDefaultLanguage then
		local langs = require('Module:Languages')
		result = result .. langs.list_ref(p.currentFrame:newChild{ args = {context.lang} })
	end
	return result
end

local function appendSubtitle(result, context, src)
	return appendProperty(result, context, src, ': ', 'subtitle')
end

local function appendOriginalTitle(result, context, src)
	return appendProperty(result, context, src, ' = ', 'originaltitle')
end

local function appendPublication(result, context, src)
	if src.publication then
		if type( src.publication.title or '') ~= 'string' then
			error('type of src.publication.title is not string but ' .. type( src.publication.title ) )
		end
		
		result = result .. ' // ' .. utils.toString( context, src.publication, options_commas_it_short )
		if src.publication.subtitle then
			result = result .. ': ' .. utils.toString( context, src.publication.subtitle, options_commas_it_short )
		end
	end
	return result
end

local function appendEditor(result, context, src)
	if src.editor or src.translator then
		result = result .. ' / '
		if src.editor then
			local prefix = i18nEditors[ context.lang ] or i18nEditors[ i18nDefaultLanguage ]
			result = result .. prefix .. getPeopleAsWikitext( context, src.editor, options_commas_responsible )
			if src.translator then
				result = result .. ', '
			end
		end
		if src.translator then
			local prefix = i18nTranslators[ context.lang ] or i18nTranslators[ i18nDefaultLanguage ]
			result = result .. prefix .. getPeopleAsWikitext( context, src.translator, options_commas_responsible )
		end
	end
	return result
end

local function appendEdition(result, context, src)
	return appendProperty(result, context, src, ' — ', 'edition')
end

local function appendPublicationData(result, context, src)
	if src.place or src.publisher or src.year then
		result = result .. ' — '
		if src.place then
			result = result .. utils.toString( context, src.place, options_commas_short )
			if src.publisher or src.year then
				result = result .. ': '
			end
		end
		if src.publisher then
			result = result .. utils.toString( context, src.publisher, options_commas_short )
			if src.year then
				result = result .. ', '
			end
		end
		if src.year then
			result = result .. utils.toString( context, src.year, options_commas )
		end
		result = result .. '.';
	end
	return result
end

local function appendVolumeAndIssue(result, context, src)
 	if src.volume or src.issue then
 		result = result .. ' — '
		local letter_vol = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ]
		local letter_iss = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ]
		if src.volume then
			result = appendProperty(result, context, src, letter_vol .. '&nbsp;', 'volume')
			result = appendProperty(result, context, src, ', ' .. letter_iss .. '&nbsp;', 'issue')
		else
			result = appendProperty(result, context, src, letter_iss .. '&nbsp;', 'issue')
		end
		result = result .. '.'
 	end
 	return result
end

local function appendPages(result, context, src)
	if src.pages then
		local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ]
		local strPages = utils.toString( context, src.pages, options_commas )
		strPages = mw.ustring.gsub( strPages, '[-—]', '—' );
		result = result .. ' — ' .. letter .. '&nbsp;' .. strPages .. '.'
	end
	return result
end

local function appendNumberOfPages(result, context, src)
	if src.numberOfPages then
		local letter = i18nNumberOfPages[ context.lang ] or i18nNumberOfPages[ i18nDefaultLanguage ]
		result = appendProperty(result, context, src, ' — ', 'numberOfPages') .. '&nbsp;' .. letter
	end
	return result
end

local function appendBookSeries(result, context, src)
	if src.bookSeries then
		result = appendProperty(result, context, src, ' — (', 'bookSeries')
	 	if src.bookSeriesVolume or src.bookSeriesIssue then
	 		result = result .. '; '
	 		local letter_vol = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ]
	 		local letter_iss = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ]
			if ( src.bookSeriesVolume ) then
				result = appendProperty(result, context, src, letter_vol .. '&nbsp;', 'bookSeriesVolume')
				result = appendProperty(result, context, src, ', ' .. letter_iss .. '&nbsp;', 'bookSeriesIssue')
			else
				result = appendProperty(result, context, src, letter_iss .. '&nbsp;', 'bookSeriesIssue')
			end
	 	end
		result = result .. ')'
	end
	return result
end

local function appendTirage(result, context, src)
	if src.tirage then
		local tirageTemplate = i18nTirage[ context.lang ] or i18nTirage[ i18nDefaultLanguage ]
		result = result .. ' — ' .. utils.toString( context, src.tirage, { separator = '; ', conjunction = '; ', format = function( data ) return mw.ustring.format(tirageTemplate, data) end } )
	end
	return result
end

local function appendIdentifiers(result, context, src)
	if src.isbn  then result = result .. ' — ISBN ' .. utils.toString( context, src.isbn, options_commas )	end
	if src.issn  then result = result .. ' — ISSN ' .. utils.toString( context, src.issn, options_issn )	end
	if src.doi   then result = result .. ' — ' .. utils.toString( context, src.doi, options_doi )			end
	if src.pmid  then result = result .. ' — ' .. utils.toString( context, src.pmid, options_pmid )			end
	if src.arxiv then result = result .. ' — ' .. utils.toString( context, src.arxiv, options_arxiv )		end
	return result
end

local function appendSourceId(result, context, src)
	if src.sourceId then
		local citetype = src.type and utils.toString(context, src.type, options_citetypes) or 'citetype_unknown'
		result = '<span class="wikidata_cite ' .. citetype .. '" data-entity-id="' .. utils.getSingle(src.sourceId) .. '">' .. result .. '</span>'
	end
	return result
end

local function appendAccessDate(result, context, src)
	if src.accessdate then
			local date = utils.getSingle(src.accessdate)
			local pattern = "(%-?%d+)%-(%d+)%-(%d+)T";
			local y, m, d = mw.ustring.match(date, pattern)
			y, m, d = tonumber(y), tonumber(m), tonumber(d)
			local date_str = (d > 0 and ' ' .. tostring(d) or '') 
						  .. (m > 0 and ' ' .. monthg[m] or '')
						  .. (y > 0 and ' ' .. tostring(y) or '')
			result = result .. " <small>Проверено" .. date_str .. ".</small>"
	end
	return result
end

local function populateUrl(context, src)
	if src.sourceId and not src.url then
		local entity = utils.getEntity(context, src.sourceId)
		if entity.sitelinks and entity.sitelinks[context.lang .. 'wikisource'] then
			src.url = ':' .. context.lang .. ':s:' .. entity.sitelinks[context.lang .. 'wikisource'].title
		end
	end
end

local function populateYear(src)
	if not src.year and src.dateOfPublication then
		local date = utils.getSingle(src.dateOfPublication)
		src.year = mw.ustring.sub(date, 2, 5)
	end
	if not src.year and src.dateOfCreation then
		local date = utils.getSingle(src.dateOfCreation)
		src.year = mw.ustring.sub(date, 2, 5)
	end
end

local function populateTitle(src)
	src.title = src.title or utils.getSingle(src.url) or '\'\'(unspecified title)\'\''
end

local function renderSource(context, src)
	options_commas_authors.format = personNameToAuthorName
	options_commas_responsible.format = personNameToResponsibleName

	context.lang = utils.getLangCode(utils.getSingle(src.lang)) or i18nDefaultLanguage

	utils.preprocessPlaces(src, context.lang)

	populateUrl(context, src)
	populateTitle(src)
	populateYear(src)

	local result = generateAuthorLinks(context, src)
	result = appendTitle(result, context, src)
	result = appendLanguage(result, context, src)
	result = appendSubtitle(result, context, src)
	result = appendOriginalTitle(result, context, src)
	result = appendPublication(result, context, src)
	
	result = result .. '<span class="wef_low_priority_links">'
	result = appendEditor(result, context, src) -- Might take current editor instead of actual. Use with caution
	result = appendEdition(result, context, src)
	result = appendPublicationData(result, context, src)
	result = appendVolumeAndIssue(result, context, src)
	result = appendPages(result, context, src)
	result = appendNumberOfPages(result, context, src)
	result = appendBookSeries(result, context, src)
	result = appendTirage(result, context, src)
	result = appendIdentifiers(result, context, src)
	result = appendSourceId(result, context, src)
	result = appendAccessDate(result, context, src)
	result = result .. '</span>'

	return result
end

local function renderReferenceImpl(currentEntity, reference, refAnchor, refAnchorYear)
	if not reference.snaks then
		return nil
	end

	-- контекст, содержит также кеш элементов
	local context = {
		cache = {}
	}

	-- данные в простом формате, согласованном с модулями формирования библиографического описания
	local data = {}

    -- забрать данные из reference
    utils.populateDataFromClaims(context, nil, reference.snaks, data)

	utils.expandSpecials(context, currentEntity, reference, data)

	local sourceEntity = nil
	if data.sourceId then
		sourceEntity = utils.getEntity(context, data.sourceId)
		if sourceEntity then
			utils.populateSourceDataImpl(context, sourceEntity, data)
		end
	end

	if data.publication then
		utils.expandPublication(context, sourceEntity, data)
	end

	utils.expandBookSeries(context, data)

	if next(data) == nil then
		return nil
	end

	local rendered = renderSource(context, data)
	if mw.ustring.len(rendered) == 0 then
		return nil
	end

	if refAnchor then
		local anchorValue = 'CITEREF' .. refAnchor .. (utils.coalesce(refAnchorYear, data.year) or '')
		rendered = '<span class="citation" id="' .. mw.uri.anchorEncode(anchorValue) .. '">' .. rendered .. '</span>'
	end

	return rendered
end

local function artificialSnaks(args)
	local snaks = {}
	if args[1] then
		entityId = mw.text.trim(args[1])
		snaks.P248 = {utils.toWikibaseEntityIdSnak("P248", entityId)}
		snaks.P805 = {utils.toWikibaseEntityIdSnak("P805", entityId)}
	end
	utils.copyArgsToSnaks(args, snaks)
	return mw.wikibase.getEntity(), {snaks = snaks}
end

function p.renderReference(frame, currentEntity, reference)
	p.currentFrame = frame

	-- template call
	if frame and not currentEntity and not reference then
		currentEntity, reference = artificialSnaks(frame.args)
	end

	local rendered = renderReferenceImpl(currentEntity, reference)
	if not rendered then
		return ''
	end
	-- Про выбор алгоритма хеширования см. [[Модуль:Hash]]. Знак подчёркивания в начале позволяет
	-- исключить ошибку, когда имя сноски — чисто числовое значение, каковыми иногда бывают хеши.
	return frame:extensionTag('ref', rendered, {name = '_' .. mw.hash.hashValue('fnv164', rendered)}) .. '[[Category:Википедия:Статьи с источниками из Викиданных]]'
end

function p.renderSource(frame)
	p.currentFrame = frame
	currentEntity, reference = artificialSnaks(frame.args)
	return renderReferenceImpl(currentEntity, reference, frame.args['ref'], frame.args['ref-year'])
end

return p;