Module:Fallback

From Wikifunctions

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

local p = {}

-- functions from dependant modules
local format = string.format
local insert = table.insert
local concat = table.concat
local trim = mw.text.trim
local getFallbacksFor = mw.language.getFallbacksFor
local messageNew = mw.message.new
local titleNew = mw.title.new -- maybe costly function call
local log = mw.log

local function exists(title)
	local ok, result = pcall(function()
		return titleNew(title).exists -- costly property read, may throw an error
	end) -- return (true, result) or (false, errorobject)
	return ok and result -- in case of error, assume false
end

-- List the full fallback chain from a language to default (usually English)
local function fblist(lang)
	local fbtable = getFallbacksFor(lang)
	insert(fbtable, 1, lang)
	--[[
	Take a translation from "Mediawiki:<Message-ID>/<language-code>" namespace
	or from a loaded i18 resource bundle in MediaWiki for its UI messages (also
	used by the "{{Int:<Message-ID>}}" parser function), before using the
	provided default value. Requires args.message = 'Message-ID', instead of
	args.message = 'actual translated message'.
	--]]
	insert(fbtable, 'message')
	insert(fbtable, 'default')
	return fbtable
end

-- args: table of translations; split keys into lists of individual language codes to be assigned with the same value
-- for example: {['en/fr']='variable'} like {['en']='variable', ['fr']="variable"}. Separators are any characters that are
-- not ASCII letters, digits, or hyphens; so you can also use ['en, fr'], or ['en fr'] keys.
-- The letter case for keys is never non-significant as language codes, so convert all keys to lowercase.
-- Note: the special keys "nocat" and "default" are treated like language codes.
local function splitlangs(args)
	local args2 = {}
	if type(args) == 'table' then
		for k, v in pairs(args) do
			if type(k) == 'string' then
				for c in k:gmatch('[%-0-9A-Za-z]+') do
						args2[c:lower()] = v
				end
			end
		end
	end
	return args2
end

