Module:Pagetype: Difference between revisions

From Zoophilia Wiki
Jump to navigationJump to search
(Created page with "-------------------------------------------------------------------------------- -- -- --...")
m (1 revision imported)
 
(2 intermediate revisions by 2 users not shown)
Line 16: Line 16:
local getArgs = require('Module:Arguments').getArgs
local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')
local yesno = require('Module:Yesno')
local nsDetectModule = require('Module:Namespace detect')
local mDisambiguation = require('Module:Disambiguation')
local nsDetect = nsDetectModule._main
local getParamMappings = nsDetectModule.getParamMappings
local getPageObject = nsDetectModule.getPageObject


local p = {}
local p = {}


local function shallowCopy(t)
-- Look up a namespace argument in the args table.
-- Makes a shallow copy of a table.
local function lookUpNamespaceArg(args, key)
local ret = {}
local arg = args[key]
for k, v in pairs(t) do
-- Convert "yes", "1" etc. to true, "no", "0" etc. to false, and leave
ret[k] = v
-- other values the same.
return yesno(arg, arg)
end
 
-- Append multiple values to an array
local function appendMultiple(target, source)
for _, value in ipairs(source) do
table.insert(target, value)
end
end
return ret
end
end


local function checkPagetypeInput(namespace, val)
-- Get argument keys for a title's namespace
-- Checks to see whether we need the default value for the given namespace,
local function getNamespaceArgKeys(title, cfg)
-- and if so gets it from the pagetypes table.
local nsInfo = mw.site.namespaces[title.namespace]
-- The yesno function returns true/false for "yes", "no", etc., and returns
local customAliases = cfg.customNamespaceAliases[title.namespace] or {}
-- val for other input.
local keys = {}
local ret = yesno(val, val)
if nsInfo.name ~= '' then
if ret and type(ret) ~= 'string' then
table.insert(keys, nsInfo.name)
ret = cfg.pagetypes[namespace]
end
if nsInfo.canonicalName ~= nsInfo.name and nsInfo.canonicalName ~= '' then
table.insert(keys, nsInfo.canonicalName)
end
end
return ret
appendMultiple(keys, nsInfo.aliases)
appendMultiple(keys, customAliases)
return keys
end
end


local function getPagetypeFromClass(class, param, aliasTable, default)
-- Get the argument for a title's namespace, if it was specified in the args
-- Gets the pagetype from a class specified from the first positional
-- table.
-- parameter.
local function getNamespaceArg(title, args, cfg)
param = yesno(param, param)
if title.isTalkPage then
if param ~= false then -- No check if specifically disallowed.
return lookUpNamespaceArg(args, cfg.talk)
for _, alias in ipairs(aliasTable) do
end
if class == alias then
for _, key in ipairs(getNamespaceArgKeys(title, cfg)) do
if type(param) == 'string' then
local arg = lookUpNamespaceArg(args, mw.ustring.lower(key))
return param
if arg ~= nil then
else
return arg
return default
end
end
end
end
end
return nil
end
-- Look up a page type specific to the title's namespace
local function getExplicitPageType(title, cfg)
if title.isTalkPage then
return cfg.talkDefault
else
return cfg.pagetypes[title.namespace]
end
end
-- Get a default page type that is not specific to the title's namespace
local function getDefaultPageType(args, cfg)
local other = lookUpNamespaceArg(args, cfg.other)
if type(other) == 'string' then
return other
else
return cfg.otherDefault
end
end
local function detectRedirects(title, args)
local redirect = lookUpNamespaceArg(args, cfg.redirect)
if redirect == false then
-- Don't detect redirects if they have been specifically disallowed.
return nil
end
-- Allow custom values for redirects.
if not title.isRedirect then
return nil
elseif type(redirect) == 'string' then
return redirect
else
return cfg.redirectDefault
end
end
end
end


local function getNsDetectValue(args)
local function detectDisambiguationPages(title, args, cfg)
-- Builds the arguments to pass to [[Module:Namespace detect]] and returns
if title.namespace ~= 0 then
-- the result.
-- Only detect disambiguation pages in mainspace
return nil
end
 
local dab = lookUpNamespaceArg(args, cfg.dab)
if dab == false then
-- Don't detect disambiguation pages if explicitly disallowed
return nil
end


