Moduuli:Sources

On otettu Wikipedii-späi

Tämän moduulin ohjeistuksen voi tehdä sivulle Moduuli:Sources/ohje

local p = {};

local i18nDefaultLanguage = 'ru';
local i18nEditors = {
	fr	= '',
	de	= 'Hrsg.: ',
	es	= '',
	en	= '',
	it	= '',
	ru	= 'под ред. ',
}
local i18nVolume = {
	fr	= 'Vol.',
	es	= 'Vol.',
	en	= 'Vol.',
	it	= 'Vol.',
	ru	= 'Т.',
}
local i18nPage = {
	fr = 'P.',
	de = 'S.',
	es = 'P.',
	en = 'P.',
	it = 'P.',
	ru = 'С.',
}

local NORMATIVE_DOCUMENTS = {
	Q20754888 = 'Закон Российской Федерации',
	Q20754884 = 'Закон РСФСР',
	Q2061228 = 'Указ Президента Российской Федерации',
}

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

local PREFIX_CITEREF = "CITEREF_";

function fixAuthorName( fullName )
	if ( not fullName ) then return fullName; end
	mw.log( 'fixAuthorName: «' .. fullName .. '»' );

	local f, i, o = mw.ustring.match( fullName, '^%s*(%a+)\,%s(%a+)%s(%a+)%s*$' );
	if ( f ) then
		mw.log( 'fixAuthorName: «' .. fullName .. '»: have «Fa, I. O.» match' );
		return f .. ' '
			.. mw.ustring.sub( i, 1, 1 ) .. '. '
			.. mw.ustring.sub( o, 1, 1 ) .. '.';
	end

	local i, o, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a%a+)%s*$');
	if ( f ) then
		mw.log( 'fixAuthorName: «' .. fullName .. '»: have «I. O. Fa» match' );
		return f .. ' ' .. i .. '. ' .. o .. '.';
	end

	local i, o, f = mw.ustring.match( fullName, '^%s*(%a+)%s(%a)\.%s(%a+)%s*$');
	if ( f ) then
		mw.log( 'fixAuthorName: «' .. fullName .. '»: have «Im O. Fa» match' );
		return f .. ' ' .. mw.ustring.sub( i, 1, 1 ) .. '. ' .. o .. '.';
	end

	local i, f = mw.ustring.match( fullName, '^%s*(%a%a+)%s(%a%a+)%s*$');
	if ( f ) then
		mw.log( 'fixAuthorName: «' .. fullName .. '»: have «Im Fa» match' );
		return f .. ' ' .. mw.ustring.sub( i, 1, 1 ) .. '.';
	end

	mw.log( 'Unmatched any pattern: «' .. fullName .. '»' );
	return fullName;
end

local options_authors = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false, formatLabel = fixAuthorName };
local options_authors_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = true , preferids = false, formatLabel = fixAuthorName };

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_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 };

function assertNotNull( argName, arg )
	if ( (not arg) or (arg == nil) ) then
		error( argName .. ' is not specified' )
	end
end

