MediaWiki REL1_27
Parser.php File Reference

PHP parser that converts wiki markup to HTML. More...

Go to the source code of this file.

Classes

class  Parser
 PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for making links), and provides a one-way transformation of that wiki markup it into (X)HTML output / markup (which in turn the browser understands, and can display). More...
 

Functions

 addTrackingCategory ( $msg)
 
 areSubpagesAllowed ()
 Return true if subpage links should be expanded on this page.
 
 argSubstitution ( $piece, $frame)
 Triple brace replacement – used for template arguments.
 
 armorLinks ( $text)
 Insert a NOPARSE hacky thing into any inline links in a chunk that's going to go through further parsing steps before inline URL expansion.
 
 attributeStripCallback (&$text, $frame=false)
 Callback from the Sanitizer for expanding items found in HTML attribute values, so they can be safely tested and escaped.
 
 braceSubstitution ( $piece, $frame)
 Return the text of a template, after recursively replacing any variables or templates within the template.
 
 callParserFunction ( $frame, $function, array $args=[])
 Call a parser function and return an array with text and flags.
 
 cleanSig ( $text, $parsing=false)
 Clean up signature text.
 
static cleanSigInSig ( $text)
 Strip 3, 4 or 5 tildes out of signatures.
 
 clearTagHooks ()
 Remove all tag hooks.
 
 closeList ( $char)
 
 closeParagraph ()
 #+ Used by doBlockLevels()
 
static createAssocArgs ( $args)
 Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
 
 disableCache ()
 Set a flag in the output object indicating that the content is dynamic and shouldn't be cached.
 
 doBlockLevels ( $text, $linestart)
 #-
 
 doDoubleUnderscore ( $text)
 Strip double-underscore items like NOGALLERY and NOTOC Fills $this->mDoubleUnderscores, returns the modified text.
 
 enableOOUI ()
 Set's up the PHP implementation of OOUI for use in this request and instructs OutputPage to enable OOUI for itself.
 
 extensionSubstitution ( $params, $frame)
 Return the text to be used for a given extension tag.
 
 extractSections ( $text, $sectionId, $mode, $newText='')
 Break wikitext input into sections, and either pull or replace some particular section's text.
 
 fetchCurrentRevisionOfTitle ( $title)
 Fetch the current revision of a given title.
 
 fetchFile ( $title, $options=[])
 Fetch a file and its title and register a reference to it.
 
 fetchFileAndTitle ( $title, $options=[])
 Fetch a file and its title and register a reference to it.
 
 fetchFileNoRegister ( $title, $options=[])
 Helper function for fetchFileAndTitle.
 
 fetchScaryTemplateMaybeFromCache ( $url)
 
 fetchTemplate ( $title)
 Fetch the unparsed text of a template and register a reference to it.
 
 fetchTemplateAndTitle ( $title)
 Fetch the unparsed text of a template and register a reference to it.
 
 findColonNoLinks ( $str, &$before, &$after)
 Split up a string on ':', ignoring any occurrences inside tags to prevent illegal overlapping.
 
 formatHeadings ( $text, $origText, $isMain=true)
 This function accomplishes several tasks: 1) Auto-number headings if that option is enabled 2) Add an [edit] link to sections for users who have enabled the option and can edit the page 3) Add a Table of contents on the top for users who have enabled the option 4) Auto-anchor headings.
 
 getCommon ( $st1, $st2)
 getCommon() returns the length of the longest common substring of both arguments, starting at the beginning of both.
 
 getCustomDefaultSort ()
 Accessor for $mDefaultSort Unlike getDefaultSort(), will return false if none is set.
 
 getDefaultSort ()
 Accessor for $mDefaultSort Will use the empty string if none is set.
 
 getExternalLinkAttribs ( $url=false)
 Get an associative array of additional HTML attributes appropriate for a particular external link.
 
static getExternalLinkRel ( $url=false, $title=null)
 Get the rel attribute for a particular external link.
 
 getFreshParser ()
 Return this parser if it is not doing anything, otherwise get a fresh parser.
 
 getFunctionHooks ()
 Get all registered function hook identifiers.
 
 getImageParams ( $handler)
 
 getRevisionId ()
 Get the ID of the revision we are parsing.
 
 getRevisionObject ()
 Get the revision object for $this->mRevisionId.
 
 getRevisionSize ()
 Get the size of the revision.
 
 getRevisionTimestamp ()
 Get the timestamp associated with the current revision, adjusted for the default server-local timestamp.
 
 getRevisionUser ()
 Get the name of the user that edited the last revision.
 
 getSection ( $text, $sectionId, $defaultText='')
 This function returns the text of a section, specified by a number ($section).
 
 getTags ()
 Accessor.
 
 getTemplateDom ( $title)
 Get the semi-parsed DOM representation of a template with a given title, and its redirect destination title.
 
 getUserSig (&$user, $nickname=false, $fancySig=null)
 Fetch the user's signature text, if any, and normalize to validated, ready-to-insert wikitext.
 
 getVariableValue ( $index, $frame=false)
 Return value of a magic variable (like PAGENAME)
 
 guessLegacySectionNameFromWikiText ( $text)
 Same as guessSectionNameFromWikiText(), but produces legacy anchors instead.
 
 guessSectionNameFromWikiText ( $text)
 Try to guess the section anchor name based on a wikitext fragment presumably extracted from a heading, for example "Header" from "== Header ==".
 
 incrementExpensiveFunctionCount ()
 Increment the expensive function count.
 
 incrementIncludeSize ( $type, $size)
 Increment an include size counter.
 
 initialiseVariables ()
 initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
 
 interwikiTransclude ( $title, $action)
 Transclude an interwiki link.
 
 isValidHalfParsedText ( $data)
 Returns true if the given array, presumed to be generated by serializeHalfParsedText(), is compatible with the current version of the parser.
 
 killMarkers ( $text)
 Remove any strip markers found in the given text.
 
 limitationWarn ( $limitationType, $current='', $max='')
 Warn the user when a parser limitation is reached Will warn at most once the user per limitation type.
 
 lock ()
 Lock the current instance of the parser.
 
 makeImage ( $title, $options, $holders=false)
 Parse image options text and use it to make an image.
 
 makeKnownLinkHolder ( $nt, $text='', $query=[], $trail='', $prefix='')
 Render a forced-blue link inline; protect against double expansion of URLs if we're in a mode that prepends full URL prefixes to internal links.
 
 markerSkipCallback ( $s, $callback)
 Call a callback function on all regions of the given text that are not inside strip markers, and replace those regions with the return value of the callback.
 
 maybeDoSubpageLink ( $target, &$text)
 Handle link to subpage if necessary.
 
 maybeMakeExternalImage ( $url)
 make an image if it's allowed, either through the global option, through the exception, or through the on-wiki whitelist
 
 nextItem ( $char)
 TODO: document.
 
static normalizeLinkUrl ( $url)
 Replace unusual escape codes in a URL with their equivalent characters.
 
static normalizeUrlComponent ( $component, $unsafe)
 
 openList ( $char)
 These next three functions open, continue, and close the list element appropriate to the prefix character passed into them.
 
 parseWidthParam ( $value)
 Parsed a width param of imagelink like 300px or 200x300px.
 
 preprocessToDom ( $text, $flags=0)
 Preprocess some wikitext and return the document tree.
 
 preSaveTransform ( $text, Title $title, User $user, ParserOptions $options, $clearState=true)
 Transform wiki markup when saving a page by doing "\\r\\n" -> "\\n" conversion, substituting signatures, {{subst:}} templates, etc.
 
 pstPass2 ( $text, $user)
 Pre-save transform helper function.
 
 renderImageGallery ( $text, $params)
 Renders an image gallery from a text with one line per image.
 
 replaceExternalLinks ( $text)
 Replace external links (REL)
 
 replaceInternalLinks ( $s)
 Process [[ ]] wikilinks.
 
 replaceInternalLinks2 (&$s)
 Process [[ ]] wikilinks (RIL)
 
 replaceLinkHolders (&$text, $options=0)
 Replace "<!--LINK-->" link placeholders with actual links, in the buffer Placeholders created in Linker::link()
 
 replaceLinkHoldersText ( $text)
 Replace "<!--LINK-->" link placeholders with plain text of links (not HTML-formatted).
 
 replaceSection ( $oldText, $sectionId, $newText)
 This function returns $oldtext after the content of the section specified by $section has been replaced with $text.
 
 replaceTransparentTags ( $text)
 Replace transparent tags in $text with the values given by the callbacks.
 