-- Get the default values.
if not mDisambiguation.isDisambiguation(title:getContent()) then
local ndArgs = {}
return nil
local defaultns = args[cfg.defaultns]
elseif type(dab) == 'string' then
if defaultns == cfg.defaultnsAll then
return dab
ndArgs = shallowCopy(cfg.pagetypes)
else
else
local defaultnsArray
return cfg.dabDefault
if defaultns == cfg.defaultnsExtended then
defaultnsArray = cfg.extendedNamespaces
elseif defaultns == cfg.defaultnsNone then
defaultnsArray = {}
else
defaultnsArray = cfg.defaultNamespaces
end
for _, namespace in ipairs(defaultnsArray) do
ndArgs[namespace] = cfg.pagetypes[namespace]
end
end
end
end


--[[
-- Gets the pagetype from a class specified from the first positional
-- Add custom values passed in from the arguments. These overwrite the
-- parameter.
-- defaults. The possible argument names are fetched from
local function getPageTypeFromClass(args, class, key, aliasTable, default)
-- Module:Namespace detect automatically in case new namespaces are
local arg = lookUpNamespaceArg(args, key)
-- added. Although we accept namespace aliases as parameters, we only pass
if arg == false then
-- the local namespace name as a parameter to Module:Namespace detect.
-- Don't check for this class if it is specifically disallowed.
-- This means that the "image" parameter can overwrite defaults for the
return nil
-- File: namespace, which wouldn't work if we passed the parameters through
-- separately.
--]]
local mappings = getParamMappings()
for ns, paramAliases in pairs(mappings) do
-- Copy the aliases table, as # doesn't work with tables returned from
-- mw.loadData.
paramAliases = shallowCopy(paramAliases)
local paramName = paramAliases[1]
-- Iterate backwards along the array so that any values for the local
-- namespace names overwrite those for namespace aliases.
for i = #paramAliases, 1, -1 do
local paramAlias = paramAliases[i]
local ndArg = checkPagetypeInput(paramAlias, args[paramAlias])
if ndArg == false then
-- If any arguments are false, convert them to nil to protect
-- against breakage by future changes to
-- [[Module:Namespace detect]].
ndArgs[paramName] = nil
elseif ndArg then
ndArgs[paramName] = ndArg
end
end
end
end
-- Check for disambiguation-class and N/A-class pages in mainspace.
if aliasTable[class] then
if ndArgs.main then
if type(arg) == 'string' then
local class = args[1]
return arg
if type(class) == 'string' then
-- Put in lower case so e.g. "Dab" and "dab" will both match.
class = mw.ustring.lower(class)
end
local dab = getPagetypeFromClass(
class,
args[cfg.dab],
cfg.dabAliases,
cfg.dabDefault
)
if dab then
ndArgs.main = dab
else
else
local na = getPagetypeFromClass(
return default
class,
args[cfg.na],
cfg.naAliases,
cfg.naDefault
)
if na then
ndArgs.main = na
end
end
end
end
end
-- If there is no talk value specified, use the corresponding subject
return nil
-- namespace for talk pages.
end
if not ndArgs.talk then
 
ndArgs.subjectns = true
-- Get page types for mainspaces pages with an explicit class specified
local function getMainNamespaceClassPageType(title, args, cfg)
if title.namespace ~= 0 then
return nil
end
end
-- Add the fallback value. This can also be customised, but it cannot be
local class = args[1]
-- disabled.
if type(class) == 'string' then
local other = args[cfg.other]
-- Put in lower case so e.g. "na" and "NA" will both match.
-- We will ignore true/false/nil results from yesno here, but using it
class = mw.ustring.lower(class)
-- anyway for consistency.
end
other = yesno(other, other)
return getPageTypeFromClass(
if type(other) == 'string' then
args,
ndArgs.other = other
class,
cfg.na,
cfg.naAliases,
cfg.naDefault
)
end
 
-- Get page type specified by an explicit namespace argument.
local function getNamespaceArgPageType(title, args, cfg)
local namespaceArg = getNamespaceArg(title, args, cfg)
if namespaceArg == true then
-- Namespace has been explicitly enabled, so return the default for
-- this namespace
return getExplicitPageType(title, cfg)
elseif namespaceArg == false then
-- Namespace has been explicitly disabled
return getDefaultPageType(args, cfg)
elseif namespaceArg then
-- This namespaces uses custom text
return namespaceArg
else
else
ndArgs.other = cfg.otherDefault
return nil
end
end
-- Allow custom page values.
ndArgs.page = args.page
return nsDetect(ndArgs)
end
end


