Jump to content

Module:Portal pictures

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Andrybak (talk | contribs) at 13:49, 25 October 2020 (fixup). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local getArgs = require('Module:Arguments').getArgs

p = {}

local function wikiError(message)
	return mw.html.create('div'):addClass('error'):wikitext(message)
end

local function getDefaultMoreLink(frame)
	local title = mw.title.getCurrentTitle()
	if title.isSubpage
	then
		return ""
	end
	return "[[" .. title.prefixedText .. "/Selected picture|More selected pictures...]]"
end

local function getPortalPotdText(frame, candidateDate, more)
	return frame:expandTemplate{
		title = "Portal POTD",
		args = {
			candidateDate,
			["more"] = more
		}
	}
end

local function extractDates(args)
	local dates = {}
	for key, value in pairs(args) do
		if value and type(key) == "number" then
			table.insert(dates, value)
		end
	end
	return dates
end

local function gallery(frame)
	local args = getArgs(frame)
	local texts = {}
	for key, value in pairs(args) do
		if value and type(key) == "number" then
			table.insert(texts,	"[[Template:POTD/" .. value .. "]]\n\n" .. getPortalPotdText(frame, value, " "))
		end
	end
	return table.concat(texts, "\n----\n")
end

local function selectRandom(frame)
	local args = getArgs(frame)
	local more = args["more"] or getDefaultMoreLink(frame)
	local dates = extractDates(args)
	
	local dateCount = #dates
	if dateCount <= 0
	then
		return wikiError("Pictures are not specified")
	end

	local text
	local candidateKey = 1
	if dateCount > 1 then math.randomseed(os.time()) end
	
	while (not text or text == "") and dateCount > 0 do
		if dateCount > 1 then candidateKey = math.random(dateCount) end
		local candidateDate = dates[candidateKey]
		local candidateTitle = mw.title.new("POTD/" .. candidateDate, "Template")
		if candidateTitle and candidateTitle.exists
		then
			text = getPortalPotdText(frame, candidateDate, more)
		end
		table.remove(dates, candidateKey)
		dateCount = dateCount - 1
	end
	if not text or text == ""
	then
		return wikiError("None of the specified pictures exist")
	end
	return text
end

function main(frame)
	local title = mw.title.getCurrentTitle()
	if title.isSubpage
	then
		return gallery(frame)
	else
		return selectRandom(frame)
	end
end

p.main = main
p.selectRandom = selectRandom
p.gallery = gallery

return p