Merge "SpecialTrackingCategories: Use Config instead of globals"
[lhc/web/wiklou.git] / includes / specials / SpecialRandomInCategory.php
1 <?php
2 /**
3 * Implements Special:RandomInCategory
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @author Brian Wolff
23 */
24
25 /**
26 * Special page to direct the user to a random page
27 *
28 * @note The method used here is rather biased. It is assumed that
29 * the use of this page will be people wanting to get a random page
30 * out of a maintenance category, to fix it up. The method used by
31 * this page should return different pages in an unpredictable fashion
32 * which is hoped to be sufficient, even if some pages are selected
33 * more often than others.
34 *
35 * A more unbiased method could be achieved by adding a cl_random field
36 * to the categorylinks table.
37 *
38 * The method used here is as follows:
39 * * Find the smallest and largest timestamp in the category
40 * * Pick a random timestamp in between
41 * * Pick an offset between 0 and 30
42 * * Get the offset'ed page that is newer than the timestamp selected
43 * The offset is meant to counter the fact the timestamps aren't usually
44 * uniformly distributed, so if things are very non-uniform at least we
45 * won't have the same page selected 99% of the time.
46 *
47 * @ingroup SpecialPage
48 */
49 class SpecialRandomInCategory extends SpecialPage {
50 protected $extra = array(); // Extra SQL statements
51 protected $category = false; // Title object of category
52 protected $maxOffset = 30; // Max amount to fudge randomness by.
53 private $maxTimestamp = null;
54 private $minTimestamp = null;
55
56 public function __construct( $name = 'RandomInCategory' ) {
57 parent::__construct( $name );
58 }
59
60 /**
61 * Set which category to use.
62 * @param Title $cat
63 */
64 public function setCategory( Title $cat ) {
65 $this->category = $cat;
66 $this->maxTimestamp = null;
67 $this->minTimestamp = null;
68 }
69
70 public function execute( $par ) {
71 $cat = false;
72
73 $categoryStr = $this->getRequest()->getText( 'category', $par );
74
75 if ( $categoryStr ) {
76 $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
77 }
78
79 if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
80 // Someone searching for something like "Wikipedia:Foo"
81 $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
82 }
83
84 if ( $cat ) {
85 $this->setCategory( $cat );
86 }
87
88 if ( !$this->category && $categoryStr ) {
89 $this->setHeaders();
90 $this->getOutput()->addWikiMsg( 'randomincategory-invalidcategory',
91 wfEscapeWikiText( $categoryStr ) );
92
93 return;
94 } elseif ( !$this->category ) {
95 $this->setHeaders();
96 $input = Html::input( 'category' );
97 $submitText = $this->msg( 'randomincategory-selectcategory-submit' )->text();
98 $submit = Html::input( '', $submitText, 'submit' );
99
100 $msg = $this->msg( 'randomincategory-selectcategory' );
101 $form = Html::rawElement( 'form', array( 'action' => wfScript() ),
102 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
103 $msg->rawParams( $input, $submit )->parse()
104 );
105 $this->getOutput()->addHtml( $form );
106
107 return;
108 }
109
110 $title = $this->getRandomTitle();
111
112 if ( is_null( $title ) ) {
113 $this->setHeaders();
114 $this->getOutput()->addWikiMsg( 'randomincategory-nopages',
115 $this->category->getText() );
116
117 return;
118 }
119
120 $query = $this->getRequest()->getValues();
121 unset( $query['title'] );
122 unset( $query['category'] );
123 $this->getOutput()->redirect( $title->getFullURL( $query ) );
124 }
125
126 /**
127 * Choose a random title.
128 * @return Title|null Title object (or null if nothing to choose from)
129 */
130 public function getRandomTitle() {
131 // Convert to float, since we do math with the random number.
132 $rand = (float)wfRandom();
133 $title = null;
134
135 // Given that timestamps are rather unevenly distributed, we also
136 // use an offset between 0 and 30 to make any biases less noticeable.
137 $offset = mt_rand( 0, $this->maxOffset );
138
139 if ( mt_rand( 0, 1 ) ) {
140 $up = true;
141 } else {
142 $up = false;
143 }
144
145 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
146
147 // Try again without the timestamp offset (wrap around the end)
148 if ( !$row ) {
149 $row = $this->selectRandomPageFromDB( false, $offset, $up );
150 }
151
152 // Maybe the category is really small and offset too high
153 if ( !$row ) {
154 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
155 }
156
157 // Just get the first entry.
158 if ( !$row ) {
159 $row = $this->selectRandomPageFromDB( false, 0, true );
160 }
161
162 if ( $row ) {
163 return Title::makeTitle( $row->page_namespace, $row->page_title );
164 }
165
166 return null;
167 }
168
169 /**
170 * @param float $rand Random number between 0 and 1
171 * @param int $offset Extra offset to fudge randomness
172 * @param bool $up True to get the result above the random number, false for below
173 *
174 * @note The $up parameter is supposed to counteract what would happen if there
175 * was a large gap in the distribution of cl_timestamp values. This way instead
176 * of things to the right of the gap being favoured, both sides of the gap
177 * are favoured.
178 * @return array Query information.
179 */
180 protected function getQueryInfo( $rand, $offset, $up ) {
181 $op = $up ? '>=' : '<=';
182 $dir = $up ? 'ASC' : 'DESC';
183 if ( !$this->category instanceof Title ) {
184 throw new MWException( 'No category set' );
185 }
186 $qi = array(
187 'tables' => array( 'categorylinks', 'page' ),
188 'fields' => array( 'page_title', 'page_namespace' ),
189 'conds' => array_merge( array(
190 'cl_to' => $this->category->getDBKey(),
191 ), $this->extra ),
192 'options' => array(
193 'ORDER BY' => 'cl_timestamp ' . $dir,
194 'LIMIT' => 1,
195 'OFFSET' => $offset
196 ),
197 'join_conds' => array(
198 'page' => array( 'INNER JOIN', 'cl_from = page_id' )
199 )
200 );
201
202 $dbr = wfGetDB( DB_SLAVE );
203 $minClTime = $this->getTimestampOffset( $rand );
204 if ( $minClTime ) {
205 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
206 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
207 }
208
209 return $qi;
210 }
211
212 /**
213 * @param float $rand Random number between 0 and 1
214 *
215 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
216 */
217 protected function getTimestampOffset( $rand ) {
218 if ( $rand === false ) {
219 return false;
220 }
221 if ( !$this->minTimestamp || !$this->maxTimestamp ) {
222 try {
223 list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
224 } catch ( MWException $e ) {
225 // Possibly no entries in category.
226 return false;
227 }
228 }
229
230 $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
231
232 return intval( $ts );
233 }
234
235 /**
236 * Get the lowest and highest timestamp for a category.
237 *
238 * @param Title $category
239 * @return array The lowest and highest timestamp
240 * @throws MWException If category has no entries.
241 */
242 protected function getMinAndMaxForCat( Title $category ) {
243 $dbr = wfGetDB( DB_SLAVE );
244 $res = $dbr->selectRow(
245 'categorylinks',
246 array(
247 'low' => 'MIN( cl_timestamp )',
248 'high' => 'MAX( cl_timestamp )'
249 ),
250 array(
251 'cl_to' => $this->category->getDBKey(),
252 ),
253 __METHOD__,
254 array(
255 'LIMIT' => 1
256 )
257 );
258 if ( !$res ) {
259 throw new MWException( 'No entries in category' );
260 }
261
262 return array( wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) );
263 }
264
265 /**
266 * @param float $rand A random number that is converted to a random timestamp
267 * @param int $offset A small offset to make the result seem more "random"
268 * @param bool $up Get the result above the random value
269 * @param string $fname The name of the calling method
270 * @return array Info for the title selected.
271 */
272 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
273 $dbr = wfGetDB( DB_SLAVE );
274
275 $query = $this->getQueryInfo( $rand, $offset, $up );
276 $res = $dbr->select(
277 $query['tables'],
278 $query['fields'],
279 $query['conds'],
280 $fname,
281 $query['options'],
282 $query['join_conds']
283 );
284
285 return $res->fetchObject();
286 }
287
288 protected function getGroupName() {
289 return 'redirects';
290 }
291 }