local function detectRedirects(args)
-- Whether the title is in the set of default active namespaces which are
local redirect = args[cfg.redirect]
-- looked up in cfg.pagetypes.
-- The yesno function returns true/false for "yes", "no", etc., and returns
local function isInDefaultActiveNamespace(title, args, cfg)
-- redirect for other input.
local defaultNamespacesKey = args[cfg.defaultns]
redirect = yesno(redirect, redirect)
if defaultNamespacesKey == cfg.defaultnsAll then
if redirect == false then
return true
-- Detect redirects unless they have been explicitly disallowed with
end
-- "redirect=no" or similar.
 
return
local defaultNamespaces
if defaultNamespacesKey == cfg.defaultnsExtended then
defaultNamespaces = cfg.extendedNamespaces
elseif defaultNamespacesKey == cfg.defaultnsNone then
defaultNamespaces = {}
else
defaultNamespaces = cfg.defaultNamespaces
end
end
local pageObject = getPageObject(args.page)
return defaultNamespaces[title.namespace] or false
-- If we are using subject namespaces elsewhere, do so here as well.
end
if pageObject
 
and not yesno(args.talk, true)
-- Get page type not specified or detected by other means
and args[cfg.defaultns] ~= cfg.defaultnsAll
local function getOtherPageType(title, args, cfg)
then
if isInDefaultActiveNamespace(title, args, cfg) then
pageObject = getPageObject(
return getExplicitPageType(title, cfg)
pageObject.subjectNsText .. ':' .. pageObject.text
else
)
return getDefaultPageType(args, cfg)
end
end
-- Allow custom values for redirects.
end
if pageObject and pageObject.isRedirect then
 
if type(redirect) == 'string' then
local function getPageType(title, args, cfg)
return redirect
return (
else
detectRedirects(title, args, cfg)
return cfg.redirectDefault
or detectDisambiguationPages(title, args, cfg)
or getMainNamespaceClassPageType(title, args, cfg)
or getNamespaceArgPageType(title, args, cfg)
or getOtherPageType(title, args, cfg)
)
end
 
local function shouldUseSubjectTitle(args, cfg)
return not yesno(args.talk, true) and args[cfg.defaultns] ~= cfg.defaultnsAll
end
 
-- Get the Scribunto title object to fetch the page type of
local function getTitle(args, cfg)
local title
if args.page then
title = mw.title.new(args.page)
if not title then
return nil
end
end
else
title = mw.title.getCurrentTitle()
end
if shouldUseSubjectTitle(args, cfg) then
return title.subjectPageTitle
else
return title
end
end
end
end


function p._main(args)
local function pluralize(pageType, cfg)
local redirect = detectRedirects(args)
if cfg.irregularPlurals[pageType] then
local pagetype = ""
return cfg.irregularPlurals[pageType]
if redirect then
pagetype = redirect
else
else
pagetype = getNsDetectValue(args)
return pageType .. cfg.plural -- often 's'
end
end
end
local function capitalize(pageType)
local first = mw.ustring.sub(pageType, 1, 1)
local rest = mw.ustring.sub(pageType, 2)
return mw.ustring.upper(first) .. rest
end
function p._main(args)
local title = getTitle(args, cfg)
local pageType = getPageType(title, args, cfg)
if yesno(args.plural, false) then
if yesno(args.plural, false) then
if cfg.irregularPlurals[pagetype] then
pageType = pluralize(pageType, cfg)
pagetype = cfg.irregularPlurals[pagetype]
else
pagetype = pagetype .. cfg.plural -- often 's'
end
end
end
if yesno(args.caps, false) then
if yesno(args.caps, false) then
pagetype = mw.ustring.upper(mw.ustring.sub(pagetype, 1, 1)) ..
pageType = capitalize(pageType)
mw.ustring.sub(pagetype, 2)
end
end
return pagetype
return pageType
end
end



Latest revision as of 20:03, 28 November 2023

This module is used to detect the page type of a given page. It detects redirect pages automatically and is highly customisable. It can be used on its own or as a meta-module to create other page-type-detection templates. This module can also be accessed using {{pagetype}}.

Syntax

