Switch some HTMLForms in special pages to OOUI
[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 FormSpecialPage {
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 protected function getFormFields() {
71 $this->addHelpLink( 'Help:RandomInCategory' );
72
73 $form = array(
74 'category' => array(
75 'type' => 'text',
76 'label-message' => 'randomincategory-category',
77 'required' => true,
78 )
79 );
80
81 return $form;
82 }
83
84 public function requiresWrite() {
85 return false;
86 }
87
88 public function requiresUnblock() {
89 return false;
90 }
91
92 protected function setParameter( $par ) {
93 // if subpage present, fake form submission
94 $this->onSubmit( array( 'category' => $par ) );
95 }
96
97 public function onSubmit( array $data ) {
98 $cat = false;
99
100 $categoryStr = $data['category'];
101
102 if ( $categoryStr ) {
103 $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
104 }
105
106 if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
107 // Someone searching for something like "Wikipedia:Foo"
108 $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
109 }
110
111 if ( $cat ) {
112 $this->setCategory( $cat );
113 }
114
115 if ( !$this->category && $categoryStr ) {
116 $msg = $this->msg( 'randomincategory-invalidcategory',
117 wfEscapeWikiText( $categoryStr ) );
118
119 return Status::newFatal( $msg );
120
121 } elseif ( !$this->category ) {
122 return false; // no data sent
123 }
124
125 $title = $this->getRandomTitle();
126
127 if ( is_null( $title ) ) {
128 $msg = $this->msg( 'randomincategory-nopages',
129 $this->category->getText() );
130
131 return Status::newFatal( $msg );
132 }
133
134 $this->getOutput()->redirect( $title->getFullURL() );
135 }
136
137 /**
138 * Choose a random title.
139 * @return Title|null Title object (or null if nothing to choose from)
140 */
141 public function getRandomTitle() {
142 // Convert to float, since we do math with the random number.
143 $rand = (float)wfRandom();
144 $title = null;
145
146 // Given that timestamps are rather unevenly distributed, we also
147 // use an offset between 0 and 30 to make any biases less noticeable.
148 $offset = mt_rand( 0, $this->maxOffset );
149
150 if ( mt_rand( 0, 1 ) ) {
151 $up = true;
152 } else {
153 $up = false;
154 }
155
156 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
157
158 // Try again without the timestamp offset (wrap around the end)
159 if ( !$row ) {
160 $row = $this->selectRandomPageFromDB( false, $offset, $up );
161 }
162
163 // Maybe the category is really small and offset too high
164 if ( !$row ) {
165 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
166 }
167
168 // Just get the first entry.
169 if ( !$row ) {
170 $row = $this->selectRandomPageFromDB( false, 0, true );
171 }
172
173 if ( $row ) {
174 return Title::makeTitle( $row->page_namespace, $row->page_title );
175 }
176
177 return null;
178 }
179
180 /**
181 * @param float $rand Random number between 0 and 1
182 * @param int $offset Extra offset to fudge randomness
183 * @param bool $up True to get the result above the random number, false for below
184 * @return array Query information.
185 * @throws MWException
186 * @note The $up parameter is supposed to counteract what would happen if there
187 * was a large gap in the distribution of cl_timestamp values. This way instead
188 * of things to the right of the gap being favoured, both sides of the gap
189 * are favoured.
190 */
191 protected function getQueryInfo( $rand, $offset, $up ) {
192 $op = $up ? '>=' : '<=';
193 $dir = $up ? 'ASC' : 'DESC';
194 if ( !$this->category instanceof Title ) {
195 throw new MWException( 'No category set' );
196 }
197 $qi = array(
198 'tables' => array( 'categorylinks', 'page' ),
199 'fields' => array( 'page_title', 'page_namespace' ),
200 'conds' => array_merge( array(
201 'cl_to' => $this->category->getDBKey(),
202 ), $this->extra ),
203 'options' => array(
204 'ORDER BY' => 'cl_timestamp ' . $dir,
205 'LIMIT' => 1,
206 'OFFSET' => $offset
207 ),
208 'join_conds' => array(
209 'page' => array( 'INNER JOIN', 'cl_from = page_id' )
210 )
211 );
212
213 $dbr = wfGetDB( DB_SLAVE );
214 $minClTime = $this->getTimestampOffset( $rand );
215 if ( $minClTime ) {
216 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
217 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
218 }
219
220 return $qi;
221 }
222
223 /**
224 * @param float $rand Random number between 0 and 1
225 *
226 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
227 */
228 protected function getTimestampOffset( $rand ) {
229 if ( $rand === false ) {
230 return false;
231 }
232 if ( !$this->minTimestamp || !$this->maxTimestamp ) {
233 try {
234 list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
235 } catch ( Exception $e ) {
236 // Possibly no entries in category.
237 return false;
238 }
239 }
240
241 $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
242
243 return intval( $ts );
244 }
245
246 /**
247 * Get the lowest and highest timestamp for a category.
248 *
249 * @param Title $category
250 * @return array The lowest and highest timestamp
251 * @throws MWException If category has no entries.
252 */
253 protected function getMinAndMaxForCat( Title $category ) {
254 $dbr = wfGetDB( DB_SLAVE );
255 $res = $dbr->selectRow(
256 'categorylinks',
257 array(
258 'low' => 'MIN( cl_timestamp )',
259 'high' => 'MAX( cl_timestamp )'
260 ),
261 array(
262 'cl_to' => $this->category->getDBKey(),
263 ),
264 __METHOD__,
265 array(
266 'LIMIT' => 1
267 )
268 );
269 if ( !$res ) {
270 throw new MWException( 'No entries in category' );
271 }
272
273 return array( wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) );
274 }
275
276 /**
277 * @param float $rand A random number that is converted to a random timestamp
278 * @param int $offset A small offset to make the result seem more "random"
279 * @param bool $up Get the result above the random value
280 * @param string $fname The name of the calling method
281 * @return array Info for the title selected.
282 */
283 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
284 $dbr = wfGetDB( DB_SLAVE );
285
286 $query = $this->getQueryInfo( $rand, $offset, $up );
287 $res = $dbr->select(
288 $query['tables'],
289 $query['fields'],
290 $query['conds'],
291 $fname,
292 $query['options'],
293 $query['join_conds']
294 );
295
296 return $res->fetchObject();
297 }
298
299 protected function getGroupName() {
300 return 'redirects';
301 }
302 }