Manual:Tag extensions

MediaWiki, the software that runs the various Wikimedia projects, allows developers to write their own extensions.

They can be additional special pages, or extensions to the wiki markup. This page is about the latter. There are two types:


 * Those used with XML-style tags in the wikitext:


 *  some text


 * The text between the tags gets passed on to a PHP function you implement. This function can then return a HTML string that gets inserted into the output in place of the tags and text. (Note that the return string should be HTML, not wiki markup.)


 * parser functions, using tags with double braces in the wikitext:



Creating an XML-style extension
MediaWiki extensions live in the  subdirectory in the MediaWiki installation. To create your own extension, first create a new file called  in this directory containing the following template code:

 some text 
 * 5) the function registered by the extension gets the text between the
 * 6) tags as input and can transform it into arbitrary HTML code.
 * 7) Note: The output is not interpreted as WikiText but directly
 * 8)       included in the HTML output. So Wiki markup is not supported.
 * 9) To activate the extension, include it from your LocalSettings.php
 * 10) with: include("extensions/YourExtensionName.php");

$wgExtensionFunctions[] = "wfExampleExtension";

function wfExampleExtension { global $wgParser; # register the extension with the WikiText parser # the first parameter is the name of the new tag. # In this case it defines the tag ...    # the second parameter is the callback function for # processing the text between the tags $wgParser->setHook( "example", "renderExample" ); }

function renderExample( $input, $argv, &$parser ) { # $argv is an array containing any arguments passed to the # extension like .. # Put this on the sandbox page: (works in MediaWiki 1.5.5) #  Testing text **example** in between the new tags $output = "Text passed into example extension: $input"; $output .= " and the value for the arg 'argument' is ". $argv["argument"]; $output .= " and the value for the arg 'argument2' is: ". $argv["argument2"]; return $output; } ?>
 * 1) The callback function for converting the input text to HTML output

Now change the tag name, the function names and of course the functionality of the callback to your liking. Note that it might be better to first install and test the example extension (see next section) and only then start customizing it.

Prior to v1.5, the $argv argument is not actually passed to your callback function. (See below.)

The Parser object, accessible via the  parameter since v1.5.8, offers some useful members:


 * disableCache : Disables the client and parser cache. Call this if the HTML you are returning changes regularly, without the source text changing.
 * mTitle : The title of the article being processed. Use this whenever you need a title, do not under any circumstances use $wgTitle.
 * mOptions : The ParserOptions object describing the user's preferences
 * mOutput : The ParserOutput object

Installing the extension
All it takes is adding a single line to the end of your  file (above the "?>"):

require_once 'extensions/YourExtensionName.php';

and you are ready to go. Go to the sandbox and see if it works.

Timing and extensions
If you change the code for an extension, all pages that use the extension will, theoretically, immediately reflect the results of new code. Technically speaking, this means your code is executed each and every time a page containing the extension is rendered.

In practice, this is often not the case, due to page caching - either by the MediaWiki software, the browser or by an intermediary proxy or firewall.

To bypass MediaWiki's parser cache and ensure a new version of the page is generated, click on edit, replace "action=edit" in the URL shown in the address bar of your browser by "action=purge" and submit the new URL. The page and all templates it references will be regenerated, ignoring all cached data. The purge action is needed if the main page itself is not modified, but the way it must be rendered has changed (the extension was modified, or only a referenced template was modified).

If this is not sufficient to get you a fresh copy of the page, you can normally bypass intermediary caches by adding '&rand=somerandomtext' to the end of the above URL. Make sure 'somerandomtext' is different every time.

Hooks
Your extension can include functions that are called at various steps of the rendering process. Many "hooks" are included in MediaWiki which you can use.

Example : Call a function just before TidyHTML is run on the (mostly rendered) page.

In Parser.php, the appropriate hook is already defined: wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );

In your extension file, add: $wgHooks['ParserBeforeTidy'][] = 'myhook' ; and your function function myhook ( &$parser, &$text ) { $text .= "and then some" ; }

Passing attributes to extensions
As of MediaWiki 1.5, the second parameter to the hook function will be an associative array of attribute => value pairs from the extension's opening tag.

In MediaWiki 1.4 and below, you can't pass attributes in the extensions opening tag. You can work around this by using a  element with a class name of your extension to be invisible and contain the attributes. The extension code can then match them from the article content. This example will extract and loop through all the attributes from a specified  class:

if (preg_match( '//', $article, $match )) { preg_match_all( '/(\\w+?)="(.+?)"/', $match[1], $match, PREG_SET_ORDER ); foreach ($match as $i) echo "attribute $i[1] contains $i[2]"; }

You would pass the attributes like this:

Parser functions
Tag hook extensions, as described above, are expected to take unprocessed text and return HTML. There is virtually no integration with the rest of the parser; for example, the output of an extension cannot be used as a template parameter. Expanding templates within extension tags is possible, but must be done manually -- an error-prone process which changes from version to version.

Parser functions, available since 1.7, provide a way to integrate much more closely with templates and other parser features. There is an embryonic parser function feature in 1.6, but using it is not recommmended, due to the differences in API and syntax.
 * seems to work well in 1.6.8 with the suggested mods as per ParserFunctions --Ernye 11:03, 9 October 2006 (UTC)

The typical syntax for a parser function is:

Creating a parser function is slightly more complicated than creating a tag hook, because the function name must be a "magic word" -- a kind of keyword that supports aliases and localisation. Below is an example of an extension that creates a parser function.

setFunctionHook( 'example', 'wfExampleParserFunction_Render' ); }

function wfExampleParserFunction_Magic( &$magicWords, $langCode ) { # Add the magic word # The first array element is case sensitive, in this case it is not case sensitive # All remaining elements are synonyms for our parser function $magicWords['example'] = array( 0, 'example' ); # unless we return true, other parser functions extensions won't get loaded. return true; }

function wfExampleParserFunction_Render( &$parser, $param1 = , $param2 =  ) { # The parser function itself # The input parameters are wikitext with templates expanded # The output should be wikitext too return "param1 is $param1 and param2 is $param2"; }

?>

With this extension enabled,

*

produces:


 * param1 is hello and param2 is hi

As with tag extensions, $parser->disableCache may be used to disable the cache for dynamic extensions.

Here is the documentation for setFunctionHook, copied from the comments in the code in includes/Parser.php:

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

Parameters:


 * string $id - The magic word ID
 * mixed $callback - The callback function (and object) to use
 * integer $flags - Optional, set it to the SFH_NO_HASH constant to call the function without "#".

Return value: The old callback function for this name, if any

Create a function, e.g. . The callback function should have the form:

function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }

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
 * noparse : Unsafe HTML tags should not be stripped, etc.
 * noargs : Don't replace triple-brace arguments in the return value
 * isHTML : The returned text is HTML, armour it against wikitext transformation

The ParserFunctions extension is a well-known collection of parser functions.

Naming
When choosing a name without a hash character (number sign, "#"), note that transclusion of a page with a name starting with that function name followed by a colon is no longer possible. In particular, avoid function names equal to a namespace name. In the case that interwiki transclusion is enabled, also avoid function names equal to an interwiki prefix.

Publishing your extensions

 * 1) Give the code and documentation on a page in the Extension namespace of  and put it in  mw:Category:Extensions.
 * 2) Notify the mediawiki-l mailing list.