Basic usage
{{#invoke:pagetype|main}}
All parameters
{{#invoke:pagetype|main
| page              = 
| defaultns         = 
| main              = 
| user              = 
| wikipedia         = 
| project           = 
| wp                = 
| file              = 
| image             = 
| mediawiki         = 
| template          = 
| help              = 
| category          = 
| portal            = 
| book              = 
| draft             = 
| education program = 
| timedtext         = 
| module            = 
| topic             = 
| special           = 
| media             = 
| talk              = 
| redirect          = 
| dab               = 
| na                = 
| other             = 
| plural            = 
}}

Basic usage

For simple detection of the page type of the current page, use the default settings:

{{#invoke:pagetype|main}}

That will produce the following results, depending on the page type or the namespace:

Page type / namespace Output
Redirects (in any namespace) redirect
Main namespace article
File namespace file
Template namespace template
Category namespace category
Module namespace module
Book namespace book
Other namespaces page

If the module is used on a talk page, it will detect the page type for the corresponding subject page.

Example
Code Result
{{#invoke:pagetype|main}} module

Page parameter

You can use the page parameter to make the module act as though it was called from that page.

{{#invoke:pagetype|main|page=page name}}
Examples
Code Result
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=UK}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom}} article
{{#invoke:pagetype|main|page=File:Example.svg}} file
{{#invoke:pagetype|main|page=Wikipedia:Namespace}} article
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt}} article

Adding and removing namespaces

It is possible to specify different behaviour for each namespace than that described in the basic usage section. For example, you might want the module to display "user page" for pages in the user namespace, instead of the default "page". To do this, you can use the code |user=yes. This looks up the typical name used for pages in the user namespace, in this case "user page", and uses that text when the module is used with a page in the user namespace. To use this with other namespaces, use the namespace name in lower case as a parameter:

{{#invoke:pagetype|main
| user              = yes
| wikipedia         = yes
| project           = yes
| wp                = yes
| mediawiki         = yes
| help              = yes
| portal            = yes
| draft             = yes
| education program = yes
| timedtext         = yes
| topic             = yes
| special           = yes
| media             = yes
}}

You can use any of the following to specify the namespace: "yes", "y", "true" or "1". They can be used in any combination of upper and lower case. (These values are defined by Module:Yesno.)

The default text for these namespaces is as follows:

Page type / namespace Output
User namespace user page
Wikipedia namespace project page
MediaWiki namespace interface page
Help namespace help page
Portal namespace portal
Draft namespace draft
Education program namespace education program page
Timed Text namespace Timed Text page
Topic namespace topic
Special namespace special page
Media namespace file

You can use a similar process to remove any of the default namespace values as well. For example, if you use the code |template=no, then the module will display "page" when used on a template page, rather than the default "template".

{{#invoke:pagetype|main
| main     = no
| file     = no
| template = no
| category = no
| module   = no
| book     = no
}}

The following values will all work to remove namespace values: "no", "n", "false" or "0". They can be used in any combination of upper and lower case.

Examples
Code Result
{{#invoke:pagetype|main|page=Wikipedia:Namespace}} article
{{#invoke:pagetype|main|page=Wikipedia:Namespace|wikipedia=yes}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom|talk=y}} talk page
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|main=no}} page
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt}} article
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt|timedtext=Yes}} article

Default namespace sets

As well as adding and removing individual namespaces, it is possible to specify different sets of namespaces by using the |defaultns=. There are four different sets available: all, extended, none and the default set. These sets allow you to specify many namespaces at once, without having to use all of the individual namespace parameters. Namespaces are set according to the following table:

Namespace Value of |defaultns= Output
none extended all Other values
Main ☒N ☑Y ☑Y ☑Y article
User ☒N ☑Y ☑Y ☒N user page
Wikipedia ☒N ☑Y ☑Y ☒N project page
File ☒N ☑Y ☑Y ☑Y file
MediaWiki ☒N ☑Y ☑Y ☒N interface page
Template ☒N ☑Y ☑Y ☑Y template
Help ☒N ☑Y ☑Y ☒N help page
Category ☒N ☑Y ☑Y ☑Y category
Portal ☒N ☑Y ☑Y ☒N portal
Book ☒N ☑Y ☑Y ☑Y book
Draft ☒N ☑Y ☑Y ☒N draft
Education Program ☒N ☒N ☑Y ☒N education program page
TimedText ☒N ☒N ☑Y ☒N Timed Text page
Module ☒N ☑Y ☑Y ☑Y module
Topic (Flow boards) ☒N ☒N ☑Y ☒N topic
All talk namespaces ☒N ☒N ☑Y ☒N talk page
Special ☒N ☒N ☑Y ☒N special page
Media ☒N ☒N ☑Y ☒N file
Examples
Code Result
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|defaultns=none}} page
{{#invoke:pagetype|main|page=Talk:United Kingdom}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom|defaultns=all}} talk page
{{#invoke:pagetype|main|page=File:Example.svg}} file
{{#invoke:pagetype|main|page=File:Example.svg|defaultns=none}} page
{{#invoke:pagetype|main|page=Wikipedia:Namespace}} article
{{#invoke:pagetype|main|page=Wikipedia:Namespace|defaultns=extended}} article
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt|defaultns=extended}} article
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt|defaultns=all}} article

Custom namespace values

It is possible to specify a custom value for any namespace:

{{#invoke:pagetype|main
| main              = custom text
| user              = custom text
| wikipedia         = custom text
| project           = custom text
| wp                = custom text
| file              = custom text
| image             = custom text
| mediawiki         = custom text
| template          = custom text
| help              = custom text
| category          = custom text
| portal            = custom text
| book              = custom text
| draft             = custom text
| education program = custom text
| timedtext         = custom text
| module            = custom text
| topic             = custom text
| special           = custom text
| media             = custom text
}}
Examples
Code Result
{{#invoke:pagetype|main|page=Wikipedia:Namespace}} article
{{#invoke:pagetype|main|page=Wikipedia:Namespace|wikipedia=custom text}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom}} article
{{#invoke:pagetype|main|page=Talk:United Kingdom|talk=custom text}} custom text
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|main=custom text}} custom text
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt}} article
{{#invoke:pagetype|main|page=TimedText:Imagine.ogg.en.srt|timedtext=custom text}} article

Talk parameter

Normally, the module will treat talk pages as if they were in the corresponding subject namespace. However, if the talk parameter is set, the module will treat talk pages separately from subject pages. The talk parameter sets values for all talk pages, i.e. pages in the Talk: namespace, pages in the User talk: namespace, pages in the Wikipedia talk: namespace, and so on.

{{#invoke:pagetype|main|talk=yes}}
{{#invoke:pagetype|main|talk=custom text}}

The default value for "talk=yes" is "talk page".

Examples
Code Result
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace}} article
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace|wikipedia=yes}} article
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace|talk=yes}} article
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace|wikipedia=yes|talk=yes}} article
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace|talk=custom text}} article
{{#invoke:pagetype|main|page=Wikipedia talk:Namespace|wikipedia=yes|talk=custom text}} article

Main namespace classes

For pages in the main namespace, it is possible to add a class value in the first positional parameter:

{{#invoke:pagetype|main|class}}

If the class value matches one of the values in the table below, it will produce an alternative to the default output of article.

Class Class values Output
Disambiguation page disambiguation, disambig, disamb, dab page
No applicable class na, n/a page

You can input the class value in any combination of upper and lower case.

Custom main namespace classes

It is also possible to specify a custom value for the main namespace classes:

{{#invoke:pagetype|main|class|dab=yes|na=yes}}
{{#invoke:pagetype|main|class|dab=custom text|na=custom text}}

This works the same way that it does for the custom namespace page types. Possible parameters are:

  • dab: a custom value for disambiguation-class pages. If set to "yes", "y", "true" or "1", this produces "disambiguation page". If set to "no", "n", "false" or "0", no custom value is produced. If set to any other value it produces that text.
  • na: a custom value for NA-class pages. It works in the same way as the dab parameter. The default value for "yes" etc. is "page".
Examples
Code Result
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|dab}} article
{{#invoke:pagetype|main|page=United Kingdom|dab|dab=custom text}} article
{{#invoke:pagetype|main|page=United Kingdom|na}} page
{{#invoke:pagetype|main|page=United Kingdom|na|na=custom text}} custom text

Redirects

By default, the module automatically detects redirects in all namespace. It is not possible to specify redirect behaviour by namespace, but you can turn redirect detection off, or use a custom value for redirect pages.

{{#invoke:pagetype|main|redirect=no}}
{{#invoke:pagetype|main|redirect=custom text}}
Examples
Code Result
{{#invoke:pagetype|main|page=UK}} article
{{#invoke:pagetype|main|page=UK|redirect=no}} article
{{#invoke:pagetype|main|page=UK|redirect=custom text}} article

Other namespaces

By default, the module produces "page" if used from a namespace that hasn't been specified. This value can be changed with the |other= parameter:

{{#invoke:pagetype|main|other=custom text}}
Examples
Code Result
{{#invoke:pagetype|main|page=Wikipedia:Namespace}} article
{{#invoke:pagetype|main|page=Wikipedia:Namespace|other=custom text}} article
{{#invoke:pagetype|main|page=Wikipedia:Namespace|other=custom text|wikipedia=wikipedia-space text}} article

Plurals

By default the module returns the name of the namespace in the singular. Adding the parameter |plural=y returns the plural form.

Code Result
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|plural=y}} articles
{{#invoke:pagetype|main|page=Category:Books}} category
{{#invoke:pagetype|main|page=Category:Books|plural=y}} categories

The rules for pluralisation can be customised in Module:Pagetype/config to allow localisation.

Capitalisation

By default the module returns the page type in lowercase. Adding the parameter |caps=y returns a version with a capital letter at the start.

Code Result
{{#invoke:pagetype|main|page=United Kingdom}} article
{{#invoke:pagetype|main|page=United Kingdom|caps=y}} Article
{{#invoke:pagetype|main|page=United Kingdom|plural=y|caps=y}} Articles

--------------------------------------------------------------------------------
--                                                                            --
--                                PAGETYPE                                    --
--                                                                            --
--      This is a meta-module intended to replace {{pagetype}} and similar    --
--      templates. It automatically detects namespaces, and allows for a      --
--      great deal of customisation. It can easily be ported to other         --
--      wikis by changing the values in the [[Module:Pagetype/config]].       --
--                                                                            --
--------------------------------------------------------------------------------

-- Load config.
local cfg = mw.loadData('Module:Pagetype/config')

-- Load required modules.
local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')
local mDisambiguation = require('Module:Disambiguation')

local p = {}

-- Look up a namespace argument in the args table.
local function lookUpNamespaceArg(args, key)
	local arg = args[key]
	-- Convert "yes", "1" etc. to true, "no", "0" etc. to false, and leave
	-- other values the same.
	return yesno(arg, arg)
end

-- Append multiple values to an array
local function appendMultiple(target, source)
	for _, value in ipairs(source) do
		table.insert(target, value)
	end
end

-- Get argument keys for a title's namespace
local function getNamespaceArgKeys(title, cfg)
	local nsInfo = mw.site.namespaces[title.namespace]
	local customAliases = cfg.customNamespaceAliases[title.namespace] or {}
	local keys = {}
	if nsInfo.name ~= '' then
		table.insert(keys, nsInfo.name)
	end
	if nsInfo.canonicalName ~= nsInfo.name and nsInfo.canonicalName ~= '' then
		table.insert(keys, nsInfo.canonicalName)
	end
	appendMultiple(keys, nsInfo.aliases)
	appendMultiple(keys, customAliases)
	return keys
end

-- Get the argument for a title's namespace, if it was specified in the args
-- table.
local function getNamespaceArg(title, args, cfg)
	if title.isTalkPage then
		return lookUpNamespaceArg(args, cfg.talk)
	end
	for _, key in ipairs(getNamespaceArgKeys(title, cfg)) do
		local arg = lookUpNamespaceArg(args, mw.ustring.lower(key))
		if arg ~= nil then
			return arg
		end
	end
	return nil
end

-- Look up a page type specific to the title's namespace
local function getExplicitPageType(title, cfg)
	if title.isTalkPage then
		return cfg.talkDefault
	else
		return cfg.pagetypes[title.namespace]
	end
end

-- Get a default page type that is not specific to the title's namespace
local function getDefaultPageType(args, cfg)
	local other = lookUpNamespaceArg(args, cfg.other)
	if type(other) == 'string' then
		return other
	else
		return cfg.otherDefault
	end
end

local function detectRedirects(title, args)
	local redirect = lookUpNamespaceArg(args, cfg.redirect)
	if redirect == false then
		-- Don't detect redirects if they have been specifically disallowed.
		return nil
	end

	-- Allow custom values for redirects.
	if not title.isRedirect then
		return nil
	elseif type(redirect) == 'string' then
		return redirect
	else
		return cfg.redirectDefault
	end
end

local function detectDisambiguationPages(title, args, cfg)
	if title.namespace ~= 0 then
		-- Only detect disambiguation pages in mainspace
		return nil
	end

	local dab = lookUpNamespaceArg(args, cfg.dab)
	if dab == false then
		-- Don't detect disambiguation pages if explicitly disallowed
		return nil
	end

	if not mDisambiguation.isDisambiguation(title:getContent()) then
		return nil
	elseif type(dab) == 'string' then
		return dab
	else
		return cfg.dabDefault
	end
end

-- Gets the pagetype from a class specified from the first positional
-- parameter.
local function getPageTypeFromClass(args, class, key, aliasTable, default)
	local arg = lookUpNamespaceArg(args, key)
	if arg == false then
		-- Don't check for this class if it is specifically disallowed.
		return nil
	end
	if aliasTable[class] then
		if type(arg) == 'string' then
			return arg
		else
			return default
		end
	end
	return nil
end

-- Get page types for mainspaces pages with an explicit class specified
local function getMainNamespaceClassPageType(title, args, cfg)
	if title.namespace ~= 0 then
		return nil
	end
	local class = args[1]
	if type(class) == 'string' then
		-- Put in lower case so e.g. "na" and "NA" will both match.
		class = mw.ustring.lower(class)
	end
	return getPageTypeFromClass(
		args,
		class,
		cfg.na,
		cfg.naAliases,
		cfg.naDefault
	)
end

-- Get page type specified by an explicit namespace argument.
local function getNamespaceArgPageType(title, args, cfg)
	local namespaceArg = getNamespaceArg(title, args, cfg)
	if namespaceArg == true then
		-- Namespace has been explicitly enabled, so return the default for
		-- this namespace
		return getExplicitPageType(title, cfg)
	elseif namespaceArg == false then
		-- Namespace has been explicitly disabled
		return getDefaultPageType(args, cfg)
	elseif namespaceArg then
		-- This namespaces uses custom text
		return namespaceArg
	else
		return nil
	end
end

-- Whether the title is in the set of default active namespaces which are
-- looked up in cfg.pagetypes.
local function isInDefaultActiveNamespace(title, args, cfg)
	local defaultNamespacesKey = args[cfg.defaultns]
	if defaultNamespacesKey == cfg.defaultnsAll then
		return true
	end

	local defaultNamespaces
	if defaultNamespacesKey == cfg.defaultnsExtended then
		defaultNamespaces = cfg.extendedNamespaces
	elseif defaultNamespacesKey == cfg.defaultnsNone then
		defaultNamespaces = {}
	else
		defaultNamespaces = cfg.defaultNamespaces
	end
	return defaultNamespaces[title.namespace] or false
end

-- Get page type not specified or detected by other means
local function getOtherPageType(title, args, cfg)
	if isInDefaultActiveNamespace(title, args, cfg) then
		return getExplicitPageType(title, cfg)
	else
		return getDefaultPageType(args, cfg)
	end
end

local function getPageType(title, args, cfg)
	return (
		detectRedirects(title, args, cfg)
		or detectDisambiguationPages(title, args, cfg)
		or getMainNamespaceClassPageType(title, args, cfg)
		or getNamespaceArgPageType(title, args, cfg)
		or getOtherPageType(title, args, cfg)
	)
end

local function shouldUseSubjectTitle(args, cfg)
	return not yesno(args.talk, true) and args[cfg.defaultns] ~= cfg.defaultnsAll
end

-- Get the Scribunto title object to fetch the page type of
local function getTitle(args, cfg)
	local title
	if args.page then
		title = mw.title.new(args.page)
		if not title then
			return nil
		end
	else
		title = mw.title.getCurrentTitle()
	end

	if shouldUseSubjectTitle(args, cfg) then
		return title.subjectPageTitle
	else
		return title
	end
end

local function pluralize(pageType, cfg)
	if cfg.irregularPlurals[pageType] then
		return cfg.irregularPlurals[pageType]
	else
		return pageType .. cfg.plural -- often 's'
	end
end

local function capitalize(pageType)
	local first = mw.ustring.sub(pageType, 1, 1)
	local rest = mw.ustring.sub(pageType, 2)
	return mw.ustring.upper(first) .. rest
end

function p._main(args)
	local title = getTitle(args, cfg)
	local pageType = getPageType(title, args, cfg)
	if yesno(args.plural, false) then
		pageType = pluralize(pageType, cfg)
	end
	if yesno(args.caps, false) then
		pageType = capitalize(pageType)
	end
	return pageType
end

function p.main(frame)
	local args = getArgs(frame)
	return p._main(args)
end

return p