--[==[
Return an error if there is not default and no English version, otherwise
return the message in the most appropriate, plus the lang code as a second value.
--]==]
local function _langSwitch(args, lang)
	-- Get the table of translations
	args = splitlangs(args)
	if not args.en and not args.default and not args.message and not args.nocat then
		return error("langSwitch error: no default")
	end
	-- Get language (either stated one or user's default language).
	if not lang then
		return '<strong class="error">langSwitch error: no lang</strong>' -- must become proper error
	end
	-- Get the list of acceptable language (lang + those in lang's fallback chain) and check their content.
	for _, code in ipairs(fblist(lang)) do
		local msg = args[code]
		if msg then
			-- Trim the assigned message value before testing it.
			msg = trim(msg)
			if msg ~= '' then
				if code == 'message' then
					-- If this is an UI message. See [[mw:Manual:Messages API]].
					msg = messageNew(args.message):inLanguage(lang)
					--[==[ If this message name does not exist, converting it to
					a string would not return an actual message, but this name
					within curved angle brackets U+29FC/U+29FD '⧼/⧽', 
					part of mathematical symbols). The UI message may also be
					disabled administratively if it causes problems.
					--]==]
					if msg:exists() and not msg:isDisabled() then
						--[==[FIXME: In which language is this message?
						This may be in some fallback language and not lang.
						Note that some UI messages may have placeholders like '%s'
						but there's no way to replace them here by actual values.
						--]==]
						return tostring(msg), lang
					end
				elseif msg == '~' then
					return nil, code
				else
					return msg, code
				end
			end
		end
	end
	return nil
end

--[==[
Version to be used from wikitext.
--]==]
local function langSwitch(frame)
	local args = splitlangs(frame.args)
	-- If no expected args provided, then check parent template/module args.
	if not args.en and not args.default and not args.nocat then
		args = frame:getParent().args
	end
	local lang
	if args.lang and args.lang ~= '' then
		lang = args.lang
		args.lang = nil
	else -- Get user's chosen language.
		lang = frame:preprocess('{{Int:Lang}}')
	end
	local str, language = _langSwitch(args, lang)
	return str -- Get the first value of the langSwitch, (the text) not the second (the language).
end

local function fallbackpage(base, lang, formatting)
	local fblangs = fblist(lang)
	for _, lang in ipairs(fblangs) do
		if exists(base .. '/' .. lang) then -- costly function call
			if formatting == 'table' then
				return {base .. '/' .. lang, lang} -- Returns name of the page + name of the language.
			else
				return base .. '/' .. lang -- Returns only the page.
			end
		end
	end
	return base
end

--[==[
Logic for [[Template:Autotranslate]].
]==]
local function autotranslate(frame)
	local args = frame.args
	if not args.lang or args.lang == '' then
		args.lang = frame:preprocess('{{Int:Lang}}') -- Get user's chosen language.
	end
	-- Find base page.
	local base = args.base
	if not base or base == '' then
		return '<strong class="error">Base page not provided for autotranslate</strong>'
	end
	if string.sub(base, 1, 9):lower() ~= 'template:' then -- the lettercase of the namespace is not significant
		base = 'Template:' .. base -- Base provided without 'Template:' part.
	end
	-- Find base template language subpage.
	local page = fallbackpage(base, args.lang)
	if not page and base ~= args.base then
		-- Try the original args.base string. This case is only needed if base is not in template namespace.
		page = fallbackpage(args.base, args.lang)
	end
	if not page then
		return format('<strong class="error">no fallback page found for autotranslate (base=[[%s]], lang=%s)</strong>', args.base, args.lang)
	end
	-- Repack args in a standard table.
	local newargs = {}
	for field, value in pairs(args) do
		if field ~= 'base' then
			newargs[field] = value
		end
	end
	-- Transclude {{page |....}} with template arguments the same as the ones passed to {{autotranslate}} template.
	return frame:expandTemplate{ title = page, args = newargs }
end

--[==[
Translate data stored in a module.
]==]
local function translate(page, key, lang)
	if type(page) == 'string' then -- If the requested translation table is not yet loaded.
		page = require('Module:' .. page)
	end
	local val
	if page[key] then
		val = page[key]
	elseif page.keys and page.keys[key] then -- Key 'keys" is an index of all keys, including redirects, see [[Module:i18n/datatype]].
		val = page.keys[key]
	end
	if val then
		return _langSwitch(val, lang)
	else
		return '⧼' .. key .. '⧽' -- U+29FC/U+29FD, like with '{{int:key}}' where message with that key does not exist
	end
end

local function translatelua(frame)
	local lang = frame.args.lang
	local page = require('Module:' .. trim(frame.args[1])) -- Page should only contain a simple of translations.
	if not lang or trim(lang) == '' then
		lang = frame:preprocess('{{Int:Lang}}')
	end
	if frame.args[2] then
		page = page[trim(frame.args[2])]
	end
	return _langSwitch(page, lang)
end

-- This test does not work ('Module:Fallback/tests/fallbacks' is missing)
local function runTests()
	local toFallbackTest = require('Module:Fallback/tests/fallbacks')
	local result = true
	log('Testing fallback chains')
	for i, t in ipairs(toFallbackTest) do
		local fbtbl = concat(fblist(t.initial), ', ')
		local expected = concat(t.expected, ', ')
		local ret = (fbtbl == expected)
		log(i, ret and 'passed' or 'FAILED', t.initial, (not ret) and ('FAILED\nis >>' .. fbtbl .. '<<\nbut should be >>' .. expected .. '<<\n') or '')
		result = result and ret
	end
	return result
end

--[==[
List all input arguments of the template that calls "{{#invoke:Fallback|showTemplateArguments}}"
]==]
local function showTemplateArguments(frame)
	local str = ''
	for name, value in pairs(frame:getParent().args) do
		if str == '' then
			str = format('%s=%s', name, value) -- argument #1
		else
			str = format('%s, %s=%s', str, name, value) -- the rest
		end
	end
	return str
end

-- exports
return {
	fblist = fblist,
	_langSwitch = _langSwitch,
	langSwitch = langSwitch,
	autotranslate = autotranslate,
	fallbackpage = fallbackpage,
	translate = translate,
	translatelua = translatelua,
	showTemplateArguments = showTemplateArguments,
	runTests = runTests,
exists = exists,
}