Modul:Wikidata/Places/peskovnik

Iz Wikipedije, proste enciklopedije
local categorizeByPlace = true;

local p = {
	config = {
		hideSameLabels = false,
		hidePartOfLabels = false,
		hideUnitsForCapitals = true,
		reverseOrder = false,
		catAmbiguousGeoChains = '[[Категория:Википедия:Страницы с неоднозначными геоцепочками]]',
		catWikibaseError = '[[Категория:Википедия:Страницы с ошибками скриптов, использующих Викиданные]]'
	}
};

--Property:P19, Property:P20, Property:P119
function p.formatPlaceWithQualifiers( context, options, statement )
	local property = mw.ustring.upper( options.property );

	local actualDateBoundariesProperties = nil;
	if property == 'P19' then actualDateBoundariesProperties = {'P569','P570'}; end
	if property == 'P20' then actualDateBoundariesProperties = {'P570','P569'}; end
	if property == 'P119' then actualDateBoundariesProperties = {'P570','P569'}; end
	if property == 'P159' then actualDateBoundariesProperties = {'P576'}; end

	local boundaries = nil;
	if actualDateBoundariesProperties ~= nil then
		boundaries = getTimeBoundariesFromProperties( context, actualDateBoundariesProperties );
		if (boundaries == nil) and (property == 'P159') then
			boundaries = {os.time() * 1000, os.time() * 1000};
		end
	end

	local entriesToLookupCategory = {};

	local circumstances = context.getSourcingCircumstances( statement );
	local result = '';
	local baseResult = context.formatSnak( options, statement.mainsnak, circumstances );
	if not baseResult then
		return nil;
	end
	
	insertFromSnak( statement.mainsnak, entriesToLookupCategory )

	local hasAdditionalQualifiers = false;
	if statement.qualifiers then
		--parent divisions
		if statement.qualifiers.P131 then
			for i, qualifier in ipairs( statement.qualifiers.P131 ) do
				local parentOptions = context.cloneOptions( options );
				local qualifierEntityId = qualifier.datavalue.value.id;
				parentOptions['text'] = getLabel( context, qualifierEntityId, boundaries );
				local link = context.formatSnak( parentOptions, qualifier );

				if p.config.reverseOrder then
					result = link .. ', ' .. result;
				else
					result = result .. ', ' .. link;
				end
				insertFromSnak( qualifier, entriesToLookupCategory )
				hasAdditionalQualifiers = true;
			end
		end

		--country
		if statement.qualifiers.P17 then
			for i, qualifier in ipairs( statement.qualifiers.P17 ) do
				local parentOptions = context.cloneOptions( options );
				local qualifierEntityId = qualifier.datavalue.value.id;
				parentOptions[ 'text' ] = getLabel( context, qualifierEntityId, boundaries );
				local link = context.formatSnak( parentOptions, qualifier );

				if p.config.reverseOrder then
					result = link .. ', ' .. result;
				else
					result = result .. ', ' .. link;
				end
				insertFromSnak( qualifier, entriesToLookupCategory )
				hasAdditionalQualifiers = true;
			end
		end
	end

	if statement.mainsnak and
		statement.mainsnak.datavalue and
		statement.mainsnak.datavalue.value and
		statement.mainsnak.datavalue.value.id
	then
		local entityId = statement.mainsnak.datavalue.value.id;
		local parentSnaks = { statement.mainsnak };
		local parentEntityIds = { entityId };

		if actualDateBoundariesProperties ~= nil then
			local filterCapitalOf = {
				[ entityId ] = getParentsInBoundariesSnakImpl( context, entityId, boundaries, {'P1376'} )
			};
			if boundaries then
				local entityOptions = context.cloneOptions( options );
				entityOptions['text'] = getLabel( context, entityId, boundaries );
				baseResult = context.formatSnak( entityOptions, statement.mainsnak, circumstances );

				local parentId = entityId;
				while parentId ~= nil do
					-- get parent
					local newParentSnaks = getParentsInBoundariesSnak( context, parentId, boundaries );
					if not newParentSnaks or #newParentSnaks == 0 then
						parentId = nil;
					elseif #newParentSnaks == 1 then
						local parentSnak = newParentSnaks[ 1 ];
						parentId = parentSnak.datavalue.value.id;

						table.insert( parentSnaks, parentSnak );
						table.insert( parentEntityIds, parentId );
						filterCapitalOf[ parentId ] = getParentsInBoundariesSnakImpl( context, parentId, boundaries, { 'P1376' } );
					else
						parentId = nil;
						if p.config and p.config.catAmbiguousGeoChains then
							result = result .. p.config.catAmbiguousGeoChains;
						end
					end
				end

				if not hasAdditionalQualifiers then
					for i = 2, #parentSnaks, 1 do
						local parentSnak = parentSnaks[ i ];
						insertFromSnak( parentSnak, entriesToLookupCategory )
					end
				end

				do
					local i = #parentSnaks;
					while i > 1 do
						local prevEntityId = parentEntityIds[ i - 1 ];
						-- TODO: use English labels, if there is no current language labels
						local prevLabel = getLabel( context, prevEntityId, boundaries ) or '';
						local nextEntityId = parentEntityIds[ i ];
						local nextLabel = getLabel( context, nextEntityId, boundaries ) or '';
						if p.config and p.config.hideSameLabels == true and prevLabel == nextLabel then
							-- do not output same label twice (NY, NY, USA)
							table.remove( parentSnaks, i );
							table.remove( parentEntityIds, i );
						elseif p.config and p.config.hidePartOfLabels == true and isPartOfNext( prevLabel, ' ' .. nextLabel ) then
							-- do not output same label if it's part of previos
							table.remove( parentSnaks, i - 1 );
							table.remove( parentEntityIds, i - 1 );
						elseif p.config and p.config.hideUnitsForCapitals == true then
							-- do not ouput items whose capital is the first item
							local capitalId = nil;
							for _capitalId, capitalSnaks in pairs( filterCapitalOf ) do
								if #capitalSnaks > 0 then
									for __, capitalSnak in pairs( capitalSnaks ) do
										if parentSnaks[ i ].datavalue.value.id == capitalSnak.datavalue.value.id then
											capitalId = _capitalId;
											break;
										end
									end
								end
							end
							if capitalId ~= nil then
								if i == #parentSnaks then
									i = i - 1;
								end
								while i > 1 and parentEntityIds[ i ] ~= capitalId do
									table.remove( parentSnaks, i );
									table.remove( parentEntityIds, i );
									i = i - 1;
								end
							end
						end
						i = i - 1;
					end
				end

				if isSkipTopLevel( parentEntityIds[ #parentEntityIds ] ) then
					table.remove( parentSnaks, #parentEntityIds );
					table.remove( parentEntityIds, #parentEntityIds );
				end

				if not hasAdditionalQualifiers then
					for i = 2, #parentSnaks, 1 do
						local parentSnak = parentSnaks[ i ];

						local parentOptions = context.cloneOptions( options );
						parentOptions['text'] = getLabel( context, parentEntityIds[ i ], boundaries );

						if p.config.reverseOrder then
							result = context.formatSnak( parentOptions, parentSnak ) .. ', ' .. result;
						else
							result = result .. ', ' .. context.formatSnak( parentOptions, parentSnak );
						end
					end
				end
			end
		end
	end

	if options[ 'thisLocationOnly' ] then
		result = baseResult  .. context.formatRefs( options, statement );
	elseif p.config.reverseOrder then
		result = result .. baseResult .. context.formatRefs( options, statement );
	else
		result = baseResult .. result .. context.formatRefs( options, statement );
	end

	if categorizeByPlace then
		if property == 'P19' then result = result .. getCategory( 'P1464', entriesToLookupCategory ); end
		if property == 'P20' then result = result .. getCategory( 'P1465', entriesToLookupCategory ); end
		if property == 'P119' then result = result .. getCategory( 'P1791', entriesToLookupCategory ); end
	end

	return result;
end

-- append entity id from snak to result
function insertFromSnak( snak, result )
	if not categorizeByPlace then
		return;
	end
	if snak and
		snak.datavalue and
		snak.datavalue.type == 'wikibase-entityid' and
		snak.datavalue.value and
		snak.datavalue.value[ 'entity-type' ] == 'item'
	then
		table.insert( result, snak.datavalue.value.id );
	end
end

function getCategory( propertyId, entriesToLookupCategoryFor )
	for _, placeId in pairs( entriesToLookupCategoryFor ) do
		local claims = mw.wikibase.getBestStatements(placeId, propertyId);

		if claims then
			for _, claim in pairs( claims ) do
				if claim.mainsnak and
					claim.mainsnak and
					claim.mainsnak.datavalue and
					claim.mainsnak.datavalue.type == 'wikibase-entityid'
				then
					local catEntityId = claim.mainsnak.datavalue.value.id;
					local catSitelink = mw.wikibase.getSitelink(catEntityId);
					if (catSitelink) then
						return '[[' .. catSitelink .. ']]';
					end
				end
			end
		end
	end
	return '';
end


local historicNamesProperties = { 'P1813', 'P1448', 'P1705' };

local langCode = mw.language.getContentLanguage():getCode();
local historicNamesPropertySelectors = {
		P1813 = 'P1813[language:' .. langCode .. ']',
		P1448 = 'P1448[language:' .. langCode .. ']',
		P1705 = 'P1705[language:' .. langCode .. ']'
};

-- get current of historic name of place
function getLabel( context, entityId, boundaries )
	if not entityId then
		return nil;
	end
	if (type(entityId) ~= 'string') then error('incorrect type of entityId argument'); end;

    local label = nil;

	-- name from properties
	local results = getParentsInBoundariesSnakImpl( context, entityId, boundaries,
		historicNamesProperties, historicNamesPropertySelectors);

	for r, result in pairs( results ) do
		if result.datavalue and
			result.datavalue.value and
			result.datavalue.value.text
		then
			label = result.datavalue.value.text;
			break;
		end
	end

    -- name from label
    if label == nil then
		label = mw.wikibase.getLabel( entityId );
    end

    return label;
end

p.getLabel = getLabel;

local function calculateEndDateTimestamp( context, options, statement )
	if not context then error( 'context not specified' ) end;
	if not options then error( 'options not specified' ) end;
	if not options.entity then error( 'options.entity missing' ) end;
	if not statement then error( 'statement not specified' ) end;

	if statement.qualifiers and statement.qualifiers.P582 then
		for i, qualifier in ipairs( statement.qualifiers.P582 ) do
			local parsedTime = context.parseTimeFromSnak( qualifier );
			if parsedTime then
				return parsedTime;
			end
		end
	end

	-- check death day... do we have it at all?
	for h, propertyId in pairs( { "P570", "P577", "P576" } ) do
		local dateClaims = context.selectClaims( options, propertyId );
		if dateClaims then
			for i, statement in ipairs( dateClaims ) do
				local parsedTime = context.parseTimeFromSnak( statement.mainsnak );
				if parsedTime then
					return parsedTime;
				end
			end
		end
	end

	-- TODO: check other "end" properties

	-- no death day
	return os.time() * 1000;
end

local function deleteTwinAncestors( countryEntityId, propertyId )
	local badTwin
	if ( countryEntityId == 'Q174193' ) then
		badTwin = 'Q145'
	elseif ( countryEntityId == 'Q838261' ) then
		badTwin = 'Q37024'
	else
		return true;
	end
	for _, claim in pairs( mw.wikibase.getBestStatements( mw.wikibase.getEntityIdForCurrentPage(), propertyId ) ) do
		if ( claim and claim.mainsnak
			and claim.mainsnak.datavalue
			and claim.mainsnak.datavalue.value
			and claim.mainsnak.datavalue.value.id ) then
			local actualId = claim.mainsnak.datavalue.value.id;
			if ( actualId == badTwin ) then
				return false;
			end
		end
	end
	return true; 
end