Extension:RandomText

From MediaWiki.org

Jump to: navigation, search
Manual on MediaWiki Extensions
List of MediaWiki Extensions
RandomText

Release status: beta

Implementation Tag
Description Inserting random text in a page
Author(s) Martin Rohrbach
Last Version 0.2 (2007-09-16)
MediaWiki 1.6.5 and higher
License No license specified
Download see below

Random Text is an extension written for MediaWiki that allows to display a random text from a list (such as a list of quotes) on a page.

Note: I know this is a fairly trivial extension but I couldn't find a hint on solving this anywhere else so I deemed it important to document it here ;)

[edit] Installation

The extension is short and sweet, copy the following to extensions/random.php:

<?php
$wgExtensionFunctions[] = "wfRandomExtension";
 
function wfRandomExtension() {
    global $wgParser;
    $wgParser->setHook( "random", "renderRandom" );
}
 
function renderRandom( $input, $argv, $parser ) {
    global $wgParser;
    $wgParser->disableCache();
 
    $values = explode("@@@", $input);
    return $parser->recursiveTagParse($values[rand(0, count($values) - 1)]);
}
 
/**
  * Add extension information to Special:Version
 */
$wgExtensionCredits['other'][] = array(
        'name' => 'RandomText',
        'author' => 'Martin Rohrbach',
        'description' => 'allows to display a random text from a list',
        'url' => 'http://www.mediawiki.org/wiki/Extension:RandomText'
        );

Now we have to load the extension in LocalSettings.php as follows:

require_once("extensions/random.php");

[edit] Usage

Basic usage is very easy, simply insert the lines you want to be randomized seperated by '@@@' and enclosed in <random>...</random> tags, for example:

<random>
Text 1
@@@
Text 2
@@@
Text 3
</random>

At this stage it gets a bit tricky though due to the automatic caching of pages in MediaWiki. If you save a page with the source code above, the page will be created and placed in the cache with one of the lines in it. This will only change once the source code is changed again. To get around this, I invalidate every page that is older than one day (= 86400 seconds), this can be achieved by placing the following in LocalSettings.php:

require("includes/GlobalFunctions.php");
$wgCacheEpoch = wfTimestamp( TS_MW, time() - 86400 ); # 60*60*24 = 1 day

Of course it is possible to set this value to a lower number but keep in mind that this will have an impact on server load as pages are regenerated more often rather than pulled from cache.

To help testing the extension without modifying the Cache Epoch, a refresh of a cached page can be forced by appending &action=purge to the URL.

[edit] Development

This extension was written by Martin Rohrbach (Martin dot Rohrbach at gmail dot com). Thanks to Hans Kramer for the suggestion to use recursiveTagParse().

[edit] Demo

[edit] Alternatives

Personal tools