Jump to content

Module:Interwiki extra

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 03:42, 21 January 2015 (add Prefix:isValidUrl). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- This module provides functions and objects for dealing with interwiki links.

local checkType = require('libraryUtil').checkType
local interwikiData = mw.loadData('Module:Interwiki/data')

--------------------------------------------------------------------------------
-- Prefix class
--------------------------------------------------------------------------------

local Prefix = {}
Prefix.__index = Prefix

function Prefix.new(code)
	checkType('Prefix.new', 1, code, 'string')
	local obj = setmetatable({}, Prefix)
	local data = interwikiData.prefixes[code]
	if not data then
		return nil
	end
	for k, v in pairs(data) do
		obj[k] = v
	end
	return obj
end

function Prefix:makeUrl(page)
	checkType('makeUrl', 1, page, 'string')
	-- In MediaWiki, interlanguage links are wiki-encoded (spaces are encoded
	-- as underscores), even if the site is not a wiki and underscores don't
	-- make sense. So we do the same here.
	page = mw.uri.encode(page, 'WIKI')
	return mw.message.newRawMessage(self.url, page):plain()
end

function Prefix:isValidUrl(url)
	checkType('isValidUrl', 1, url, 'string')
	local obj1 = mw.uri.new(self.url)
	local obj2 = mw.uri.new(url)
	if not obj2 then
		return false
	elseif obj1.protocol and obj1.protocol ~= obj2.protocol then
		-- Protocols only have to match if the prefix URL isn't protocol-relative
		return false
	elseif obj1.host ~= obj2.host then
		return false
	end
	local function makePathQuery(obj)
		return obj.path .. (obj.queryString or '')
	end
	local pathQuery1 = makePathQuery(obj1)
	local pathQuery2 = makePathQuery(obj2)
	-- Turn pathQuery1 into a string pattern by escaping all punctuation, then
	-- replacing the "$1" parameter (which will have become "%$1") with ".*"
	local pattern = pathQuery1:gsub('%p', '%%%0'):gsub('%%$1', '.*')
	pattern = '^' .. pattern .. '$'
	return pathQuery2:find(pattern) ~= nil
end

return Prefix