|
Parallel Visions: City of Angels City of Demons ebook and trade paperback available on Amazon (or here). |
![]() |
|||
RandomFunctions (PHP)
Contents
Documentation
See: RandomFunctions Documentation
Install
require_once( "$IP/extensions/RandomFunctions/RandomFunctions.php" );
Dependencies
- Arrays -- mw:Extensions:Arrays -- http://www.mediawiki.org/wiki/Extension:Arrays
- HashTables -- http://www.mediawiki.org/wiki/Extension:HashTables
Useful additions
- Loops -- mediawikiwiki:Extension:Loops
- Variables -- mediawikiwiki:Extension:Variables
Tests
PHP Code
<?php
/*
Defines a subset of parser functions that must clear the cache to be useful.
{{#d2:}} Returns 1 or 2.
{{#d2:N}} Returns the sum of N d2 rolls.
{{#d4:}} Returns a die 4 roll. (i.e. 1 to 4)
{{#d4:N}} Returns the sum of N d4 rolls.
{{#d6:}} Returns a die 6 roll. (i.e. 1 to 6)
{{#d6:N}} Returns the sum of N d6 rolls.
{{#d8:}} Returns a die 8 roll. (i.e. 1 to 8)
{{#d8:N}} Returns the sum of N d8 rolls.
{{#d10:}} Returns a die 10 roll. (i.e. 1 to 10)
{{#d10:N}} Returns the sum of N d10 rolls.
{{#d12:}} Returns a die 12 roll. (i.e. 1 to 12)
{{#d12:N}} Returns the sum of N d12 rolls.
{{#d20:}} Returns a die 20 roll. (i.e. 1 to 20)
{{#d20:N}} Returns the sum of N d20 rolls.
{{#d100:}} Returns a die 100 roll. (i.e. 1 to 100)
{{#d100:N}} Returns the sum of N d100 rolls.
{{#dieRoll:}} Returns a die 6 roll. (i.e. 1 to 6)
{{#dieRoll:X}} Returns a die X roll. (i.e. 1 to X)
{{#dieRoll:X|Y}} Returns the sum of X die Y rolls.
{{#coinFlip:}} Returns 'heads' or 'tails'.
{{#coinFlip:X}} Returns X or 'tails'.
{{#coinFlip:X|Y}} Returns X or Y.
{{#maxRandom:}} Returns the maximum random integer. (i.e. mt_getrandmax() )
{{#rand:}} Returns a random integer between 0 and maxRandom, inclusive.
{{#rand:X}} Returns a random integer between 0 and X, inclusive.
{{#rand:X|Y}} Returns a random integer between X and Y, inclusive. (i.e. mt_rand( $X, $Y ) )
{{#seed:}} Seed the random number generator. (i.e. mt_srand() )
{{#seed:X}} Seed the random number generator with X. (i.e. mt_srand( $X ) )
Author: Fritz Freiheit
Version 1.0 (2012/06/09)
*/
//$wgExtensionFunctions[] = 'wfRandomFunctions';
$wgExtensionCredits['parserhook'][] = array(
'name' => 'RandomFunctions',
'version' => '1.0',
'url' => 'http://www.fritzfreiheit.com/wiki/RandomFunctions',
'author' => 'Fritz Freiheit',
'description' => 'Defines a set random functions available as parser functions.'
);
$wgHooks['LanguageGetMagic'][] = 'wfRandomFunctionsLanguageGetMagic';
$wgHooks['ParserFirstCallInit'][] = 'wfRegisterRandomFunctions';
/**
* @param $parser Parser
* @return bool
*/
function wfRegisterRandomFunctions( $parser )
{
global $wgExtRandomFunctions;
global $wgExtRandomTables;
$wgExtRandomFunctions = new ExtRandomFunctions();
// These functions are dependent on the Arrays() extension
// http://www.mediawiki.org/wiki/Extension:Arrays
$wgExtRandomTables = new ExtRandomTables();
$parser->setHook( 'rTable', array( &$wgExtRandomTables, 'fRandomTable' ) );
$parser->setHook( 'tDisplay', array( &$wgExtRandomTables, 'fTableDisplay' ) );
$parser->setHook( 'tPick', array( &$wgExtRandomTables, 'fTablePick' ) );
$parser->setFunctionHook( 'pickFrom', array( &$wgExtRandomTables, 'fPickFrom' ), SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'd2', array( &$wgExtRandomFunctions, 'fD2' ) );
$parser->setFunctionHook( 'd4', array( &$wgExtRandomFunctions, 'fD4' ) );
$parser->setFunctionHook( 'd6', array( &$wgExtRandomFunctions, 'fD6' ) );
$parser->setFunctionHook( 'd8', array( &$wgExtRandomFunctions, 'fD8' ) );
$parser->setFunctionHook( 'd10', array( &$wgExtRandomFunctions, 'fD10' ) );
$parser->setFunctionHook( 'd12', array( &$wgExtRandomFunctions, 'fD12' ) );
$parser->setFunctionHook( 'd20', array( &$wgExtRandomFunctions, 'fD20' ) );
$parser->setFunctionHook( 'd100', array( &$wgExtRandomFunctions, 'fD100' ) );
$parser->setFunctionHook( 'dieRoll', array( &$wgExtRandomFunctions, 'fDieRoll' ) );
$parser->setFunctionHook( 'flipCoin', array( &$wgExtRandomFunctions, 'fFlipCoin' ) );
$parser->setFunctionHook( 'maxRandom', array( &$wgExtRandomFunctions, 'fMaxRandom' ) );
$parser->setFunctionHook( 'rand', array( &$wgExtRandomFunctions, 'fRandom' ) );
$parser->setFunctionHook( 'seed', array( &$wgExtRandomFunctions, 'fSeed' ) );
$parser->setFunctionHook( 'selectFrom',array( &$wgExtRandomFunctions, 'fSelectFrom' ), SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'selectFrom1',array( &$wgExtRandomFunctions, 'fSelectFrom1' ), SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'selectFromNoDuplicates',array( &$wgExtRandomFunctions, 'fSelectFromNoDuplicates' ), SFH_OBJECT_ARGS );
return true;
}
function wfRandomFunctionsLanguageGetMagic( &$magicWords, $langCode )
{
switch ( $langCode )
{
default:
$magicWords['d2'] = array( 0, 'd2' );
$magicWords['d4'] = array( 0, 'd4' );
$magicWords['d6'] = array( 0, 'd6' );
$magicWords['d8'] = array( 0, 'd8' );
$magicWords['d10'] = array( 0, 'd10' );
$magicWords['d12'] = array( 0, 'd12' );
$magicWords['d20'] = array( 0, 'd20' );
$magicWords['d100'] = array( 0, 'd100' );
$magicWords['dieRoll'] = array( 0, 'dieRoll' );
$magicWords['flipCoin'] = array( 0, 'flipCoin' );
$magicWords['maxRandom'] = array( 0, 'maxRandom' );
$magicWords['pickFrom'] = array( 0, 'pickFrom' );
$magicWords['rand'] = array( 0, 'rand' );
$magicWords['seed'] = array( 0, 'seed' );
$magicWords['selectFrom']= array( 0, 'selectFrom' );
$magicWords['selectFrom1']= array( 0, 'selectFrom1' );
$magicWords['selectFromNoDuplicates']= array( 0, 'selectFromNoDuplicates' );
}
return true;
}
class ExtFritzsFunctions
{
}
class ExtRandomFunctions
{
public static function fD2( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 2 ); }
return self::funcDieRoll( $x, 2 );
}
public static function fD4( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 4 ); }
return self::funcDieRoll( $x, 4 );
}
public static function fD6( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 6 ); }
return self::funcDieRoll( $x, 6 );
}
public static function fD8( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 8 ); }
return self::funcDieRoll( $x, 8 );
}
public static function fD10( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 10 ); }
return self::funcDieRoll( $x, 10 );
}
public static function fD12( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 12 ); }
return self::funcDieRoll( $x, 12 );
}
public static function fD20( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 20 ); }
return self::funcDieRoll( $x, 20 );
}
public static function fD100( &$parser, $x = 0 )
{
$parser->disableCache();
$x = intval($x);
if ( 0 == $x ) { return self::funcDieRoll( 1, 100 ); }
return self::funcDieRoll( $x, 100 );
}
public static function fDieRoll( &$parser, $x = 0, $y = 0 )
{
$parser->disableCache();
return self::funcDieRoll( $x, $y );
}
public static function funcDieRoll( $x = 0, $y = 0 )
{
$x = intval($x);
$y = intval($y);
if ( $x < 0 ) { $x = 0; }
if ( $y < 0 ) { $y = 0; }
if ( 0 < $y )
{
if ( $x < 2 )
{
return self::funcRandom( 1, $y );
}
$total = 0;
$i = 1;
for ( ; $i <= $x; $i++ )
{
$total = $total + self::funcRandom( 1, $y );
}
return $total;
}
if ( $x < 1 ) { $x = 6; }
return self::funcRandom( 1, $x );
}
public static function fFlipCoin( &$parser, $x = 'heads', $y = 'tails' )
{
$parser->disableCache();
$d2 = self::funcDieRoll( 1, 2 );
if ( 1 == $d2 ) { return $x; }
return $y;
}
public static function fMaxRandom()
{
// http://www.php.net/manual/en/function.mt-getrandmax.php
return mt_getrandmax();
}
public static function fRandom( &$parser, $x = 0, $y = 0 )
{
$parser->disableCache();
return self::funcRandom( $x, $y );
}
public static function funcRandom( $x = 0, $y = 0 )
{
// http://php.net/manual/en/function.mt-rand.php
$x = intval($x);
$y = intval($y);
if ( $x < 0 ) { $x = 0; }
if ( $y < 0 ) { $y = 0; }
if ( 0 == $y )
{
if ( 0 == $x )
{
return mt_rand();
}
return mt_rand( 0, $x );
}
return mt_rand( $x, $y );
}
public static function fSeed( $x = 0 )
{
// http://www.php.net/manual/en/function.mt-srand.php
$x = intval($x);
if ( 0 == $x )
{
mt_srand();
}
else
{
mt_srand( $x );
}
return true;
}
/**
* arg[0] is count of elements to return
* arg[1] to arg[n] is the list of elements
* Algorithm:
* Concatenate randomly selected elements from list from 1 to count, max is 1000.
*/
public static function fSelectFrom( $parser, $frame, $args )
{
$count = isset($args[0]) ? intval(trim( $frame->expand( $args[0] ) ) ) : 1;
$entries = count($args);
$result = '';
if ( $entries <= 0 )
{
return '';
}
else if ( $entries == 1 )
{
return trim( $frame->expand( $args[0] ) );
}
else if ( $count > 1000 )
{
$count = 1000;
}
else if ( $count <= 0 )
{
$count = 1;
}
$result = '';
$entries = $entries - 1;
for ( $i = 0; $i < $count; $i++ )
{
$index = mt_rand( 1, $entries );
$result .= ltrim( $frame->expand( $args[$index] ) );
}
$parser->disableCache();
return rtrim( $result );
}
/**
* arg[0] is count of elements to return
* arg[1] to arg[n] is the list of elements
* Algorithm:
* Concatenate randomly selected elements from list from 1 to count, max is 1000.
*/
public static function fSelectFrom1( $parser, $frame, $args )
{
$count = 1;
$entries = count($args);
$result = '';
if ( $entries <= 0 )
{
return '';
}
else if ( $entries == 1 )
{
return trim( $frame->expand( $args[0] ) );
}
$entries = $entries - 1;
$index = mt_rand( 0, $entries );
$result = ltrim( $frame->expand( $args[$index] ) );
$parser->disableCache();
return rtrim( $result );
}
/**
* arg[0] is count of elements to return
* arg[1] to arg[n] is the list of elements
* Algorithm:
* Concatenate elements from randomized list of elements from 1 to count.
*/
public static function fSelectFromNoDuplicates( $parser, $frame, $args )
{
$count = isset($args[0]) ? intval(trim( $frame->expand( $args[0] ) ) ) : 1;
$entries = count($args);
$result = '';
if ( $entries <= 0 )
{
return '';
}
else if ( $entries == 1 )
{
return trim( $frame->expand( $args[0] ) );
}
else if ( $count > ($entries-1) )
{
$count = $entries-1;
}
else if ( $count <= 0 )
{
$count = 1;
}
unset($args[0]);
$keys = array_rand( $args, $count );
if ( is_array( $keys ) )
{
foreach ( $keys as $key )
{
$result .= ltrim( $frame->expand( $args[$key] ) );
}
}
else
{
$result = ltrim( $frame->expand( $args[$keys] ) );
}
$parser->disableCache();
return rtrim( $result );
}
}
class ExtRandomTables
{
// http://www.mediawiki.org/wiki/Manual:Parser_functions
// http://www.mediawiki.org/wiki/Manual:Tag_extensions
// http://php.net/manual/en/language.types.array.php
// http://php.net/manual/en/function.preg-match.php
/**
* arg[0] is the table name
* arg[1] to arg[n] is the list of elements
* Algorithm:
*
*/
public static function fPickFrom( $parser, $frame, $args )
{
$name = isset($args[0]) ? trim( $frame->expand( $args[0] ) ) : '';
$pick = '';
//$pick .= 'pick from ';
if ( '' == $name )
{
$pick .= 'PICK FAILED-NO TABLE NAME';
}
else
{
$table = self::getArrayExtensionArray( $parser, $name );
if ( null == $table )
{
$pick .= '[' . $name . ']';
}
else
{
//$pick .= ' "' . $name . '" is "';
$pick .= self::funcTablePick( $name, $table );
//$pick .= '"';
}
}
$pick = $parser->recursiveTagParse( $pick, $frame );
$parser->disableCache();
return $pick;
}
public static function fTableDisplay( $input, $args, $parser, $frame )
{
$name = self::funcResolveName( $args, $parser, $frame );
$table = self::getArrayExtensionArray( $parser, $name );
$input .= '==' . $name . '==' . "\n";
$input .= self::funcTableDisplay( $name, $table );
$input = $parser->recursiveTagParse( $input, $frame );
return $input;
}
public static function funcTableDisplay( $name, $table, $display = '' )
{
if ( null == $table )
{
return '[' . $name . ']' . ' not found.';
}
$count = count( $table );
$itemCount = 0;
$repeatCount = 0;
$display .= '{|' . "\n";
for ( $i = 0; $i < $count; $i++ )
{
$item = $table[$i];
$nextIndex = $i + 1;
$itemCount += 1;
if ( $nextIndex < $count && $table[$i] == $table[$nextIndex] )
{
$repeatCount += 1;
}
else
{
$display .= '|-' . "\n";
$range = '';
if ( 0 == $repeatCount )
{
$range = $itemCount;
}
else
{
$start = $itemCount - $repeatCount;
$range .= $start . ' - ' . $itemCount;
}
$displayItem = '';
$displayItem .= '<nowiki>';
$displayItem .= $item;
$displayItem .= '</nowiki>';
$display .= '|' . $range . '||' . $displayItem . "\n";
$repeatCount = 0;
}
}
$display .= '|}' . "\n";
return $display;
}
public static function funcSingleLineTableDisplay( $name, $table, $display = '' )
{
$count = count( $table );
$count = count( $target );
for ( $i = 0; $i < $count; $i++ )
{
$displayItem = '';
$displayItem .= '<nowiki>';
$displayItem .= $target[$i];
$displayItem .= '</nowiki>';
$display .= '*' . ' ' . $displayItem . "\n";
}
return $display;
}
public static function funcResolveName( $args, $parser, $frame )
{
$name = trim( $frame->expand( $args['name'] ) );
$prefix = trim( $parser->recursiveTagParse( '{{{prefix|}}}', $frame ) );
if ( '' != $prefix )
{
$name = $prefix . '.' . $name;
}
return $name;
}
public static function fTablePick( $input, $args, $parser, $frame )
{
$returnEmpty = array_key_exists( 'returnEmpty', $args ) ? trim( $args[ 'returnEmpty' ] ) : null ;
if ( null != $returnEmpty )
{
$pattern = '/(\d+)\s*\\/\s*(\d+)/';
$matchCount = preg_match( $pattern, $returnEmpty, $matches );
$x = intval( $matches[1] );
$y = intval( $matches[2] );
$r = ExtRandomFunctions::funcRandom( 1, $y );
if ( $r <= $x )
{
return '';
}
}
$name = self::funcResolveName( $args, $parser, $frame );
$table = self::getArrayExtensionArray( $parser, $name );
$input = self::funcTablePick( $name, $table );
$input = $parser->recursiveTagParse( $input, $frame );
$parser->disableCache();
return $input;
}
public static function funcTablePick( $name, $table )
{
$count = count( $table );
$index = ExtRandomFunctions::funcRandom( 0, ($count - 1) );
$result = $table[$index];
return $result;
}
public static function funcInjectPrefix( $item, $prefix )
{
if ( '' === $prefix || null === $prefix )
{
return $item;
}
$pattern = '/\\{\\{#pickFrom:([^\\.{\\}\\|]+)([^\\.\\{\\}]*)\\}\\}/';
$replace = '{{#pickFrom:' . $prefix . '.${1}${2}}}';
$item = preg_replace( $pattern, $replace, $item );
return $item;
}
public static function fRandomTable( $input, $args, $parser, $frame )
{
$name = self::funcResolveName( $args, $parser, $frame );
$prefix = trim( $parser->recursiveTagParse( '{{{prefix|}}}', $frame ) );
$mode = array_key_exists( 'mode', $args ) ? $args['mode'] : 'default';
$input = trim( $input );
$lines = explode( "\n", $input );
$count = count($lines);
$target = array();
if ( 'singleLine' == $mode )
{
foreach ( $lines as $line )
{
$value = self::funcInjectPrefix( trim( $line ), $prefix );
$target[] = $value;
}
}
else
{
$pattern = '/^\s*;\s*(\d+)\s*;(.*)$/';
$itemCount = 0;
$lastIndex = 0;
$glue = array_key_exists( 'glue', $args ) ? $args['glue'] : "\n";
for ( $i = 0; $i < $count; $i++ )
{
$line = $lines[$i];
$matchCount = preg_match( $pattern, $line, $matches );
if ( 0 == $matchCount )
{
for ( $j = $lastIndex; $j < $itemCount; $j++ )
{
$value = self::funcInjectPrefix( trim( $line ), $prefix );
$target[$j] = $target[$j] . $glue . $value;
}
}
else
{
$weight = intval( $matches[1] );
if ( 0 < $weight )
{
$value = self::funcInjectPrefix( trim( $matches[2] ), $prefix );
$lastIndex = $itemCount;
for ( $j = 0; $j < $weight; $j++ )
{
$target[] = $value; // append to array
$itemCount += 1;
}
}
}
}
// the goal here is collect lines of the form:
//;1;This line appears once in the target array
//;2;This line appears twice in the target array
//;;This line appears once in the target array
//;1;This multi-line element appears once in the target array
//Part of the prior element, seperated by a "\n"
//;1;Another single line
}
// store the array
self::setArrayExtensionArray( $parser, $name, $target );
$displayTable = array_key_exists( 'displayTable', $args ) ? true : false;
$display = '';
if ( $displayTable )
{
$display .= '==' . $name . '==' . "\n";
$display .= self::funcSingleLineTableDisplay( $name, $target );
}
$input = $parser->recursiveTagParse( $display, $frame );
$parser->disableCache();
return $input;
//$prefix = trim( $parser->recursiveTagParse( '{{{prefix|}}}', $frame ) );
//return '[' . $prefix . '.' . $name . ']';
}
/**
* Gets an array from ArrayExtension, returns null if the extension wasn't found or
* the array doesn't exist.
* Handles different versions of ArrayExtension.
*
* @since 1.0
*
* @return array|null
*/
protected static function getArrayExtensionArray( $parser, $arrayId )
{
// null will be returnded if no array found
$array = null;
//if( class_exists( 'ExtArrays' ) )
//{
// ArrayExtension 2.0+
$array = ExtArrays::get( $parser )->getArray( $arrayId );
//}
//elseif( isset( $wgArrayExtension ) && isset( $wgArrayExtension->mArrayExtension ) )
//{
// // ArrayExtension before 2.0
// if( array_key_exists( $arrayId, $wgArrayExtension->mArrayExtension ) )
// {
// // array exist
// $array = $wgArrayExtension->mArrayExtension[ $arrayId ];
// }
//}
return $array;
}
/**
* Sends an array to ArrayExtension and stores it. Takes care of different ArrayExtension versions.
* The array should be sanitized in case ArrayExtension before 2.0 is being used.
*
* @since 1.0
*
* @return boolean whether array was sent to ArrayExtension successful
*/
protected static function setArrayExtensionArray( $parser, $arrayId, $array = array() )
{
//if( class_exists( 'ExtArrays' ) )
//{
// ArrayExtension 2.0+
ExtArrays::get( $parser )->createArray( $arrayId, $array );
return true;
//}
//elseif( isset( $wgArrayExtension ) && isset( $wgArrayExtension->mArrayExtension ) )
//{
// // ArrayExtension before 2.0
// if( array_key_exists( $arrayId, $wgArrayExtension->mArrayExtension ) )
// {
// // array exist
// $array = $wgArrayExtension->mArrayExtension[ $arrayId ];
// }
// else
// {
// $array = array();
// }
//}
return false;
}
}
>
[[File:|right|thumbnail|50px]]
Categories[edit]