static replaceUnusualEscapes ( $url)
 Replace unusual escape codes in a URL with their equivalent characters.
 
 replaceVariables ( $text, $frame=false, $argsOnly=false)
 Replace magic variables, templates, and template arguments with the appropriate text.
 
 serializeHalfParsedText ( $text)
 Save the parser state required to convert the given half-parsed text to HTML.
 
 setDefaultSort ( $sort)
 Mutator for $mDefaultSort.
 
 setFunctionHook ( $id, $callback, $flags=0)
 Create a function, e.g.
 
 setFunctionTagHook ( $tag, $callback, $flags)
 Create a tag function, e.g.
 
 setHook ( $tag, $callback)
 Create an HTML-style tag, e.g.
 
 setTransparentTagHook ( $tag, $callback)
 As setHook(), but letting the contents be parsed.
 
static splitWhitespace ( $s)
 Return a three-element array: leading whitespace, string contents, trailing whitespace.
 
 startExternalParse (Title $title=null, ParserOptions $options, $outputType, $clearState=true)
 Set up some variables which are usually set up in parse() so that an external function can call some class members with confidence.
 
 startParse (Title $title=null, ParserOptions $options, $outputType, $clearState=true)
 
static statelessFetchRevision ( $title, $parser=false)
 Wrapper around Revision::newFromTitle to allow passing additional parameters without passing them on to it.
 
static statelessFetchTemplate ( $title, $parser=false)
 Static function to get a template Can be overridden via ParserOptions::setTemplateCallback().
 
 stripAltText ( $caption, $holders)
 
static stripOuterParagraph ( $html)
 Strip outer.
 
 stripSectionName ( $text)
 Strips a text string of wikitext for use in a section anchor.
 
 testPreprocess ( $text, Title $title, ParserOptions $options)
 
 testPst ( $text, Title $title, ParserOptions $options)
 
 testSrvus ( $text, Title $title, ParserOptions $options, $outputType=self::OT_HTML)
 strip/replaceVariables/unstrip for preprocessor regression testing
 
 transformMsg ( $text, $options, $title=null)
 Wrapper for preprocess()
 
 unserializeHalfParsedText ( $data)
 Load the parser state given in the $data array, which is assumed to have been generated by serializeHalfParsedText().
 
 validateSig ( $text)
 Check that the user's signature contains no bad XML.
 

Variables

 $buffer = ''
 
 $i = 0
 
 $output = ''
 
 $state = ''
 

Detailed Description

PHP parser that converts wiki markup to HTML.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. http://www.gnu.org/copyleft/gpl.html

Definition in file Parser.php.

Function Documentation

◆ addTrackingCategory()

addTrackingCategory (   $msg)
See also
ParserOutput::addTrackingCategory()
Parameters
string$msgMessage key
Returns
bool Whether the addition was successful

Definition at line 4420 of file Parser.php.

Referenced by doDoubleUnderscore(), limitationWarn(), and makeImage().

◆ areSubpagesAllowed()

areSubpagesAllowed ( )

Return true if subpage links should be expanded on this page.

Returns
bool

Definition at line 2414 of file Parser.php.

References MWNamespace\hasSubpages().

Referenced by replaceInternalLinks2().

◆ argSubstitution()

argSubstitution (   $piece,
  $frame 
)

Triple brace replacement – used for template arguments.

Access:\n private
Parameters
array$piece
PPFrame$frame
Returns
array

Definition at line 4199 of file Parser.php.

References $ret, incrementIncludeSize(), and limitationWarn().

◆ armorLinks()

armorLinks (   $text)

Insert a NOPARSE hacky thing into any inline links in a chunk that's going to go through further parsing steps before inline URL expansion.

Not needed quite as much as it used to be since free links are a bit more sensible these days. But bracketed links are still an issue.

Parameters
string$textMore-or-less HTML
Returns
string Less-or-more HTML with NOPARSE bits

Definition at line 2405 of file Parser.php.

Referenced by makeKnownLinkHolder(), and replaceInternalLinks2().

◆ attributeStripCallback()

attributeStripCallback ( $text,
  $frame = false 
)

Callback from the Sanitizer for expanding items found in HTML attribute values, so they can be safely tested and escaped.

Parameters
string$text
bool | PPFrame$frame
Returns
string

Definition at line 5812 of file Parser.php.

References replaceVariables().

◆ braceSubstitution()

braceSubstitution (   $piece,
  $frame 
)

Return the text of a template, after recursively replacing any variables or templates within the template.

Parameters
array$pieceThe parts of the template $piece['title']: the title, i.e. the part before the | $piece['parts']: the parameter array $piece['lineStart']: whether the brace was at the start of a line
PPFrame$frameThe current frame, contains template arguments
Exceptions
Exception
Returns
string The text of the template

Definition at line 3462 of file Parser.php.

References $args, $context, $i, $limit, $name, $ret, $title, $value, callParserFunction(), SpecialPageFactory\capturePath(), disableCache(), MagicWord\get(), MagicWord\getCacheTTL(), getTemplateDom(), getVariableValue(), in, incrementIncludeSize(), interwikiTransclude(), MWNamespace\isNonincludable(), limitationWarn(), list, maybeDoSubpageLink(), Title\newFromText(), NS_TEMPLATE, or, preprocessToDom(), PPFrame\RECOVER_ORIG, RequestContext\setTitle(), PPFrame\STRIP_COMMENTS, wfDebug(), wfEscapeWikiText(), and wfMessage().

◆ callParserFunction()

callParserFunction (   $frame,
  $function,
array  $args = [] 
)

Call a parser function and return an array with text and flags.

The returned array will always contain a boolean 'found', indicating whether the parser function was found or not. It may also contain the following: text: string|object, resulting wikitext or PP DOM object isHTML: bool, $text is HTML, armour it against wikitext transformation isChildObj: bool, $text is a DOM node needing expansion in a child frame isLocalObj: bool, $text is a DOM node needing expansion in the current frame nowiki: bool, wiki markup in $text should be escaped

Since
1.21
Parameters
PPFrame$frameThe current frame, contains template arguments
string$functionFunction name
array$argsArguments to the function
Exceptions
MWException
Returns
array

Definition at line 3780 of file Parser.php.

References $args, $flags, $parser, $wgContLang, as, false, global, list, and preprocessToDom().

Referenced by braceSubstitution().

◆ cleanSig()

cleanSig (   $text,
  $parsing = false 
)

Clean up signature text.

1) Strip 3, 4 or 5 tildes out of signatures

See also
cleanSigInSig 2) Substitute all transclusions
Parameters
string$text
bool$parsingWhether we're cleaning (preferences save) or parsing
Returns
string Signature text

Definition at line 5024 of file Parser.php.

References $wgTitle, cleanSigInSig(), MagicWord\get(), global, lock(), preprocessToDom(), and startParse().

Referenced by getUserSig().

◆ cleanSigInSig()

static cleanSigInSig (   $text)
static

Strip 3, 4 or 5 tildes out of signatures.

Parameters
string$text
Returns
string Signature text with /~{3,5}/ removed

Definition at line 5061 of file Parser.php.

Referenced by cleanSig(), and getUserSig().

◆ clearTagHooks()

clearTagHooks ( )

Remove all tag hooks.

Definition at line 5195 of file Parser.php.

◆ closeList()

closeList (   $char)
Todo:
Document
Parameters
string$char
Access:\n private
Returns
string

Definition at line 2533 of file Parser.php.

Referenced by doBlockLevels().

◆ closeParagraph()

closeParagraph ( )

#+ Used by doBlockLevels()

Access:\n private
Returns
string

Definition at line 2437 of file Parser.php.

Referenced by doBlockLevels(), and openList().

◆ createAssocArgs()

static createAssocArgs (   $args)
static

Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.

Parameters
array$args
Returns
array

Definition at line 3392 of file Parser.php.

References $args, $name, $value, and as.

◆ disableCache()

disableCache ( )

Set a flag in the output object indicating that the content is dynamic and shouldn't be cached.

Definition at line 5795 of file Parser.php.

References wfDebug().

Referenced by braceSubstitution().

◆ doBlockLevels()

doBlockLevels (   $text,
  $linestart 
)

#-

