Jump to content

Module:Selected current events

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Evad37 (talk | contribs) at 01:14, 23 May 2018 (non-greedy quantifier). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

function setCleanArgs(argsTable)
	local cleanArgs = {}
	for key, val in pairs(argsTable) do
		if type(val) == 'string' then
			val = val:match('^%s*(.-)%s*$')
			if val ~= '' then
				cleanArgs[key] = val
			end
		else
			cleanArgs[key] = val
		end
	end
	return cleanArgs
end

-- Get current events for a "YYYY Month D" date. Returns a table of list items.
function getCurrentEvents(date, keepPatterns, skipPatterns)
	local title = mw.title.new("Portal:Current events/" .. date)
	local raw = title:getContent()
	local lines = mw.text.split( raw , '\n')
	local items = {}
	for i, v in ipairs(lines) do
		local keep = false
		local skip = false
		if string.sub( v, 0, 2 ) == '**' then
			local text = mw.ustring.gsub(v, "%[%[(.-)%]%]","%1") -- remove wikilink brackets for better pattern matching
			text = mw.ustring.gsub(text, "%|"," ") -- remove pipes that would have been in piped links
			text = mw.ustring.gsub(text, "%[.-%]"," ") -- remove external links
			for ii, keepPatt in pairs(keepPatterns) do
				if not keep and mw.ustring.find(v, keepPatt) then
					keep = true
				end
			end
			if #skipPatterns > 0 then
				for iii, skipPatt in pairs(skipPatterns) do
					if not skip and mw.ustring.find(v, skipPatt) then
						skip = true			
					end
				end
			end
		end
		if keep and not skip then
			local item = mw.ustring.gsub(v, "%*+","*")
			table.insert(items, item)
		end
	end
	return items
end



local p = {}

p.main = function(frame)
	local parent = frame.getParent(frame)
	local parentArgs = parent.args
	local args = setCleanArgs(parentArgs)
	if args['not'] and not args['not1'] then
		args['not1'] = args['not']
	end
	local lang = mw.language.new('en')

	local patterns = {}
	local skipPatterns = {}
	local ii = 1
	while args[ii] do
		patterns[ii] = args[ii]
		ii = ii + 1
	end
	local iii = 1
	while args['not'..iii] do
		skipPatterns[iii] = args['not'..iii]
		iii = iii + 1
	end

	if #patterns < 1 then
		return error("Search pattern not set")
	end

	local allItems = {}
	local daysAgo = 0
	while daysAgo < (tonumber(args.days) or 30) do
		local dailyItems = getCurrentEvents(lang:formatDate('Y F j', 'now - '..daysAgo..' days'), patterns, skipPatterns)
		for i, item in ipairs(dailyItems) do
			table.insert(allItems, item)
		end
		daysAgo = daysAgo + 1
	end

	if #allItems < 1 then
		return 'No recent news'
	end

	local output = ''
	local itemIndex = 1
	local maxItems = math.min(#allItems, (tonumber(args.max) or 6))
	while itemIndex <= maxItems do
		output = output .. allItems[itemIndex] .. '\n'
		itemIndex = itemIndex + 1
	end
	return output


end

return p