(bug 11562) API: Added a user_registration parameter/field to the list=allusers query...
[lhc/web/wiklou.git] / includes / SpecialRandompage.php
1 <?php
2
3 /**
4 * Special page to direct the user to a random page
5 *
6 * @addtogroup SpecialPage
7 * @author Rob Church <robchur@gmail.com>, Ilmari Karonen
8 * @license GNU General Public Licence 2.0 or later
9 */
10
11 /**
12 * Main execution point
13 * @param $par Namespace to select the page from
14 */
15 function wfSpecialRandompage( $par = null ) {
16 global $wgOut, $wgContLang;
17
18 $rnd = new RandomPage();
19 $rnd->setNamespace( $wgContLang->getNsIndex( $par ) );
20 $rnd->setRedirect( false );
21
22 $title = $rnd->getRandomTitle();
23
24 if( is_null( $title ) ) {
25 $wgOut->addWikiText( wfMsg( 'randompage-nopages' ) );
26 return;
27 }
28
29 $wgOut->reportTime();
30 $wgOut->redirect( $title->getFullUrl() );
31 }
32
33
34 /**
35 * Special page to direct the user to a random page
36 *
37 * @addtogroup SpecialPage
38 */
39 class RandomPage {
40 private $namespace = NS_MAIN; // namespace to select pages from
41 private $redirect = false; // select redirects instead of normal pages?
42
43 public function getNamespace ( ) {
44 return $this->namespace;
45 }
46 public function setNamespace ( $ns ) {
47 if( $ns < NS_MAIN ) $ns = NS_MAIN;
48 $this->namespace = $ns;
49 }
50 public function getRedirect ( ) {
51 return $this->redirect;
52 }
53 public function setRedirect ( $redirect ) {
54 $this->redirect = $redirect;
55 }
56
57 /**
58 * Choose a random title.
59 * @return Title object (or null if nothing to choose from)
60 */
61 public function getRandomTitle ( ) {
62 $randstr = wfRandom();
63 $row = $this->selectRandomPageFromDB( $randstr );
64
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. :)
71 */
72 if( !$row )
73 $row = $this->selectRandomPageFromDB( "0" );
74
75 if( $row )
76 return Title::makeTitleSafe( $this->namespace, $row->page_title );
77 else
78 return null;
79 }
80
81 private function selectRandomPageFromDB ( $randstr ) {
82 global $wgExtraRandompageSQL;
83 $fname = 'RandomPage::selectRandomPageFromDB';
84
85 $dbr = wfGetDB( DB_SLAVE );
86
87 $use_index = $dbr->useIndexClause( 'page_random' );
88 $page = $dbr->tableName( 'page' );
89
90 $ns = (int) $this->namespace;
91 $redirect = $this->redirect ? 1 : 0;
92
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";
101
102 $sql = $dbr->limitResult( $sql, 1, 0 );
103 $res = $dbr->query( $sql, $fname );
104 return $dbr->fetchObject( $res );
105 }
106 }
107
108