Make lists from lines starting with ':', '*', '#', etc. (DBL)

Parameters
string$text
bool$linestartWhether or not this is at the start of a line.
Access:\n private
Returns
string The lists rendered as HTML

Definition at line 2560 of file Parser.php.

References $output, $t, $term, as, closeList(), closeParagraph(), StringUtils\explode(), findColonNoLinks(), getCommon(), nextItem(), and openList().

Referenced by Parser\internalParseHalfParsed().

◆ doDoubleUnderscore()

doDoubleUnderscore (   $text)

Strip double-underscore items like NOGALLERY and NOTOC Fills $this->mDoubleUnderscores, returns the modified text.

Parameters
string$text
Returns
string

Definition at line 4365 of file Parser.php.

References addTrackingCategory(), as, MagicWord\get(), MagicWord\getDoubleUnderscoreArray(), and NS_CATEGORY.

Referenced by Parser\internalParse().

◆ enableOOUI()

enableOOUI ( )

Set's up the PHP implementation of OOUI for use in this request and instructs OutputPage to enable OOUI for itself.

Since
1.26

Definition at line 6501 of file Parser.php.

References OutputPage\setupOOUI().

◆ extensionSubstitution()

extensionSubstitution (   $params,
  $frame 
)

Return the text to be used for a given extension tag.

This is the ghost of strip().

Parameters
array$paramsAssociative array of parameters: name PPNode for the tag name attr PPNode for unparsed text where tag attributes are thought to be attributes Optional associative array of parsed attributes inner Contents of extension element noClose Original text did not have a close tag
PPFrame$frame
Exceptions
MWException
Returns
string

Definition at line 4252 of file Parser.php.

References $content, $flags, $name, $output, $params, $parser, as, Sanitizer\decodeTagAttributes(), and list.

◆ extractSections()

extractSections (   $text,
  $sectionId,
  $mode,
  $newText = '' 
)
private

Break wikitext input into sections, and either pull or replace some particular section's text.

External callers should use the getSection and replaceSection methods.

Parameters
string$textPage wikitext
string | number$sectionIdA section identifier string of the form: "<flag1> - <flag2> - ... - <section number>"

Currently the only recognised flag is "T", which means the target section number was derived during a template inclusion parse, in other words this is a template section edit link. If no flags are given, it was an ordinary section edit link. This flag is required to avoid a section numbering mismatch when a section is enclosed by "<includeonly>" (bug 6563).

The section number 0 pulls the text before the first heading; other numbers will pull the given section along with its lower-level subsections. If the section is not found, $mode=get will return $newtext, and $mode=replace will return $text.

Section 0 is always considered to exist, even if it only contains the empty string. If $text is the empty string and section 0 is replaced, $newText is returned.

Parameters
string$modeOne of "get" or "replace"
string$newTextReplacement text for section data.
Returns
string For "get", the extracted section text. for "replace", the whole page with the section replaced.

Definition at line 5892 of file Parser.php.

References $flags, $wgTitle, as, global, lock(), preprocessToDom(), PPFrame\RECOVER_ORIG, startParse(), and used.

Referenced by getSection(), and replaceSection().

◆ fetchCurrentRevisionOfTitle()

fetchCurrentRevisionOfTitle (   $title)

Fetch the current revision of a given title.

Note that the revision (and even the title) may not exist in the database, so everything contributing to the output of the parser should use this method where possible, rather than getting the revisions themselves. This method also caches its results, so using it benefits performance.

Since
1.24
Parameters
Title$title
Returns
Revision

Definition at line 3922 of file Parser.php.

References $title.

◆ fetchFile()

fetchFile (   $title,
  $options = [] 
)

Fetch a file and its title and register a reference to it.

If 'broken' is a key in $options then the file will appear as a broken thumbnail.

Parameters
Title$title
array$optionsArray of options to RepoGroup::findFile
Returns
File|bool

Definition at line 4085 of file Parser.php.

References $options, $title, and fetchFileAndTitle().

◆ fetchFileAndTitle()

fetchFileAndTitle (   $title,
  $options = [] 
)

Fetch a file and its title and register a reference to it.

If 'broken' is a key in $options then the file will appear as a broken thumbnail.

Parameters
Title$title
array$optionsArray of options to RepoGroup::findFile
Returns
array ( File or false, Title of file )

Definition at line 4096 of file Parser.php.

References $options, $time, $title, and fetchFileNoRegister().

Referenced by fetchFile(), and makeImage().

◆ fetchFileNoRegister()

fetchFileNoRegister (   $title,
  $options = [] 
)
protected

Helper function for fetchFileAndTitle.

Also useful if you need to fetch a file but not use it yet, for example to get the file's handler.

Parameters
Title$title
array$optionsArray of options to RepoGroup::findFile
Returns
File|bool

Definition at line 4121 of file Parser.php.

References $options, $title, RepoGroup\singleton(), and wfFindFile().

Referenced by fetchFileAndTitle(), and renderImageGallery().

◆ fetchScaryTemplateMaybeFromCache()

fetchScaryTemplateMaybeFromCache (   $url)
Parameters
string$url
Returns
mixed|string

Definition at line 4159 of file Parser.php.

References $dbr, $req, $status, $wgTranscludeCacheExpiry, DB_MASTER, DB_SLAVE, global, wfGetDB(), and wfMessage().

Referenced by interwikiTransclude().

◆ fetchTemplate()

fetchTemplate (   $title)

Fetch the unparsed text of a template and register a reference to it.

Parameters
Title$title
Returns
string|bool

Definition at line 3982 of file Parser.php.

References $title, and fetchTemplateAndTitle().

◆ fetchTemplateAndTitle()

fetchTemplateAndTitle (   $title)

Fetch the unparsed text of a template and register a reference to it.

Parameters
Title$title
Returns
array ( string or false, Title )

Definition at line 3954 of file Parser.php.

References $title, and as.

Referenced by fetchTemplate(), and getTemplateDom().

◆ findColonNoLinks()

findColonNoLinks (   $str,
$before,
$after 
)

Split up a string on ':', ignoring any occurrences inside tags to prevent illegal overlapping.

Parameters
string$strThe string to split
string&$beforeSet to everything before the ':'
string&$afterSet to everything after the ':'
Exceptions
MWException
Returns
string The position of the ':', or false if none found

Definition at line 2775 of file Parser.php.

References $i, $state, and wfDebug().

Referenced by doBlockLevels().

◆ formatHeadings()

formatHeadings (   $text,
  $origText,
  $isMain = true 
)

This function accomplishes several tasks: 1) Auto-number headings if that option is enabled 2) Add an [edit] link to sections for users who have enabled the option and can edit the page 3) Add a Table of contents on the top for users who have enabled the option 4) Auto-anchor headings.

It loops through all headlines, collects the necessary data, then splits up the string and re-inserts the newly formatted headlines.

Parameters
string$text
string$origTextOriginal, untouched wikitext
bool$isMain
Returns
mixed|string
Access:\n private

Definition at line 4440 of file Parser.php.

References $i, $matches, $wgExperimentalHtmlIds, $wgMaxTocLevel, as, Html\element(), Sanitizer\escapeId(), false, global, list, Linker\makeHeadline(), Sanitizer\normalizeSectionNameWhitespace(), preprocessToDom(), PPFrame\RECOVER_ORIG, replaceLinkHoldersText(), Linker\tocIndent(), Linker\tocLine(), Linker\tocLineEnd(), Linker\tocList(), and Linker\tocUnindent().

Referenced by Parser\internalParse().

◆ getCommon()

getCommon (   $st1,
  $st2 
)

getCommon() returns the length of the longest common substring of both arguments, starting at the beginning of both.

Access:\n private
Parameters
string$st1
string$st2
Returns
int

Definition at line 2457 of file Parser.php.

References $i.

Referenced by doBlockLevels().

◆ getCustomDefaultSort()

getCustomDefaultSort ( )

Accessor for $mDefaultSort Unlike getDefaultSort(), will return false if none is set.

Returns
string|bool

Definition at line 6174 of file Parser.php.

◆ getDefaultSort()

getDefaultSort ( )

Accessor for $mDefaultSort Will use the empty string if none is set.

This value is treated as a prefix, so the empty string is equivalent to sorting by page name.

Returns
string

Definition at line 6160 of file Parser.php.

Referenced by replaceInternalLinks2().

◆ getExternalLinkAttribs()

