API: Compatibility fix for 5.0.x. Define array_intersect_key if not already defined...
[mediawiki.git] / includes / SpecialRandompage.php
blob427342745e7d9f9f3be163ce794144006e41ee81
1 <?php
3 /**
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
9 */
11 /**
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();
19 $rnd->setNamespace( $wgContLang->getNsIndex( $par ) );
20 $rnd->setRedirect( false );
22 $title = $rnd->getRandomTitle();
24 if( is_null( $title ) ) {
25 $wgOut->addWikiText( wfMsg( 'randompage-nopages' ) );
26 return;
29 $wgOut->reportTime();
30 $wgOut->redirect( $title->getFullUrl() );
34 /**
35 * Special page to direct the user to a random page
37 * @addtogroup SpecialPage
39 class RandomPage {
40 private $namespace = NS_MAIN; // namespace to select pages from
41 private $redirect = false; // select redirects instead of normal pages?
43 public function getNamespace ( ) {
44 return $this->namespace;
46 public function setNamespace ( $ns ) {
47 if( $ns < NS_MAIN ) $ns = NS_MAIN;
48 $this->namespace = $ns;
50 public function getRedirect ( ) {
51 return $this->redirect;
53 public function setRedirect ( $redirect ) {
54 $this->redirect = $redirect;
57 /**
58 * Choose a random title.
59 * @return Title object (or null if nothing to choose from)
61 public function getRandomTitle ( ) {
62 $randstr = wfRandom();
63 $row = $this->selectRandomPageFromDB( $randstr );
65 /* If we picked a value that was higher than any in
66 * the DB, wrap around and select the page with the
67 * lowest value instead! One might think this would
68 * skew the distribution, but in fact it won't cause
69 * any more bias than what the page_random scheme
70 * causes anyway. Trust me, I'm a mathematician. :)
72 if( !$row )
73 $row = $this->selectRandomPageFromDB( "0" );
75 if( $row )
76 return Title::makeTitleSafe( $this->namespace, $row->page_title );
77 else
78 return null;
81 private function selectRandomPageFromDB ( $randstr ) {
82 global $wgExtraRandompageSQL;
83 $fname = 'RandomPage::selectRandomPageFromDB';
85 $dbr = wfGetDB( DB_SLAVE );
87 $use_index = $dbr->useIndexClause( 'page_random' );
88 $page = $dbr->tableName( 'page' );
90 $ns = (int) $this->namespace;
91 $redirect = $this->redirect ? 1 : 0;
93 $extra = $wgExtraRandompageSQL ? "AND ($wgExtraRandompageSQL)" : "";
94 $sql = "SELECT page_title
95 FROM $page $use_index
96 WHERE page_namespace = $ns
97 AND page_is_redirect = $redirect
98 AND page_random >= $randstr
99 $extra
100 ORDER BY page_random";
102 $sql = $dbr->limitResult( $sql, 1, 0 );
103 $res = $dbr->query( $sql, $fname );
104 return $dbr->fetchObject( $res );