Modiwl:Commons category

Documentation for this module may be created at Modiwl:Commons category/doc

--script that retrieves basic data stored in Wikidata, for the datamodel, 
-- see https://www.mediawiki.org/wiki/Extension:Wikibase_Client/Lua
local p = {}

-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.pageId(frame)
	local entity = mw.wikibase.getEntityObject()
	if not entity then return nil else return entity.id end
end

-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata. 
-- Redirects from category items to article items
function p.articleId(frame)
	local entity
	local q = frame.args.wikidata or frame.args.Wikidata
	if q then
		entity = mw.wikibase.getEntityObject(q)
	else
		entity = mw.wikibase.getEntityObject()
	end	
	local qCode = nil

	if entity then 
		local s = entity:getBestStatements( 'P31' )
		if s[1] and s[1].mainsnak.datavalue.value['numeric-id']==4167836 then 
			-- if "instance of" (P31) = "Wikimedia category" (Q4167836)
			s = entity:getBestStatements( 'P301' ) -- category's main topic 
			if s[1] then
				-- if property "category's main topic" (P301) is set
				qCode = 'Q'..s[1].mainsnak.datavalue.value['numeric-id']  
			end
		else
			-- if "instance of" (P31) != "Wikimedia category" (Q4167836)
			qCode = entity.id 
		end
	end
	return qCode
end

-- returns name of commons category stored in one of 3 possible places
-- INPUTS:
--   Wikidata - optional wikidata q-code (used mostly for testing)
--   link     - number between 1 and 3, specifies which one of 3 links to fillow
--              used for testing
function p.property373(frame)
	local entity
	local q = frame.args.wikidata or frame.args.Wikidata
	local n = frame.args.link or '0'
	local n = tonumber(n)
	if q then
		entity = mw.wikibase.getEntityObject(q)
	else
		entity = mw.wikibase.getEntityObject()
	end
	if entity then 
		-- Link #1: sitelink from category item
		local sitelink = entity:getSitelink('commonswiki')
		if sitelink and mw.ustring.match( sitelink, 'Category:') and (n==0 or n==1) then
			sitelink = mw.ustring.gsub( sitelink, 'Category:', '')
			return sitelink
		end
		-- Link #2: property P373 from category item
		local s = entity:getBestStatements( 'P373' )
		if s[1] and s[1].mainsnak.datavalue.value and (n==0 or n==2) then 
			return s[1].mainsnak.datavalue.value
		end
		-- Link #3: property P373 from article item
		s = entity:getBestStatements( 'P301' ) -- category's main topic 
		if s[1] then -- if property "category's main topic" (P301) is set
			qCode = 'Q'..s[1].mainsnak.datavalue.value['numeric-id']  
			entity = mw.wikibase.getEntityObject(qCode)
			if entity then 
				local s = entity:getBestStatements( 'P373' )
				if s[1] and s[1].mainsnak.datavalue.value and (n==0 or n==3)  then 
					return s[1].mainsnak.datavalue.value
				end
			end
		end
	end
	return n
end

return p