Apply live hack from Wikimedia code base: profiling point around SVN version lookup
[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 * Special page to direct the user to a random page
13 *
14 * @addtogroup SpecialPage
15 */
16 class RandomPage extends SpecialPage {
17 private $namespace = NS_MAIN; // namespace to select pages from
18
19 function __construct( $name = 'Randompage' ){
20 parent::__construct( $name );
21 }
22
23 public function getNamespace() {
24 return $this->namespace;
25 }
26
27 public function setNamespace ( $ns ) {
28 if( $ns < NS_MAIN ) $ns = NS_MAIN;
29 $this->namespace = $ns;
30 }
31
32 // select redirects instead of normal pages?
33 // Overriden by SpecialRandomredirect
34 public function isRedirect(){
35 return false;
36 }
37
38 public function execute( $par ) {
39 global $wgOut, $wgContLang;
40
41 if ($par)
42 $this->setNamespace( $wgContLang->getNsIndex( $par ) );
43
44 $title = $this->getRandomTitle();
45
46 if( is_null( $title ) ) {
47 $this->setHeaders();
48 $wgOut->addWikiText( wfMsg( strtolower( $this->mName ) . '-nopages' ) );
49 return;
50 }
51
52 $query = $this->isRedirect() ? 'redirect=no' : '';
53 $wgOut->redirect( $title->getFullUrl( $query ) );
54 }
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->isRedirect() ? 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