MediaWiki code snippets

From Organic Design wiki
Revision as of 13:53, 16 June 2013 by Nad (talk | contribs) (Get a list of articles using a template: simplify with foreach)

Contents

Getting in to MediaWiki coding

Here's a useful checklist of things to have set up before starting with MediaWiki development; see also MW:How to debug and MW:Developer hub.

  • Full browser and shell access to a running instance of every major version you're likely to work with
  • Local access to the source code for all those versions
  • Use wfDebugDieBacktrace() to stop code and report the call stack (see better way below)
  • Use debug=1 in the query-string when making requests to MediaWiki. This will prevent any caching or code minification
  • A good text editor with regular expression support file search capability (we use Geany which runs on most platforms)
  • Tools or code for being able to stop the php code and output the necessary items in the scope
  • Tools for debugging the JS and CSS environment (eg. firebug)
  • Bookmarks for all the documentation you've found useful
  • Bookmarks to code snippets and examples (within your own wiki, http://mediawiki.org, other sites and in the mediawiki code)
  • Your own repository of snippets for achieving common objectives in the mediawiki runtime environment

General PHP coding tips

Remember to set full reporting of errors and exceptions with the following addition to LocalSettings.php

{{{1}}}


A simple way to exit and output the call stack at a particular point in any PHP code is to use this:

{{{1}}}

Articles

Get article content

{{{1}}}

Edit or create an article

Editing or creating an article are both achieved using the Article::doEdit method which takes three parameters (the third is optional). The first two are the text content and edit summary. The third optional parameter is for flags which adjust the operation. The available flags and their meaning are listed below followed by example usage.

  • EDIT_NEW: Article is known or assumed to be non-existent, create a new one
  • EDIT_UPDATE: Article is known or assumed to be pre-existing, update it
  • EDIT_MINOR: Mark this edit minor, if the user is allowed to do so
  • EDIT_SUPPRESS_RC: Do not log the change in recentchanges
  • EDIT_FORCE_BOT: Mark the edit a "bot" edit regardless of user rights
  • EDIT_DEFER_UPDATES: Defer some of the updates until the end of index.php
  • EDIT_AUTOSUMMARY: Fill in blank summaries with generated text where possible
EDIT_MINOR);

</php>

  • Note: $wgUser must be set before calling this function.

Image URLs

Given the name of an image page, obtain the full URL of the image.

{{{1}}}

Image links

Sometimes you might want to prevent images from linking to the image page. This extension function removes the link.

i', '$1', $text );

return true; } </php>

Adding stub code to newly created articles

This will add {{stub}} to the beginning of article content when it is first created. It can then be removed on a subsequent edit if desired.

{{{1}}}

Security

Only allow articles in a specific category to be editable

Probably the most common security-related LocalSettings hack is to allow pages in locked down wikis to be publicly viewable if they're in a particular category. This following example adds articles in Category:Public to the $wgWhitelistRead array.

{{{1}}}

Add group information in body element classes

From MediaWiki 1.17 onwards, the OutputPageBodyAttributes hook can be used to modify the classes and other attributes of the body tag. In the following example the hook is being used to add classes to the body tag depending on whether the user is anonymous, logged-in or a sysop.

{{{1}}}

Prevent users from editing other users pages

Here's an example which was created in response to a support-desk question. It prevents users from editing other users user-pages:

{{{1}}}

Restrict namespaces from anonymous users

Here is a similar example which restricts all namespaces except MAIN from anonymous users:

{{{1}}}

Redirect sysops to HTTPS

The following snippet causes all requests to be redirected to HTTPS if the user is a sysop. It also bounces users to non-HTTPS if not a sysop which can be useful if you don't want HTTPS links showing up in search engines for example if you have a self-signed certificate (it doesn't do this if the user is on the login page though since that confuses our bots that use HTTPS connections):

Check whether or not a request is local

The following code checks if a request is local, and works regardless of the IP address or whether it's IPv4 or IPv6.

<php>

