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 ) );
42 $title = $this->getRandomTitle();
44 if( is_null( $title ) ) {
46 $wgOut->addWikiMsg( strtolower( $this->mName
) . '-nopages', $wgContLang->getNsText( $this->namespace ) );
50 $query = $this->isRedirect() ?
'redirect=no' : '';
51 $wgOut->redirect( $title->getFullUrl( $query ) );
56 * Choose a random title.
57 * @return Title object (or null if nothing to choose from)
59 public function getRandomTitle() {
60 $randstr = wfRandom();
61 $row = $this->selectRandomPageFromDB( $randstr );
63 /* If we picked a value that was higher than any in
64 * the DB, wrap around and select the page with the
65 * lowest value instead! One might think this would
66 * skew the distribution, but in fact it won't cause
67 * any more bias than what the page_random scheme
68 * causes anyway. Trust me, I'm a mathematician. :)
71 $row = $this->selectRandomPageFromDB( "0" );
74 return Title
::makeTitleSafe( $row->page_namespace
, $row->page_title
);
79 private function selectRandomPageFromDB( $randstr ) {
80 global $wgExtraRandompageSQL;
81 $fname = 'RandomPage::selectRandomPageFromDB';
83 $dbr = wfGetDB( DB_SLAVE
);
85 $use_index = $dbr->useIndexClause( 'page_random' );
86 $page = $dbr->tableName( 'page' );
88 $ns = implode( ",", $this->namespaces
);
89 $redirect = $this->isRedirect() ?
1 : 0;
91 $extra = $wgExtraRandompageSQL ?
"AND ($wgExtraRandompageSQL)" : "";
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, $fname );
102 return $dbr->fetchObject( $res );