getExternalLinkAttribs (   $url = false)

Get an associative array of additional HTML attributes appropriate for a particular external link.

This currently may include rel => nofollow (depending on configuration, namespace, and the URL's domain) and/or a target attribute (depending on configuration).

Parameters
string | bool$urlOptional URL, to extract the domain from for rel => nofollow if appropriate
Returns
array Associative array of HTML attributes

Definition at line 1889 of file Parser.php.

References $attribs, and getExternalLinkRel().

Referenced by Parser\makeFreeExternalLink(), and replaceExternalLinks().

◆ getExternalLinkRel()

static getExternalLinkRel (   $url = false,
  $title = null 
)
static

Get the rel attribute for a particular external link.

Since
1.21
Parameters
string | bool$urlOptional URL, to extract the domain from for rel => nofollow if appropriate
Title$titleOptional Title, for wgNoFollowNsExceptions lookups
Returns
string|null Rel attribute for $url

Definition at line 1868 of file Parser.php.

References $title, $wgNoFollowDomainExceptions, $wgNoFollowLinks, $wgNoFollowNsExceptions, global, and wfMatchesDomainList().

Referenced by getExternalLinkAttribs().

◆ getFreshParser()

getFreshParser ( )

Return this parser if it is not doing anything, otherwise get a fresh parser.

You can use this method by doing $myParser = $wgParser->getFreshParser(), or more simply $wgParser->getFreshParser()->parse( ... ); if you're unsure if $wgParser is safe to use.

Since
1.24
Returns
Parser A parser object that is not parsing anything

Definition at line 6486 of file Parser.php.

References $wgParserConf, and global.

◆ getFunctionHooks()

getFunctionHooks ( )

Get all registered function hook identifiers.

Returns
array

Definition at line 5282 of file Parser.php.

◆ getImageParams()

getImageParams (   $handler)
Parameters
MediaHandler$handler
Returns
array

Definition at line 5509 of file Parser.php.

References $handler, $name, $type, and as.

Referenced by makeImage().

◆ getRevisionId()

getRevisionId ( )

Get the ID of the revision we are parsing.

Returns
int|null

Definition at line 6042 of file Parser.php.

◆ getRevisionObject()

getRevisionObject ( )

Get the revision object for $this->mRevisionId.

Returns
Revision|null Either a Revision object or null
Since
1.23 (public since 1.23)

Definition at line 6052 of file Parser.php.

References $rev, and Revision\newFromId().

Referenced by getRevisionSize(), getRevisionTimestamp(), and getRevisionUser().

◆ getRevisionSize()

getRevisionSize ( )

Get the size of the revision.

Returns
int|null Revision size

Definition at line 6124 of file Parser.php.

References getRevisionObject().

Referenced by getVariableValue().

◆ getRevisionTimestamp()

getRevisionTimestamp ( )

Get the timestamp associated with the current revision, adjusted for the default server-local timestamp.

Returns
string

Definition at line 6081 of file Parser.php.

References $timestamp, $wgContLang, getRevisionObject(), global, and wfTimestampNow().

Referenced by getVariableValue().

◆ getRevisionUser()

getRevisionUser ( )

Get the name of the user that edited the last revision.

Returns
string User name

Definition at line 6104 of file Parser.php.

References getRevisionObject().

Referenced by getVariableValue().

◆ getSection()

getSection (   $text,
  $sectionId,
  $defaultText = '' 
)

This function returns the text of a section, specified by a number ($section).

A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or the first section before any such heading (section 0).

If a section contains subsections, these are also returned.

Parameters
string$textText to look in
string | number$sectionIdSection identifier as a number or string (e.g. 0, 1 or 'T-1').
string$defaultTextDefault to return if section is not found
Returns
string Text of the requested section

Definition at line 6017 of file Parser.php.

References extractSections().

◆ getTags()

getTags ( )

Accessor.

Returns
array

Definition at line 5823 of file Parser.php.

Referenced by EnhancedChangesList\getLineData(), and EnhancedChangesList\recentChangesBlockLine().

◆ getTemplateDom()

getTemplateDom (   $title)

Get the semi-parsed DOM representation of a template with a given title, and its redirect destination title.

Cached.

Parameters
Title$title
Returns
array

Definition at line 3879 of file Parser.php.

References $title, fetchTemplateAndTitle(), list, Title\makeTitle(), and preprocessToDom().

Referenced by braceSubstitution().

◆ getUserSig()

getUserSig ( $user,
  $nickname = false,
  $fancySig = null 
)

Fetch the user's signature text, if any, and normalize to validated, ready-to-insert wikitext.

If you have pre-fetched the nickname or the fancySig option, you can specify them here to save a database query. Do not reuse this parser instance after calling getUserSig(), as it may have changed if it's the $wgParser.

Parameters
User$user
string | bool$nicknameNickname to use or false to use user's default nickname
bool | null$fancySigwhether the nicknname is the complete signature or null to use default value
Returns
string

Definition at line 4961 of file Parser.php.

References $user, $username, $wgMaxSigChars, cleanSig(), cleanSigInSig(), global, validateSig(), wfDebug(), wfEscapeWikiText(), and wfMessage().

Referenced by pstPass2().

◆ getVariableValue()

◆ guessLegacySectionNameFromWikiText()

guessLegacySectionNameFromWikiText (   $text)

Same as guessSectionNameFromWikiText(), but produces legacy anchors instead.

For use in redirects, since IE6 interprets Redirect: headers as something other than UTF-8 (apparently?), resulting in breakage.

Parameters
string$textThe section name
Returns
string An anchor

Definition at line 6202 of file Parser.php.

References Sanitizer\escapeId(), Sanitizer\normalizeSectionNameWhitespace(), and stripSectionName().

◆ guessSectionNameFromWikiText()

guessSectionNameFromWikiText (   $text)

Try to guess the section anchor name based on a wikitext fragment presumably extracted from a heading, for example "Header" from "== Header ==".

Parameters
string$text
Returns
string

Definition at line 6187 of file Parser.php.

References Sanitizer\escapeId(), Sanitizer\normalizeSectionNameWhitespace(), and stripSectionName().

◆ incrementExpensiveFunctionCount()

incrementExpensiveFunctionCount ( )

Increment the expensive function count.

Returns
bool False if the limit has been exceeded

Definition at line 4352 of file Parser.php.

◆ incrementIncludeSize()

incrementIncludeSize (   $type,
  $size 
)

Increment an include size counter.

Parameters
string$typeThe type of expansion
int$sizeThe size of the text
Returns
bool False if this inclusion would take it over the maximum, true otherwise

Definition at line 4338 of file Parser.php.

References $type.

Referenced by argSubstitution(), and braceSubstitution().

◆ initialiseVariables()

initialiseVariables ( )

initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers

Access:\n private

Definition at line 3288 of file Parser.php.

References MagicWord\getSubstIDs(), and MagicWord\getVariableIDs().

Referenced by Parser\firstCallInit().

◆ interwikiTransclude()

interwikiTransclude (   $title,
  $action 
)

Transclude an interwiki link.

Parameters
Title$title
string$action
Returns
string

Definition at line 4140 of file Parser.php.

References $title, $wgEnableScaryTranscluding, fetchScaryTemplateMaybeFromCache(), global, and wfMessage().

Referenced by braceSubstitution().

◆ isValidHalfParsedText()

isValidHalfParsedText (   $data)

Returns true if the given array, presumed to be generated by serializeHalfParsedText(), is compatible with the current version of the parser.

Parameters
array$data
Returns
bool

Definition at line 6400 of file Parser.php.

◆ killMarkers()

killMarkers (   $text)

Remove any strip markers found in the given text.

Parameters
string$textInput string
Returns
string

Definition at line 6330 of file Parser.php.

◆ limitationWarn()

limitationWarn (   $limitationType,
  $current = '',
  $max = '' 
)

Warn the user when a parser limitation is reached Will warn at most once the user per limitation type.

The results are shown during preview and run through the Parser (See EditPage.php)

Parameters
string$limitationTypeShould be one of: 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category') 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category') 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category') 'node-count-exceeded' (corresponding messages: 'node-count-exceeded-warning', 'node-count-exceeded-category') 'expansion-depth-exceeded' (corresponding messages: 'expansion-depth-exceeded-warning', 'expansion-depth-exceeded-category')
string | int | null$currentCurrent value
string | int | null$maxMaximum allowed, when an explicit limit has been exceeded, provide the values (optional)