function isLocal() { return preg_match_all( "

Only allow raw HTML in a specific sysop-editable namespace

First set up that namespace in LocalSettings and protect it so that only sysops can edit it, for example:

{{{1}}}


Then the nest thing is to only allow Raw HTML to work in that namespace. It's turned on by default, and then disabled if the current title is not in the NS_HTML namespace:

{{{1}}}

Returning content to the client

Raw wikitext content

This function returns the raw content specified in $text, it can be called any time from extension-setup or after. If the $save parameter is supplied it will bring up a download dialog with the default name set to $save, otherwise it will download and open unprompted. If $expand is set to true, then any templates, parser-functions or variables in the content will be expanded.


{{{1}}}

Return an HTTP error page

{{{1}}}

Domain-based default redirect

If no page title is specified, redirect to a default depending on the domain name in the requested URL. In this example requests to abc.org or any of it's subdomains with no title specified will redirect to the Welcome to ABC article, and any requests to the exact domain of www.xyz.org without a title end up at the XYZ Home article. Titleless requests to any other domain which resolves to this example wiki will be unaffected and left to the rest of the configuration to deal with. This code should be executed early in the LocalSettings before any extensions are included, but after $wgServer is defined.

Add a meta tags to the page

{{{1}}}

Using the parser

Parse wikitext

{{{1}}}

Expand templates only

{{{1}}}

Replace triple-brace arguments in wikitext content

<php>

$parser->replaceVariables($wikitext, $args, true); </php>

If $wikitext is set to "hello {{{you}}} this is {{{me}}}", then the "you" and "me" keys of the $args array will replace the corresponding triple-brace arguments in the wikitext content. This is a useful method to know because there are actually a number of difficulties involved in implementing it since it must account for both named and ordered parameters and default values (which can also contain brace-expressions).

Using named parameters from a parser-function callback

You can use named parameters in your parser functions, eg {{#drops:for=Rikkukin the Defender|zone=The Ascent|h=3}}, but you will need to manually split the args into key/value pairs in your callback function, such as in the following example code:

{{{1}}}

This snippet will create a hash from the arguments passed to your callback function (ignoring any which are objects such as the first one which is $parser). The resulting hash will contain numeric keys for all the normal non-named parameters in your parser-function, and non-numeric keys matching all the name=value parameters.

Return codes for parser functions

Typical example.

{{{1}}}

See also: http://www.organicdesign.co.nz/Extension:Example

Protecting raw HTML output from modification by MediaWiki

See: How can I avoid modification of my extension's HTML output on mediawiki.org. Thanks to Duesentrieb for digging out this info.

Post processing to remove unwanted breaks and entities from output

\s*<br\s*/>\s*

JavaScript

Here's some JavaScript snippets that can be added to MediaWiki:Common.js

Make sortable table states persistent with cookies

Note that this function requires getCookie and setCookie which are currently in our navbar.js. They're just the standard cookie getting and setting functions recommended by W3C.

{{{1}}}

MediaWiki Environment

Article title

This should be called at an appropriate time such as from the OutputPageBeforeHTML hook.

<php>

$wgOut->setPageTitle( 'foo' ); </php>

Article queries

Info.svg See MW:Manual:Database access for additional information about database access in MediaWiki.


List article titles from a category

{{{1}}}

Adjust the $list addition to your own needs. This example creates a title object for each and then calls the getPrefixedText method which returns the title as a string including namespace.

List categories an article belongs to

{{{1}}}

Check if a title is in a category

{{{1}}}

Get a list of articles in a namespace (number)

{{{1}}}

Get a list of articles using a template

{{{1}}}

Remove category pages for empty categories

{{{1}}}

Article queries using DPL

This DPL query example provides a standard list of page links in wikitext bullet list format.

{{#dpl:category=Foo|format=,*[[%PAGE%]],\n,}}

Misc

examineBraces

This function returns an array of the brace structure found in the passed wikitext parameter. This has also been implemented in Perl, see the wikiExamineBraces function in wiki.pl.

{{{1}}}

' ) {

$brace =& $braces[$depths[$depth-1]]; $brace[LENGTH] = $match[0][1] - $brace[OFFSET] + 2; $brace[DEPTH] = $depth--; } else { $depths[$depth++] = count( $braces ); $braces[] = array( NAME => $match[1][0], OFFSET => $match[0][1] ); } } return $braces; } </php>}}


The following input,

foo{{#bar:baz|biz{{foo|shmoo}}}}{{moo}}baz


Gives the following array:

Array(
    [0] => Array(
        [NAME]   => #bar
        [OFFSET] => 3
        [LENGTH] => 29
        [DEPTH]  => 1
        )

    [1] => Array(
        [NAME]   => foo
        [OFFSET] => 17
        [LENGTH] => 13
        [DEPTH]  => 2
        )

    [2] => Array(
        [NAME]   => moo
        [OFFSET] => 32
        [LENGTH] => 7
        [DEPTH]  => 1
        )
    )

The array output is designed to integrate with the substr_replace function arguments subject, replace, offset, length. The index 0, 1, 2 order referes to the order functions are found (from left to right).

Google Analytics

{{{1}}}

Force all headings to use outline numbering

There is a user-preference to make all headings use outline numbering, but no way to make that a default for all users. Here's a few lines of code which can be added to your LocalSettings.php file which do that.

{{{1}}}

Create a sysop account from LocalSettings.php

If you don't have admin access to a wiki, but you do have access to the LocalSettings.php file you can create a sysop account by adding the following snippet. Note that this is only temporary and after the snippet is removed the user will no longer have admin access, so to make it permanent, go to Special:UserRights and change the group membership for your user (you may have to set "bot" or something for this since both "sysop" and "beauracrat" will be checked). You can then remove the snippet from LocalSettings.php (and then remove yourself from the "bot" group if you had to add that).

{{{1}}}

Manipulating the search index for an article

The output of parser-functions are not included in the search indexing, so here's a snippet to add custom phrases to the index when an article is saved.

{{{1}}}

Integrating with the Skin

Adding a new action tab

The following code adds a new action tab with a corresponding link. To process the new action, add a processing function to the UnknownAction hook.

{{{1}}}


The Vector skin (optional on 1.16, default on 1.17 onwards) uses a new hook, SkinTemplateNavigation. You can cover both Vector and earlier skins like Monobook or Modern by including code for both hooks. The example below uses the MediaWiki namespace to name the relevant elements of the array. You can put this code in LocalSettings after the inclusion of extensions.

{{{1}}}

Wikitext in Sidebar

By default the MediaWiki:Sidebar article content is not normal wikitext. This snippet fixes that and also ensures that the content can fall back to an i18n message if the article is not present - the normal behaviour for articles in the MediaWiki namespace. The simplest way is to replace a section such as toolbox or navlinks in the skins/MonoBook.php file with the following:

{{{1}}}


The procedure is the same with Vector-based skins, the change is you now place the code inside divs of id portal and then id body, as per the other examples in skins/Vector.php. It should replace the following code and/or the toolbox:

<php>

<?php $this->renderPortals( $this->data['sidebar'] ); ?> </php>


For MediaWiki 1.18 and above

It often not desirable to modify the codebase, so a preferable method is to attach a function to an appropriate hook that does something similar to the above example. As of MediaWiki-1.18, I've found the best way is to attach a function to the BeforePageDisplay hook by adding the following snippet to your LocalSettings.php file:

{{{1}}}


This creates a CSS-addressable div element containing the parsed content from the MediaWiki:Sidebar article. You can then use some JavaScript added to your MediaWiki:Common.js to move the element into a more appropriate location in the page DOM. For example the following JavaScript snippet inserts the rendered wikitext below the site logo.

{{{1}}}

Development server identification

The idea is to have a picture or text that allows a developer to quickly see that they are on the development instance and not the production instance of MediaWiki. By adding to the content of $wgSiteNotice in a conditional every article will have the change for that domain map.

{{{1}}}

This approach was based on W:User:East718/include, and the image source is Image:Gnome-devel.svg

Importing and Exporting articles

The following snippet imports articles from the XML export file named in $file into the main namespace. The $resultCount variable holds the number of articles imported on success.

{{{1}}}


This one exports the current revision of all articles whose names are contained in the $pages array to the file named in $file.

{{{1}}}


Editing Tools

Display WYSIWYG (Rich Text) Editing Toolbar by Default

Mediawiki 1.16

In MediaWiki 1.16, you need to install the UsabilityInitiative Extension, load custom JavaScript and add a jQuery snippet to enable the advanced editing functionality. You can manually load jQuery (if it is not already loaded elsewhere) and a JavaScript file in the skin to accomplish this:

<php>

$out->addScriptFile($wgStylePath .'/path-to-js/jquery.js'); $out->addScriptFile($wgStylePath .'/path-to-js/onload.js'); </php>


Then just create onload.js, paste in this code and save it:

<js>

$(document).ready(function() { if($('.wikiEditor-ui-toolbar')) { $('.wikiEditor-ui-toolbar .sections .section-advanced').css('display','block'); } $( '.ns-talk .lqt-j-togglepage' ).css( 'display', 'block' ); }); </js>


MediaWiki 1.18

It is recommended that MediaWiki 1.18 or above be used - in MediaWiki 1.18 the process is simpler and you need no JavaScript. The WikiEditor extension comes with MediaWiki, you just need to enable it in LocalSettings:

<php>

require_once( "$IP/extensions/WikiEditor/WikiEditor.php" ); </php>


You can also make the WYSIWYG wiki editor global for all users (so they don't need to set it in Preferences) by adding to LocalSettings:

{{{1}}}


Finally, you can enable the additional Advanced toolbar by default. In LocalSettings, add:

{{{1}}}


Then create the file advanced.ui.css, add the following code and save it to the path you have specified above:

<css>

.wikiEditor-ui-toolbar .sections { display: block; overflow-x: hidden; overflow-y: hidden; height: 33px; }

.wikiEditor-ui-toolbar .sections .section { display: block; } </css>


This overrides the CSS settings in load.php, which has the Advanced toolbar hidden by default, even when the WYSIWYG is installed.

JavaScript and AJAX

See also