Module:User name utils
Lua implementation of the getCanonical() and isValid() functions from https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/refs/heads/master/includes/User/UserNameUtils.php
Originally created to validate usernames before creating a User info card, since the {{#uic:}} parser function adds pages to the category Category:Pages with an IP as user info card target if getCanonical() returns false.
Usage
{{#invoke:User name utils|getCanonical|name}} Returns a normalized version of name if valid, and an empty string if not valid. Normalization will, among other things, capitalize the first letter, remove the "User:" namespace prefix if present, replace underscores with spaces, and decode HTML entities.
{{#invoke:User name utils|isValid|name}} Returns "1" if name is a valid username (including leading capitalization and without the namespace), and an empty string if not valid. Note that "example" would be considered invalid because it does not have a leading capital letter, and "User:Example" would be considered invalid because the namespace is specified.
The p._getCanonical(name) and p._isValid(name) functions can be accessed directly from other Lua modules and behave similarly, except _getCanonical returns boolean false instead of an empty string for invalid names, and _isValid returns boolean true or false.
-- Lua implementation of mediawiki/core/+/refs/heads/master/includes/User/UserNameUtils.php
-- with the default RIGOR_VALID option
local p = {}
local IPV4_ADDRESS = "%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?"
local lang = mw.getContentLanguage()
function p._getCanonical(name)
if (name or '') == '' then
return false
end
-- force usernames to capital
name = lang:ucfirst(name)
-- Reject names containing '#'; these will be cleaned up
-- with title normalisation, but then it's too late to
-- check elsewhere
if mw.ustring.match(name, "#") then
return false
end
-- Clean up name according to title rules
local title = mw.title.new(name,2)
-- Check for invalid titles
if title == nil or title.namespace ~= 2 or title.isExternal then
return false
end
name = title.text
return p._isValid(name) and name or false
end
function p._isValid(name)
if (name or '') == '' or
require('Module:IPAddress')._isIpOrRange(name) ~= "" or
mw.ustring.match(name, "^" .. IPV4_ADDRESS .. "$") or -- anyIPv4, even if invalid
mw.ustring.match(name, "^" .. IPV4_ADDRESS .. "-" .. IPV4_ADDRESS .. "$") or -- isLikeIPv4DashRange
mw.ustring.match(name, "/") or
name ~= lang:ucfirst(name) then
return false
end
-- Ensure that the name can't be misresolved as a different title,
-- such as with extra namespace keys at the start.
local title = mw.title.new(name)
if not title or
title.namespace ~= 0 or
name ~= title.text then
return false
end
return true
end
function p.getCanonical(frame)
local name = p._getCanonical(frame.args[1])
return name and name or ""
end
function p.isValid(frame)
return p._isValid(frame.args[1]) and "1" or ""
end
return p