Definition at line 3440 of file Parser.php.

References addTrackingCategory(), and wfMessage().

Referenced by argSubstitution(), braceSubstitution(), and Parser\parse().

◆ lock()

lock ( )
protected

Lock the current instance of the parser.

This is meant to stop someone from calling the parser recursively and messing up all the strip state.

Exceptions
MWExceptionIf parser is in a parse
Returns
ScopedCallback The lock will be released once the return value goes out of scope.

Definition at line 6441 of file Parser.php.

Referenced by cleanSig(), extractSections(), RedisLockManager\getLocksOnServer(), Parser\getPreloadText(), BagOStuff\getScopedLock(), DatabaseBase\getScopedLockAndFlush(), BagOStuff\incr(), BagOStuff\mergeViaLock(), Parser\parse(), Parser\preprocess(), preSaveTransform(), PoolCounterRedis\release(), ComposerLockTest\setUp(), ComposerLockTest\testGetInstalledDependencies(), and testSrvus().

◆ makeImage()

makeImage (   $title,
  $options,
  $holders = false 
)

Parse image options text and use it to make an image.

Parameters
Title$title
string$options
LinkHolderArray | bool$holders
Returns
string HTML

Definition at line 5557 of file Parser.php.

References $handler, $options, $params, $ret, $time, $title, $type, $value, addTrackingCategory(), as, StringUtils\explode(), fetchFileAndTitle(), getImageParams(), key, list, Linker\makeImageLink(), Title\newFromText(), parseWidthParam(), and stripAltText().

Referenced by replaceInternalLinks2().

◆ makeKnownLinkHolder()

makeKnownLinkHolder (   $nt,
  $text = '',
  $query = [],
  $trail = '',
  $prefix = '' 
)

Render a forced-blue link inline; protect against double expansion of URLs if we're in a mode that prepends full URL prefixes to internal links.

Since this little disaster has to split off the trail text to avoid breaking URLs in the following text without breaking trails on the wiki links, it's been made into a horrible function.

Parameters
Title$nt
string$text
array | string$query
string$trail
string$prefix
Returns
string HTML-wikitext mix oh yuck

Definition at line 2380 of file Parser.php.

References $link, $query, armorLinks(), Linker\linkKnown(), list, Linker\splitTrail(), and wfCgiToArray().

◆ markerSkipCallback()

markerSkipCallback (   $s,
  $callback 
)

Call a callback function on all regions of the given text that are not inside strip markers, and replace those regions with the return value of the callback.

For example, with input:

aaa<MARKER>bbb

This will call the callback function twice, with 'aaa' and 'bbb'. Those two strings will be replaced with the value returned by the callback in each case.

Parameters
string$s
callable$callback
Returns
string

Definition at line 6300 of file Parser.php.

References $i, $out, and $s.

◆ maybeDoSubpageLink()

maybeDoSubpageLink (   $target,
$text 
)

Handle link to subpage if necessary.

Parameters
string$targetThe source of the link
string&$textThe link text, modified as necessary
Returns
string The full name of the link
Access:\n private

Definition at line 2427 of file Parser.php.

References Linker\normalizeSubpageLink().

Referenced by braceSubstitution(), and replaceInternalLinks2().

◆ maybeMakeExternalImage()

maybeMakeExternalImage (   $url)
private

make an image if it's allowed, either through the global option, through the exception, or through the on-wiki whitelist

Parameters
string$url
Returns
string

Definition at line 1990 of file Parser.php.

References as, Linker\makeExternalImage(), text, and wfMessage().

Referenced by Parser\makeFreeExternalLink(), and replaceExternalLinks().

◆ nextItem()

nextItem (   $char)

TODO: document.

Parameters
string$char
Access:\n private
Returns
string

Definition at line 2507 of file Parser.php.

Referenced by doBlockLevels().

◆ normalizeLinkUrl()

static normalizeLinkUrl (   $url)
static

Replace unusual escape codes in a URL with their equivalent characters.

This generally follows the syntax defined in RFC 3986, with special consideration for HTTP query strings.

Parameters
string$url
Returns
string

Definition at line 1931 of file Parser.php.

References $ret, and normalizeUrlComponent().

Referenced by replaceUnusualEscapes().

◆ normalizeUrlComponent()

static normalizeUrlComponent (   $component,
  $unsafe 
)
staticprivate

Definition at line 1967 of file Parser.php.

References $matches, and use.

Referenced by normalizeLinkUrl().

◆ openList()

openList (   $char)

These next three functions open, continue, and close the list element appropriate to the prefix character passed into them.

Access:\n private
Parameters
string$char
Returns
string

Definition at line 2481 of file Parser.php.

References closeParagraph().

Referenced by doBlockLevels().

◆ parseWidthParam()

parseWidthParam (   $value)

Parsed a width param of imagelink like 300px or 200x300px.

Parameters
string$value
Returns
array
Since
1.20

Definition at line 6412 of file Parser.php.

References $value.

Referenced by makeImage().

◆ preprocessToDom()

preprocessToDom (   $text,
  $flags = 0 
)

Preprocess some wikitext and return the document tree.

This is the ghost of replace_variables().

Parameters
string$textThe text to parse
int$flagsBitwise combination of:
  • self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being included. Default is to assume a direct page view.

The generated DOM tree must depend only on the input text and the flags. The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.

Any flag added to the $flags parameter here, or any other parameter liable to cause a change in the DOM tree for a given text, must be passed through the section identifier in the section edit link and thus back to extractSections().

The output of this function is currently only cached in process memory, but a persistent cache may be implemented at a later date which takes further advantage of these strict dependency requirements.

Returns
PPNode

Definition at line 3318 of file Parser.php.

References $flags.

Referenced by braceSubstitution(), callParserFunction(), cleanSig(), extractSections(), formatHeadings(), Parser\getPreloadText(), getTemplateDom(), Parser\internalParse(), and replaceVariables().

◆ preSaveTransform()

preSaveTransform (   $text,
Title  $title,
User  $user,
ParserOptions  $options,
  $clearState = true 
)

Transform wiki markup when saving a page by doing "\\r\\n" -> "\\n" conversion, substituting signatures, {{subst:}} templates, etc.

Parameters
string$textThe text to transform
Title$titleThe Title object for the current article
User$userThe User object describing the current user
ParserOptions$optionsParsing options
bool$clearStateWhether to clear the parser state first
Returns
string The altered wiki markup

Definition at line 4850 of file Parser.php.

References $options, $user, lock(), pstPass2(), and startParse().

Referenced by testPst().

◆ pstPass2()

pstPass2 (   $text,
  $user 
)
private

Pre-save transform helper function.

Parameters
string$text
User$user
Returns
string

Definition at line 4882 of file Parser.php.

References $t, $timestamp, $user, $wgContLang, MWTimestamp\getLocalInstance(), getUserSig(), global, Title\legalChars(), replaceVariables(), and use.

Referenced by preSaveTransform().

◆ renderImageGallery()

renderImageGallery (   $text,
  $params 
)

Renders an image gallery from a text with one line per image.

text labels may be given by using |-style alternative text. E.g. Image:one.jpg|The number "1" Image:tree.jpg|A tree given as text will return the HTML of a gallery with two images, labeled 'The number "1"' and 'A tree'.

Parameters
string$text
array$params
Returns
string HTML

Definition at line 5347 of file Parser.php.

References $e, $handler, $html, $line, $lines, $link, $matches, $options, $params, $parser, $title, as, StringUtils\explode(), ImageGalleryBase\factory(), fetchFileNoRegister(), Title\getLinkURL(), list, Title\newFromText(), NS_FILE, replaceInternalLinks(), replaceLinkHoldersText(), stripAltText(), Sanitizer\validateTagAttributes(), and wfDebug().

◆ replaceExternalLinks()

replaceExternalLinks (   $text)

Replace external links (REL)

Note: this is all very hackish and the order of execution matters a lot. Make sure to run tests/parserTests.php if you change this code.

Access:\n private
Parameters
string$text
Exceptions
MWException
Returns
string

Definition at line 1792 of file Parser.php.

References $i, $s, Sanitizer\cleanUrl(), getExternalLinkAttribs(), list, Linker\makeExternalLink(), maybeMakeExternalImage(), and Linker\splitTrail().

Referenced by Parser\internalParse(), and replaceInternalLinks2().

