Extension:RandomSelection

From MediaWiki.org

Jump to: navigation, search

             

Manual on MediaWiki Extensions
List of MediaWiki Extensions
Crystal Clear action run.png
RandomSelection

Release status: stable

Implementation  Tag
Description Displays a random option from the given set.
Author(s)  Ross McClure
Last Version  2.1.4 (30th September, 2009)
MediaWiki  1.7+
License No license specified
Download see below
Changelog
Example  Example

check usage (experimental)

The RandomSelection extension allows for randomly-generated content inside your wiki; e.g. rotating images, random greetings, etc.

[edit] Usage

To choose between one or more options, simply place each option inside an <option> tag, like so:

<choose>
<option>This is the first choice.</option>
<option>This is the second choice.</option>
<option>And so on...</option>
</choose>

From each set of <choose> tags, precisely one <option> tag will be selected at random, and its contents shown.

If you'd like some options to be shown more often than others, you can add weight to the option tags, like so:

<choose>

<option weight="2">This option will be shown twice as often as a normal option.</option>

<option>By default, options have a weight of 1.</option>

<option weight="1.5">This option also has a weight of 1.  Fractional portions are ignored.</option>

</choose>

Anything can be placed inside of option tags: links, images, even templates. Note, however, that template arguments will not be expanded due to bugzilla:2257.

[edit] Code

The code in this page will only work in MediaWiki 1.7 and above. (Alternate version for 1.5 and above)


<?php
/**
 * RandomSelection -- randomly displays one of the given options.
 * Usage: <choose><option>A</option><option>B</option></choose>
 * Optional parameter: <option weight="3"> == 3x weight given
 *
 * @file
 * @ingroup Extensions
 * @version 2.1.4
 * @date 30 September 2009
 * @author Ross McClure <http://www.mediawiki.org/wiki/User:Algorithm>
 * @link http://www.mediawiki.org/wiki/Extension:RandomSelection Documentation
 */
 
if( !defined( 'MEDIAWIKI' ) ) {
	die( "This is not a valid entry point to MediaWiki.\n" );
}
 
// Avoid unstubbing $wgParser on setHook() too early on modern (1.12+) MW versions, as per r35980
if( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
	$wgHooks['ParserFirstCallInit'][] = 'wfRandomSelection';
} else {
	$wgExtensionFunctions[] = 'wfRandomSelection';
}
 
$wgExtensionCredits['parserhook'][] = array(
	'name' => 'RandomSelection',
	'version' => '2.1.4',
	'author' => 'Ross McClure',
	'description' => 'Displays a random option from the given set.',
	'url' => 'http://www.mediawiki.org/wiki/Extension:RandomSelection',
);
 
function wfRandomSelection() {
	global $wgParser;
	$wgParser->setHook( 'choose', 'renderChosen' );
	return true;
}
 
function renderChosen( $input, $argv, &$parser ) {
	# Prevent caching
	$parser->disableCache();
 
	# Parse the options and calculate total weight
	$len = preg_match_all( "/<option(?:(?:\\s[^>]*?)?\\sweight=[\"']?([^\\s>]+))?"
		. "(?:\\s[^>]*)?>([\\s\\S]*?)<\\/option>/", $input, $out );
	$r = 0;
	for( $i = 0; $i < $len; $i++ ) {
		if( strlen( $out[1][$i] ) == 0 )
			$out[1][$i] = 1;
		else
			$out[1][$i] = intval( $out[1][$i] );
		$r += $out[1][$i];
	}
 
	# Choose an option at random
	if( $r <= 0 )
		return '';
	$r = mt_rand( 1, $r );
	for( $i = 0; $i < $len; $i++ ) {
		$r -= $out[1][$i];
		if( $r <= 0 ) {
			$input = $out[2][$i];
			break;
		}
	}
 
	# If running new parser, take the easy way out
	if( defined( 'Parser::VERSION' ) && version_compare( Parser::VERSION, '1.6.1', '>' ) ) {
		return $parser->recursiveTagParse( $input );
	}
 
	# Otherwise, create new parser to handle rendering
	$localParser = new Parser();
 
	# Initialize defaults, then copy info from parent parser
	$localParser->clearState();
	$localParser->mTagHooks         = $parser->mTagHooks;
	$localParser->mTemplates        = $parser->mTemplates;
	$localParser->mTemplatePath     = $parser->mTemplatePath;
	$localParser->mFunctionHooks    = $parser->mFunctionHooks;
	$localParser->mFunctionSynonyms = $parser->mFunctionSynonyms;
 
	# Render the chosen option
	$output = $localParser->parse( $input, $parser->mTitle,
					$parser->mOptions, false, false );
	return $output->getText();
}

[edit] Changelog

  • Dec 10 07 -- Updated for compatibility with MW 1.12's new parser model
  • Feb 23 08 -- Minor bugfix
  • May 8 08 -- Bugfix
  • July 08 -- Use ParserFirstCallInit hook if it's available
  • 30 September 2009 -- Doxygen comments added + minor tweaks