Jump to content

Module:DailyFeatured

From the Vrienden Universe, a fictional wiki

Documentation for this module may be created at Module:DailyFeatured/doc

local p = {}

local function getPool()
	local content = mw.getCurrentFrame():expandTemplate{ title = "Featured pool" }
	local pages = {}

	for line in mw.text.gsplit(content or "", "\n", true) do
		line = mw.text.trim(line)
		if line ~= "" then
			line = line:gsub("^%*%s*", "")
			if line ~= "" then
				table.insert(pages, line)
			end
		end
	end

	return pages
end

local function cleanWikitext(s)
	if not s or s == "" then
		return ""
	end
	s = s:gsub("<!--.-?-->", "")
	s = s:gsub("%[%[File:.-%]%]", "")
	s = s:gsub("%{%b{}%}", "")
	s = s:gsub("<ref.->.-</ref>", "")
	s = s:gsub("<ref.->", "")
	s = s:gsub("\r", ""):gsub("[ \t]+", " ")
	return mw.text.trim(s)
end

local function extractHeadlineFromContent(wikitext)
	if not wikitext or wikitext == "" then
		return ""
	end

	-- 1) Prefer lead text (first meaningful non-empty line before any heading)
	for line in mw.text.gsplit(wikitext, "\n", true) do
		local raw = line
		local cleaned = cleanWikitext(line)

		-- stop at first heading: end of lead section
		if raw:match("^==+%s*[^=].-==+%s*$") then
			break
		end

		if cleaned ~= ""
			and not cleaned:match("^__%u+__$")
			and not cleaned:match("^%[%[Category:") then
			if #cleaned > 200 then
				cleaned = cleaned:sub(1, 197) .. "…"
			end
			return cleaned
		end
	end

	-- 2) Fallback: first heading title
	for line in mw.text.gsplit(wikitext, "\n", true) do
		local cleaned = cleanWikitext(line)
		if cleaned:match("^==+%s*[^=].-==+%s*$") then
			cleaned = cleaned:gsub("^=+%s*", ""):gsub("%s*=+$", "")
			cleaned = mw.text.trim(cleaned)
			if cleaned ~= "" then
				return cleaned
			end
		end
	end

	-- 3) Final fallback: any meaningful line
	for line in mw.text.gsplit(wikitext, "\n", true) do
		local cleaned = cleanWikitext(line)
		if cleaned ~= ""
			and not cleaned:match("^__%u+__$")
			and not cleaned:match("^%[%[Category:") then
			if #cleaned > 200 then
				cleaned = cleaned:sub(1, 197) .. "…"
			end
			return cleaned
		end
	end

	return ""
end

function p.main(frame)
	local pages = getPool()
	if #pages == 0 then
		return "No featured pages defined."
	end

	local day = tonumber(os.date("%j")) -- day of year
	local index = (day % #pages) + 1
	local title = pages[index]

	local args = (frame and frame.args) or {}
	if args.titleonly == "1" then
		return title
	end

	local page = mw.title.new(title)
	local headline = ""

	if page and page.exists then
		local content = page:getContent() or ""
		headline = extractHeadlineFromContent(content)
	end

	if headline == "" then
		headline = "Featured page for " .. os.date("%d %B %Y") .. "."
	end

	return string.format(
		"'''[[%s]]'''<div style=\"margin-top:0.35em;\"><small>%s</small></div>",
		title,
		headline
	)
end

return p