2012-10-01

Created page with "{{ExtensionTypes}} right Individual projects will often find it useful to '''extend the built-in wiki mar..."

New page

{{ExtensionTypes}}

[[File:MediaWiki-extensions-icon.svg|125px|alt=MediaWiki extensions|right]]

Individual projects will often find it useful to '''extend the built-in wiki markup''' with additional capabilities, whether simple string processing, or full-blown information retrieval. Tag Extensions allow users to create new custom tags that do just that. For example, one might use a tag extension to introduce a simple <donation /> tag, which injects a donation form into the page. Extensions, along with [[Manual:Parser Functions|Parser Functions]] and [[Manual:Hooks|Hooks]] are the most effective way to change or enhance the functionality of MediaWiki. To see existing extensions built by other MediaWiki users see: [[Extension Matrix]]. You should always check the matrix before you start work on an extension to make sure someone else hasn't done exactly what you are trying to do.

A simple tag extension consists of a [[w:Callback (computer science)|callback]] function, which is [[w:Hooking|hooked]] to the parser so that, when the parser runs, it will find and replace all instances of a specific tag, calling the corresponding [[w:Callback (computer science)|callback]] function to render the actual HTML.

==Example==

This example registers a callback function for the <sample> tag. When a user adds this tag to a page like this:

...input...

, the parser will call the wfSampleRender() function, passing in three arguments:

;$input : Input between the <sample> and </sample> tags, or '''null''' if the tag is "closed", i.e. <sample />

;$args : Tag arguments, which are entered like HTML tag attributes; this is an associative array indexed by attribute name.

;$parser : The parent parser (a Parser object); more advanced extensions use this to obtain the contextual Title, parse wiki text, expand braces, register link relationships and dependencies, etc.

;$frame : The parent frame (a PPFrame object). This is used together with $parser to provide the parser with more complete information on the context in which the extension was called.

==Attributes==

Let's look at another example:

This example dumps the attributes passed to the tag, along with their values. It's quite evident that this allows for flexible specification of new, custom tags. You might, for example, define a tag extension that allows a user to inject a contact form on their user page, using something like <emailform to="User" email="user@foo.com" />.

There is a veritable plethora of tag extensions available for MediaWiki, some of which are [[:Category:Parser extensions|listed on this site]]; others can be found via a quick web search. While a number of these are quite specialised for their use case, there are a great deal of well-loved and well-used extensions providing varying degrees of functionality.

==Conventions==

While an extension can be a single file, it is recommended that, for each extension, a separate subdirectory extension_name of the extensions directory is created, containing three files:

*a small setup file, ''extension_name''.setup.php

*an internationalisation file, ''extension_name''.i18n.php

*a ''extension_name''.body.php file with the bulk of the code.

By convention, the setup file will add an element to the [[Manual:$wgAutoloadClasses|$wgAutoloadClasses]] array, which specifies which files are to be loaded:

$wgAutoloadClasses[''extension_name''] = dirname(__FILE__) . '/''extension_name''.body.php';

For more general instructions, see [[Manual:Developing_extensions]].

==Publishing your extensions==

#Create a new page on this wiki named Extension:
with information on your extension, how to install it, and screenshots of it in use. A convenient template has been created to hold this information called [[:Template:Extension]]. See the template page for more information. You should also add as much detail as possible to the body of the page, and it is wise to check back fairly regularly to respond to user questions on the associated talk page. Also, make sure the page belongs to [[:Category:Extensions]].

#Extensions that create new [[Manual:Hooks|hooks]] within the extension code should register them on [[extension hook registry]].

#Notify the [[mail:mediawiki-l|mediawiki-l]] mailing list.

