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