Leaguepedia | League of Legends Esports Wiki
Advertisement

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

local util_args = require('Module:ArgsUtil')
local util_cargo = require("Module:CargoUtil")
local util_html = require("Module:HtmlUtil")
local util_map = require('Module:MapUtil')
local util_table = require("Module:TableUtil")
local util_text = require("Module:TextUtil")
local util_vars = require("Module:VarsUtil")
local i18n = require("Module:I18nUtil")
local lang = mw.getLanguage('en')
local LCS = require('Module:LuaClassSystem')
local h = {}
local p = {}

local ILLEGAL_CHARACTERS = { 'File:' }

local RR = LCS.class()

function p.test(frame)
	local args = util_args.merge()
	return RR(args.text):run()
end

function p.main(text, args)
	return RR(tostring(text), args):run()
end

function RR:init(text, args)
	self.args = args or {}
	self.text = text
end

function RR:run()
	if util_args.castAsBool(self.args.allow_redirects) then return self.text end
	local links = self:getLinks()
	if #links == 0 then return self.text end
	-- local result = self:makeAndRunQuery(links)
	-- local newText = self:makeReplacements(result)
	return self.text
end

function RR:getLinks()
	local links = {}
	local hash = {}
	for link in self.text:gmatch('%[%[([^|#%%;"\']-)|') do
		if link and not hash[link] then
			hash[link] = true
			if not h.hasIllegalCharacter(link) then
				links[#links+1] = link
			end
		end
	end
	for link in self.text:gmatch('%[%[([^|#%%;"\']-)%]%]') do
		if link and not hash[link] then
			hash[link] = true
			if not h.hasIllegalCharacter(link) then
				links[#links+1] = link
			end
		end
	end
	return links
end

function h.hasIllegalCharacter(link)
	for _, char in ipairs(ILLEGAL_CHARACTERS) do
		if link:find(char) then
			return true
		end
	end
	return false
end

function RR:makeAndRunQuery(links)
	local query = {
		tables = { '_pageData' },
		where = {
			util_cargo.concatWhereOr(
				util_map.safe(links, util_map.formatInto, '_pageName="%s"')
			),
			'_isRedirect="1"',
		},
		fields = {
			'_pageName=Link',
			'_pageNameOrRedirect=Target',
		}
	}
	return util_cargo.getConstDict(query, 'Link', 'Target')
end

function RR:makeReplacements(result)
	local newText = self.text
	local wrapperEnd = '</span>'
	for link, target in pairs(result) do
		local wrapperStart = ('<span data-target="%s">'):format(link)
		newText = newText:gsub(
			('%%[%%[%s%%|(.-)]%%]'):format(link),
			('%s[[%s|%%1]]%s'):format(wrapperStart, target, wrapperEnd)
		):gsub(
			('%%[%%[(%s)%%]%%]'):format(link),
			('%s[[%s|%s]]%s'):format(wrapperStart, target, link, wrapperEnd)
		):gsub(
			('%%[%%[%s%%|(.-)]%%]'):format(util_text.lcfirst(link)),
			('%s[[%s|%%1]]%s'):format(wrapperStart, target, wrapperEnd)
		):gsub(
			('%%[%%[(%s)%%]%%]'):format(util_text.lcfirst(link)),
			('%s[[%s|%s]]%s'):format(wrapperStart, target, util_text.lcfirst(link), wrapperEnd)
		)
	end
	return newText
end

return p
Advertisement