Module:Wikibase utils

--[=[ Utility functions for handling Wikibase entity data

Functions in this module should be highly generic ]=]

local p = {} --p stands for package

--[=[ Get the entity for a QID, or a page title ]=] function p.getEntity( titleOrQid ) local item local t = type( titleOrQid ) if t == 'table' then -- this is a title object item = mw.wikibase.getEntity(			mw.wikibase.getEntityIdForTitle( titleOrQid.fullText )		) elseif t == 'number' then -- construct a QID string item = mw.wikibase.getEntity( 'Q' .. titleOrQid ) elseif t == 'string' then if string.match( titleOrQid, 'Q%d+$', 1 ) then -- it's a QID item = mw.wikibase.getEntity( titleOrQid ) else -- assume it's a page title string item = mw.wikibase.getEntity(				mw.wikibase.getEntityIdForTitle( titleOrQid )			) end end return item end

--[=[ Return a table of qualifiers for a statement with the given qualifier property

If the statement does not have that qualifier, or has no qualifiers at all, return an empty table. ]=] function p.getQualifiersOfStatementWithPid( statement, wantedQualifierPid ) local qualifiers = statement.qualifiers or {} local matchingQualifiers = qualifiers[ wantedQualifierPid ] or {} return matchingQualifiers end

--[=[ Return the value Qid of a snak Returns nil if the snak datatype is not wikibase-item or has no value --]=] function p.getSnakValueQid( snak ) -- bad data type if snak.snaktype ~= 'value' or snak.datatype ~= 'wikibase-item' or snak.datavalue.type ~= 'wikibase-entityid' then return nil end return snak.datavalue.value.id end

--[=[ Return the year of a date snak Returns nil if the snak datatype is not type 'time' or has no value --]=] function p.getSnakValueYear( snak ) -- bad data type if snak.snaktype ~= 'value' or snak.datatype ~= 'time' or snak.datavalue.type ~= 'time' then return nil end local yrStr = string.gsub( snak.datavalue.value.time, '[+-]?(%d+)-.*', '%1' ) return tonumber( yrStr ) end

return p