function isEmpty( str )
	return ( not str ) or ( str == nil ) or ( #str == 0 );
end

function getEntity( context, entityId )
	assertNotNull( 'context', context );
	assertNotNull( 'entityId', entityId );

	local cached = context.cache[ entityId ];
	if ( cached ) then return cached; end;

	local result = mw.wikibase.getEntity( entityId );
	if ( result ) then
		context.cache[ entityId ] = result;
	end

	return result;
end

function renderSource( src )
	mw.logObject( src );
	
	local context = {
		cache = {},
		lang = getLangCode( getSingle( src.lang ) ) or i18nDefaultLanguage,
	}

	src.title = src.title or getSingle( src.url ) or '\'\'(unspecified title)\'\''

	if ( src.code and not src.url ) then
		local entity = mw.wikibase.getEntity( src.code );
		if ( entity.sitelinks and entity.sitelinks[ context.lang .. 'wikisource'] ) then
			src.url = ':' .. context.lang .. ':s:' .. entity.sitelinks[ context.lang .. 'wikisource' ].title;
		else
			src.url = ':' .. (mw.wikibase.sitelink( src.code ) or ( 'd:' .. src.code ))
			src.url = ':' .. src.url;
		end
	end

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

	local result = '';
	if ( src.author ) then
		result = result .. toString( context, src.author, options_authors );
	end
	if ( string.len( result ) ~= 0 ) then
		result = result .. ' ';
	end
 
 	if ( src.part ) then
 		if ( src.url ) then
			local url = getSingle( src.url );
			if ( string.sub( url, 1, 1 ) == ':' ) then
				result = result .. '[[' .. url .. '|' .. toString( context, src.part, options_commas_nolinks ) .. ']]';
			else
				result = result .. '[' .. url .. ' ' .. toString( context, src.part, options_commas_nolinks ) .. ']';
			end
		end
		result = result .. ' // ' .. toString( context, src.title, options_commas );
	else
		-- title only
 		if ( src.url ) then
			local url = getSingle( src.url );
			if ( string.sub( url, 1, 1 ) == ':' ) then
				result = result .. '[[' .. url .. '|' .. toString( context, src.title, options_commas_nolinks ) .. ']]';
			else
				result = result .. '[' .. url .. ' ' .. toString( context, src.title, options_commas_nolinks ) .. ']';
			end
		end
 	end

	if ( src.originaltitle ) then
		result = result .. ' = ' .. toString( context, src.originaltitle, options_commas );
	end

	if ( src.publication ) then
		result = result .. ' // ' .. toString( context, src.publication, options_commas_it );
	end

	if ( src.editor ) then
		local prefix = i18nEditors[ context.lang ] or i18nEditors[ i18nDefaultLanguage ];
		result = result .. ' / ' .. prefix .. toString( context, src.editor, 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 );
			if ( src.year ) then
				result = result .. ', ';
			end
		end
		if ( src.year ) then
			result = result .. toString( context, src.year, options_commas );
		end
		result = result .. '.';
	end
 
	if ( src.volume ) then
		local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
		result = result .. ' — ' .. letter .. ' ' .. toString( context, src.volume, options_commas ) .. '.';
	end
 
	if ( src.issue ) then
		result = result .. ' — № ' .. toString( context, src.issue, options_commas ) .. '.';
	end
 
	if ( src.page ) then
		local letter = i18nPage[ context.lang ] or i18nPage[ i18nDefaultLanguage ];
		result = result .. ' — ' .. letter .. ' ' .. toString( context, src.page, options_commas )  .. '.';
	end
 
	if ( src.isbn ) then
		result = result .. ' — ISBN ' .. toString( context, src.isbn, options_commas );
	end

	if ( src.issn ) then
		result = result .. ' — ISSN ' .. toString( context, src.issn, options_commas );
	end

	if ( src.doi ) then
		result = result .. ' — [http://dx.doi.org/' .. mw.uri.encode( src.doi ) .. ' DOI ' .. src.doi .. ']';
	end

	if ( src.entityId ) then
		if ( src.type and src.entityId ) then
			-- wrap into span to target from JS
			result = '<span class="' .. toString( context, src.type, options_citetypes ) .. '" data-entity-id="' .. getSingle( src.entityId ) .. '">' .. result .. '</span>'
		else
			result = '<span class="citetype_unknown" data-entity-id="' .. getSingle( src.entityId ) .. '">' .. 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

	return {text = result, code = src.code};
end

function renderShortReference( src )
	context = {
		cache = {},
		lang = getSingle( src.lang ) or i18nDefaultLanguage;
	};
	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
 
	if ( src.issue ) then
		result = result .. ' — №&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
	end
 
	if ( src.page ) then
		local letter = i18nPage[ context.lang ] or i18nPage[ i18nDefaultLanguage ];
		result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.page, options_commas )  .. '.';
	end