See also [[Manual:Developing extensions#Publishing your extension|publishing your extension]].

==FAQ==

===Security Concerns===

You'll notice above that the input in the examples above is escaped using [http://uk3.php.net/manual/en/function.htmlspecialchars.php htmlspecialchars()] before being returned. It is vital that all user input is treated in this manner before echoing it back to the clients, to avoid introducing vectors for arbitrary [[w:Code injection|HTML injection]], which can lead to [[w:Cross-site scripting|cross-site scripting]] vulnerabilities.

===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.

===How do I disable caching for pages using my extension?===

Since MediaWiki 1.5, the parser is passed as the third parameter to an extension. This parser can be used to invalidate the cache like this:

====Regenerating the page when another page is edited ====

Maybe you don't want to disable caching entirely, you just want the page to be regenerated whenever another page is edited, similar to the way that template transclusions are handled. This can be done using the parser object that is passed to your hook function. The following method was lifted from [[Manual:CoreParserFunctions.php|CoreParserFunctions.php]] and appears to work for this purpose.

===How do I render wikitext in my extension?===

====Since version 1.16====

{{mW 1.16|and later}}

Parser hook functions are passed a reference to the parser object and a frame object; these should be used to parse wikitext.

Parser::recursiveTagParse() has been around since version 1.8. Its advantages include simplicity (it takes just one argument and returns a string) and the fact that it parses extension tags in $text, so you can nest extension tags.

The second parameter to recursiveTagParse, $frame, is an optional argument introduced in MW 1.16 alpha (r55682).

* If $frame is provided (using the value of $frame passed to your extension), then any template parameters in $text will be expanded. In other words, content such as
{{{1}}}
will be recognized and converted into the appropriate value.

* If $frame is not provided (e.g., $parser->recursiveTagParse( $text )), or if $frame is set to false, then template parameters will not be expanded;
{{{1}}}
will not be altered. Although this unlikely to be the desired behavior, this was the only option available before MW 1.16.

However, one step of parsing that is still skipped for tags, even when using recursiveTagParse, is Parser::preSaveTransform. preSaveTransform is the first step of parsing, responsible for making permanent changes to the about-to-be saved wikitext, such as:

* Converting signatures (
~~~
,
~~~~
,
~~~~~
)

* Expanding link labels, also known as the ''pipe-trick'' (e.g., changing
[[Help:Contents|]]
into
[[Help:Contents|Contents]]
). Without this step, shorthand links such as
[[Help:Contents|]]
are considered to be invalid, and are left in their wikitext form when parsed.

* Expanding
{{subst:}}
templates.

The original call to preSaveTransform intentionally skips such conversions within all extension tags. If you need pre save transform to be done, you should consider using a [[manual:Parser functions|parser function]] instead. All tag extensions can also be called as a parser function using
{{#tag:tagname|attribute_name=value|input}}
which will have pre save transform applied.

====Version 1.8 to version 1.15 ====

{{MW 1.8|up to MW 1.15}}

The only difference before 1.16 is that the $frame argument was not available for Parser::recursiveTagParse().

If the resulting inability to recognize template variables is a problem, see [[#Extensions and Templates|Extensions and Templates]] and [[bugzilla:2257|bug 2257]] for more information and workarounds.

===How can I pass XML-style parameters in my extension tag?===

====Since version 1.5====

Since MediaWiki 1.5, XML-style parameters (tag attributes) are supported. The parameters are passed as the second parameter to the hook function, as an associative array. The value strings have already had HTML character entities decoded for you, so if you emit them back to HTML, don't forget to use htmlspecialchars( $codeToEncode, ENT_QUOTES ), to avoid the risk of HTML injection.

===How can I avoid modification of my extension's HTML output?===

The return value of a tag extension is considered ''almost'' parsed text, which means its not treated as pure html, but still modified slightly. There are two main things that are done to the output of a tag extension (Along with a couple other minor things):

*Replace strip markers. Strip markers are certain items that look like UNIQe62a6957e0dbf6e-item-53--QINU which are inserted at various stages of processing wikitext to act as a marker to re-insert removed content at a later time. This is not something extensions usually need to worry about.

*[http://svn.wikimedia.org/doc/classParser.html#ad463888e40c078ac9bcfcaf1231e39d7 Parser::doBlockLevels] which turns *'s into lists, and turns any line starting with a leading space into a <pre> among other things. This can sometimes be an issue in some extensions.

Tag extensions also support returning an array instead of just a string (Much like parser functions) in order to change how the return value is interpreted. The 0th value of the array must be the html. The "markerType" key can be set to nowiki in order to stop further parsing. Doing something like return array( $html, "markerType" => 'nowiki' ); would ensure that the $html value is not further modified and treated as just plain html.

===How do I get my extension to show up on Special:Version?===

In order for your extension to be displayed on the MediaWiki [[Special:Version]] page, you must assign extension credits within the PHP code.

To do this, add a [[Manual:$wgExtensionCredits|$wgExtensionCredits]] variable as the first executable line of code before the hook line or function definition.

An example extension credit is:

Replace validextensionclass with one of the following (unless your extension falls under multiple classes—then create a credit for ''each'' class):

*'specialpage'—reserved for additions to MediaWiki Special Pages;

*'parserhook'—used if your extension modifies, complements, or replaces the parser functions in MediaWiki;

*'variable'—extension that add multiple functionality to MediaWiki;

*'media'—used if your extension is a media handler of some sort

*'other'—all other extensions.

The myextensionmsg is the name of an interface/i18n message that describes your extension that will need to be defined in your extension's i18n.php file. If you omit this field, the description field will be used instead.

==See also==

*[[Help:Magic words]] - List of special tag/variables like
{{PAGENAME}}
,
{{SERVER}}
, ...

*[[Manual:Extensions]]

*[[Extensions FAQ]]

*[[:Category:Extensions]]

*[[Extension Matrix]]

*[[Manual:$wgExtensionFunctions]]

*[[Project:Extension requests]]

{{Languages|Manual:Tag extensions}}

{{extensions}}

[[Category:Customization techniques|{{PAGENAME}}]]

[[Category:MediaWiki Development]]

[[Category:Parser extensions|*]]

Show more