◆ replaceInternalLinks()

replaceInternalLinks (   $s)

Process [[ ]] wikilinks.

Parameters
string$s
Returns
string Processed text
Access:\n private

Definition at line 2049 of file Parser.php.

References $s, and replaceInternalLinks2().

Referenced by Parser\internalParse(), and renderImageGallery().

◆ replaceInternalLinks2()

◆ replaceLinkHolders()

replaceLinkHolders ( $text,
  $options = 0 
)

Replace "<!--LINK-->" link placeholders with actual links, in the buffer Placeholders created in Linker::link()

Parameters
string$text
int$options

Definition at line 5319 of file Parser.php.

Referenced by Parser\internalParseHalfParsed().

◆ replaceLinkHoldersText()

replaceLinkHoldersText (   $text)

Replace "<!--LINK-->" link placeholders with plain text of links (not HTML-formatted).

Parameters
string$text
Returns
string

Definition at line 5330 of file Parser.php.

Referenced by formatHeadings(), renderImageGallery(), and stripAltText().

◆ replaceSection()

replaceSection (   $oldText,
  $sectionId,
  $newText 
)

This function returns $oldtext after the content of the section specified by $section has been replaced with $text.

If the target section does not exist, $oldtext is returned unchanged.

Parameters
string$oldTextFormer text of the article
string | number$sectionIdSection identifier as a number or string (e.g. 0, 1 or 'T-1').
string$newTextReplacing text
Returns
string Modified text

Definition at line 6033 of file Parser.php.

References extractSections().

◆ replaceTransparentTags()

replaceTransparentTags (   $text)

Replace transparent tags in $text with the values given by the callbacks.

Transparent tag hooks are like regular XML-style tag hooks, except they operate late in the transformation sequence, on HTML instead of wikitext.

Parameters
string$text
Returns
string

Definition at line 5841 of file Parser.php.

References $content, $matches, $output, $params, $tag, as, and list.

Referenced by Parser\internalParseHalfParsed().

◆ replaceUnusualEscapes()

static replaceUnusualEscapes (   $url)
static

Replace unusual escape codes in a URL with their equivalent characters.

Deprecated:
since 1.24, use normalizeLinkUrl
Parameters
string$url
Returns
string

Definition at line 1917 of file Parser.php.

References normalizeLinkUrl(), and wfDeprecated().

◆ replaceVariables()

replaceVariables (   $text,
  $frame = false,
  $argsOnly = false 
)

Replace magic variables, templates, and template arguments with the appropriate text.

Templates are substituted recursively, taking care to avoid infinite loops.

Note that the substitution depends on value of $mOutputType: self::OT_WIKI: only {{subst:}} templates self::OT_PREPROCESS: templates but not extension tags self::OT_HTML: all templates and extension tags

Parameters
string$textThe text to transform
bool | PPFrame$frameObject describing the arguments passed to the template. Arguments may also be provided as an associative array, as was the usual case before MW1.12. Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
bool$argsOnlyOnly do argument (triple-brace) expansion, not double-brace expansion.
Returns
string

Definition at line 3363 of file Parser.php.

References $flags, PPFrame\NO_TEMPLATES, preprocessToDom(), and wfDebug().

Referenced by attributeStripCallback(), Parser\internalParse(), Parser\preprocess(), pstPass2(), Parser\recursivePreprocess(), and testSrvus().

◆ serializeHalfParsedText()

serializeHalfParsedText (   $text)

Save the parser state required to convert the given half-parsed text to HTML.

"Half-parsed" in this context means the output of recursiveTagParse() or internalParse(). This output has strip markers from replaceVariables (extensionSubstitution() etc.), and link placeholders from replaceLinkHolders().

Returns an array which can be serialized and stored persistently. This array can later be loaded into another parser instance with unserializeHalfParsedText(). The text can then be safely incorporated into the return value of a parser hook.

Parameters
string$text
Returns
array

Definition at line 6350 of file Parser.php.

◆ setDefaultSort()

setDefaultSort (   $sort)

Mutator for $mDefaultSort.

Parameters
string$sortNew value

Definition at line 6145 of file Parser.php.

References $sort.

◆ setFunctionHook()

setFunctionHook (   $id,
  $callback,
  $flags = 0 
)

Create a function, e.g.

{{sum:1|2|3}} The callback function should have the form: function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }

Or with Parser::SFH_OBJECT_ARGS: function myParserFunction( $parser, $frame, $args ) { ... }

The callback may either return the text result of the function, or an array with the text in element 0, and a number of flags in the other elements. The names of the flags are specified in the keys. Valid flags are: found The text returned is valid, stop processing the template. This is on by default. nowiki Wiki markup in the return value should be escaped isHTML The returned text is HTML, armour it against wikitext transformation

Parameters
string$idThe magic word ID
callable$callbackThe callback function (and object) to use
int$flagsA combination of the following flags: Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}

Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This allows for conditional expansion of the parse tree, allowing you to eliminate dead branches and thus speed up parsing. It is also possible to analyse the parse tree of the arguments, and to control the way they are expanded.

The $frame parameter is a PPFrame. This can be used to produce expanded text from the arguments, for instance: $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';

For technical reasons, $args[0] is pre-expanded and will be a string. This may change in future versions. Please call $frame->expand() on it anyway so that your code keeps working if/when this is changed.

If you want whitespace to be trimmed from $args, you need to do it yourself, post- expansion.

Please read the documentation in includes/parser/Preprocessor.php for more information about the methods available in PPFrame and PPNode.

Exceptions
MWException
Returns
string|callable The old callback function for this name, if any

Definition at line 5244 of file Parser.php.

References $flags, $wgContLang, as, MagicWord\get(), and global.

◆ setFunctionTagHook()

setFunctionTagHook (   $tag,
  $callback,
  $flags 
)

Create a tag function, e.g.

"<test>some stuff</test>". Unlike tag hooks, tag functions are parsed at preprocessor level. Unlike parser functions, their content is not preprocessed.

Parameters
string$tag
callable$callback
int$flags
Exceptions
MWException
Returns
null

Definition at line 5296 of file Parser.php.

References $flags, and $tag.

◆ setHook()

setHook (   $tag,
  $callback 
)

Create an HTML-style tag, e.g.

"<yourtag>special text</yourtag>" The callback should have the following form: function myParserHook( $text, $params, $parser, $frame ) { ... }

Transform and return $text. Use $parser for any required context, e.g. use $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions

Hooks may return extended information by returning an array, of which the first numbered element (index 0) must be the return string, and all other entries are extracted into local variables within an internal function in the Parser class.

This interface (introduced r61913) appears to be undocumented, but 'markerType' is used by some core tag hooks to override which strip array their results are placed in. Use great caution if attempting this interface, as it is not documented and injudicious use could smash private variables.

Parameters
string$tagThe tag to use, e.g. 'hook' for "<hook>"
callable$callbackThe callback function (and object) to use for the tag
Exceptions
MWException
Returns
callable|null The old value of the mTagHooks array associated with the hook

Definition at line 5150 of file Parser.php.

References $tag.

◆ setTransparentTagHook()

setTransparentTagHook (   $tag,
  $callback 
)

As setHook(), but letting the contents be parsed.

Transparent tag hooks are like regular XML-style tag hooks, except they operate late in the transformation sequence, on HTML instead of wikitext.

This is probably obsoleted by things dealing with parser frames? The only extension currently using it is geoserver.

Since
1.10
Todo:
better document or deprecate this
Parameters
string$tagThe tag to use, e.g. 'hook' for "<hook>"
callable$callbackThe callback function (and object) to use for the tag
Exceptions
MWException
Returns
callable|null The old value of the mTagHooks array associated with the hook

Definition at line 5181 of file Parser.php.

References $tag.

◆ splitWhitespace()

static splitWhitespace (   $s)
static

Return a three-element array: leading whitespace, string contents, trailing whitespace.

Parameters
string$s
Returns
array

Definition at line 3330 of file Parser.php.

References $s.

◆ startExternalParse()

startExternalParse ( Title  $title = null,
ParserOptions  $options,
  $outputType,
  $clearState = true 
)

Set up some variables which are usually set up in parse() so that an external function can call some class members with confidence.

Parameters
Title | null$title
ParserOptions$options
int$outputType
bool$clearState

Definition at line 5075 of file Parser.php.

References $options, $title, and startParse().

◆ startParse()

