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 * Special page to direct the user to a random page
14 * @addtogroup SpecialPage
16 class RandomPage
extends SpecialPage
{
17 private $namespace = NS_MAIN
; // namespace to select pages from
18 private $redirect = false; // select redirects instead of normal pages?
20 public function getNamespace ( ) {
21 return $this->namespace;
24 function getTitle($par=null) {
25 return SpecialPage
::getTitleFor("Randompage");
28 function getLocalName() {
29 return SpecialPage
::getLocalNameFor("Randompage");
32 public function setHeaders() {}
33 public function outputHeader() {}
35 public function setNamespace ( $ns ) {
36 if( $ns < NS_MAIN
) $ns = NS_MAIN
;
37 $this->namespace = $ns;
39 public function getRedirect ( ) {
40 return $this->redirect
;
42 public function setRedirect ( $redirect ) {
43 $this->redirect
= $redirect;
46 public function execute( $par = null ) {
47 global $wgOut, $wgContLang;
50 $this->setNamespace( $wgContLang->getNsIndex( $par ) );
51 $this->setRedirect( false );
53 $title = $this->getRandomTitle();
55 if( is_null( $title ) ) {
56 $wgOut->addWikiText( wfMsg( 'randompage-nopages' ) );
60 $wgOut->redirect( $title->getFullUrl() );
65 * Choose a random title.
66 * @return Title object (or null if nothing to choose from)
68 public function getRandomTitle ( ) {
69 $randstr = wfRandom();
70 $row = $this->selectRandomPageFromDB( $randstr );
72 /* If we picked a value that was higher than any in
73 * the DB, wrap around and select the page with the
74 * lowest value instead! One might think this would
75 * skew the distribution, but in fact it won't cause
76 * any more bias than what the page_random scheme
77 * causes anyway. Trust me, I'm a mathematician. :)
80 $row = $this->selectRandomPageFromDB( "0" );
83 return Title
::makeTitleSafe( $this->namespace, $row->page_title
);
88 private function selectRandomPageFromDB ( $randstr ) {
89 global $wgExtraRandompageSQL;
90 $fname = 'RandomPage::selectRandomPageFromDB';
92 $dbr = wfGetDB( DB_SLAVE
);
94 $use_index = $dbr->useIndexClause( 'page_random' );
95 $page = $dbr->tableName( 'page' );
97 $ns = (int) $this->namespace;
98 $redirect = $this->redirect ?
1 : 0;
100 $extra = $wgExtraRandompageSQL ?
"AND ($wgExtraRandompageSQL)" : "";
101 $sql = "SELECT page_title
102 FROM $page $use_index
103 WHERE page_namespace = $ns
104 AND page_is_redirect = $redirect
105 AND page_random >= $randstr
107 ORDER BY page_random";
109 $sql = $dbr->limitResult( $sql, 1, 0 );
110 $res = $dbr->query( $sql, $fname );
111 return $dbr->fetchObject( $res );