Jump to content

Module:UserLinks/shared

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 05:55, 3 April 2014 (make makeWikilink function more flexible). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- This module stores functions that are shared between [[Module:UserLinks]]
-- and [[Module:UserLinks/extra]].

-- Load data and define often-used variables
local data = mw.loadData('Module:UserLinks/data')
local namespaces = mw.site.namespaces

-- Define namespaces for which links need to be escaped with the colon trick.
-- See [[w:en:Help:Colon trick]].
local colonNamespaces = {
	[6] = true, -- File
	[14] = true, -- Category
}

local p = {}

function p.raiseError(message, section, level)
	if section then
		message = message .. '|' .. section
	end
	if not level or level == 0 then
		level = 0
	else
		level = level + 1
	end
	error(message, level)
end

function p.makeWikitextError(encodedMessage, demo)
	local message, section = mw.ustring.match(encodedMessage, '^(.-)|(.*)$')
	message = message or encodedMessage
	if section then
		section = ' ([[Template:User-multi#' .. section .. '|help]])'
	else
		section = ''
	end
	local category
	if not demo then
		category = '[[Category:UserLinks transclusions with errors]]'
		mCategoryHandler = require('Module:Category handler')
		category = mCategoryHandler.main{
			all = category -- Categorise all namespaces, but not blacklisted pages.
		}
	end
	category = category or ''
	return string.format(
		'<strong class="error">[[Template:User-multi|User-multi]] error: %s%s.</strong>%s',
		message, section, category
	)
end

function p.makeWikilink(interwiki, namespace, page, display)
	interwiki = interwiki or ''
	local colon
	if interwiki ~= '' then
		interwiki = interwiki .. ':'
		colon = ':'
	elseif colonNamespaces[namespace] then
		colon = ':'
	end
	colon = colon or ''
	local nsText = namespaces[namespace].name
	if namespace ~= 0 then
		nsText = nsText .. ':'
	end
	if display then
		display = display:gsub(' ', '&nbsp;')
		return string.format(
			'[[%s%s%s%s|%s]]',
			colon, interwiki, nsText, page, display
		)
	else
		return string.format(
			'[[%s%s%s%s]]',
			colon, interwiki, nsText, page
		)
	end
end

function p.makeUrlLink(page, query, display)
	query = query or {}
	local url = mw.uri.fullUrl(page, query)
	url = tostring(url)
	if display then
		display = display:gsub(' ', '&nbsp;')
		return string.format('[%s %s]', url, display)
	else
		return string.format('[%s]', url)
	end
end

function p.message(key)
	local msg = data[key]
	return msg or p.raiseError(
		'No message found with key "' .. tostring(key) .. '"',
		'No message found',
		2
	)
end

return p