Module:Broken links

-- Module to generate wikitext broken external link reports. -- Uses data from 'Module:Broken links/brokenLinks.json'. -- Example usage: --  -- Console example: --  mw.log(p._main)

require('strict')

local p = {} local yesno = require('Module:Yesno') local arguments = require("Module:Arguments")

local json_default = "brokenLinks.json"

local function _generate_wikitext(json, page, pattern) local wikitext = {} table.insert(wikitext, ": Generator: " .. json.tool) table.insert(wikitext, ": Timestamp: " .. json.timestamp) local articles = {} for article, links in pairs(json.results) do		table.insert(articles, {article, links}) end if page == "" then table.sort(articles, function (v1, v2) return v1[1] < v2[1] end) end local counter = 0 for _, pair in ipairs(articles) do		local article, links = unpack(pair) if page == "" or article == page then table.insert(wikitext, "* " .. article .. "") local previous_counter = counter for link, status_ in pairs(links) do				if status_:match(pattern) then table.insert(wikitext, "** " .. link .. " (" .. status_ .. ")")					counter = counter + 1 end end if counter == previous_counter then table.remove(wikitext) end end end local summary = ": Total " .. #articles .. " articles, " .. counter .. (counter == 1 and " broken link" or " broken links") if page ~= "" then summary = summary .. ", page '" .. page .. "'"				.. (json.results[page] == nil and " (no data)" or "") end if pattern ~= "" then summary = summary .. ", filtered by '" .. pattern .. "'"	end table.insert(wikitext, 3, summary) return wikitext end

local function _load_data(args) local json_source = args["json_data"] or args[1] or json_default

local json = nil if json_source:match("^Module:") then json = mw.loadJsonData(json_source) else json = mw.loadJsonData("Module:Broken links/" .. json_source) end return json end

function p._main(args) args = args or {} local json = _load_data(args)

local pattern = args["pattern"] or args[2] or "" local page = args["page"] or args[3] or "" local wikitext = _generate_wikitext(json, page, pattern)

local is_summary = yesno(args["summary"] or args[4] or "false") if is_summary then return table.concat({unpack(wikitext, 1, 3)}, "\n") .. "\n" else return table.concat(wikitext, "\n") .. "\n" end end

function p.main(frame) local args = arguments.getArgs(frame,		{trim = true, removeBlanks = true, frameOnly = true}) return p._main(args) end

return p