Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / specials / SpecialRandomInCategory.php
blobadf12d40a650853d67cb3d26bf976e39b3d8aedf
1 <?php
2 /**
3 * Implements Special:RandomInCategory
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.
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.
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
20 * @file
21 * @ingroup SpecialPage
22 * @author Brian Wolff
25 /**
26 * Special page to direct the user to a random page
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.
35 * A more unbiased method could be achieved by adding a cl_random field
36 * to the categorylinks table.
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.
47 * @ingroup SpecialPage
49 class SpecialRandomInCategory extends FormSpecialPage {
50 /** @var string[] */
51 protected $extra = []; // Extra SQL statements
52 /** @var Title|false */
53 protected $category = false; // Title object of category
54 /** @var int */
55 protected $maxOffset = 30; // Max amount to fudge randomness by.
56 /** @var int|null */
57 private $maxTimestamp = null;
58 /** @var int|null */
59 private $minTimestamp = null;
61 public function __construct( $name = 'RandomInCategory' ) {
62 parent::__construct( $name );
65 /**
66 * Set which category to use.
67 * @param Title $cat
69 public function setCategory( Title $cat ) {
70 $this->category = $cat;
71 $this->maxTimestamp = null;
72 $this->minTimestamp = null;
75 protected function getFormFields() {
76 $this->addHelpLink( 'Help:RandomInCategory' );
78 return [
79 'category' => [
80 'type' => 'title',
81 'namespace' => NS_CATEGORY,
82 'relative' => true,
83 'label-message' => 'randomincategory-category',
84 'required' => true,
89 public function requiresWrite() {
90 return false;
93 public function requiresUnblock() {
94 return false;
97 protected function getDisplayFormat() {
98 return 'ooui';
101 protected function alterForm( HTMLForm $form ) {
102 $form->setSubmitTextMsg( 'randomincategory-submit' );
105 protected function setParameter( $par ) {
106 // if subpage present, fake form submission
107 $this->onSubmit( [ 'category' => $par ] );
110 public function onSubmit( array $data ) {
111 $cat = false;
113 $categoryStr = $data['category'];
115 if ( $categoryStr ) {
116 $cat = Title::newFromText( $categoryStr, NS_CATEGORY );
119 if ( $cat && $cat->getNamespace() !== NS_CATEGORY ) {
120 // Someone searching for something like "Wikipedia:Foo"
121 $cat = Title::makeTitleSafe( NS_CATEGORY, $categoryStr );
124 if ( $cat ) {
125 $this->setCategory( $cat );
128 if ( !$this->category && $categoryStr ) {
129 $msg = $this->msg( 'randomincategory-invalidcategory',
130 wfEscapeWikiText( $categoryStr ) );
132 return Status::newFatal( $msg );
134 } elseif ( !$this->category ) {
135 return false; // no data sent
138 $title = $this->getRandomTitle();
140 if ( is_null( $title ) ) {
141 $msg = $this->msg( 'randomincategory-nopages',
142 $this->category->getText() );
144 return Status::newFatal( $msg );
147 $this->getOutput()->redirect( $title->getFullURL() );
151 * Choose a random title.
152 * @return Title|null Title object (or null if nothing to choose from)
154 public function getRandomTitle() {
155 // Convert to float, since we do math with the random number.
156 $rand = (float)wfRandom();
157 $title = null;
159 // Given that timestamps are rather unevenly distributed, we also
160 // use an offset between 0 and 30 to make any biases less noticeable.
161 $offset = mt_rand( 0, $this->maxOffset );
163 if ( mt_rand( 0, 1 ) ) {
164 $up = true;
165 } else {
166 $up = false;
169 $row = $this->selectRandomPageFromDB( $rand, $offset, $up );
171 // Try again without the timestamp offset (wrap around the end)
172 if ( !$row ) {
173 $row = $this->selectRandomPageFromDB( false, $offset, $up );
176 // Maybe the category is really small and offset too high
177 if ( !$row ) {
178 $row = $this->selectRandomPageFromDB( $rand, 0, $up );
181 // Just get the first entry.
182 if ( !$row ) {
183 $row = $this->selectRandomPageFromDB( false, 0, true );
186 if ( $row ) {
187 return Title::makeTitle( $row->page_namespace, $row->page_title );
190 return null;
194 * @param float $rand Random number between 0 and 1
195 * @param int $offset Extra offset to fudge randomness
196 * @param bool $up True to get the result above the random number, false for below
197 * @return array Query information.
198 * @throws MWException
199 * @note The $up parameter is supposed to counteract what would happen if there
200 * was a large gap in the distribution of cl_timestamp values. This way instead
201 * of things to the right of the gap being favoured, both sides of the gap
202 * are favoured.
204 protected function getQueryInfo( $rand, $offset, $up ) {
205 $op = $up ? '>=' : '<=';
206 $dir = $up ? 'ASC' : 'DESC';
207 if ( !$this->category instanceof Title ) {
208 throw new MWException( 'No category set' );
210 $qi = [
211 'tables' => [ 'categorylinks', 'page' ],
212 'fields' => [ 'page_title', 'page_namespace' ],
213 'conds' => array_merge( [
214 'cl_to' => $this->category->getDBkey(),
215 ], $this->extra ),
216 'options' => [
217 'ORDER BY' => 'cl_timestamp ' . $dir,
218 'LIMIT' => 1,
219 'OFFSET' => $offset
221 'join_conds' => [
222 'page' => [ 'INNER JOIN', 'cl_from = page_id' ]
226 $dbr = wfGetDB( DB_REPLICA );
227 $minClTime = $this->getTimestampOffset( $rand );
228 if ( $minClTime ) {
229 $qi['conds'][] = 'cl_timestamp ' . $op . ' ' .
230 $dbr->addQuotes( $dbr->timestamp( $minClTime ) );
233 return $qi;
237 * @param float $rand Random number between 0 and 1
239 * @return int|bool A random (unix) timestamp from the range of the category or false on failure
241 protected function getTimestampOffset( $rand ) {
242 if ( $rand === false ) {
243 return false;
245 if ( !$this->minTimestamp || !$this->maxTimestamp ) {
246 try {
247 list( $this->minTimestamp, $this->maxTimestamp ) = $this->getMinAndMaxForCat( $this->category );
248 } catch ( Exception $e ) {
249 // Possibly no entries in category.
250 return false;
254 $ts = ( $this->maxTimestamp - $this->minTimestamp ) * $rand + $this->minTimestamp;
256 return intval( $ts );
260 * Get the lowest and highest timestamp for a category.
262 * @param Title $category
263 * @return array The lowest and highest timestamp
264 * @throws MWException If category has no entries.
266 protected function getMinAndMaxForCat( Title $category ) {
267 $dbr = wfGetDB( DB_REPLICA );
268 $res = $dbr->selectRow(
269 'categorylinks',
271 'low' => 'MIN( cl_timestamp )',
272 'high' => 'MAX( cl_timestamp )'
275 'cl_to' => $this->category->getDBkey(),
277 __METHOD__,
279 'LIMIT' => 1
282 if ( !$res ) {
283 throw new MWException( 'No entries in category' );
286 return [ wfTimestamp( TS_UNIX, $res->low ), wfTimestamp( TS_UNIX, $res->high ) ];
290 * @param float $rand A random number that is converted to a random timestamp
291 * @param int $offset A small offset to make the result seem more "random"
292 * @param bool $up Get the result above the random value
293 * @param string $fname The name of the calling method
294 * @return array Info for the title selected.
296 private function selectRandomPageFromDB( $rand, $offset, $up, $fname = __METHOD__ ) {
297 $dbr = wfGetDB( DB_REPLICA );
299 $query = $this->getQueryInfo( $rand, $offset, $up );
300 $res = $dbr->select(
301 $query['tables'],
302 $query['fields'],
303 $query['conds'],
304 $fname,
305 $query['options'],
306 $query['join_conds']
309 return $res->fetchObject();
312 protected function getGroupName() {
313 return 'redirects';