3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Specials
;
23 use BadMethodCallException
;
24 use MediaWiki\HTMLForm\HTMLForm
;
25 use MediaWiki\SpecialPage\FormSpecialPage
;
26 use MediaWiki\Status\Status
;
27 use MediaWiki\Title\Title
;
29 use Wikimedia\Rdbms\IConnectionProvider
;
30 use Wikimedia\Rdbms\SelectQueryBuilder
;
33 * Redirect to a random page in a category
35 * @note The method used here is rather biased. It is assumed that
36 * the use of this page will be people wanting to get a random page
37 * out of a maintenance category, to fix it up. The method used by
38 * this page should return different pages in an unpredictable fashion
39 * which is hoped to be sufficient, even if some pages are selected
40 * more often than others.
42 * A more unbiased method could be achieved by adding a cl_random field
43 * to the categorylinks table.
45 * The method used here is as follows:
46 * * Find the smallest and largest timestamp in the category
47 * * Pick a random timestamp in between
48 * * Pick an offset between 0 and 30
49 * * Get the offset'ed page that is newer than the timestamp selected
50 * The offset is meant to counter the fact the timestamps aren't usually
51 * uniformly distributed, so if things are very non-uniform at least we
52 * won't have the same page selected 99% of the time.
54 * @ingroup SpecialPage
57 class SpecialRandomInCategory
extends FormSpecialPage
{
58 /** @var string[] Extra SQL statements */
59 protected $extra = [];
60 /** @var Title|false Title object of category */
61 protected $category = false;
62 /** @var int Max amount to fudge randomness by */
63 protected $maxOffset = 30;
65 private $maxTimestamp = null;
67 private $minTimestamp = null;
69 private IConnectionProvider
$dbProvider;
71 public function __construct( IConnectionProvider
$dbProvider ) {
72 parent
::__construct( 'RandomInCategory' );
73 $this->dbProvider
= $dbProvider;
77 * Set which category to use.
79 public function setCategory( Title
$cat ) {
80 $this->category
= $cat;
81 $this->maxTimestamp
= null;
82 $this->minTimestamp
= null;
85 protected function getFormFields() {
86 $this->addHelpLink( 'Help:RandomInCategory' );
91 'namespace' => NS_CATEGORY
,
93 'label-message' => 'randomincategory-category',
99 public function requiresPost() {
103 protected function getDisplayFormat() {
107 protected function alterForm( HTMLForm
$form ) {
108 $form->setSubmitTextMsg( 'randomincategory-submit' );
111 protected function getSubpageField() {
115 public function onSubmit( array $data ) {
118 $categoryStr = $data['category'];
120 if ( $categoryStr ) {
121 $cat = Title
::newFromText( $categoryStr, NS_CATEGORY
);
124 if ( $cat && $cat->getNamespace() !== NS_CATEGORY
) {
125 // Someone searching for something like "Wikipedia:Foo"
126 $cat = Title
::makeTitleSafe( NS_CATEGORY
, $categoryStr );
130 $this->setCategory( $cat );
133 if ( !$this->category
&& $categoryStr ) {
134 $msg = $this->msg( 'randomincategory-invalidcategory',
135 wfEscapeWikiText( $categoryStr ) );
137 return Status
::newFatal( $msg );
139 } elseif ( !$this->category
) {
140 return false; // no data sent
143 $title = $this->getRandomTitle();
145 if ( $title === null ) {
146 $msg = $this->msg( 'randomincategory-nopages',
147 $this->category
->getText() );
149 return Status
::newFatal( $msg );
152 $query = $this->getRequest()->getQueryValues();
153 unset( $query['title'] );
154 $this->getOutput()->redirect( $title->getFullURL( $query ) );
158 * Choose a random title.
159 * @return Title|null Title object or null if nothing to choose from
161 public function getRandomTitle() {
162 // Convert to float, since we do math with the random number.
163 $rand = (float)wfRandom();
165 // Given that timestamps are rather unevenly distributed, we also
166 // use an offset between 0 and 30 to make any biases less noticeable.
167 $offset = mt_rand( 0, $this->maxOffset
);
169 if ( mt_rand( 0, 1 ) ) {
175 $row = $this->selectRandomPageFromDB( $rand, $offset, $up, __METHOD__
);
177 // Try again without the timestamp offset (wrap around the end)
179 $row = $this->selectRandomPageFromDB( false, $offset, $up, __METHOD__
);
182 // Maybe the category is really small and offset too high
184 $row = $this->selectRandomPageFromDB( $rand, 0, $up, __METHOD__
);
187 // Just get the first entry.
189 $row = $this->selectRandomPageFromDB( false, 0, true, __METHOD__
);
193 return Title
::makeTitle( $row->page_namespace
, $row->page_title
);
200 * @note The $up parameter is supposed to counteract what would happen if there
201 * was a large gap in the distribution of cl_timestamp values. This way instead
202 * of things to the right of the gap being favoured, both sides of the gap
205 * @param float|false $rand Random number between 0 and 1
206 * @param int $offset Extra offset to fudge randomness
207 * @param bool $up True to get the result above the random number, false for below
208 * @return SelectQueryBuilder
210 protected function getQueryBuilder( $rand, $offset, $up ) {
211 if ( !$this->category
instanceof Title
) {
212 throw new BadMethodCallException( 'No category set' );
214 $dbr = $this->dbProvider
->getReplicaDatabase();
215 $queryBuilder = $dbr->newSelectQueryBuilder()
216 ->select( [ 'page_title', 'page_namespace' ] )
217 ->from( 'categorylinks' )
218 ->join( 'page', null, 'cl_from = page_id' )
219 ->where( [ 'cl_to' => $this->category
->getDBkey() ] )
220 ->andWhere( $this->extra
)
221 ->orderBy( 'cl_timestamp', $up ? SelectQueryBuilder
::SORT_ASC
: SelectQueryBuilder
::SORT_DESC
)
225 $minClTime = $this->getTimestampOffset( $rand );
227 $op = $up ?
'>=' : '<=';
228 $queryBuilder->andWhere(
229 $dbr->expr( 'cl_timestamp', $op, $dbr->timestamp( $minClTime ) )
233 return $queryBuilder;
237 * @param float|false $rand Random number between 0 and 1
238 * @return int|false A random (unix) timestamp from the range of the category or false on failure
240 protected function getTimestampOffset( $rand ) {
241 if ( $rand === false ) {
244 if ( !$this->minTimestamp ||
!$this->maxTimestamp
) {
245 $minAndMax = $this->getMinAndMaxForCat();
246 if ( $minAndMax === null ) {
247 // No entries in this category.
250 [ $this->minTimestamp
, $this->maxTimestamp
] = $minAndMax;
253 $ts = ( $this->maxTimestamp
- $this->minTimestamp
) * $rand +
$this->minTimestamp
;
255 return intval( $ts );
259 * Get the lowest and highest timestamp for a category.
261 * @return array|null The lowest and highest timestamp, or null if the category has no entries.
263 protected function getMinAndMaxForCat() {
264 $dbr = $this->dbProvider
->getReplicaDatabase();
265 $res = $dbr->newSelectQueryBuilder()
266 ->select( [ 'low' => 'MIN( cl_timestamp )', 'high' => 'MAX( cl_timestamp )' ] )
267 ->from( 'categorylinks' )
268 ->where( [ 'cl_to' => $this->category
->getDBkey(), ] )
269 ->caller( __METHOD__
)->fetchRow();
274 return [ (int)wfTimestamp( TS_UNIX
, $res->low
), (int)wfTimestamp( TS_UNIX
, $res->high
) ];
278 * @param float|false $rand A random number that is converted to a random timestamp
279 * @param int $offset A small offset to make the result seem more "random"
280 * @param bool $up Get the result above the random value
281 * @param string $fname The name of the calling method
282 * @return stdClass|false Info for the title selected.
284 private function selectRandomPageFromDB( $rand, $offset, $up, $fname ) {
285 return $this->getQueryBuilder( $rand, $offset, $up )->caller( $fname )->fetchRow();
288 protected function getGroupName() {
294 * Retain the old class name for backwards compatibility.
295 * @deprecated since 1.41
297 class_alias( SpecialRandomInCategory
::class, 'SpecialRandomInCategory' );