startParse ( Title  $title = null,
ParserOptions  $options,
  $outputType,
  $clearState = true 
)
private
Parameters
Title | null$title
ParserOptions$options
int$outputType
bool$clearState

Definition at line 5087 of file Parser.php.

References $options, and $title.

Referenced by cleanSig(), extractSections(), Parser\getPreloadText(), Parser\parse(), Parser\preprocess(), preSaveTransform(), startExternalParse(), and testSrvus().

◆ statelessFetchRevision()

static statelessFetchRevision (   $title,
  $parser = false 
)
static

Wrapper around Revision::newFromTitle to allow passing additional parameters without passing them on to it.

Since
1.24
Parameters
Title$title
Parser | bool$parser
Returns
Revision

Definition at line 3945 of file Parser.php.

References $title, and Revision\newFromTitle().

◆ statelessFetchTemplate()

static statelessFetchTemplate (   $title,
  $parser = false 
)
static

Static function to get a template Can be overridden via ParserOptions::setTemplateCallback().

Parameters
Title$title
bool | Parser$parser
Returns
array

Definition at line 3995 of file Parser.php.

References $content, $i, $parser, $rev, $title, $wgContLang, global, Revision\newFromId(), Revision\newFromTitle(), NS_MEDIAWIKI, LinkCache\singleton(), and wfMessage().

◆ stripAltText()

stripAltText (   $caption,
  $holders 
)
protected
Parameters
string$caption
LinkHolderArray | bool$holders
Returns
mixed|string

Definition at line 5772 of file Parser.php.

References replaceLinkHoldersText(), and Sanitizer\stripAllTags().

Referenced by makeImage(), and renderImageGallery().

◆ stripOuterParagraph()

static stripOuterParagraph (   $html)
static

Strip outer.

tag from the HTML source of a single paragraph.

Returns original HTML if the

tag has any attributes, if there's no wrapping

tag, or if there is more than one

tag in the input HTML.

Parameters
string$html
Returns
string
Since
1.24

Definition at line 6465 of file Parser.php.

References $html.

◆ stripSectionName()

stripSectionName (   $text)

Strips a text string of wikitext for use in a section anchor.

Accepts a text string and then removes all wikitext from the string and leaves only the resultant text (i.e. the result of [[User:WikiSysop|Sysop]] would be "Sysop" and the result of [[User:WikiSysop]] would be "User:WikiSysop") - this is intended to create valid section anchors by mimicing the output of the parser when headings are parsed.

Parameters
string$textText string to be stripped of wikitext for use in a Section anchor
Returns
string Filtered text string

Definition at line 6223 of file Parser.php.

References StringUtils\delimiterReplace().

Referenced by guessLegacySectionNameFromWikiText(), and guessSectionNameFromWikiText().

◆ testPreprocess()

testPreprocess (   $text,
Title  $title,
ParserOptions  $options 
)
Parameters
string$text
Title$title
ParserOptions$options
Returns
string

Definition at line 6280 of file Parser.php.

References $options, $title, and testSrvus().

◆ testPst()

testPst (   $text,
Title  $title,
ParserOptions  $options 
)
Parameters
string$text
Title$title
ParserOptions$options
Returns
string

Definition at line 6270 of file Parser.php.

References $options, $title, and preSaveTransform().

◆ testSrvus()

testSrvus (   $text,
Title  $title,
ParserOptions  $options,
  $outputType = self::OT_HTML 
)

strip/replaceVariables/unstrip for preprocessor regression testing

Parameters
string$text
Title$title
ParserOptions$options
int$outputType
Returns
string

Definition at line 6252 of file Parser.php.

References $options, lock(), Sanitizer\removeHTMLtags(), replaceVariables(), and startParse().

Referenced by testPreprocess().

◆ transformMsg()

transformMsg (   $text,
  $options,
  $title = null 
)

Wrapper for preprocess()

Parameters
string$textThe text to preprocess
ParserOptions$optionsOptions
Title | null$titleTitle object or null to use $wgTitle
Returns
string

Definition at line 5106 of file Parser.php.

References $options, $title, $wgTitle, and global.

◆ unserializeHalfParsedText()

unserializeHalfParsedText (   $data)

Load the parser state given in the $data array, which is assumed to have been generated by serializeHalfParsedText().

The text contents is extracted from the array, and its markers are transformed into markers appropriate for the current Parser instance. This transformed text is returned, and can be safely included in the return value of a parser hook.

If the $data array has been stored persistently, the caller should first check whether it is still valid, by calling isValidHalfParsedText().

Parameters
array$dataSerialized data
Exceptions
MWException
Returns
string

Definition at line 6375 of file Parser.php.

◆ validateSig()

validateSig (   $text)

Check that the user's signature contains no bad XML.

Parameters
string$text
Returns
string|bool An expanded string, or false if invalid.

Definition at line 5010 of file Parser.php.

References Xml\isWellFormedXmlFragment().

Referenced by getUserSig().

Variable Documentation

◆ $buffer

◆ $i

$i = 0
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 1694 of file Parser.php.

