4 * Special page to direct the user to a random page
6 * @addtogroup SpecialPage
7 * @author Rob Church <robchur@gmail.com>, Ilmari Karonen
8 * @license GNU General Public Licence 2.0 or later
12 * Main execution point
13 * @param $par Namespace to select the page from
15 function wfSpecialRandompage( $par = null ) {
16 global $wgOut, $wgContLang;
18 $rnd = new RandomPage();
21 // Select a random content namespace to use.
22 global $wgContentNamespaces;
23 $n = array_rand( $wgContentNamespaces );
24 $rnd->setNamespace( $wgContentNamespaces[$n] );
27 $rnd->setNamespace( $wgContLang->getNsIndex( $par ) );
30 $rnd->setRedirect( false );
32 $title = $rnd->getRandomTitle();
34 if( is_null( $title ) ) {
35 $wgOut->addWikiText( wfMsg( 'randompage-nopages' ) );
40 $wgOut->redirect( $title->getFullUrl() );
45 * Special page to direct the user to a random page
47 * @addtogroup SpecialPage
50 private $namespace = NS_MAIN
; // namespace to select pages from
51 private $redirect = false; // select redirects instead of normal pages?
53 public function getNamespace ( ) {
54 return $this->namespace;
56 public function setNamespace ( $ns ) {
57 if( $ns < NS_MAIN
) $ns = NS_MAIN
;
58 $this->namespace = $ns;
60 public function getRedirect ( ) {
61 return $this->redirect
;
63 public function setRedirect ( $redirect ) {
64 $this->redirect
= $redirect;
68 * Choose a random title.
69 * @return Title object (or null if nothing to choose from)
71 public function getRandomTitle ( ) {
72 $randstr = wfRandom();
73 $row = $this->selectRandomPageFromDB( $randstr );
75 /* If we picked a value that was higher than any in
76 * the DB, wrap around and select the page with the
77 * lowest value instead! One might think this would
78 * skew the distribution, but in fact it won't cause
79 * any more bias than what the page_random scheme
80 * causes anyway. Trust me, I'm a mathematician. :)
83 $row = $this->selectRandomPageFromDB( "0" );
86 return Title
::makeTitleSafe( $this->namespace, $row->page_title
);
91 private function selectRandomPageFromDB ( $randstr ) {
92 global $wgExtraRandompageSQL;
93 $fname = 'RandomPage::selectRandomPageFromDB';
95 $dbr = wfGetDB( DB_SLAVE
);
97 $use_index = $dbr->useIndexClause( 'page_random' );
98 $page = $dbr->tableName( 'page' );
100 $ns = (int) $this->namespace;
101 $redirect = $this->redirect ?
1 : 0;
103 $extra = $wgExtraRandompageSQL ?
"AND ($wgExtraRandompageSQL)" : "";
104 $sql = "SELECT page_title
105 FROM $page $use_index
106 WHERE page_namespace = $ns
107 AND page_is_redirect = $redirect
108 AND page_random >= $randstr
110 ORDER BY page_random";
112 $sql = $dbr->limitResult( $sql, 1, 0 );
113 $res = $dbr->query( $sql, $fname );
114 return $dbr->fetchObject( $res );