|
This extension allows for randomly-generated content inside your wiki; e.g. rotating images, random greetings, etc.
Example
The code in this page will only work in MediaWiki 1.5 and above. (Alternate version for 1.4.x)
Algorithm 05:57, 8 September 2005 (UTC)
- <?php
- # Wiki random selection extension
- # Randomly chooses one of the given options to display.
- # Usage: <choose><option>A</option><option>B</option></choose>
- # Optional parameter: <option weight="3"> == 3x weight given
-
- $wgExtensionFunctions[] = "wfChooseExt";
-
- function wfChooseExt()
- {
- global $wgParser;
- $wgParser->setHook( "choose", "renderChosen" );
- }
-
- function renderChosen( $input )
- {
- # Prevent caching
- global $wgParser;
- $wgParser->disableCache();
-
- # Choose an option at random
- $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];
- }
- 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;
- }
- }
-
- # Render chosen text
- global $wgUser, $wgTitle;
- $parserOptions = ParserOptions::newFromUser( $wgUser );
- $localParser = new Parser();
- $input = $localParser->parse($input, $wgTitle, $parserOptions, false);
- return $input->mText;
- }
- ?>
复制代码
|
|