4 * Special page to direct the user to a random page
7 * @author Rob Church <robchur@gmail.com>, Ilmari Karonen
8 * @license GNU General Public Licence 2.0 or later
10 class RandomPage
extends SpecialPage
{
11 private $namespaces; // namespaces to select pages from
13 function __construct( $name = 'Randompage' ){
14 global $wgContentNamespaces;
16 $this->namespaces
= $wgContentNamespaces;
18 parent
::__construct( $name );
21 public function getNamespaces() {
22 return $this->namespaces
;
25 public function setNamespace ( $ns ) {
26 if( !$ns ||
$ns < NS_MAIN
) $ns = NS_MAIN
;
27 $this->namespaces
= array( $ns );
30 // select redirects instead of normal pages?
31 // Overriden by SpecialRandomredirect
32 public function isRedirect(){
36 public function execute( $par ) {
37 global $wgOut, $wgContLang;
40 $this->setNamespace( $wgContLang->getNsIndex( $par ) );
43 $title = $this->getRandomTitle();
45 if( is_null( $title ) ) {
47 $wgOut->addWikiMsg( strtolower( $this->mName
) . '-nopages', $wgContLang->getNsText( $this->namespace ) );
51 $query = $this->isRedirect() ?
'redirect=no' : '';
52 $wgOut->redirect( $title->getFullUrl( $query ) );
57 * Choose a random title.
58 * @return Title object (or null if nothing to choose from)
60 public function getRandomTitle() {
61 $randstr = wfRandom();
62 $row = $this->selectRandomPageFromDB( $randstr );
64 /* If we picked a value that was higher than any in
65 * the DB, wrap around and select the page with the
66 * lowest value instead! One might think this would
67 * skew the distribution, but in fact it won't cause
68 * any more bias than what the page_random scheme
69 * causes anyway. Trust me, I'm a mathematician. :)
72 $row = $this->selectRandomPageFromDB( "0" );
75 return Title
::makeTitleSafe( $row->page_namespace
, $row->page_title
);
80 private function selectRandomPageFromDB( $randstr ) {
81 global $wgExtraRandompageSQL;
82 $dbr = wfGetDB( DB_SLAVE
);
84 $use_index = $dbr->useIndexClause( 'page_random' );
85 $page = $dbr->tableName( 'page' );
87 $ns = implode( ",", $this->namespaces
);
88 $redirect = $this->isRedirect() ?
1 : 0;
90 $extra = $wgExtraRandompageSQL ?
"AND ($wgExtraRandompageSQL)" : "";
91 $extra .= $this->addExtraSQL() ?
"AND (".$this-addExtraSQL().")" : "";
92 $sql = "SELECT page_title, page_namespace
94 WHERE page_namespace IN ( $ns )
95 AND page_is_redirect = $redirect
96 AND page_random >= $randstr
98 ORDER BY page_random";
100 $sql = $dbr->limitResult( $sql, 1, 0 );
101 $res = $dbr->query( $sql, __METHOD__
);
102 return $dbr->fetchObject( $res );
105 // an alternative to $wgExtraRandompageSQL so extensions
106 // can add their own SQL by overriding this function
107 public function addExtraSQL() {