CodeDiscussionEditHistoryLinksLink countSubpages:DocumentationTestsResultsSandboxLive codeAll modules
Note: This module is used on a lot of pages. In order not to put too much load on the servers, edits should be kept to a bare minimum. Pleasediscuss proposed changes onthe talk page first. Afterwards, changes caninitially be done at and tested withModule:Redirect/sandbox.
|
This module implements templates that detect and resolve redirects and soft category redirects.
Soft redirects are hard to detect and costly as they require loading and parsing the wiki page content of 'Category:' pages.
Soft redirects are category pages containing the template
or one of its known aliases on Commons (there are too many!!!):
For the full list of aliases (simple redirections) of {{Category redirect}}, see
For the full list of derived templates (specifying an embeddedreason parameter passed to the main template), see
The 'target' parameter value for these templates may be prefixed by 'Category:' or ':Category:' or not (it is implied).
There should exist only one soft-redirect or redirection per page. If you need several redirections (because the original name was ambiguous and could refer to several distinct topics), this means that this redirection page has to be converted into adisambiguation page, providing a list of links to the different possible targets (each linked target page may be possibly followed by a short descriptive comment without any link, in order to help users making the right choice).
-- This module provides functions for getting the target of a redirect page.localp={}localchar=mw.ustring.char-- proxy to load the module lazily, replaced by the actual loaded functionlocalgetArgs=function(...)getArgs=require('Module:Arguments').getArgsreturngetArgs(...)end-- Gets a mw.title object, using pcall to avoid generating script errors if we-- are over the expensive function count limit (among other possible causes).localfunctiongetTitle(...)localsuccess,titleObj=pcall(mw.title.new,...)ifsuccessthenreturntitleObjelsereturnnilendend--[[Detect hard redirect in wiki page content (not used inside this module)]]functionp.getTargetFromText(text)text=textor''returntext:match('^#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt][%s:]*%[%[[%s_:]*([^]|]-)[%s_]*%]%]')end--[[Detect soft redirect in wiki page content of 'Category:' pages, using template{{Category redirect|target}}or one of its known aliases on Commons (there are too many!!!):{{Category Redirect|target}}{{Categoryredirect|target}}{{Cat redirect|target}}{{Catredirect|target}}{{Catredir|target}}{{Cat-redirect|target}}{{Cat-red|target}}{{Redirect category|target}}{{Redirect cat|target}}{{Seecat|target}}{{See cat|target}}{{Endashcatredirect|target}}{{Synonym taxon category redirect|target}}{{Invalid taxon category redirect|target}}{{Monotypic taxon category redirect|target}}The `target` value may be prefixed by 'Category:' or not (implied). For the full list of aliases, seehttps://commons.wikimedia.org/w/index.php?title=Special:WhatLinksHere/Template:Category_redirect&hidetrans=1&hidelinks=1]]functionp.getTargetFromCatRedirect(content)-- Basic filtering: only in the relevant content shown on target page itselfcontent=(contentor''):gsub('<!%-%-(.-)%-%->','')-- Discard HTML comments.:gsub('<includeonly%s*>(.-)</includeonly>','')-- Discard 'includeonly' sections and their content.:gsub('<includeonly%s*>(.-)$','')-- Discard unclosed 'includeonly' sections.:gsub('<[/]?onlyinclude%s*>','')-- Discard 'onlyinclude' opening/closing tags.:gsub('<[/]?noinclude%s*>','')-- Discard 'noinclude' opening/closing tags.:gsub('</?nowiki%s*/?>','')-- Discard nowiki opening/closing/selfclosed tags.-- Locate the template transclusion, keep their parameters only.-- Note: there may potentially be several instances, this should not occur.content=content:match('^#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt][%s:]*%[%[[%s_:]*([^]|]-)[%s_]*%]%]')orcontent:match('{{[%s_]*[Cc]ategory*[%s_]*[Rr]edirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Cc]at[%s_]*[Rr]edirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Cc]at-[Rr]edirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Cc]at[%s_]*[Rr]edir[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Cc]at-red[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Rr]edirect[%s_]*[Cc]ategory[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Rr]edirect[%s_]*[Cc]at[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Ss]ee[%s_]*[Cc]at[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Ee]ndashcatredirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Ss]ynonym[%s_]*taxon[%s_]*category[%s_]*redirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Ii]nvalid[%s_]*taxon[%s_]*category[%s_]*redirect[%s_]*|[%s_:]*(.-)[%s_]*}}')orcontent:match('{{[%s_]*[Mm]onotypic[%s_]*taxon[%s_]*category[%s_]*redirect[%s_]*|[%s_:]*(.-)[%s_]*}}')ifnotcontentthenreturnnilenddo-- Parse template parameters (they may be in arbitrary order).localparams,n={},0forparamincontent:gmatch('([^|]+)')dolocalkeylocalpos=param:find('=')ifposthenkey=param:sub(1,pos-1):match('^%s*(.-)%s*$')-- split then trimparam=param:sub(pos+1):match('^%s*(.-)%s*$')-- split then trimelsen=n+1key=tostring(n)endparams[key]=paramend-- The target is in parameter ['1'] of the template transclusion.content=params['1']end-- Check there's an effective target parameter to the template.ifnotcontentthenreturnnilendcontent=content-- The target parameter may contain some known character entities-- (their validity in page names is not checked here, just parsed).:gsub('&([#%d%a]+);',function(entity)ifentity:sub(1,1)=='#'thenlocalcodepointifentity:sub(2,2)=='x'thencodepoint=tonumber(entity:sub(3),16)elsecodepoint=tonumber(entity:sub(2))endifcodepointand(codepoint>=0x0009andcodepoint<=0x000Dor-- Accept some whitespace C0 controls.codepoint>=0x0020andcodepoint<=0x10FFFD-- Normal range.and(codepoint<0x0080orcodepoint>0x009F)-- Exclude C1 controls.and(codepoint<0xDC00orcodepoint>0xDFFF)-- Exclude surrogates.and(codepoint<0xFDD0orcodepoint>0xFDEF)-- Exclude non-characters in BMP.andcodepoint%0x10000<=0xFFFD-- Exclude non-characters at end of planes.)thenreturnchar(codepoint)endelseifentity=='amp'thenreturn'&'endifentity=='gt'thenreturn'>'endifentity=='lt'thenreturn'<'endifentity=='quot'thenreturn'"'endendreturnentityend)-- Normalize spaces in the target according to Mediawiki pagename rules.:gsub('[%s_]+',' ')-- The target parameter should be trimmed by the template.:match('^ ?(.-) ?$')-- The target should not be empty and not contain tag delimiters or other character forbidden in full page names.-- Note: templates used inside the target parameter of the soft redirect are not expanded (there should be none),-- as this is costly or memory intensive and slow (would require invoking a full mediawiki parser).ifcontent==''orcontent:find('[<>%[%]{|}]')thenreturnnilend-- The 'Category:' namespace is implied (it will be prefixed by a ':' to create a link)return'Category:'..(content:match('^:*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy] *: *(.-)$')orcontent)end-- Get page name that a redirect leads to, or nil if it isn't a redirect.-- fulltext is an optional option: when set, it indicates if we want the `.fullText`, otherwise we get the `.prefixedText`.functionp.getTargetFrom(obj,fulltext)--[[obj:getContent() is intensive for large pages, but obj.redirectTarget returns directlythe target without needing to load and parse the text content of the wiki page.This works for wiki pages that are hard redirects (content starting by '#REDIRECT').In this case, using p.getTargetFromText(obj:getContent()) is not needed.]]localr=obj.isRedirectandobj.redirectTargetifnotrthen--[[For pages using soft redirects (like categories), we must detect the templateused in the page content itself (this may be costly in memory and slow if notloaded in the cache of page contents).]]ifobj:inNamespace('Category')thenr=p.getTargetFromCatRedirect(obj:getContent())ifrthenlocalobj2=getTitle(r)ifobj2then-- Detect when getTitle fails.obj=obj2-- True replacement with the target.-- Special: the replacement may also be a hard redirect.r=obj.isRedirectandobj.redirectTarget-- Not done here: second soft redirect detection.endendendifnotrandobj.isRedirectthen-- The page is a redirect, but matching failed, which may be a bug-- in the redirect matching pattern, so throw an error.error(string.format('could not parse redirect on page "%s"',fulltextandobj.fullTextorobj.prefixedText))endr=fulltextandobj.fullTextorobj.prefixedTextendreturnrendlocalfunctionfmtTitle(target,fulltext,ensureTitleExists)localtitleObjiftype(target)=='string'ortype(target)=='number'thentitleObj=getTitle(target)elseiftype(target)=='table'andtype(target.getContent)=='function'thentitleObj=targetelseerror(string.format('bad argument #1 to "fmtTitle": string, number, or title object expected, got %s',type(target)),2)endiftitleObjthenifnotensureTitleExistsorensureTitleExistsandtitleObj.existsthenreturnfulltextandtitleObj.fullTextortitleObj.prefixedTextendendend-- Gets the target of a redirect. If the page specified is not a redirect,-- returns nil.functionp.getTarget(page,rname,fulltext,ensureTitleExists)-- Get the title object. Both page names and title objects are allowed-- as input.localtitleObjiftype(page)=='string'ortype(page)=='number'thentitleObj=getTitle(page)elseiftype(page)=='table'andtype(page.getContent)=='function'thentitleObj=pageelseerror(string.format('bad argument #1 to "getTarget": string, number, or title object expected, got %s',type(page)),2)endiftitleObjandtitleObj.existsand(titleObj.isRedirectortitleObj:inNamespace('Category'))then-- Find the target by using string matching on the page content.returnfmtTitle(p.getTargetFrom(titleObj,fulltext),fulltext,ensureTitleExists)endend--[[-- Given a single page name determines what page it redirects to and returns the-- target page name, or the passed page name when not a redirect. The passed-- page name can be given as plain text or as a page link.---- Returns page name as plain text, or when the bracket parameter is given, as a-- page link. Returns an error message when page does not exist or the redirect-- target cannot be determined for some reason.--]]functionp.luaMain(rname,bracket,fulltext,ensureTitleExists)iftype(rname)~='string'ornotrname:find('%S')thenreturnnilendrname=rname:match('%[%[[%s_:]*([^%]|]-)[%s_]*%]%]')orrname:match('^[%s_:]*([%]|]-)[^%s_]*$')orrnamelocalret=p.getTarget(rname,fulltext,ensureTitleExists)orfmtTitle(rname,fulltext,ensureTitleExists)locallink=bracketand(ret==rnameand'[[:%s]]'or'[[:%s|%s]]')or'%s'returnretandlink:format(ret,rname)endlocalfunctionuse(x)returnxand(x=='1'orx=='t'orx=='true'orx=='y'orx=='yes')ornilend-- Provides access to the luaMain function from wikitext, may return redlinks,-- albeit page titles that do not exist in the wiki.-- Parameters alt, bracket, fulltext, ensureTitleExists are optionalfunctionp.main(frame)localargs=getArgs(frame,{frameOnly=true})localrname=args[1]localalt=args[2]or''localbracket=use(args.bracket)localfulltext=use(args.fulltext)localensureTitleExists=use(args.noredlinks)returnp.luaMain(rname,bracket,fulltext,ensureTitleExists)oraltend-- main variant, returns empty string if a redlink would be returned otherwise.-- '|noredlinks=true' by default.functionp.mainE(frame)localargs=getArgs(frame,{frameOnly=true})localrname=args[1]localalt=args[2]or''localbracket=use(args.bracket)localfulltext=use(args.fulltext)returnp.luaMain(rname,bracket,fulltext,true)oraltend-- main variant, returns args[2] if a redlink would be returned otherwise.-- '|bracket=true|noredlinks=true' by defaultfunctionp.mainA(frame)localargs=getArgs(frame,{frameOnly=true})localrname=args[1]localalt=args[2]or''localbracket=use(args.bracket)returnp.luaMain(rname,bracket,true,true)oraltend-- Returns true if the specified page is a redirect, and false otherwise.functionp.luaIsRedirect(page)localtitleObj=getTitle(page)ifnottitleObjthenreturnfalseendiftitleObj.isRedirectthenreturntrueelsereturnfalseendend-- Provides access to the luaIsRedirect function from wikitext, returning 'yes'-- if the specified page is a redirect, and the blank string otherwise.functionp.isRedirect(frame)localargs=getArgs(frame,{frameOnly=true})ifp.luaIsRedirect(args[1])thenreturn'yes'elsereturn''endendreturnp