actually, there's no need to make it so complicated after all... :/
[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 class RandomPage {
35 private $namespace = NS_MAIN; // namespace to select pages from
36 private $redirect = false; // select redirects instead of normal pages?
37
38 public function getNamespace ( ) {
39 return $this->namespace;
40 }
41 public function setNamespace ( $ns ) {
42 if( $ns < NS_MAIN ) $ns = NS_MAIN;
43 $this->namespace = $ns;
44 }
45 public function getRedirect ( ) {
46 return $this->redirect;
47 }
48 public function setRedirect ( $redirect ) {
49 $this->redirect = $redirect;
50 }
51
52 /**
53 * Choose a random title.
54 * @return Title object (or null if nothing to choose from)
55 */
56 public function getRandomTitle ( ) {
57 $randstr = wfRandom();
58 $row = $this->selectRandomPageFromDB( $randstr );
59
60 /* If we picked a value that was higher than any in
61 * the DB, wrap around and select the page with the
62 * lowest value instead! One might think this would
63 * skew the distribution, but in fact it won't cause
64 * any more bias than what the page_random scheme
65 * causes anyway. Trust me, I'm a mathematician. :)
66 */
67 if( !$row )
68 $row = $this->selectRandomPageFromDB( "0" );
69
70 if( $row )
71 return Title::makeTitleSafe( $this->namespace, $row->page_title );
72 else
73 return null;
74 }
75
76 private function selectRandomPageFromDB ( $randstr ) {
77 global $wgExtraRandompageSQL;
78 $fname = 'RandomPage::selectRandomPageFromDB';
79
80 $dbr = wfGetDB( DB_SLAVE );
81
82 $use_index = $dbr->useIndexClause( 'page_random' );
83 $page = $dbr->tableName( 'page' );
84
85 $ns = (int) $this->namespace;
86 $redirect = $this->redirect ? 1 : 0;
87
88 $extra = $wgExtraRandompageSQL ? "AND ($wgExtraRandompageSQL)" : "";
89 $sql = "SELECT page_title
90 FROM $page $use_index
91 WHERE page_namespace = $ns
92 AND page_is_redirect = $redirect
93 AND page_random >= $randstr
94 $extra
95 ORDER BY page_random";
96
97 $sql = $dbr->limitResult( $sql, 1, 0 );
98 $res = $dbr->query( $sql, $fname );
99 return $dbr->fetchObject( $res );
100 }
101 }
102
103 ?>