end

function getSingle( value )
	if ( not value ) then
		return;
	end
	if ( type( value ) == 'string' ) then
		return value;
	elseif ( type( value ) == 'table' ) then
		if ( value.id ) then
			return value.id;
		end

		for i, tableValue in pairs( value ) do
			return getSingle( tableValue );
		end
	end

	return '(unknown)';
end

function fSelf( value ) return value; end

function toString( 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 options.format( value.id );
			else
				if ( options.nolinks ) then
					local formatLabel = options.formatLabel or fSelf;
					return options.format( formatLabel( value.label or mw.wikibase.label( value.id ) or '\'\'(untranslated title)\'\'' ) );
				else
					return options.format( renderLink( context, value.id, value.label, options ) );
				end
			end
		end

		local resultList = {};
		for i, tableValue in pairs( value ) do
			table.insert( resultList, toString( context, tableValue, options ) );
		end

		return mw.text.listToText( resultList, options.separator, options.conjunction);
	else
		return options.format( '(unknown type)' );
	end

	return '';
end

function renderLink( context, entityId, customTitle, options )
	if ( not entityId ) then
		error("entityId is not specified");
	end

	local formatLabel = options.formatLabel or fSelf;
	local title = customTitle;

	if ( isEmpty( title ) ) then
		local entity = getEntity( context, entityId );
		-- official name P1448
		-- short name P1813
		if ( isEmpty( title ) and options.short ) then
			if ( entity.claims and entity.claims.P1813 ) then
				for _, claim in pairs( entity.claims.P1813 ) do
					mw.log( claim.mainsnak.datavalue.value.language );
					mw.log( context.lang );
					mw.log( claim.mainsnak.datavalue.value.language == context.lang );
					mw.log( claim.mainsnak.datavalue.value.text );
					if ( claim
							and claim.mainsnak
							and claim.mainsnak.datavalue
							and claim.mainsnak.datavalue.value
							and claim.mainsnak.datavalue.value.language == context.lang ) then
						title = claim.mainsnak.datavalue.value.text;
						break;
					end
				end
			end
		end
		-- person name P1559
		-- labels
		if ( isEmpty( title ) and entity.labels[ context.lang ] ) then
			title = entity.labels[ context.lang ].value;
			mw.log('Got title of ' .. entityId .. ' from label: «' .. title .. '»' )
		end
	end

	local actualText = formatLabel( title or '\'\'(untranslated)\'\'' );
	local link = mw.wikibase.sitelink( entityId ) or ( ':d:' .. entityId )
	return '[[' .. link .. '|' .. actualText .. ']]';
end

-- Expand special types of references when additional data could be found in OTHER entity properties
function expandSpecials( currentEntity, reference, data )
	if ( reference.snaks.P248
			and reference.snaks.P248[1]
			and reference.snaks.P248[1].datavalue
			and reference.snaks.P248[1].datavalue.value["numeric-id"]) then
		local sourceId = "Q" .. reference.snaks.P248[1].datavalue.value["numeric-id"];

		-- Gemeinsame Normdatei -- specified by P227
		if ( sourceId == 'Q36578' ) then
			appendSnaks( currentEntity.claims, 'P227', data, 'title', { format = function( gnd ) return 'Record #' .. gnd; end } );
			appendSnaks( currentEntity.claims, 'P227', data, 'url', { format = function( gnd ) return 'http://d-nb.info/gnd/' .. gnd .. '/'; end } );
		end
		
		-- BNF -- specified by P268
		if ( sourceId == 'Q15222191' ) then
			appendSnaks( currentEntity.claims, 'P268', data, 'title', { format = function( id ) return 'Record #' .. id; end } );
			appendSnaks( currentEntity.claims, 'P268', data, 'url', { format = function( id ) return 'http://catalogue.bnf.fr/ark:/12148/cb' .. id; end } );
			expandSpecialsQualifiers( currentEntity, 'P268', data );
		end

		-- Find a Grave -- specified by P535
		if ( sourceId == 'Q63056' ) then
			appendSnaks( currentEntity.claims, 'P535', data, 'url', { format = function( id ) return 'http://www.findagrave.com/cgi-bin/fg.cgi?page=gr&GRid=' .. id; end } );
			expandSpecialsQualifiers( currentEntity, 'P535', data );
		end

		--  Dizionario Biografico degli Italiani -- specified by P1986
		if ( sourceId == 'Q1128537' ) then
			if ( not data.lang ) then data.lang = { id = 'Q652' } end;
			appendSnaks( currentEntity.claims, 'P1986', data, 'url', { format = function( id ) return 'http://www.treccani.it/enciclopedia/' .. id .. '_%28Dizionario_Biografico%29/' end } );
			expandSpecialsQualifiers( currentEntity, 'P1986', data );
		end

		-- Union List of Artist Names -- specified by P245
		if ( sourceId == 'Q2494649' ) then
			appendSnaks( currentEntity.claims, 'P245', data, 'url', { format = function( id ) return 'http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid=' .. id end } );
			expandSpecialsQualifiers( currentEntity, 'P245', data );
		end

		-- Gran Enciclopèdia Catalana -- specified by P1296
		if ( sourceId == 'Q2664168' ) then
			appendSnaks( currentEntity.claims, 'P1296', data, 'url', { format = function( id ) return 'http://www.enciclopedia.cat/enciclop%C3%A8dies/gran-enciclop%C3%A8dia-catalana/EC-GEC-' .. id .. '.xml'; end } );
			expandSpecialsQualifiers( currentEntity, 'P1296', data );
		end

		-- Encyclopædia Britannica online -- specified by P1417
		if ( sourceId == 'Q5375741' ) then
			appendSnaks( currentEntity.claims, 'P1417', data, 'url', { format = function( id ) return 'http://global.britannica.com/EBchecked/topic/' .. id .. '/'; end } );
			expandSpecialsQualifiers( currentEntity, 'P1417', data );
		end

		-- Electronic Jewish Encyclopedia (Elektronnaja Evrejskaja Entsiklopedia) -- specified by P1438
		if ( sourceId == 'Q1967250' ) then
			appendSnaks( currentEntity.claims, 'P1438', data, 'url', { format = function( id ) return 'http://www.eleven.co.il/article/' .. id; end } );
			expandSpecialsQualifiers( currentEntity, 'P1438', data );
		end

		-- sports-reference.com -- specified by P1447
		if ( sourceId == 'Q18002875' ) then
			appendSnaks( currentEntity.claims, 'P1447', data, 'url', { format = function( id ) return 'http://www.sports-reference.com/olympics/athletes/' .. id .. '.html'; end } );
			expandSpecialsQualifiers( currentEntity, 'P1447', data );
		end

		-- do we have appropriate record in P1343 ?
		local claims = findClaimsByValue( currentEntity, 'P1343', sourceId );
		if ( claims and #claims ~= 0 ) then
			appendQualifiers( claims, 'P958', data, 'part', {} );
			appendQualifiers( claims, 'P953', data, 'url', {} );
			appendQualifiers( claims, 'P854', data, 'url', {} );
			appendQualifiers( claims, 'P357', data, 'title', {} ); -- obsolete
			appendQualifiers( claims, 'P1476', data, 'title', {} );
			appendQualifiers( claims, 'P478', data, 'volume', {} );
		end
	end
end

function expandSpecialsQualifiers( entity, propertyId, result )
	if ( entity.claims and entity.claims[propertyId] ) then
		local claims = entity.claims[propertyId];
		appendQualifiers( claims, 'P958', result, 'part', {} );
		appendQualifiers( claims, 'P953', result, 'url', {} );
		appendQualifiers( claims, 'P854', result, 'url', {} );
		appendQualifiers( claims, 'P357', result, 'title', {} ); -- obsolete
		appendQualifiers( claims, 'P1476', result, 'title', {} );
		appendQualifiers( claims, 'P478', result, 'volume', {} );
	end
end

function findClaimsByValue( entity, propertyId, value )
	local result = {};
	if ( entity and entity.claims and entity.claims[propertyId] ) then
		for i, claim in pairs( entity.claims[propertyId] ) do
			if ( claim.mainsnak and claim.mainsnak.datavalue ) then
				local datavalue = claim.mainsnak.datavalue;
				if ( datavalue.type == "string" and datavalue.value == value 
					or datavalue.type == "wikibase-entityid" and datavalue.value["entity-type"] == "item" and tostring( datavalue.value["numeric-id"] ) == mw.ustring.sub( value, 2 ) ) then
					table.insert( result, claim );
				end
			end
		end
	end
	return result;
end

function appendSnaks( allSnaks, snakPropertyId, result, property, options )
	-- do not populate twice
	if ( result[property] ) then return result end;

	if ( allSnaks and allSnaks[ snakPropertyId ] ) then
		for k, snak in pairs( allSnaks[ snakPropertyId ] ) do
			if ( snak and snak.mainsnak and snak.mainsnak.datavalue ) then
				--it's a claim
				appendImpl( snak.mainsnak.datavalue, result, property, options );
			elseif ( snak and snak.datavalue ) then
				-- it's a snak
				appendImpl( snak.datavalue, result, property, options );
			end
		end
	end
end

function appendQualifiers( claims, qualifierPropertyId, result, property, options )
	-- do not populate twice
	if ( result[property] ) then return result end;

	for i, claim in pairs( claims ) do
		if ( claim.qualifiers and claim.qualifiers[ qualifierPropertyId ] ) then
			for k, qualifier in pairs( claim.qualifiers[ qualifierPropertyId ] ) do
				if ( qualifier and qualifier.datavalue ) then
					appendImpl( qualifier.datavalue, result, property, options );
				end
			end
		end
	end
end

function appendImpl( datavalue, result, property, options )
	if ( datavalue.type == 'string' ) then
		local value = datavalue.value;
		if ( options.format ) then
			value = options.format( value );
		end
		if ( not result[property] ) then
			result[property] = {};
		elseif ( type( result[property] ) == 'string' or ( type( result[property] ) == 'table' and type( result[property].id ) == 'string' ) ) then
			result[property] = { result[property] };
		end
		table.insert( result[property], value);
	elseif ( datavalue.type == 'monolingualtext' ) then
		local value = datavalue.value.text;
		if ( options.format ) then
			value = options.format( value );
		end
		if ( not result[property] ) then
			result[property] = {};
		elseif ( type( result[property] ) == 'string' or ( type( result[property] ) == 'table' and type( result[property].id ) == 'string' ) ) then
			result[property] = { result[property] };
		end
		table.insert( result[property], value);
	elseif ( datavalue.type == 'wikibase-entityid' ) then
		local value = datavalue.value;
		if ( not result[property] ) then
			result[property] = {};
		elseif ( type( result[property] ) == 'string' or ( type( result[property] ) == 'table' and type( result[property].id ) == 'string' ) ) then
			result[property] = { result[property] };
		end
		table.insert( result[property], { id = 'Q' .. value["numeric-id"] });
	elseif datavalue.type == 'time' then
		local value = datavalue.value;
		if ( options.format ) then
			value = options.format( value );
		end
		if ( not result[property] ) then
			result[property] = {};
		elseif ( type( result[property] ) == 'string' or ( type( result[property] ) == 'table' and type( result[property].id ) == 'string' ) ) then
			result[property] = { result[property] };
		end
		table.insert( result[property], tostring( value.time ));
    end 
end

function expandPublication( data )
	local publication = data.publication;

	-- use only first one
	if ( type( publication ) == 'table' and publication[1] and publication[1].id ) then
		data.publication = publication[1];
		publication = data.publication;
	end

	if ( publication and publication.id ) then
		populateSourceData( publication.id, data );
	end
end

function populateSourceData( entityId, plainData )
	return populateSourceDataImpl( mw.wikibase.getEntity( entityId ), plainData );
end

function populateSourceDataImpl( entity, plainData )
	populateDataFromClaims( entity.claims, plainData );

	local normativeTitle = getNormativeTitle( entity )
	if ( normativeTitle ) then
		local y, m, d = mw.ustring.match( getSingle( plainData.dateOfCreation ) , "(%-?%d+)%-(%d+)%-(%d+)T" );
		y,m,d = tonumber(y),tonumber(m),tonumber(d);
		plainData.title = { normativeTitle .. " от&nbsp;" .. tostring(d) .. "&nbsp;" .. monthg[m]  .. " " .. tostring(y) .. "&nbsp;г. №&nbsp;" .. getSingle( plainData.docNumber ) .. ' «' .. getSingle( plainData.title ) .. '»' }
	end

	if ( not plainData.title ) then
		if ( entity.labels and entity.labels.ru and entity.labels.ru.value ) then
			plainData.title = { entity.labels.ru.value };
		end
	end

	return plainData;
end

function populateDataFromClaims( claims, data )
	appendSnaks( claims, 'P50', data, 'author', {} );
	appendSnaks( claims, 'P407', data, 'lang', {} );
	appendSnaks( claims, 'P364', data, 'lang', {} );
	appendSnaks( claims, 'P958', data, 'part', {} );
	appendSnaks( claims, 'P357', data, 'title', {} ); -- obsolete
	appendSnaks( claims, 'P1476', data, 'title', {} );
	appendSnaks( claims, 'P953', data, 'url', {} );
	appendSnaks( claims, 'P854', data, 'url', {} );
	appendSnaks( claims, 'P856', data, 'url', {} );
	appendSnaks( claims, 'P1433', data, 'publication', {} );
	appendSnaks( claims, 'P123', data, 'publisher', {} );
	appendSnaks( claims, 'P291', data, 'place', {} );
	appendSnaks( claims, 'P304', data, 'page', {} );
	appendSnaks( claims, 'P478', data, 'volume', {} );
	appendSnaks( claims, 'P571', data, 'dateOfCreation', {} );
	appendSnaks( claims, 'P577', data, 'dateOfPublication', {} );
	appendSnaks( claims, 'P212', data, 'isbn', {} ); -- ISBN-13
	appendSnaks( claims, 'P957', data, 'isbn', {} ); -- ISBN-10

    -- web
	appendSnaks( claims, 'P813', data, 'accessdate', {} );

    -- docs
	appendSnaks( claims, 'P1545', data, 'docNumber', {} );

	-- other
	appendSnaks( claims, 'P31', data, 'type', {} );
	return src;
end

function updateWithRef( reference, src )
	-- specified
	if ( reference.snaks.O662 ) then
		local cid = reference.snaks.P662[1].datavalue.value;
		src.code = src.code .. '-cid:' .. cid;
		src.title = 'Compound Summary for: CID ' .. cid;
		src.url = 'http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=' .. cid;
		src.publication = { id = 'Q278487', label = 'PubChem' };
	end

	populateDataFromClaims(reference.snaks, src);
	return src;
end

function p.renderSource( frame )
	local arg = frame.args[1];
	return p.renderSourceImpl( mw.text.trim( arg ) );
end

function p.renderSourceImpl( entityId )
	assertNotNull('entityId', entityId)
	if ( mw.ustring.sub( entityId, 1, 1 ) ~= 'Q' ) then error( 'Incorrect entity ID: «' .. entityId .. '»' ); end;

	local value = {};
	value["numeric-id"] = string.sub( entityId , 2);
	local snak = { datavalue = { value = value } };
	local properties = {};
	properties[1] = snak;
	
	local rendered = renderReferenceImpl( mw.wikibase.getEntity(), { snaks = { P248 = properties } } );
	if ( rendered ) then return rendered.text end;
end

function p.renderReference( frame, currentEntity, reference )

	-- template call
	if ( frame and not currentEntity and not reference ) then
		local value = {};
		value["numeric-id"] = string.sub( frame.args[1] , 2);
		local snak = { datavalue = { value =value } };
		local properties = {};
		properties[1] = snak;

		currentEntity = mw.wikibase.getEntity();
		reference = { snaks = { P248 = properties } };
	end

	local rendered = renderReferenceImpl( currentEntity, reference );

	if ( not rendered ) then
		return '';
	end

	local result;
	local code = rendered.code or mw.text.encode( rendered.text );
	result = frame:extensionTag( 'ref', rendered.text, {name = code} ) .. '[[Category:Википедия:Статьи с источниками из Викиданных]]';

	if ( not rendered.found ) then
		result = result .. '[[Category:Википедия:Статьи с неоформленными источниками из Викиданных]]';
	end

	return result;
end

function renderReferenceImpl( currentEntity, reference )
	if ( not reference.snaks ) then
		return nil;
	end

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

	local entityId, sourceEntity;
	if ( reference and reference.snaks and reference.snaks.P248 ) then
		for _, snak in pairs ( reference.snaks.P248 ) do
			if ( snak.datavalue ) then
				entityId = 'Q' .. snak.datavalue.value["numeric-id"];
				sourceEntity = mw.wikibase.getEntity( entityId );
				data.code = entityId;
				data.entityId = entityId;
				break;
			end
		end
	end

	updateWithRef( reference, data );
	expandSpecials( currentEntity, reference, data );
	if ( sourceEntity ) then
		populateSourceDataImpl( sourceEntity, data );
	end
	expandPublication( data );

	local rendered;
	if ( p.short ) then
		rendered = renderShortReference( data );
	else
		rendered = renderSource( data );
	end

	if ( mw.ustring.len( rendered.text ) == 0 ) then
		return nil;
	end

	rendered.found = found;
	return rendered;
end

function getNormativeTitle( entity )
	if ( not entity or not entity.claims or not entity.claims.P31 ) then
		return;
	end

	for _, claim in pairs( entity.claims.P31 ) do
		if ( claim and claim.mainsnak and claim.mainsnak.datavalue and claim.mainsnak.datavalue.value and claim.mainsnak.datavalue.value["numeric-id"] ) then
			local classId = 'Q' .. claim.mainsnak.datavalue.value["numeric-id"];
			local title = NORMATIVE_DOCUMENTS[ classId ];
			if ( title ) then
				return title;
			end
		end
	end

	return;
end

local LANG_CACHE = 	{
	Q150	= 'fr',
	Q188	= 'de',
	Q1321	= 'es',
	Q1860	= 'en',
	Q652	= 'it',
	Q7737	= 'ru',
}

function getLangCode( langEntityId )
	if ( not langEntityId ) then
		return;
	end

	-- small optimization
	local cached = LANG_CACHE[ langEntityId ];
	if ( cached ) then return cached; end

	local langEntity = mw.wikibase.getEntity( langEntityId );
	if ( not langEntity ) then
		mw.log( '[getLangCode] Missing entity ' .. langEntityId );
	else
		if ( langEntity.claims and langEntity.claims.P424 ) then
			for _, claim in pairs( langEntity.claims.P424 ) do
				if ( claim
						and claim.mainsnak
						and claim.mainsnak.datavalue
						and claim.mainsnak.datavalue.value ) then
					return '' .. claim.mainsnak.datavalue.value;
				end
			end
		end
	end

	return;
end

return p;