Referenced by ParserDiffTest\__call(), MappedDiff\__construct(), JSNode\__construct(), LoadBalancer\__construct(), DateFormatter\__construct(), DiffHistoryBlob\__sleep(), StatusValue\__toString(), DiffHistoryBlob\__wakeup(), MemcachedClient\_connect_sock(), LocalIdLookupTest\addDBData(), AuthManagerSpecialPage\addTabIndex(), SpecialPasswordReset\alterForm(), ApiQuerySiteinfo\appendDbReplLagInfo(), SiteConfiguration\arrayMerge(), DatabaseSqliteTest\assertResultIs(), MediaWikiTestCase\assertSelect(), Benchmarker\bench(), BenchmarkHooks\benchHooks(), BenchmarkPurge\benchSquid(), braceSubstitution(), SpecialEditTags\buildCheckBoxes(), SectionProfiler\calculateOverhead(), SectionProfiler\calltreeCount(), TableDiffFormatter\changed(), ApiMain\checkConditionalRequestHeaders(), TextPassDumperDatabaseTest\checkpointHelper(), Status\cleanParams(), LocalFileRestoreBatch\cleanupFailedBatch(), DumpMultiWriter\closeAndRename(), Exif\collapseData(), ImageListPager\combineResult(), DiffHistoryBlob\compress(), CompressOld\compressWithConcat(), UploadFromChunks\concatenateChunks(), MagicVariableTest\createProviderUpTo(), SqlBagOStuff\createTables(), LayeredParameterizedPassword\crypt(), Pbkdf2Password\crypt(), DatabaseSqlite\dataSeek(), SqlBagOStuff\deleteAll(), SqlBagOStuff\deleteObjectsExpiringBefore(), WikiDiff3\diff(), RecompressTracked\dispatch(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), JobQueueFederated\doBatchPush(), PopulateFilearchiveSha1\doDBUpdates(), PopulateImageSha1\doDBUpdates(), JobQueueRedis\doGetSiblingQueueSizes(), Parser\doHeadings(), FileBackendStore\doOperationsInternal(), Parser\doQuotes(), RefreshLinks\doRefreshLinks(), FileBackendTest\doTestConcatenate(), FileBackendTest\doTestGetFileContents(), FileBackendTest\doTestGetLocalCopy(), FileBackendTest\doTestGetLocalReference(), FileBackendTest\doTestLockCalls(), LinkHolderArray\doVariants(), MultiWriteBagOStuff\doWrite(), ApiMain\encodeRequestLogValue(), TextPassDumper\endElement(), StringUtilsTest\escaped(), ApiProtect\execute(), ApiUndelete\execute(), BenchmarkHooks\execute(), BenchmarkParse\execute(), CleanupRemovedModules\execute(), UploadStashCleanup\execute(), GenerateCommonPassword\execute(), FindDeprecated\execute(), GetSlaveServer\execute(), ImportTextFiles\execute(), DatabaseLag\execute(), MakeTestEdits\execute(), McTest\execute(), PopulateCategory\execute(), PPFuzzTester\execute(), MwSql\execute(), StringUtils\explodeMarkup(), FSFile\extensionFromPath(), FileBackend\extensionFromPath(), LogFormatter\extractParameters(), MssqlBlob\fetch(), DatabaseMysqlBase\fieldInfo(), ProcessCacheLRUTest\fillCache(), Maintenance\finalSetup(), findColonNoLinks(), ForkController\forkWorkers(), BlockLogFormatter\formatBlockFlags(), formatHeadings(), BatchRowUpdateTest\genSelectResult(), MemcachedClient\get_sock(), SpecialPageFactory\getAliasList(), LoadBalancer\getAnyOpenConnection(), FileBackendDBRepoWrapper\getBackendPaths(), MagicWordArray\getBaseRegex(), ImageHistoryPseudoPager\getBody(), IndexPager\getBody(), MWNamespace\getCanonicalIndex(), DiffOp\getClosing(), getCommon(), LoadBalancer\getConnection(), FileRepo\getDeletedHashPath(), DjVuHandler\getDimensionInfo(), MediaHandler\getEntireText(), ApiBase\getExamplesMessages(), ProcessCacheLRUTest\getExpectedCache(), DumpMultiWriter\getFilenames(), MWHttpRequest\getFinalUrl(), FileRepo\getHashPathForLevel(), ApiHelp\getHelpInternal(), RandomImageGenerator\getImageSpec(), Xhprof\getInclusiveMetrics(), LoadMonitorMySQL\getLagTimes(), MediaWiki\Auth\ConfirmLinkAuthenticationRequestTest\getLinkRequests(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest\getLinkRequests(), LoadBalancer\getMasterPos(), LoadBalancer\getMaxLag(), Languages\getMessagesWithDubiousLinks(), ApiBase\getModuleFromPath(), ApiParamInfo\getModuleInfo(), Language\getMonthAbbreviationsArray(), Language\getMonthNamesArray(), DateFormatter\getMonthRegex(), RedisBagOStuff\getMulti(), WANObjectCache\getMulti(), HTMLFormField\getNearestFieldByName(), ApiPageSet\getPositiveIntegers(), RandomImageGenerator\getRandomColor(), RandomImageGenerator\getRandomLines(), LoadBalancer\getRandomNonLagged(), RandomImageGenerator\getRandomWordPairs(), LoadBalancer\getReaderIndex(), UIDGenerator\getSequentialPerNodeIDs(), LoadBalancer\getServerInfo(), LoadBalancer\getServerName(), MagicWord\getSynonym(), SpecialBlock\getTargetAndType(), FileJournal\getTimestampedUUID(), UploadBase\getTitle(), FileCacheBase\hashSubdirectory(), LoadBalancer\haveIndex(), Language\hebrewNumeral(), ZipDirectoryReader\hexDump(), ParserDiffTest\init(), HTMLFormField\isHiddenRecurse(), Http\isLocalURL(), LoadBalancer\isNonZeroLoad(), SpecialBookSources\isValidISBN(), PPNode_DOM\item(), PPNode_Hash_Array\item(), RecompressTracked\killSlaveProcs(), WikiDiff3\lcs_rec(), Language\listToText(), GenerateSitemap\main(), PPFuzzTester\makeInputText(), BenchWikimediaBaseConvert\makeRandomNumber(), EditPage\makeSafe(), SiteImporter\makeSite(), markerSkipCallback(), BatchRowUpdateTest\mockUpdate(), Xml\monthSelector(), DatabaseMysql\mysqlConnect(), JobQueueTest\newDedupedJob(), JobQueueTest\newJob(), LBFactorySimple\newMainLB(), LoadBalancer\openConnection(), LoadBalancer\openForeignConnection(), ImagePage\openShowImage(), ImageQueryPage\outputResults(), QueryPage\outputResults(), PurgeChangedPages\pageableSortedRows(), IPTC\parse(), JSMinPlus\parseTree(), LayeredParameterizedPassword\partialCrypt(), BacklinkCache\partitionResult(), ApiResult\path(), ArrayUtils\pickRandom(), SpecialSearch\powerSearchBox(), Preprocessor_Hash\preprocessToObj(), HooksTest\provideHooks(), LocalIdLookupTest\provideIsAttachedShared(), RefreshLinksPartitionTest\provider_backlinks(), MediaWiki\Auth\AuthManager\providerArrayFromSpecs(), DeferredStringifierTest\provideToString(), FileRepo\publishBatch(), BenchmarkPurge\randomTitle(), BenchmarkPurge\randomUrlList(), TextPassDumper\readDump(), GIFMetadataExtractor\readGCT(), ContribsPager\reallyDoQuery(), DeletedContribsPager\reallyDoQuery(), EnhancedChangesList\recentChangesBlockGroup(), JSParser\reduce(), DateFormatter\reformat(), SectionProfiler\remapCallTree(), RegexlikeReplacer\replace(), replaceExternalLinks(), Language\romanNumeral(), SquidPurgeClientPool\run(), ApiQueryBacklinksprop\run(), FileOpBatch\runParallelBatches(), LoadBalancer\setServerInfo(), ApiRevisionDeleteTest\setUp(), BaseDumpTest\setUpPrefetch(), TextPassDumperDatabaseTest\setUpStub(), DiffEngine\shiftBoundaries(), Maintenance\shouldExecute(), UpdateCollation\showSortKeySizeHistogram(), AuthManagerSpecialPage\sortFormDescriptorFields(), RecompressTracked\startSlaveProcs(), statelessFetchTemplate(), JSParser\Statement(), SyncFileBackend\syncFileBatch(), MediaWiki\Auth\AuthManagerTest\testAccountCreation(), MediaWiki\Auth\AuthManagerTest\testAccountLink(), MediaWiki\Auth\AuthManagerTest\testAuthentication(), LanguageConverterTest\testAutoConvertT124404(), WfShellExecTest\testBug67870(), WANObjectCacheTest\testCheckKeyInitHoldoff(), HashBagOStuffTest\testClear(), HashBagOStuffTest\testDelete(), ApiDocumentationTest\testDocumentationExists(), UserTest\testEditCount(), HashBagOStuffTest\testEvictionAdd(), MediaWiki\Auth\AuthenticationRequestTest\testGetUsernameFromRequests(), MediaWiki\Logger\Monolog\KafkaHandlerTest\testHandlesNullFormatterResult(), PoolCounterTest\testHashKeyIntoSlots(), HashRingTest\testHashRing(), FormatMetadataTest\testInvalidDate(), IPTest\testInvalidIPs(), JobQueueTest\testJobOrder(), MediaWiki\Session\SessionManagerTest\testLoadSessionInfoFromStore(), WfGetCallerTest\testN(), MediaWiki\Auth\AbstractPrimaryAuthenticationProviderTest\testProviderRevokeAccessForUser(), MediaWiki\Auth\AbstractSecondaryAuthenticationProviderTest\testProviderRevokeAccessForUser(), UIDGeneratorTest\testRawUUIDv4(), UIDGeneratorTest\testRawUUIDv4QuickRand(), BatchRowUpdateTest\testReaderBasicIterate(), BatchRowUpdateTest\testReaderSelectConditionsMultiplePrimaryKeys(), JobQueueTest\testRootDeduplication(), CachedBagOStuffTest\testSetAndDelete(), WANObjectCacheTest\testSetOver(), SearchSuggestionSetTest\testShrink(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testTestForAuthentication(), UIDGeneratorTest\testTimestampedUID(), UIDGeneratorTest\testUUIDv1(), UIDGeneratorTest\testUUIDv4(), IPTest\testValidIPs(), TransactionProfiler\transactionWritingOut(), BitmapHandler\transformImageMagickExt(), Language\tsToHebrew(), Language\tsToIranian(), EditPage\unmakeSafe(), ZipDirectoryReader\unpack(), MediaWiki\Auth\AuthManagerTest\usernameForCreation(), LoadBalancer\waitFor(), LoadBalancer\waitForAll(), LoadBalancer\waitForOne(), LBFactory\waitForReplication(), wfCountDown(), wfExtractThumbRequestInfo(), wfHtmlValidationHandler(), wfIsBadImage(), DumpMultiWriter\writeClosePage(), DumpMultiWriter\writeCloseStream(), DumpMultiWriter\writeOpenPage(), DumpMultiWriter\writeOpenStream(), and DumpMultiWriter\writeRevision().

◆ $output

foreach($arr as $r) if( $state==='b'|| $state==='ib') if($state==='i'||$state==='bi'||$state==='ib') if( $state==='bi') if ($state==='both' &&$buffer) return $output = ''

Definition at line 1691 of file Parser.php.

Referenced by doBlockLevels(), extensionSubstitution(), and replaceTransparentTags().

◆ $state